@developer.notchatbot/webchat 1.0.5 → 1.0.6

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.
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */(function(e){function t(j,U){var z=j.length;j.push(U);e:for(;0<z;){var V=z-1>>>1,G=j[V];if(0<o(G,U))j[V]=U,j[z]=G,z=V;else break e}}function n(j){return j.length===0?null:j[0]}function r(j){if(j.length===0)return null;var U=j[0],z=j.pop();if(z!==U){j[0]=z;e:for(var V=0,G=j.length,F=G>>>1;V<F;){var b=2*(V+1)-1,L=j[b],B=b+1,_=j[B];if(0>o(L,z))B<G&&0>o(_,L)?(j[V]=_,j[B]=z,V=B):(j[V]=L,j[b]=z,V=b);else if(B<G&&0>o(_,z))j[V]=_,j[B]=z,V=B;else break e}}return U}function o(j,U){var z=j.sortIndex-U.sortIndex;return z!==0?z:j.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,m=a.now();e.unstable_now=function(){return a.now()-m}}var v=[],S=[],T=1,R=null,C=3,O=!1,f=!1,E=!1,P=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate!="undefined"?setImmediate:null;typeof navigator!="undefined"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function h(j){for(var U=n(S);U!==null;){if(U.callback===null)r(S);else if(U.startTime<=j)r(S),U.sortIndex=U.expirationTime,t(v,U);else break;U=n(S)}}function w(j){if(E=!1,h(j),!f)if(n(v)!==null)f=!0,M(c);else{var U=n(S);U!==null&&A(w,U.startTime-j)}}function c(j,U){f=!1,E&&(E=!1,y(s),s=-1),O=!0;var z=C;try{for(h(U),R=n(v);R!==null&&(!(R.expirationTime>U)||j&&!x());){var V=R.callback;if(typeof V=="function"){R.callback=null,C=R.priorityLevel;var G=V(R.expirationTime<=U);U=e.unstable_now(),typeof G=="function"?R.callback=G:R===n(v)&&r(v),h(U)}else r(v);R=n(v)}if(R!==null)var F=!0;else{var b=n(S);b!==null&&A(w,b.startTime-U),F=!1}return F}finally{R=null,C=z,O=!1}}var u=!1,l=null,s=-1,g=5,p=-1;function x(){return!(e.unstable_now()-p<g)}function D(){if(l!==null){var j=e.unstable_now();p=j;var U=!0;try{U=l(!0,j)}finally{U?N():(u=!1,l=null)}}else u=!1}var N;if(typeof d=="function")N=function(){d(D)};else if(typeof MessageChannel!="undefined"){var k=new MessageChannel,I=k.port2;k.port1.onmessage=D,N=function(){I.postMessage(null)}}else N=function(){P(D,0)};function M(j){l=j,u||(u=!0,N())}function A(j,U){s=P(function(){j(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(j){j.callback=null},e.unstable_continueExecution=function(){f||O||(f=!0,M(c))},e.unstable_forceFrameRate=function(j){0>j||125<j?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):g=0<j?Math.floor(1e3/j):5},e.unstable_getCurrentPriorityLevel=function(){return C},e.unstable_getFirstCallbackNode=function(){return n(v)},e.unstable_next=function(j){switch(C){case 1:case 2:case 3:var U=3;break;default:U=C}var z=C;C=U;try{return j()}finally{C=z}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(j,U){switch(j){case 1:case 2:case 3:case 4:case 5:break;default:j=3}var z=C;C=j;try{return U()}finally{C=z}},e.unstable_scheduleCallback=function(j,U,z){var V=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?V+z:V):z=V,j){case 1:var G=-1;break;case 2:G=250;break;case 5:G=1073741823;break;case 4:G=1e4;break;default:G=5e3}return G=z+G,j={id:T++,callback:U,priorityLevel:j,startTime:z,expirationTime:G,sortIndex:-1},z>V?(j.sortIndex=z,t(S,j),n(v)===null&&j===n(S)&&(E?(y(s),s=-1):E=!0,A(w,z-V))):(j.sortIndex=G,t(v,j),f||O||(f=!0,M(c))),j},e.unstable_shouldYield=x,e.unstable_wrapCallback=function(j){var U=C;return function(){var z=C;C=U;try{return j.apply(this,arguments)}finally{C=z}}}})(Ds),Ns.exports=Ds;var vf=Ns.exports;/**
17
+ */(function(e){function t(j,U){var z=j.length;j.push(U);e:for(;0<z;){var W=z-1>>>1,G=j[W];if(0<o(G,U))j[W]=U,j[z]=G,z=W;else break e}}function n(j){return j.length===0?null:j[0]}function r(j){if(j.length===0)return null;var U=j[0],z=j.pop();if(z!==U){j[0]=z;e:for(var W=0,G=j.length,F=G>>>1;W<F;){var b=2*(W+1)-1,L=j[b],B=b+1,_=j[B];if(0>o(L,z))B<G&&0>o(_,L)?(j[W]=_,j[B]=z,W=B):(j[W]=L,j[b]=z,W=b);else if(B<G&&0>o(_,z))j[W]=_,j[B]=z,W=B;else break e}}return U}function o(j,U){var z=j.sortIndex-U.sortIndex;return z!==0?z:j.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,m=a.now();e.unstable_now=function(){return a.now()-m}}var v=[],S=[],T=1,R=null,C=3,O=!1,f=!1,E=!1,P=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate!="undefined"?setImmediate:null;typeof navigator!="undefined"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function h(j){for(var U=n(S);U!==null;){if(U.callback===null)r(S);else if(U.startTime<=j)r(S),U.sortIndex=U.expirationTime,t(v,U);else break;U=n(S)}}function w(j){if(E=!1,h(j),!f)if(n(v)!==null)f=!0,M(c);else{var U=n(S);U!==null&&A(w,U.startTime-j)}}function c(j,U){f=!1,E&&(E=!1,y(s),s=-1),O=!0;var z=C;try{for(h(U),R=n(v);R!==null&&(!(R.expirationTime>U)||j&&!x());){var W=R.callback;if(typeof W=="function"){R.callback=null,C=R.priorityLevel;var G=W(R.expirationTime<=U);U=e.unstable_now(),typeof G=="function"?R.callback=G:R===n(v)&&r(v),h(U)}else r(v);R=n(v)}if(R!==null)var F=!0;else{var b=n(S);b!==null&&A(w,b.startTime-U),F=!1}return F}finally{R=null,C=z,O=!1}}var u=!1,l=null,s=-1,g=5,p=-1;function x(){return!(e.unstable_now()-p<g)}function D(){if(l!==null){var j=e.unstable_now();p=j;var U=!0;try{U=l(!0,j)}finally{U?N():(u=!1,l=null)}}else u=!1}var N;if(typeof d=="function")N=function(){d(D)};else if(typeof MessageChannel!="undefined"){var k=new MessageChannel,I=k.port2;k.port1.onmessage=D,N=function(){I.postMessage(null)}}else N=function(){P(D,0)};function M(j){l=j,u||(u=!0,N())}function A(j,U){s=P(function(){j(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(j){j.callback=null},e.unstable_continueExecution=function(){f||O||(f=!0,M(c))},e.unstable_forceFrameRate=function(j){0>j||125<j?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):g=0<j?Math.floor(1e3/j):5},e.unstable_getCurrentPriorityLevel=function(){return C},e.unstable_getFirstCallbackNode=function(){return n(v)},e.unstable_next=function(j){switch(C){case 1:case 2:case 3:var U=3;break;default:U=C}var z=C;C=U;try{return j()}finally{C=z}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(j,U){switch(j){case 1:case 2:case 3:case 4:case 5:break;default:j=3}var z=C;C=j;try{return U()}finally{C=z}},e.unstable_scheduleCallback=function(j,U,z){var W=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?W+z:W):z=W,j){case 1:var G=-1;break;case 2:G=250;break;case 5:G=1073741823;break;case 4:G=1e4;break;default:G=5e3}return G=z+G,j={id:T++,callback:U,priorityLevel:j,startTime:z,expirationTime:G,sortIndex:-1},z>W?(j.sortIndex=z,t(S,j),n(v)===null&&j===n(S)&&(E?(y(s),s=-1):E=!0,A(w,z-W))):(j.sortIndex=G,t(v,j),f||O||(f=!0,M(c))),j},e.unstable_shouldYield=x,e.unstable_wrapCallback=function(j){var U=C;return function(){var z=C;C=U;try{return j.apply(this,arguments)}finally{C=z}}}})(Ds),Ns.exports=Ds;var vf=Ns.exports;/**
18
18
  * @license React
19
19
  * react-dom.production.min.js
20
20
  *
@@ -37,7 +37,7 @@ Error generating stack: `+i.message+`
37
37
  *
38
38
  * This source code is licensed under the MIT license found in the
39
39
  * LICENSE file in the root directory of this source tree.
40
- */var Ch=oe,xh=Symbol.for("react.element"),Eh=Symbol.for("react.fragment"),Oh=Object.prototype.hasOwnProperty,Rh=Ch.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Th={key:!0,ref:!0,__self:!0,__source:!0};function Hc(e,t,n){var r,o={},i=null,a=null;n!==void 0&&(i=""+n),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(a=t.ref);for(r in t)Oh.call(t,r)&&!Th.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:xh,type:e,key:i,ref:a,props:o,_owner:Rh.current}}Xo.Fragment=Eh,Xo.jsx=Hc,Xo.jsxs=Hc,zc.exports=Xo;var J=zc.exports;const bh=({isOpen:e,onClick:t,primaryColor:n="#007bff",position:r="bottom-right",marginBottom:o=16,marginSide:i=16,hasNewMessages:a=!1,isMobile:m=!1})=>{const v=()=>{const T={backgroundColor:n,zIndex:2147483647,bottom:`${o}px`};return r==="bottom-left"?Zt(yt({},T),{left:`${i}px`}):Zt(yt({},T),{right:`${i}px`})},S=()=>{const T="nbc-fixed nbc-w-16 nbc-h-16 nbc-rounded-full nbc-text-white nbc-shadow-lg nbc-transition-all nbc-duration-300 nbc-flex nbc-items-center nbc-justify-center nbc-border-0 nbc-cursor-pointer hover:nbc-scale-105";let R="";return m?R=e?"nbc-hidden":"nbc-flex":R="nbc-flex",`${T} ${R} ${e?"nbc-rotate-180":""}`};return J.jsxs("button",{onClick:t,className:S(),style:v(),"aria-label":e?"Close chat":"Open chat",children:[a&&!e&&J.jsxs(J.Fragment,{children:[J.jsx("div",{className:"nbc-absolute nbc-top-0 nbc-right-0 nbc-w-3 nbc-h-3 nbc-bg-green-400 nbc-rounded-full nbc-animate-ping nbc-opacity-75"}),J.jsx("div",{className:"nbc-absolute nbc-top-0 nbc-right-0 nbc-w-4 nbc-h-4 nbc-bg-green-500 nbc-rounded-full nbc-border-2 nbc-border-white nbc-flex nbc-items-center nbc-justify-center nbc-shadow-md nbc-animate-bounce",children:J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-white nbc-rounded-full"})})]}),e?J.jsx("svg",{className:"nbc-w-8 nbc-h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}):J.jsx("svg",{className:"nbc-w-8 nbc-h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z M8 12h.01 M12 12h.01 M16 12h.01"})})]})},Ah=({title:e,onClose:t,primaryColor:n="#f59e0b",avatar:r,closeButtonIcon:o="default",closeButtonText:i="×",closeButtonCustomIcon:a})=>{const m=()=>{switch(o){case"text":return J.jsx("span",{className:"nbc-text-sm nbc-font-bold nbc-leading-none",children:i});case"custom":return a?a.startsWith("<svg")?J.jsx("div",{className:"nbc-w-5 nbc-h-5 nbc-flex nbc-items-center nbc-justify-center",dangerouslySetInnerHTML:{__html:a}}):J.jsx("img",{src:a,alt:"Close",className:"nbc-w-5 nbc-h-5"}):J.jsx("svg",{className:"nbc-w-5 nbc-h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})});default:return J.jsx("svg",{className:"nbc-w-5 nbc-h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}};return J.jsxs("div",{className:"nbc-p-2 nbc-text-white nbc-flex nbc-justify-between nbc-items-center nbc-font-medium",style:{backgroundColor:n},children:[J.jsxs("div",{className:"nbc-flex nbc-items-center nbc-space-x-3 nbc-text-black",children:[r?J.jsx("img",{src:r,alt:"Avatar",className:"nbc-w-10 nbc-h-10 nbc-rounded-full nbc-object-cover"}):J.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"nbc-w-8 nbc-h-8 nbc-bg-white nbc-rounded-full nbc-p-1",children:[J.jsx("path",{d:"M12 6V2H8"}),J.jsx("path",{d:"m8 18-4 4V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2Z"}),J.jsx("path",{d:"M2 12h2"}),J.jsx("path",{d:"M9 11v2"}),J.jsx("path",{d:"M15 11v2"}),J.jsx("path",{d:"M20 12h2"})]}),J.jsx("h3",{className:"nbc-m-0 nbc-text-lg nbc-font-bold nbc-text-white",children:e})]}),J.jsx("button",{onClick:t,className:"nbc-bg-transparent nbc-border-0 nbc-text-white nbc-cursor-pointer nbc-p-1 nbc-rounded-full nbc-flex nbc-items-center nbc-justify-center hover:nbc-bg-black hover:nbc-bg-opacity-20 nbc-transition-colors nbc-duration-200 nbc-w-8 nbc-h-8","aria-label":"Close chat",children:m()})]})};function Ih(e){if(!e)return"";const t=new Date(e),n=t.getDate().toString().padStart(2,"0"),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getFullYear(),i=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0");return`${n}/${r}/${o} ${i}:${a}`}const Fc=e=>{var o,i;const t=new Date(e),n=new Date,r=new Date(n);return r.setDate(r.getDate()-1),t.toDateString()===n.toDateString()?(i=(o=Ih(e.toString()))==null?void 0:o.split(" ")[1])!=null?i:"":t.toDateString()===r.toDateString()?"Yesterday":t.getFullYear()===n.getFullYear()?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})},Mh=({message:e,avatar:t})=>e.sender==="user"?J.jsx("div",{className:"nbc-flex nbc-justify-end nbc-mb-4",children:J.jsxs("div",{className:"nbc-max-w-xs nbc-px-4 nbc-py-3 nbc-rounded-2xl nbc-text-sm nbc-leading-relaxed nbc-bg-gray-100 nbc-text-gray-900 nbc-rounded-br-md",children:[J.jsx("div",{className:"nbc-whitespace-pre-wrap nbc-break-words",children:e.text}),J.jsx("div",{className:"nbc-text-xs nbc-mt-1 nbc-opacity-70 nbc-text-right",children:Fc(e.timestamp)})]})}):J.jsx("div",{className:"nbc-flex nbc-justify-start nbc-mb-4",children:J.jsxs("div",{className:"nbc-flex nbc-items-start nbc-space-x-3",children:[J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-py-3",children:[t&&J.jsx("img",{src:t,alt:"AI Assistant",className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-object-cover nbc-flex-shrink-0"}),J.jsx("div",{className:"nbc-text-xs nbc-text-gray-500 nbc-opacity-70 nbc-whitespace-nowrap",children:Fc(e.timestamp)})]}),J.jsx("div",{className:"nbc-max-w-xs nbc-py-3 nbc-rounded-2xl nbc-text-sm nbc-leading-relaxed nbc-bg-white nbc-text-gray-800 nbc-rounded-bl-md",children:J.jsx("div",{className:"nbc-whitespace-pre-wrap nbc-break-words",children:e.text})})]})}),Ph=({avatar:e})=>J.jsx("div",{className:"nbc-flex nbc-justify-start nbc-mb-4",children:J.jsxs("div",{className:"nbc-flex nbc-items-start nbc-space-x-3",children:[J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-py-3",children:[e&&J.jsx("img",{src:e,alt:"AI Assistant",className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-object-cover nbc-flex-shrink-0"}),J.jsx("div",{className:"nbc-text-xs nbc-text-gray-500 nbc-opacity-70 nbc-whitespace-nowrap",children:" "})]}),J.jsx("div",{className:"nbc-bg-white nbc-px-4 nbc-py-3 nbc-rounded-2xl nbc-rounded-bl-md nbc-shadow-sm",children:J.jsxs("div",{className:"nbc-flex nbc-space-x-1",children:[J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-gray-400 nbc-rounded-full nbc-animate-bounce",style:{animationDelay:"0ms"}}),J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-gray-400 nbc-rounded-full nbc-animate-bounce",style:{animationDelay:"150ms"}}),J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-gray-400 nbc-rounded-full nbc-animate-bounce",style:{animationDelay:"300ms"}})]})})]})}),kh=({messages:e,isTyping:t,avatar:n})=>{const r=oe.useRef(null),o=()=>{var i;(i=r.current)==null||i.scrollIntoView({behavior:"smooth"})};return oe.useEffect(()=>{o()},[e,t]),J.jsxs("div",{className:"nbc-flex-1 nbc-overflow-y-auto nbc-px-2 nbc-pt-4",style:{scrollbarWidth:"thin",scrollbarColor:"#d1d5db #f9fafb"},children:[J.jsx("style",{children:`
40
+ */var Ch=oe,xh=Symbol.for("react.element"),Eh=Symbol.for("react.fragment"),Oh=Object.prototype.hasOwnProperty,Rh=Ch.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Th={key:!0,ref:!0,__self:!0,__source:!0};function Hc(e,t,n){var r,o={},i=null,a=null;n!==void 0&&(i=""+n),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(a=t.ref);for(r in t)Oh.call(t,r)&&!Th.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:xh,type:e,key:i,ref:a,props:o,_owner:Rh.current}}Xo.Fragment=Eh,Xo.jsx=Hc,Xo.jsxs=Hc,zc.exports=Xo;var J=zc.exports;const bh=({isOpen:e,onClick:t,primaryColor:n="#007bff",position:r="bottom-right",marginBottom:o=16,marginSide:i=16,hasNewMessages:a=!1,isMobile:m=!1})=>{const v=()=>{const T={backgroundColor:n,zIndex:2147483647,bottom:`${o}px`};return r==="bottom-left"?Zt(yt({},T),{left:`${i}px`}):Zt(yt({},T),{right:`${i}px`})},S=()=>{const T="nbc-fixed nbc-w-16 nbc-h-16 nbc-rounded-full nbc-text-white nbc-shadow-lg nbc-transition-all nbc-duration-300 nbc-flex nbc-items-center nbc-justify-center nbc-border-0 nbc-cursor-pointer hover:nbc-scale-105";let R="";return m?R=e?"nbc-hidden":"nbc-flex":R="nbc-flex",`${T} ${R} ${e?"nbc-rotate-180":""}`};return J.jsxs("button",{onClick:t,className:S(),style:v(),"aria-label":e?"Close chat":"Open chat",children:[a&&!e&&J.jsxs(J.Fragment,{children:[J.jsx("div",{className:"nbc-absolute nbc-top-0 nbc-right-0 nbc-w-3 nbc-h-3 nbc-bg-green-400 nbc-rounded-full nbc-animate-ping nbc-opacity-75"}),J.jsx("div",{className:"nbc-absolute nbc-top-0 nbc-right-0 nbc-w-4 nbc-h-4 nbc-bg-green-500 nbc-rounded-full nbc-border-2 nbc-border-white nbc-flex nbc-items-center nbc-justify-center nbc-shadow-md nbc-animate-bounce",children:J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-white nbc-rounded-full"})})]}),e?J.jsx("svg",{className:"nbc-w-8 nbc-h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}):J.jsx("svg",{className:"nbc-w-8 nbc-h-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z M8 12h.01 M12 12h.01 M16 12h.01"})})]})},Ah=({title:e,onClose:t,primaryColor:n="#f59e0b",avatar:r,closeButtonIcon:o="default",closeButtonText:i="×",closeButtonCustomIcon:a})=>{const m=()=>{switch(o){case"text":return J.jsx("span",{className:"nbc-text-sm nbc-font-bold nbc-leading-none",children:i});case"custom":return a?a.startsWith("<svg")?J.jsx("div",{className:"nbc-w-5 nbc-h-5 nbc-flex nbc-items-center nbc-justify-center",dangerouslySetInnerHTML:{__html:a}}):J.jsx("img",{src:a,alt:"Close",className:"nbc-w-5 nbc-h-5"}):J.jsx("svg",{className:"nbc-w-5 nbc-h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})});default:return J.jsx("svg",{className:"nbc-w-5 nbc-h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}};return J.jsxs("div",{className:"nbc-p-2 nbc-text-white nbc-flex nbc-justify-between nbc-items-center nbc-font-medium",style:{backgroundColor:n},children:[J.jsxs("div",{className:"nbc-flex nbc-items-center nbc-space-x-3 nbc-text-black",children:[r?J.jsx("img",{src:r,alt:"Avatar",className:"nbc-w-10 nbc-h-10 nbc-rounded-full nbc-object-cover"}):J.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"nbc-w-8 nbc-h-8 nbc-bg-white nbc-rounded-full nbc-p-1",children:[J.jsx("path",{d:"M12 6V2H8"}),J.jsx("path",{d:"m8 18-4 4V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2Z"}),J.jsx("path",{d:"M2 12h2"}),J.jsx("path",{d:"M9 11v2"}),J.jsx("path",{d:"M15 11v2"}),J.jsx("path",{d:"M20 12h2"})]}),J.jsx("h3",{className:"nbc-m-0 nbc-text-lg nbc-font-bold nbc-text-white",children:e})]}),J.jsx("button",{onClick:t,className:"nbc-bg-transparent nbc-border-0 nbc-text-white nbc-cursor-pointer nbc-p-1 nbc-rounded-full nbc-flex nbc-items-center nbc-justify-center hover:nbc-bg-black hover:nbc-bg-opacity-20 nbc-transition-colors nbc-duration-200 nbc-w-8 nbc-h-8","aria-label":"Close chat",children:m()})]})},Ih=e=>{if(e instanceof Date)return e;const t=e.endsWith("Z")?e:`${e}Z`;return new Date(t)};function Fc(e){if(!e)return"";const t=Ih(e),n=t.getDate().toString().padStart(2,"0"),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getFullYear(),i=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0");return`${n}/${r}/${o} ${i}:${a}`}const Mh=({message:e,avatar:t})=>e.sender==="user"?J.jsx("div",{className:"nbc-flex nbc-justify-end nbc-mb-4",children:J.jsxs("div",{className:"nbc-max-w-xs nbc-px-4 nbc-py-3 nbc-rounded-2xl nbc-text-sm nbc-leading-relaxed nbc-bg-gray-100 nbc-text-gray-900 nbc-rounded-br-md",children:[J.jsx("div",{className:"nbc-whitespace-pre-wrap nbc-break-words",children:e.text}),J.jsx("div",{className:"nbc-text-xs nbc-mt-1 nbc-opacity-70 nbc-text-right",children:Fc(String(e.timestamp)).split(" ")[1].substring(0,5)})]})}):J.jsx("div",{className:"nbc-flex nbc-justify-start nbc-mb-4",children:J.jsxs("div",{className:"nbc-flex nbc-items-start nbc-space-x-3",children:[J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-py-3",children:[t&&J.jsx("img",{src:t,alt:"AI Assistant",className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-object-cover nbc-flex-shrink-0"}),J.jsx("div",{className:"nbc-text-xs nbc-text-gray-500 nbc-opacity-70 nbc-whitespace-nowrap",children:Fc(String(e.timestamp)).split(" ")[1].substring(0,5)})]}),J.jsx("div",{className:"nbc-max-w-xs nbc-py-3 nbc-rounded-2xl nbc-text-sm nbc-leading-relaxed nbc-bg-white nbc-text-gray-800 nbc-rounded-bl-md",children:J.jsx("div",{className:"nbc-whitespace-pre-wrap nbc-break-words",children:e.text})})]})}),Ph=({avatar:e})=>J.jsx("div",{className:"nbc-flex nbc-justify-start nbc-mb-4",children:J.jsxs("div",{className:"nbc-flex nbc-items-start nbc-space-x-3",children:[J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-py-3",children:[e&&J.jsx("img",{src:e,alt:"AI Assistant",className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-object-cover nbc-flex-shrink-0"}),J.jsx("div",{className:"nbc-text-xs nbc-text-gray-500 nbc-opacity-70 nbc-whitespace-nowrap",children:" "})]}),J.jsx("div",{className:"nbc-bg-white nbc-px-4 nbc-py-3 nbc-rounded-2xl nbc-rounded-bl-md nbc-shadow-sm",children:J.jsxs("div",{className:"nbc-flex nbc-space-x-1",children:[J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-gray-400 nbc-rounded-full nbc-animate-bounce",style:{animationDelay:"0ms"}}),J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-gray-400 nbc-rounded-full nbc-animate-bounce",style:{animationDelay:"150ms"}}),J.jsx("div",{className:"nbc-w-2 nbc-h-2 nbc-bg-gray-400 nbc-rounded-full nbc-animate-bounce",style:{animationDelay:"300ms"}})]})})]})}),kh=({messages:e,isTyping:t,avatar:n})=>{const r=oe.useRef(null),o=()=>{var i;(i=r.current)==null||i.scrollIntoView({behavior:"smooth"})};return oe.useEffect(()=>{o()},[e,t]),J.jsxs("div",{className:"nbc-flex-1 nbc-overflow-y-auto nbc-px-2 nbc-pt-4",style:{scrollbarWidth:"thin",scrollbarColor:"#d1d5db #f9fafb"},children:[J.jsx("style",{children:`
41
41
  .nbc-flex-1::-webkit-scrollbar {
42
42
  width: 6px;
43
43
  }
@@ -59,7 +59,7 @@ Error generating stack: `+i.message+`
59
59
  .nbc-flex-1::-webkit-scrollbar-button:vertical:end:increment {
60
60
  display: none;
61
61
  }
62
- `}),e.map(i=>J.jsx(Mh,{message:i,avatar:n},i.id)),t&&J.jsx(Ph,{avatar:n}),J.jsx("div",{ref:r})]})},Nh=({onSendMessage:e,placeholder:t="Escribe un mensaje...",disabled:n=!1})=>{const[r,o]=oe.useState(""),i=m=>{m.preventDefault(),r.trim()&&!n&&(e(r.trim()),o(""))},a=m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),r.trim()&&!n&&(e(r.trim()),o("")))};return J.jsx("form",{onSubmit:i,className:"nbc-bg-white nbc-border-t nbc-border-gray-100",children:J.jsxs("div",{className:"nbc-relative",children:[J.jsx("input",{type:"text",value:r,onChange:m=>o(m.target.value),onKeyPress:a,placeholder:t,className:"nbc-w-full nbc-px-4 nbc-pr-12 nbc-text-base nbc-outline-none nbc-text-gray-900 nbc-bg-white nbc-transition-all nbc-duration-200",style:{height:"48px"}}),J.jsx("button",{type:"submit",disabled:!r.trim()||n,className:"nbc-absolute nbc-right-2 nbc-top-1/2 nbc-transform nbc--translate-y-1/2 nbc-w-8 nbc-h-8 nbc-text-gray-500 hover:nbc-text-gray-700 nbc-rounded-full nbc-text-sm nbc-font-medium nbc-transition-all nbc-duration-200 disabled:nbc-opacity-50 disabled:nbc-cursor-not-allowed nbc-border-0 nbc-cursor-pointer nbc-flex nbc-items-center nbc-justify-center hover:nbc-bg-gray-100",children:J.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:" 24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"nbc-w-5 nbc-h-5",children:[J.jsx("path",{d:"m22 2-7 20-4-9-9-4Z"}),J.jsx("path",{d:"M22 2 11 13"})]})})]})})},Dh=({avatar:e})=>{const t=[{type:"bot",lines:3,widths:["w-full","w-3/4","w-1/2"]},{type:"user",lines:1,widths:["w-2/3"]},{type:"bot",lines:2,widths:["w-full","w-5/6"]},{type:"user",lines:2,widths:["w-3/4","w-1/2"]}];return J.jsxs("div",{className:"nbc-flex-1 nbc-flex nbc-flex-col nbc-space-y-4 nbc-p-4",children:[t.map((n,r)=>J.jsx("div",{className:`nbc-flex ${n.type==="user"?"nbc-justify-end":"nbc-justify-start"} nbc-mb-4`,children:n.type==="user"?J.jsx("div",{className:"nbc-w-full nbc-max-w-xs nbc-py-3 nbc-space-y-2",children:n.widths.map((o,i)=>J.jsx("div",{className:`nbc-h-4 nbc-bg-gray-100 nbc-rounded nbc-animate-pulse ${o}`},i))}):J.jsxs("div",{className:"nbc-w-full nbc-flex nbc-items-start nbc-space-x-3",children:[J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-py-3",children:[e?J.jsx("img",{src:e,alt:"AI Assistant",className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-object-cover nbc-flex-shrink-0 nbc-opacity-50"}):J.jsx("div",{className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-bg-gray-300 nbc-animate-pulse"}),J.jsx("div",{className:"nbc-w-10 nbc-h-3 nbc-bg-gray-200 nbc-rounded nbc-animate-pulse nbc-mt-1"})]}),J.jsx("div",{className:"nbc-w-full nbc-max-w-xs nbc-py-3 nbc-space-y-2",children:n.widths.map((o,i)=>J.jsx("div",{className:`nbc-h-4 nbc-bg-gray-200 nbc-rounded nbc-animate-pulse ${o}`},i))})]})},r)),J.jsx("div",{className:"nbc-text-center nbc-text-sm nbc-text-gray-500 nbc-animate-pulse",children:"Cargando conversación..."})]})},Lh=({isOpen:e,onClose:t,config:n,messages:r,onSendMessage:o,isLoading:i=!1,isAiTyping:a=!1,position:m,marginBottom:v,marginSide:S,isMobile:T=!1,apiKeyMissing:R=!1})=>{const[C,O]=oe.useState(!1),[f,E]=oe.useState(!1),P=w=>{o(w)};if(oe.useEffect(()=>{e?(E(!0),setTimeout(()=>O(!0),10)):(O(!1),setTimeout(()=>E(!1),300))},[e]),!f)return null;const y=()=>{const w=m||n.position||"bottom-right",c=v||n.marginBottom||16,u=S||n.marginSide||16,g={width:"400px",height:"580px",zIndex:2147483647,bottom:`${c+64+10}px`};return w==="bottom-left"?Zt(yt({},g),{left:`${u}px`}):Zt(yt({},g),{right:`${u}px`})},d=()=>`nbc-fixed nbc-bg-white nbc-rounded-lg nbc-shadow-2xl nbc-flex nbc-flex-col nbc-overflow-hidden nbc-font-sans nbc-transition-all nbc-duration-300 nbc-ease-out ${T?"nbc-inset-0 nbc-w-full nbc-h-full nbc-rounded-none":"nbc-w-auto nbc-h-auto nbc-rounded-lg nbc-inset-auto"} ${C?"nbc-opacity-100 nbc-scale-100 nbc-translate-y-0":"nbc-opacity-0 nbc-scale-95 nbc-translate-y-2"}`,h=()=>T?{zIndex:2147483647}:y();return J.jsxs("div",{className:d(),style:h(),children:[J.jsx(Ah,{title:n.title||"Chat",onClose:t,primaryColor:n.primaryColor,avatar:n.avatar,closeButtonIcon:n.closeButtonIcon,closeButtonText:n.closeButtonText,closeButtonCustomIcon:n.closeButtonCustomIcon}),R?J.jsx("div",{className:"nbc-flex-1 nbc-flex nbc-items-center nbc-justify-center nbc-min-h-[220px]",children:J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-gap-2 nbc-text-black nbc-font-medium nbc-text-[15px] nbc-bg-none nbc-shadow-none nbc-p-0 nbc-rounded-none nbc-text-center",children:[J.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"28",height:"28",fill:"none",viewBox:"0 0 24 24",stroke:"#ef4444",strokeWidth:"2",style:{marginBottom:4},children:[J.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"#ef4444",strokeWidth:"2",fill:"none"}),J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4m0 4h.01"})]}),"Falta la API Key"]})}):i?J.jsx(Dh,{avatar:n.avatar}):J.jsx(kh,{messages:r,isTyping:a,avatar:n.avatar}),J.jsxs("div",{className:"nbc-mb-1 nbc-flex nbc-items-end nbc-justify-center nbc-text-xs nbc-text-black",children:[J.jsx("span",{children:"Powered by"})," ",J.jsx("a",{href:"https://notchatbot.com",target:"_blank",rel:"noopener noreferrer",className:"nbc-font-bold nbc-text-black",children:"NotChatbot"})]}),J.jsx(Nh,{onSendMessage:P,placeholder:n.placeholder||"Escribe un mensaje...",disabled:a||R})]})};function Xt(){const t=Date.now().toString(16).padStart(12,"0"),n=new Uint8Array(10);crypto.getRandomValues(n);const r=Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join("");return[t.slice(0,8),t.slice(8,12),"7"+r.slice(0,3),(parseInt(r.slice(3,4),16)&3|8).toString(16)+r.slice(4,7),r.slice(7,19)].join("-")}function Gc(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function ms(e,t,n={}){const{expires:r,maxAge:o,domain:i,path:a="/",secure:m=window.location.protocol==="https:",sameSite:v="lax"}=n;let S=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r&&(S+=`; expires=${r.toUTCString()}`),o!==void 0&&(S+=`; max-age=${o}`),i&&(S+=`; domain=${i}`),S+=`; path=${a}`,m&&(S+="; secure"),S+=`; samesite=${v}`,document.cookie=S}function Wc(e){const t=encodeURIComponent(e),n=document.cookie.split(";");for(let r of n)if(r=r.trim(),r.startsWith(t+"="))return decodeURIComponent(r.substring(t.length+1));return null}function jh(e,t={}){ms(e,"",Zt(yt({},t),{expires:new Date(0)}))}function Vc(){try{const e="__webchat_test__";ms(e,"test");const t=Wc(e)==="test";return jh(e),t}catch(e){return!1}}const $c="notchatbot",Uh=24;function vs(){if(!Vc())return console.warn("WebChat: Cookies not supported, using session-only data"),{conversationId:Xt(),conversationStarted:!1};const e=Wc($c);if(e)try{const n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.conversationId=="string"&&typeof n.conversationStarted=="boolean"&&Gc(n.conversationId))return n}catch(n){console.warn("WebChat: Invalid notchatbot cookie format, creating new one")}const t={conversationId:Xt(),conversationStarted:!1};return Kc(t),t}function Kc(e){if(!Vc()){console.warn("WebChat: Cookies not supported, cannot save data");return}if(!e||!Gc(e.conversationId))throw new Error("Invalid cookie data: conversationId must be a valid UUIDv7");if(typeof e.conversationStarted!="boolean")throw new Error("Invalid cookie data: conversationStarted must be a boolean");const t=Uh*60*60;ms($c,JSON.stringify(e),{maxAge:t,secure:window.location.protocol==="https:",sameSite:"lax",path:"/"})}function Bh(e){const t=vs(),n=Zt(yt({},t),{conversationStarted:e});return Kc(n),n}function Qc(){return vs().conversationId}function Jc(){return vs().conversationStarted}const _h=()=>{if(typeof window=="undefined")return!1;const t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),n=window.innerWidth<=768,r="ontouchstart"in window||navigator.maxTouchPoints>0;return t||n&&r},gs=()=>_h()?"mobile":"desktop",zh=e=>{if(typeof window=="undefined")return()=>{};let t=gs();const n=()=>{const r=gs();r!==t&&(t=r,e(r))};return window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)}},Zo=e=>{const t=gs(),n=Zt(yt({},e),{position:e.position||"bottom-right",marginBottom:e.marginBottom||16,marginSide:e.marginSide||16}),r=t==="mobile"?e.mobile:e.desktop;return r&&(r.position!==void 0&&(n.position=r.position),r.marginBottom!==void 0&&(n.marginBottom=r.marginBottom),r.marginSide!==void 0&&(n.marginSide=r.marginSide)),n},Hh=e=>{const t=Zo(e);return{position:t.position,marginBottom:t.marginBottom,marginSide:t.marginSide}},Fh=()=>dt(this,null,function*(){try{return(yield(yield fetch("https://api.ipify.org?format=json")).json()).ip||"unknown"}catch(e){return console.warn("WebChat: Could not fetch user IP:",e),`fallback_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}});function Gh(){return typeof window=="undefined"?!1:window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname.includes("localhost")}function Yc(){return Gh()?{baseUrl:"http://localhost:3001",chatEndpoint:"http://localhost:3001/api/webchat",conversationEndpoint:"http://localhost:3001/api/webchat/conversation"}:{baseUrl:"https://next.notchatbot.com",chatEndpoint:"https://next.notchatbot.com/api/webchat",conversationEndpoint:"https://next.notchatbot.com/api/webchat/conversation"}}function Wh(){return Yc().chatEndpoint}function Xc(){return Yc().conversationEndpoint}const Vh=(e,t)=>dt(this,null,function*(){try{const n=Xc(),r=yield fetch(`${n}?conversationId=${e}&chatbotUid=${t}`);return r.ok?yield r.json():(console.warn("WebChat: Failed to fetch conversation history:",r.status,r.statusText),null)}catch(n){return console.error("WebChat: Error fetching conversation history:",n),null}}),$h=e=>e.map((t,n)=>({id:t.id||(Date.now()+n).toString(),text:t.content||t.text||"",sender:t.role==="user"?"user":"bot",timestamp:t.createdAt?new Date(t.createdAt):new Date})),Kh=(e,t)=>e.map(n=>({id:n.id,content:n.text,role:n.sender==="user"?"user":"assistant",type:"text",createdAt:n.timestamp.toISOString(),conversationId:t}));var Zc={exports:{}};/*!
62
+ `}),e.map(i=>J.jsx(Mh,{message:i,avatar:n},i.id)),t&&J.jsx(Ph,{avatar:n}),J.jsx("div",{ref:r})]})},Nh=({onSendMessage:e,placeholder:t="Escribe un mensaje...",disabled:n=!1})=>{const[r,o]=oe.useState(""),i=m=>{m.preventDefault(),r.trim()&&!n&&(e(r.trim()),o(""))},a=m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),r.trim()&&!n&&(e(r.trim()),o("")))};return J.jsx("form",{onSubmit:i,className:"nbc-bg-white nbc-border-t nbc-border-gray-100",children:J.jsxs("div",{className:"nbc-relative",children:[J.jsx("input",{type:"text",value:r,onChange:m=>o(m.target.value),onKeyPress:a,placeholder:t,className:"nbc-w-full nbc-px-4 nbc-pr-12 nbc-text-base nbc-outline-none nbc-text-gray-900 nbc-bg-white nbc-transition-all nbc-duration-200",style:{height:"48px"}}),J.jsx("button",{type:"submit",disabled:!r.trim()||n,className:"nbc-absolute nbc-right-2 nbc-top-1/2 nbc-transform nbc--translate-y-1/2 nbc-w-8 nbc-h-8 nbc-text-gray-500 hover:nbc-text-gray-700 nbc-rounded-full nbc-text-sm nbc-font-medium nbc-transition-all nbc-duration-200 disabled:nbc-opacity-50 disabled:nbc-cursor-not-allowed nbc-border-0 nbc-cursor-pointer nbc-flex nbc-items-center nbc-justify-center hover:nbc-bg-gray-100",children:J.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:" 24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"nbc-w-5 nbc-h-5",children:[J.jsx("path",{d:"m22 2-7 20-4-9-9-4Z"}),J.jsx("path",{d:"M22 2 11 13"})]})})]})})},Dh=({avatar:e})=>{const t=[{type:"bot",lines:3,widths:["w-full","w-3/4","w-1/2"]},{type:"user",lines:1,widths:["w-2/3"]},{type:"bot",lines:2,widths:["w-full","w-5/6"]},{type:"user",lines:2,widths:["w-3/4","w-1/2"]}];return J.jsxs("div",{className:"nbc-flex-1 nbc-flex nbc-flex-col nbc-space-y-4 nbc-p-4",children:[t.map((n,r)=>J.jsx("div",{className:`nbc-flex ${n.type==="user"?"nbc-justify-end":"nbc-justify-start"} nbc-mb-4`,children:n.type==="user"?J.jsx("div",{className:"nbc-w-full nbc-max-w-xs nbc-py-3 nbc-space-y-2",children:n.widths.map((o,i)=>J.jsx("div",{className:`nbc-h-4 nbc-bg-gray-100 nbc-rounded nbc-animate-pulse ${o}`},i))}):J.jsxs("div",{className:"nbc-w-full nbc-flex nbc-items-start nbc-space-x-3",children:[J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-py-3",children:[e?J.jsx("img",{src:e,alt:"AI Assistant",className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-object-cover nbc-flex-shrink-0 nbc-opacity-50"}):J.jsx("div",{className:"nbc-w-7 nbc-h-7 nbc-rounded-full nbc-bg-gray-300 nbc-animate-pulse"}),J.jsx("div",{className:"nbc-w-10 nbc-h-3 nbc-bg-gray-200 nbc-rounded nbc-animate-pulse nbc-mt-1"})]}),J.jsx("div",{className:"nbc-w-full nbc-max-w-xs nbc-py-3 nbc-space-y-2",children:n.widths.map((o,i)=>J.jsx("div",{className:`nbc-h-4 nbc-bg-gray-200 nbc-rounded nbc-animate-pulse ${o}`},i))})]})},r)),J.jsx("div",{className:"nbc-text-center nbc-text-sm nbc-text-gray-500 nbc-animate-pulse",children:"Cargando conversación..."})]})},Lh=({isOpen:e,onClose:t,config:n,messages:r,onSendMessage:o,isLoading:i=!1,isAiTyping:a=!1,position:m,marginBottom:v,marginSide:S,isMobile:T=!1,apiKeyMissing:R=!1})=>{const[C,O]=oe.useState(!1),[f,E]=oe.useState(!1),P=w=>{o(w)};if(oe.useEffect(()=>{e?(E(!0),setTimeout(()=>O(!0),10)):(O(!1),setTimeout(()=>E(!1),300))},[e]),!f)return null;const y=()=>{const w=m||n.position||"bottom-right",c=v||n.marginBottom||16,u=S||n.marginSide||16,g={width:"400px",height:"580px",zIndex:2147483647,bottom:`${c+64+10}px`};return w==="bottom-left"?Zt(yt({},g),{left:`${u}px`}):Zt(yt({},g),{right:`${u}px`})},d=()=>`nbc-fixed nbc-bg-white nbc-rounded-lg nbc-shadow-2xl nbc-flex nbc-flex-col nbc-overflow-hidden nbc-font-sans nbc-transition-all nbc-duration-300 nbc-ease-out ${T?"nbc-inset-0 nbc-w-full nbc-h-full nbc-rounded-none":"nbc-w-auto nbc-h-auto nbc-rounded-lg nbc-inset-auto"} ${C?"nbc-opacity-100 nbc-scale-100 nbc-translate-y-0":"nbc-opacity-0 nbc-scale-95 nbc-translate-y-2"}`,h=()=>T?{zIndex:2147483647}:y();return J.jsxs("div",{className:d(),style:h(),children:[J.jsx(Ah,{title:n.title||"Chat",onClose:t,primaryColor:n.primaryColor,avatar:n.avatar,closeButtonIcon:n.closeButtonIcon,closeButtonText:n.closeButtonText,closeButtonCustomIcon:n.closeButtonCustomIcon}),R?J.jsx("div",{className:"nbc-flex-1 nbc-flex nbc-items-center nbc-justify-center nbc-min-h-[220px]",children:J.jsxs("div",{className:"nbc-flex nbc-flex-col nbc-items-center nbc-gap-2 nbc-text-black nbc-font-medium nbc-text-[15px] nbc-bg-none nbc-shadow-none nbc-p-0 nbc-rounded-none nbc-text-center",children:[J.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"28",height:"28",fill:"none",viewBox:"0 0 24 24",stroke:"#ef4444",strokeWidth:"2",style:{marginBottom:4},children:[J.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"#ef4444",strokeWidth:"2",fill:"none"}),J.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4m0 4h.01"})]}),"Falta la API Key"]})}):i?J.jsx(Dh,{avatar:n.avatar}):J.jsx(kh,{messages:r,isTyping:a,avatar:n.avatar}),J.jsxs("div",{className:"nbc-mb-1 nbc-flex nbc-items-end nbc-justify-center nbc-text-xs nbc-text-black",children:[J.jsx("span",{children:"Powered by"})," ",J.jsx("a",{href:"https://notchatbot.com",target:"_blank",rel:"noopener noreferrer",className:"nbc-font-bold nbc-text-black",children:"NotChatbot"})]}),J.jsx(Nh,{onSendMessage:P,placeholder:n.placeholder||"Escribe un mensaje...",disabled:a||R})]})};function Xt(){const t=Date.now().toString(16).padStart(12,"0"),n=new Uint8Array(10);crypto.getRandomValues(n);const r=Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join("");return[t.slice(0,8),t.slice(8,12),"7"+r.slice(0,3),(parseInt(r.slice(3,4),16)&3|8).toString(16)+r.slice(4,7),r.slice(7,19)].join("-")}function Gc(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function ms(e,t,n={}){const{expires:r,maxAge:o,domain:i,path:a="/",secure:m=window.location.protocol==="https:",sameSite:v="lax"}=n;let S=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;r&&(S+=`; expires=${r.toUTCString()}`),o!==void 0&&(S+=`; max-age=${o}`),i&&(S+=`; domain=${i}`),S+=`; path=${a}`,m&&(S+="; secure"),S+=`; samesite=${v}`,document.cookie=S}function Wc(e){const t=encodeURIComponent(e),n=document.cookie.split(";");for(let r of n)if(r=r.trim(),r.startsWith(t+"="))return decodeURIComponent(r.substring(t.length+1));return null}function jh(e,t={}){ms(e,"",Zt(yt({},t),{expires:new Date(0)}))}function Vc(){try{const e="__webchat_test__";ms(e,"test");const t=Wc(e)==="test";return jh(e),t}catch(e){return!1}}const $c="notchatbot",Uh=24;function vs(){if(!Vc())return console.warn("WebChat: Cookies not supported, using session-only data"),{conversationId:Xt(),conversationStarted:!1};const e=Wc($c);if(e)try{const n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.conversationId=="string"&&typeof n.conversationStarted=="boolean"&&Gc(n.conversationId))return n}catch(n){console.warn("WebChat: Invalid notchatbot cookie format, creating new one")}const t={conversationId:Xt(),conversationStarted:!1};return Kc(t),t}function Kc(e){if(!Vc()){console.warn("WebChat: Cookies not supported, cannot save data");return}if(!e||!Gc(e.conversationId))throw new Error("Invalid cookie data: conversationId must be a valid UUIDv7");if(typeof e.conversationStarted!="boolean")throw new Error("Invalid cookie data: conversationStarted must be a boolean");const t=Uh*60*60;ms($c,JSON.stringify(e),{maxAge:t,secure:window.location.protocol==="https:",sameSite:"lax",path:"/"})}function Bh(e){const t=vs(),n=Zt(yt({},t),{conversationStarted:e});return Kc(n),n}function Qc(){return vs().conversationId}function Jc(){return vs().conversationStarted}const _h=()=>{if(typeof window=="undefined")return!1;const t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),n=window.innerWidth<=768,r="ontouchstart"in window||navigator.maxTouchPoints>0;return t||n&&r},gs=()=>_h()?"mobile":"desktop",zh=e=>{if(typeof window=="undefined")return()=>{};let t=gs();const n=()=>{const r=gs();r!==t&&(t=r,e(r))};return window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)}},Zo=e=>{const t=gs(),n=Zt(yt({},e),{position:e.position||"bottom-right",marginBottom:e.marginBottom||16,marginSide:e.marginSide||16}),r=t==="mobile"?e.mobile:e.desktop;return r&&(r.position!==void 0&&(n.position=r.position),r.marginBottom!==void 0&&(n.marginBottom=r.marginBottom),r.marginSide!==void 0&&(n.marginSide=r.marginSide)),n},Hh=e=>{const t=Zo(e);return{position:t.position,marginBottom:t.marginBottom,marginSide:t.marginSide}},Fh=()=>dt(this,null,function*(){try{return(yield(yield fetch("https://api.ipify.org?format=json")).json()).ip||"unknown"}catch(e){return console.warn("WebChat: Could not fetch user IP:",e),`fallback_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}});function Gh(){return typeof window=="undefined"?!1:window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname.includes("localhost")}function Yc(){return Gh()?{baseUrl:"http://localhost:3001",chatEndpoint:"http://localhost:3001/api/webchat",conversationEndpoint:"http://localhost:3001/api/webchat/conversation"}:{baseUrl:"https://next.notchatbot.com",chatEndpoint:"https://next.notchatbot.com/api/webchat",conversationEndpoint:"https://next.notchatbot.com/api/webchat/conversation"}}function Wh(){return Yc().chatEndpoint}function Xc(){return Yc().conversationEndpoint}const Vh=(e,t)=>dt(this,null,function*(){try{const n=Xc(),r=yield fetch(`${n}?conversationId=${e}&chatbotUid=${t}`);return r.ok?yield r.json():(console.warn("WebChat: Failed to fetch conversation history:",r.status,r.statusText),null)}catch(n){return console.error("WebChat: Error fetching conversation history:",n),null}}),$h=e=>e.map((t,n)=>{let r;return t.createdAt?r=t.createdAt.endsWith("Z")?t.createdAt:`${t.createdAt}Z`:r=new Date().toISOString(),{id:t.id||(Date.now()+n).toString(),text:t.content||t.text||"",sender:t.role==="user"?"user":"bot",timestamp:r}}),Kh=(e,t)=>e.map(n=>({id:n.id,content:n.text,role:n.sender==="user"?"user":"assistant",type:"text",createdAt:n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp,conversationId:t}));var Zc={exports:{}};/*!
63
63
  * @license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
64
64
  *
65
65
  * Ably JavaScript Library v1.2.50
@@ -79,16 +79,16 @@ Error generating stack: `+i.message+`
79
79
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
80
80
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
81
81
  PERFORMANCE OF THIS SOFTWARE.
82
- ***************************************************************************** */var i=function(I,M){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,j){A.__proto__=j}||function(A,j){for(var U in j)Object.prototype.hasOwnProperty.call(j,U)&&(A[U]=j[U])},i(I,M)};function a(I,M){if(typeof M!="function"&&M!==null)throw new TypeError("Class extends value "+String(M)+" is not a constructor or null");i(I,M);function A(){this.constructor=I}I.prototype=M===null?Object.create(M):(A.prototype=M.prototype,new A)}var m=function(){return m=Object.assign||function(M){for(var A,j=1,U=arguments.length;j<U;j++){A=arguments[j];for(var z in A)Object.prototype.hasOwnProperty.call(A,z)&&(M[z]=A[z])}return M},m.apply(this,arguments)};function v(I,M){var A={};for(var j in I)Object.prototype.hasOwnProperty.call(I,j)&&M.indexOf(j)<0&&(A[j]=I[j]);if(I!=null&&typeof Object.getOwnPropertySymbols=="function")for(var U=0,j=Object.getOwnPropertySymbols(I);U<j.length;U++)M.indexOf(j[U])<0&&Object.prototype.propertyIsEnumerable.call(I,j[U])&&(A[j[U]]=I[j[U]]);return A}function S(I,M,A,j){var U=arguments.length,z=U<3?M:j===null?j=Object.getOwnPropertyDescriptor(M,A):j,V;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")z=Reflect.decorate(I,M,A,j);else for(var G=I.length-1;G>=0;G--)(V=I[G])&&(z=(U<3?V(z):U>3?V(M,A,z):V(M,A))||z);return U>3&&z&&Object.defineProperty(M,A,z),z}function T(I,M){return function(A,j){M(A,j,I)}}function R(I,M){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(I,M)}function C(I,M,A,j){function U(z){return z instanceof A?z:new A(function(V){V(z)})}return new(A||(A=Promise))(function(z,V){function G(L){try{b(j.next(L))}catch(B){V(B)}}function F(L){try{b(j.throw(L))}catch(B){V(B)}}function b(L){L.done?z(L.value):U(L.value).then(G,F)}b((j=j.apply(I,M||[])).next())})}function O(I,M){var A={label:0,sent:function(){if(z[0]&1)throw z[1];return z[1]},trys:[],ops:[]},j,U,z,V;return V={next:G(0),throw:G(1),return:G(2)},typeof Symbol=="function"&&(V[Symbol.iterator]=function(){return this}),V;function G(b){return function(L){return F([b,L])}}function F(b){if(j)throw new TypeError("Generator is already executing.");for(;A;)try{if(j=1,U&&(z=b[0]&2?U.return:b[0]?U.throw||((z=U.return)&&z.call(U),0):U.next)&&!(z=z.call(U,b[1])).done)return z;switch(U=0,z&&(b=[b[0]&2,z.value]),b[0]){case 0:case 1:z=b;break;case 4:return A.label++,{value:b[1],done:!1};case 5:A.label++,U=b[1],b=[0];continue;case 7:b=A.ops.pop(),A.trys.pop();continue;default:if(z=A.trys,!(z=z.length>0&&z[z.length-1])&&(b[0]===6||b[0]===2)){A=0;continue}if(b[0]===3&&(!z||b[1]>z[0]&&b[1]<z[3])){A.label=b[1];break}if(b[0]===6&&A.label<z[1]){A.label=z[1],z=b;break}if(z&&A.label<z[2]){A.label=z[2],A.ops.push(b);break}z[2]&&A.ops.pop(),A.trys.pop();continue}b=M.call(I,A)}catch(L){b=[6,L],U=0}finally{j=z=0}if(b[0]&5)throw b[1];return{value:b[0]?b[1]:void 0,done:!0}}}var f=Object.create?function(I,M,A,j){j===void 0&&(j=A),Object.defineProperty(I,j,{enumerable:!0,get:function(){return M[A]}})}:function(I,M,A,j){j===void 0&&(j=A),I[j]=M[A]};function E(I,M){for(var A in I)A!=="default"&&!Object.prototype.hasOwnProperty.call(M,A)&&f(M,I,A)}function P(I){var M=typeof Symbol=="function"&&Symbol.iterator,A=M&&I[M],j=0;if(A)return A.call(I);if(I&&typeof I.length=="number")return{next:function(){return I&&j>=I.length&&(I=void 0),{value:I&&I[j++],done:!I}}};throw new TypeError(M?"Object is not iterable.":"Symbol.iterator is not defined.")}function y(I,M){var A=typeof Symbol=="function"&&I[Symbol.iterator];if(!A)return I;var j=A.call(I),U,z=[],V;try{for(;(M===void 0||M-- >0)&&!(U=j.next()).done;)z.push(U.value)}catch(G){V={error:G}}finally{try{U&&!U.done&&(A=j.return)&&A.call(j)}finally{if(V)throw V.error}}return z}function d(){for(var I=[],M=0;M<arguments.length;M++)I=I.concat(y(arguments[M]));return I}function h(){for(var I=0,M=0,A=arguments.length;M<A;M++)I+=arguments[M].length;for(var j=Array(I),U=0,M=0;M<A;M++)for(var z=arguments[M],V=0,G=z.length;V<G;V++,U++)j[U]=z[V];return j}function w(I,M,A){if(A||arguments.length===2)for(var j=0,U=M.length,z;j<U;j++)(z||!(j in M))&&(z||(z=Array.prototype.slice.call(M,0,j)),z[j]=M[j]);return I.concat(z||Array.prototype.slice.call(M))}function c(I){return this instanceof c?(this.v=I,this):new c(I)}function u(I,M,A){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var j=A.apply(I,M||[]),U,z=[];return U={},V("next"),V("throw"),V("return"),U[Symbol.asyncIterator]=function(){return this},U;function V(_){j[_]&&(U[_]=function(W){return new Promise(function(Y,X){z.push([_,W,Y,X])>1||G(_,W)})})}function G(_,W){try{F(j[_](W))}catch(Y){B(z[0][3],Y)}}function F(_){_.value instanceof c?Promise.resolve(_.value.v).then(b,L):B(z[0][2],_)}function b(_){G("next",_)}function L(_){G("throw",_)}function B(_,W){_(W),z.shift(),z.length&&G(z[0][0],z[0][1])}}function l(I){var M,A;return M={},j("next"),j("throw",function(U){throw U}),j("return"),M[Symbol.iterator]=function(){return this},M;function j(U,z){M[U]=I[U]?function(V){return(A=!A)?{value:c(I[U](V)),done:U==="return"}:z?z(V):V}:z}}function s(I){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var M=I[Symbol.asyncIterator],A;return M?M.call(I):(I=typeof P=="function"?P(I):I[Symbol.iterator](),A={},j("next"),j("throw"),j("return"),A[Symbol.asyncIterator]=function(){return this},A);function j(z){A[z]=I[z]&&function(V){return new Promise(function(G,F){V=I[z](V),U(G,F,V.done,V.value)})}}function U(z,V,G,F){Promise.resolve(F).then(function(b){z({value:b,done:G})},V)}}function g(I,M){return Object.defineProperty?Object.defineProperty(I,"raw",{value:M}):I.raw=M,I}var p=Object.create?function(I,M){Object.defineProperty(I,"default",{enumerable:!0,value:M})}:function(I,M){I.default=M};function x(I){if(I&&I.__esModule)return I;var M={};if(I!=null)for(var A in I)A!=="default"&&Object.prototype.hasOwnProperty.call(I,A)&&f(M,I,A);return p(M,I),M}function D(I){return I&&I.__esModule?I:{default:I}}function N(I,M,A,j){if(A==="a"&&!j)throw new TypeError("Private accessor was defined without a getter");if(typeof M=="function"?I!==M||!j:!M.has(I))throw new TypeError("Cannot read private member from an object whose class did not declare it");return A==="m"?j:A==="a"?j.call(I):j?j.value:M.get(I)}function k(I,M,A,j,U){if(j==="m")throw new TypeError("Private method is not writable");if(j==="a"&&!U)throw new TypeError("Private accessor was defined without a setter");if(typeof M=="function"?I!==M||!U:!M.has(I))throw new TypeError("Cannot write private member to an object whose class did not declare it");return j==="a"?U.call(I,A):U?U.value=A:M.set(I,A),A}},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0}),r.allToUpperCase=r.allToLowerCase=r.encodeBody=r.decodeBody=r.Format=r.promisify=r.trim=r.arrChooseN=r.randomHexString=r.randomString=r.cheapRandStr=r.dataSizeBytes=r.inspectBody=r.inspectError=r.isErrorInfoOrPartialErrorInfo=r.now=r.parseQueryString=r.toQueryString=r.arrPopRandomElement=r.defaultPostHeaders=r.defaultGetHeaders=r.allSame=r.arrEvery=r.arrFilter=r.arrMap=r.safeArrForEach=r.arrForEach=r.forInOwnNonNullProperties=r.valuesArray=r.keysArray=r.arrWithoutValue=r.arrDeleteValue=r.arrIn=r.arrIndexOf=r.arrSubtract=r.arrIntersectOb=r.arrIntersect=r.intersect=r.containsValue=r.inherits=r.prototypicalClone=r.shallowClone=r.isEmptyArg=r.isOnlyPropIn=r.isEmpty=r.isObject=r.ensureArray=r.isArray=r.copy=r.mixin=void 0,r.arrEquals=r.toBase64=r.matchDerivedChannel=r.shallowEquals=r.getGlobalObject=r.getRetryTime=r.getJitterCoefficient=r.getBackoffCoefficient=void 0;var a=o(0),m=a.__importDefault(o(3)),v=a.__importStar(o(8)),S=a.__importDefault(o(4)),T=o(11),R=o(31);function C(H){return Math.floor(Math.random()*H.length)}function O(H){for(var $=[],K=1;K<arguments.length;K++)$[K-1]=arguments[K];for(var ee=0;ee<$.length;ee++){var ie=$[ee];if(!ie)break;var Ve=Object.prototype.hasOwnProperty;for(var Dr in ie)(!Ve||Ve.call(ie,Dr))&&(H[Dr]=ie[Dr])}return H}r.mixin=O;function f(H){return O({},H)}r.copy=f,r.isArray=Array.isArray||function(H){return Object.prototype.toString.call(H)=="[object Array]"};function E(H){return h(H)?[]:(0,r.isArray)(H)?H:[H]}r.ensureArray=E;function P(H){return Object.prototype.toString.call(H)=="[object Object]"}r.isObject=P;function y(H){for(var $ in H)return!1;return!0}r.isEmpty=y;function d(H,$){for(var K in H)if(K!==$)return!1;return!0}r.isOnlyPropIn=d;function h(H){return H==null}r.isEmptyArg=h;function w(H){var $=new Object;for(var K in H)$[K]=H[K];return $}r.shallowClone=w;function c(H,$){var K=function(){function ie(){}return ie}();K.prototype=H;var ee=new K;return $&&O(ee,$),ee}r.prototypicalClone=c;var u=function(H,$){if(m.default.Config.inherits){m.default.Config.inherits(H,$);return}H.super_=$,H.prototype=c($.prototype,{constructor:H})};r.inherits=u;function l(H,$){for(var K in H)if(H[K]==$)return!0;return!1}r.containsValue=l;function s(H,$){return(0,r.isArray)($)?g(H,$):p(H,$)}r.intersect=s;function g(H,$){for(var K=[],ee=0;ee<H.length;ee++){var ie=H[ee];(0,r.arrIndexOf)($,ie)!=-1&&K.push(ie)}return K}r.arrIntersect=g;function p(H,$){for(var K=[],ee=0;ee<H.length;ee++){var ie=H[ee];ie in $&&K.push(ie)}return K}r.arrIntersectOb=p;function x(H,$){for(var K=[],ee=0;ee<H.length;ee++){var ie=H[ee];(0,r.arrIndexOf)($,ie)==-1&&K.push(ie)}return K}r.arrSubtract=x,r.arrIndexOf=Array.prototype.indexOf?function(H,$,K){return H.indexOf($,K)}:function(H,$,K){K=K||0;for(var ee=H.length;K<ee;K++)if(H[K]===$)return K;return-1};function D(H,$){return(0,r.arrIndexOf)(H,$)!==-1}r.arrIn=D;function N(H,$){var K=(0,r.arrIndexOf)(H,$),ee=K!=-1;return ee&&H.splice(K,1),ee}r.arrDeleteValue=N;function k(H,$){var K=H.slice();return N(K,$),K}r.arrWithoutValue=k;function I(H,$){var K=[];for(var ee in H)$&&!Object.prototype.hasOwnProperty.call(H,ee)||K.push(ee);return K}r.keysArray=I;function M(H,$){var K=[];for(var ee in H)$&&!Object.prototype.hasOwnProperty.call(H,ee)||K.push(H[ee]);return K}r.valuesArray=M;function A(H,$){for(var K in H)Object.prototype.hasOwnProperty.call(H,K)&&H[K]&&$(K)}r.forInOwnNonNullProperties=A,r.arrForEach=Array.prototype.forEach?function(H,$){H.forEach($)}:function(H,$){for(var K=H.length,ee=0;ee<K;ee++)$(H[ee],ee,H)};function j(H,$){return(0,r.arrForEach)(H.slice(),$)}r.safeArrForEach=j,r.arrMap=Array.prototype.map?function(H,$){return H.map($)}:function(H,$){for(var K=[],ee=H.length,ie=0;ie<ee;ie++)K.push($(H[ie],ie,H));return K},r.arrFilter=Array.prototype.filter?function(H,$){return H.filter($)}:function(H,$){for(var K=[],ee=H.length,ie=0;ie<ee;ie++)$(H[ie])&&K.push(H[ie]);return K},r.arrEvery=Array.prototype.every?function(H,$){return H.every($)}:function(H,$){for(var K=H.length,ee=0;ee<K;ee++)if(!$(H[ee],ee,H))return!1;return!0};function U(H,$){if(H.length===0)return!0;var K=H[0][$];return(0,r.arrEvery)(H,function(ee){return ee[$]===K})}r.allSame=U;var z={json:"application/json",jsonp:"application/javascript",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack"};function V(H,$){var K=z[$||he.json];return{accept:K,"X-Ably-Version":v.default.protocolVersion.toString(),"Ably-Agent":(0,v.getAgentString)(H)}}r.defaultGetHeaders=V;function G(H,$){var K,ee=K=z[$||he.json];return{accept:ee,"content-type":K,"X-Ably-Version":v.default.protocolVersion.toString(),"Ably-Agent":(0,v.getAgentString)(H)}}r.defaultPostHeaders=G;function F(H){return H.splice(C(H),1)[0]}r.arrPopRandomElement=F;function b(H){var $=[];if(H)for(var K in H)$.push(encodeURIComponent(K)+"="+encodeURIComponent(H[K]));return $.length?"?"+$.join("&"):""}r.toQueryString=b;function L(H){for(var $,K=/([^?&=]+)=?([^&]*)/g,ee={};$=K.exec(H);)ee[decodeURIComponent($[1])]=decodeURIComponent($[2]);return ee}r.parseQueryString=L,r.now=Date.now||function(){return new Date().getTime()};function B(H){return typeof H=="object"&&H!==null&&(H.constructor.name=="ErrorInfo"||H.constructor.name=="PartialErrorInfo")}r.isErrorInfoOrPartialErrorInfo=B;function _(H){var $,K;return H instanceof Error||(($=H==null?void 0:H.constructor)===null||$===void 0?void 0:$.name)==="ErrorInfo"||((K=H==null?void 0:H.constructor)===null||K===void 0?void 0:K.name)==="PartialErrorInfo"?H.toString():m.default.Config.inspect(H)}r.inspectError=_;function W(H){return m.default.BufferUtils.isBuffer(H)?H.toString():typeof H=="string"?H:m.default.Config.inspect(H)}r.inspectBody=W;function Y(H){if(m.default.BufferUtils.isBuffer(H))return m.default.BufferUtils.byteLength(H);if(typeof H=="string")return m.default.Config.stringByteSize(H);throw new Error("Expected input of Utils.dataSizeBytes to be a buffer or string, but was: "+typeof H)}r.dataSizeBytes=Y;function X(){return String(Math.random()).substr(2)}r.cheapRandStr=X;var te=function(H){if(m.default.Config.getRandomValues&&typeof Uint8Array!="undefined"){var $=new Uint8Array(H);return m.default.Config.getRandomValues($),m.default.BufferUtils.base64Encode($)}for(var K=m.default.BufferUtils.base64CharSet,ee=Math.round(H*4/3),ie="",Ve=0;Ve<ee;Ve++)ie+=K[C(K)];return ie};r.randomString=te;var re=function(H){if(m.default.Config.getRandomValues&&typeof Uint8Array!="undefined"){var $=new Uint8Array(H);return m.default.Config.getRandomValues($),m.default.BufferUtils.hexEncode($)}for(var K=m.default.BufferUtils.hexCharSet,ee=H*2,ie="",Ve=0;Ve<ee;Ve++)ie+=K[C(K)];return ie};r.randomHexString=re;function le(H,$){for(var K=Math.min($,H.length),ee=H.slice(),ie=[],Ve=0;Ve<K;Ve++)ie.push(F(ee));return ie}r.arrChooseN=le,r.trim=String.prototype.trim?function(H){return H.trim()}:function(H){return H.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function Z(H,$,K){return new Promise(function(ee,ie){H[$].apply(H,a.__spreadArray(a.__spreadArray([],K,!1),[function(Ve,Dr){Ve?ie(Ve):ee(Dr)}],!1))})}r.promisify=Z;var he;(function(H){H.msgpack="msgpack",H.json="json"})(he=r.Format||(r.Format={}));function Me(H,$){return $=="msgpack"?m.default.Config.msgpack.decode(H):JSON.parse(String(H))}r.decodeBody=Me;function _e(H,$){return $=="msgpack"?m.default.Config.msgpack.encode(H,!0):JSON.stringify(H)}r.encodeBody=_e;function Ee(H){return H.map(function($){return $&&$.toLowerCase()})}r.allToLowerCase=Ee;function Mt(H){return H.map(function($){return $&&$.toUpperCase()})}r.allToUpperCase=Mt;function qo(H){return Math.min((H+2)/3,2)}r.getBackoffCoefficient=qo;function ft(){return 1-Math.random()*.2}r.getJitterCoefficient=ft;function ei(H,$){return H*qo($)*ft()}r.getRetryTime=ei;function ws(){return i||(typeof window!="undefined"?window:self)}r.getGlobalObject=ws;function Ss(H,$){return Object.keys(H).every(function(K){return H[K]===$[K]})&&Object.keys($).every(function(K){return $[K]===H[K]})}r.shallowEquals=Ss;function sp(H){var $=/^(\[([^?]*)(?:(.*))\])?(.+)$/,K=H.match($);if(!K||!K.length||K.length<5)throw new S.default("regex match failed",400,40010);if(K[2])throw new S.default("cannot use a derived option with a ".concat(K[2]," channel"),400,40010);return{qualifierParam:K[3]||"",channelName:K[4]}}r.matchDerivedChannel=sp;function lp(H){return m.default.Config.createHmac?Buffer.from(H,"ascii").toString("base64"):(0,T.stringify)((0,R.parse)(H))}r.toBase64=lp;function up(H,$){return H.length===$.length&&(0,r.arrEvery)(H,function(K,ee){return K===$[ee]})}r.arrEquals=up}).call(this,o(13))},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importDefault(o(3)),v=i||(typeof window!="undefined"?window:self),S;(function(f){f[f.None=0]="None",f[f.Error=1]="Error",f[f.Major=2]="Major",f[f.Minor=3]="Minor",f[f.Micro=4]="Micro"})(S||(S={}));function T(f,E){return"".concat(f).padStart(E?3:2,"0")}function R(f){return m.default.Config.logTimestamps?function(E){var P=new Date;f(T(P.getHours())+":"+T(P.getMinutes())+":"+T(P.getSeconds())+"."+T(P.getMilliseconds(),1)+" "+E)}:f}var C=function(){var f,E,P,y;return typeof Window=="undefined"&&typeof WorkerGlobalScope=="undefined"||typeof((E=(f=v==null?void 0:v.console)===null||f===void 0?void 0:f.log)===null||E===void 0?void 0:E.apply)=="function"?(P=function(){for(var d=[],h=0;h<arguments.length;h++)d[h]=arguments[h];console.log.apply(console,d)},y=console.warn?function(){for(var d=[],h=0;h<arguments.length;h++)d[h]=arguments[h];console.warn.apply(console,d)}:P):v!=null&&v.console.log?P=y=function(){Function.prototype.apply.call(console.log,console,arguments)}:P=y=function(){},[P,y].map(R)},O=function(){function f(){f.logLevel=f.LOG_DEFAULT}return f.initLogHandlers=function(){var E=C(),P=E[0],y=E[1];this.logHandler=P,this.logErrorHandler=y},f.renamedClientOption=function(E,P){f.deprecationWarning("The `".concat(E,"` client option has been renamed to `").concat(P,"`. Please update your code to use `").concat(P,"` instead. `").concat(E,"` will be removed in a future version."))},f.renamedMethod=function(E,P,y){f.deprecationWarning("`".concat(E,"`’s `").concat(P,"` method has been renamed to `").concat(y,"`. Please update your code to use `").concat(y,"` instead. `").concat(P,"` will be removed in a future version."))},f.deprecationWarning=function(E){f.shouldLog(S.Error)&&f.logErrorHandler("Ably: Deprecation warning - ".concat(E))},f.logLevel=S.Error,f.LOG_NONE=S.None,f.LOG_ERROR=S.Error,f.LOG_MAJOR=S.Major,f.LOG_MINOR=S.Minor,f.LOG_MICRO=S.Micro,f.LOG_DEFAULT=S.Error,f.LOG_DEBUG=S.Micro,f.logAction=function(E,P,y){f.shouldLog(E)&&(E===S.Error?f.logErrorHandler:f.logHandler)("Ably: "+P+": "+y)},f.deprecated=function(E,P){f.deprecationWarning("".concat(E," is deprecated and will be removed in a future version. ").concat(P))},f.shouldLog=function(E){return E<=f.logLevel},f.setLog=function(E,P){E!==void 0&&(f.logLevel=E),P!==void 0&&(f.logHandler=f.logErrorHandler=P)},f}();r.default=O}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function a(){}return a}();r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.PartialErrorInfo=void 0;var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1));function v(R){var C="["+R.constructor.name;return R.message&&(C+=": "+R.message),R.statusCode&&(C+="; statusCode="+R.statusCode),R.code&&(C+="; code="+R.code),R.cause&&(C+="; cause="+m.inspectError(R.cause)),R.href&&!(R.message&&R.message.indexOf("help.ably.io")>-1)&&(C+="; see "+R.href+" "),C+="]",C}var S=function(R){i.__extends(C,R);function C(O,f,E,P){var y=R.call(this,O)||this;return typeof Object.setPrototypeOf!="undefined"&&Object.setPrototypeOf(y,C.prototype),y.code=f,y.statusCode=E,y.cause=P,y}return C.prototype.toString=function(){return v(this)},C.fromValues=function(O){var f=O,E=f.message,P=f.code,y=f.statusCode;if(typeof E!="string"||typeof P!="number"||typeof y!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+a.default.Config.inspect(O));var d=Object.assign(new C(E,P,y),O);return d.code&&!d.href&&(d.href="https://help.ably.io/error/"+d.code),d},C}(Error);r.default=S;var T=function(R){i.__extends(C,R);function C(O,f,E,P){var y=R.call(this,O)||this;return typeof Object.setPrototypeOf!="undefined"&&Object.setPrototypeOf(y,C.prototype),y.code=f,y.statusCode=E,y.cause=P,y}return C.prototype.toString=function(){return v(this)},C}(Error);r.PartialErrorInfo=T},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){if(typeof ArrayBuffer=="function"){var a=i,m=a.lib,v=m.WordArray,S=v.init,T=v.init=function(R){if(R instanceof ArrayBuffer&&(R=new Uint8Array(R)),(R instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&R instanceof Uint8ClampedArray||R instanceof Int16Array||R instanceof Uint16Array||R instanceof Int32Array||R instanceof Uint32Array||R instanceof Float32Array||R instanceof Float64Array)&&(R=new Uint8Array(R.buffer,R.byteOffset,R.byteLength)),R instanceof Uint8Array){for(var C=R.byteLength,O=[],f=0;f<C;f++)O[f>>>2]|=R[f]<<24-f%4*8;S.call(this,O,C)}else S.apply(this,arguments)};T.prototype=v}}(),i.lib.WordArray})},function(n,r,o){(function(i){(function(a,m){n.exports=m()})(this,function(){var a=a||function(m,v){var S;if(typeof window!="undefined"&&window.crypto&&(S=window.crypto),!S&&typeof window!="undefined"&&window.msCrypto&&(S=window.msCrypto),!S&&typeof i!="undefined"&&i.crypto&&(S=i.crypto),!S)try{S=o(44)}catch(u){}var T=function(){if(S){if(typeof S.getRandomValues=="function")try{return S.getRandomValues(new Uint32Array(1))[0]}catch(u){}if(typeof S.randomBytes=="function")try{return S.randomBytes(4).readInt32LE()}catch(u){}}throw new Error("Native crypto module could not be used to get secure random number.")},R=Object.create||function(){function u(){}return function(l){var s;return u.prototype=l,s=new u,u.prototype=null,s}}(),C={},O=C.lib={},f=O.Base=function(){return{extend:function(u){var l=R(this);return u&&l.mixIn(u),(!l.hasOwnProperty("init")||this.init===l.init)&&(l.init=function(){l.$super.init.apply(this,arguments)}),l.init.prototype=l,l.$super=this,l},create:function(){var u=this.extend();return u.init.apply(u,arguments),u},init:function(){},mixIn:function(u){for(var l in u)u.hasOwnProperty(l)&&(this[l]=u[l]);u.hasOwnProperty("toString")&&(this.toString=u.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),E=O.WordArray=f.extend({init:function(u,l){u=this.words=u||[],l!=v?this.sigBytes=l:this.sigBytes=u.length*4},toString:function(u){return(u||y).stringify(this)},concat:function(u){var l=this.words,s=u.words,g=this.sigBytes,p=u.sigBytes;if(this.clamp(),g%4)for(var x=0;x<p;x++){var D=s[x>>>2]>>>24-x%4*8&255;l[g+x>>>2]|=D<<24-(g+x)%4*8}else for(var x=0;x<p;x+=4)l[g+x>>>2]=s[x>>>2];return this.sigBytes+=p,this},clamp:function(){var u=this.words,l=this.sigBytes;u[l>>>2]&=4294967295<<32-l%4*8,u.length=m.ceil(l/4)},clone:function(){var u=f.clone.call(this);return u.words=this.words.slice(0),u},random:function(u){for(var l=[],s=0;s<u;s+=4)l.push(T());return new E.init(l,u)}}),P=C.enc={},y=P.Hex={stringify:function(u){for(var l=u.words,s=u.sigBytes,g=[],p=0;p<s;p++){var x=l[p>>>2]>>>24-p%4*8&255;g.push((x>>>4).toString(16)),g.push((x&15).toString(16))}return g.join("")},parse:function(u){for(var l=u.length,s=[],g=0;g<l;g+=2)s[g>>>3]|=parseInt(u.substr(g,2),16)<<24-g%8*4;return new E.init(s,l/2)}},d=P.Latin1={stringify:function(u){for(var l=u.words,s=u.sigBytes,g=[],p=0;p<s;p++){var x=l[p>>>2]>>>24-p%4*8&255;g.push(String.fromCharCode(x))}return g.join("")},parse:function(u){for(var l=u.length,s=[],g=0;g<l;g++)s[g>>>2]|=(u.charCodeAt(g)&255)<<24-g%4*8;return new E.init(s,l)}},h=P.Utf8={stringify:function(u){try{return decodeURIComponent(escape(d.stringify(u)))}catch(l){throw new Error("Malformed UTF-8 data")}},parse:function(u){return d.parse(unescape(encodeURIComponent(u)))}},w=O.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new E.init,this._nDataBytes=0},_append:function(u){typeof u=="string"&&(u=h.parse(u)),this._data.concat(u),this._nDataBytes+=u.sigBytes},_process:function(u){var l,s=this._data,g=s.words,p=s.sigBytes,x=this.blockSize,D=x*4,N=p/D;u?N=m.ceil(N):N=m.max((N|0)-this._minBufferSize,0);var k=N*x,I=m.min(k*4,p);if(k){for(var M=0;M<k;M+=x)this._doProcessBlock(g,M);l=g.splice(0,k),s.sigBytes-=I}return new E.init(l,I)},clone:function(){var u=f.clone.call(this);return u._data=this._data.clone(),u},_minBufferSize:0});O.Hasher=w.extend({cfg:f.extend(),init:function(u){this.cfg=this.cfg.extend(u),this.reset()},reset:function(){w.reset.call(this),this._doReset()},update:function(u){return this._append(u),this._process(),this},finalize:function(u){u&&this._append(u);var l=this._doFinalize();return l},blockSize:16,_createHelper:function(u){return function(l,s){return new u.init(s).finalize(l)}},_createHmacHelper:function(u){return function(l,s){return new c.HMAC.init(u,s).finalize(l)}}});var c=C.algo={};return C}(Math);return a})}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(2)),v=i.__importDefault(o(3));function S(C,O,f){try{O.apply(C,f)}catch(E){m.default.logAction(m.default.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+E+"; stack = "+(E&&E.stack))}}function T(C,O,f){for(var E,P,y,d=0;d<C.length;d++)if(E=C[d],f&&(E=E[f]),a.isArray(E)){for(;(P=a.arrIndexOf(E,O))!==-1;)E.splice(P,1);f&&E.length===0&&delete C[d][f]}else if(a.isObject(E))for(y in E)Object.prototype.hasOwnProperty.call(E,y)&&a.isArray(E[y])&&T([E],O,y)}var R=function(){function C(){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}return C.prototype.on=function(){for(var O=this,f=[],E=0;E<arguments.length;E++)f[E]=arguments[E];if(f.length===1){var P=f[0];if(typeof P=="function")this.any.push(P);else throw new Error("EventListener.on(): Invalid arguments: "+v.default.Config.inspect(f))}if(f.length===2){var y=f[0],d=f[1];if(typeof d!="function")throw new Error("EventListener.on(): Invalid arguments: "+v.default.Config.inspect(f));if(a.isEmptyArg(y))this.any.push(d);else if(a.isArray(y))y.forEach(function(w){O.on(w,d)});else{if(typeof y!="string")throw new Error("EventListener.on(): Invalid arguments: "+v.default.Config.inspect(f));var h=this.events[y]||(this.events[y]=[]);h.push(d)}}},C.prototype.off=function(){for(var O,f=this,E=[],P=0;P<arguments.length;P++)E[P]=arguments[P];if(E.length==0||a.isEmptyArg(E[0])&&a.isEmptyArg(E[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}var y=E[0],d=E[1],h=null,w=null;if(E.length===1||!d)typeof y=="function"?h=y:w=y;else{if(typeof d!="function")throw new Error("EventEmitter.off(): invalid arguments:"+v.default.Config.inspect(E));O=[y,d],w=O[0],h=O[1]}if(h&&a.isEmptyArg(w)){T([this.any,this.events,this.anyOnce,this.eventsOnce],h);return}if(a.isArray(w)){w.forEach(function(c){f.off(c,h)});return}if(typeof w!="string")throw new Error("EventEmitter.off(): invalid arguments:"+v.default.Config.inspect(E));h?T([this.events,this.eventsOnce],h,w):(delete this.events[w],delete this.eventsOnce[w])},C.prototype.listeners=function(O){if(O){var f=this.events[O]||[];return this.eventsOnce[O]&&Array.prototype.push.apply(f,this.eventsOnce[O]),f.length?f:null}return this.any.length?this.any:null},C.prototype.emit=function(O){for(var f=[],E=1;E<arguments.length;E++)f[E-1]=arguments[E];var P={event:O},y=[];this.anyOnce.length&&(Array.prototype.push.apply(y,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(y,this.any);var d=this.eventsOnce[O];d&&(Array.prototype.push.apply(y,d),delete this.eventsOnce[O]);var h=this.events[O];h&&Array.prototype.push.apply(y,h),a.arrForEach(y,function(w){S(P,w,f)})},C.prototype.once=function(){for(var O=this,f=[],E=0;E<arguments.length;E++)f[E]=arguments[E];var P=f.length;if((P===0||P===1&&typeof f[0]!="function")&&v.default.Config.Promise){var y=f[0];return new v.default.Config.Promise(function(l){O.once(y,l)})}var d=f[0],h=f[1];if(f.length===1&&typeof d=="function")this.anyOnce.push(d);else if(a.isEmptyArg(d)){if(typeof h!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));this.anyOnce.push(h)}else if(a.isArray(d)){var w=this,c=function(){var l=Array.prototype.slice.call(arguments);if(a.arrForEach(d,function(s){w.off(s,c)}),typeof h!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));h.apply(this,l)};a.arrForEach(d,function(l){w.on(l,c)})}else{if(typeof d!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));var u=this.eventsOnce[d]||(this.eventsOnce[d]=[]);if(h){if(typeof h!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));u.push(h)}}},C.prototype.whenState=function(O,f,E){for(var P=this,y=[],d=3;d<arguments.length;d++)y[d-3]=arguments[d];var h={event:O};if(typeof O!="string"||typeof f!="string")throw"whenState requires a valid event String argument";if(typeof E!="function"&&v.default.Config.Promise)return new v.default.Config.Promise(function(w){C.prototype.whenState.apply(P,[O,f,w].concat(y))});O===f?S(h,E,y):this.once(O,E)},C}();r.default=R},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.getDefaults=r.normaliseOptions=r.objectifyOptions=r.getAgentString=r.getHosts=r.getFallbackHosts=r.environmentFallbackHosts=r.getHttpScheme=r.getPort=r.getHost=void 0;var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1)),v=i.__importDefault(o(2)),S=i.__importDefault(o(4)),T=o(43),R="ably-js/"+T.version,C={ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,preferenceConnectTimeout:6e3,parallelUpgradeDelay:6e3},httpMaxRetryCount:3,maxMessageSize:65536,version:T.version,protocolVersion:2,agent:R,getHost:O,getPort:f,getHttpScheme:E,environmentFallbackHosts:P,getFallbackHosts:y,getHosts:d,checkHost:h,objectifyOptions:l,normaliseOptions:s};function O(p,x,D){return D?x=x==p.restHost&&p.realtimeHost||x||p.realtimeHost:x=x||p.restHost,x}r.getHost=O;function f(p,x){return x||p.tls?p.tlsPort:p.port}r.getPort=f;function E(p){return p.tls?"https://":"http://"}r.getHttpScheme=E;function P(p){return[p+"-a-fallback.ably-realtime.com",p+"-b-fallback.ably-realtime.com",p+"-c-fallback.ably-realtime.com",p+"-d-fallback.ably-realtime.com",p+"-e-fallback.ably-realtime.com"]}r.environmentFallbackHosts=P;function y(p){var x=p.fallbackHosts,D=typeof p.httpMaxRetryCount!="undefined"?p.httpMaxRetryCount:C.httpMaxRetryCount;return x?m.arrChooseN(x,D):[]}r.getFallbackHosts=y;function d(p){return[p.restHost].concat(y(p))}r.getHosts=d;function h(p){if(typeof p!="string")throw new S.default("host must be a string; was a "+typeof p,4e4,400);if(!p.length)throw new S.default("host must not be zero-length",4e4,400)}function w(p,x,D){return p.realtimeHost?p.realtimeHost:p.restHost?(v.default.logAction(v.default.LOG_MINOR,"Defaults.normaliseOptions",'restHost is set to "'+p.restHost+'" but realtimeHost is not set, so setting realtimeHost to "'+p.restHost+'" too. If this is not what you want, please set realtimeHost explicitly.'),p.restHost):x?C.REALTIME_HOST:D+"-"+C.REALTIME_HOST}function c(p){var x={};for(var D in C.TIMEOUTS)x[D]=p[D]||C.TIMEOUTS[D];return x}function u(p){var x=C.agent;if(p.agents)for(var D in p.agents)x+=" "+D+"/"+p.agents[D];return x}r.getAgentString=u;function l(p){return typeof p=="string"?p.indexOf(":")==-1?{token:p}:{key:p}:p}r.objectifyOptions=l;function s(p){if(p.host&&(v.default.renamedClientOption("host","restHost"),p.restHost=p.host),p.wsHost&&(v.default.renamedClientOption("wsHost","realtimeHost"),p.realtimeHost=p.wsHost),p.queueEvents&&(v.default.renamedClientOption("queueEvents","queueMessages"),p.queueMessages=p.queueEvents),p.headers&&v.default.deprecated("the `headers` client option",""),p.fallbackHostsUseDefault){if(p.fallbackHosts){var x="fallbackHosts and fallbackHostsUseDefault cannot both be set";throw v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions",x),new S.default(x,4e4,400)}if(p.port||p.tlsPort){var x="fallbackHostsUseDefault cannot be set when port or tlsPort are set";throw v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions",x),new S.default(x,4e4,400)}p.environment?v.default.deprecated("The `fallbackHostsUseDefault` client option","If you’re using this client option to force the library to make use of fallback hosts even though you’ve set the `environment` client option, then this is no longer necessary: remove your usage of the `fallbackHostsUseDefault` client option and the library will then automatically choose the correct fallback hosts to use for the specified environment."):v.default.deprecated("The `fallbackHostsUseDefault` client option","If you’re using this client option to force the library to make use of fallback hosts even though you’re not using the primary Ably environment, then stop using `fallbackHostsUseDefault`, and update your code to either pass the `environment` client option (in which case the library will automatically choose the correct fallback hosts to use for the specified environment), or to pass the `fallbackHosts` client option to specify a custom list of fallback hosts to use (for example, if you’re using a custom CNAME, in which case Ably will have provided you with an explicit list of fallback hosts)."),p.fallbackHosts=C.FALLBACK_HOSTS}p.recover===!0&&(v.default.deprecated("The ability to use a boolean value for the `recover` client option","If you wish for the connection to always be recovered, replace `{ recover: true }` with a function that always passes `true` to its callback: `{ recover: function(lastConnectionDetails, cb) { cb(true); } }`"),p.recover=function(F,b){b(!0)}),typeof p.recover=="function"&&p.closeOnUnload===!0&&(v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),p.recover=void 0),"closeOnUnload"in p||(p.closeOnUnload=!p.recover),p.transports&&m.arrIn(p.transports,"xhr")&&(v.default.deprecationWarning('The "xhr" transport has been renamed to "xhr_streaming". Please update your client options code to use `transports: ["xhr_streaming"]` instead. The ability to use `transports: ["xhr"]` will be removed in a future version.'),m.arrDeleteValue(p.transports,"xhr"),p.transports.push("xhr_streaming")),"queueMessages"in p||(p.queueMessages=!0);var D=p.environment&&String(p.environment).toLowerCase()||C.ENVIRONMENT,N=!D||D==="production";!p.fallbackHosts&&!p.restHost&&!p.realtimeHost&&!p.port&&!p.tlsPort&&(p.fallbackHosts=N?C.FALLBACK_HOSTS:P(D));var k=p.restHost||(N?C.REST_HOST:D+"-"+C.REST_HOST),I=w(p,N,D);m.arrForEach((p.fallbackHosts||[]).concat(k,I),h),p.port=p.port||C.PORT,p.tlsPort=p.tlsPort||C.TLS_PORT,"tls"in p||(p.tls=!0);var M=c(p);if("useBinaryProtocol"in p?p.useBinaryProtocol=a.default.Config.supportsBinary&&p.useBinaryProtocol:p.useBinaryProtocol=a.default.Config.preferBinary,p.clientId){var A=p.headers=p.headers||{};A["X-Ably-ClientId"]=a.default.BufferUtils.base64Encode(a.default.BufferUtils.utf8Encode(p.clientId))}"idempotentRestPublishing"in p||(p.idempotentRestPublishing=!0),p.promises&&!a.default.Config.Promise&&(v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions","{promises: true} was specified, but no Promise constructor found; disabling promises"),p.promises=!1);var j=null,U=p.connectivityCheckUrl;if(p.connectivityCheckUrl){var z=p.connectivityCheckUrl.split("?"),V=z[0],G=z[1];j=G?m.parseQueryString(G):{},V.indexOf("://")===-1&&(V="https://"+V),U=V}return i.__assign(i.__assign({},p),{useBinaryProtocol:"useBinaryProtocol"in p?a.default.Config.supportsBinary&&p.useBinaryProtocol:a.default.Config.preferBinary,realtimeHost:I,restHost:k,maxMessageSize:p.maxMessageSize||C.maxMessageSize,timeouts:M,connectivityCheckParams:j,connectivityCheckUrl:U})}r.normaliseOptions=s,r.default=C;function g(p){return Object.assign(C,p)}r.getDefaults=g},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(3)),m=i.__importDefault(o(2)),v=i.__importDefault(o(4)),S=i.__importStar(o(1));function T(f){return!f||!f.channelOptions?{channelOptions:f,plugins:{},baseEncodedPreviousPayload:void 0}:f}function R(f){if(f&&f.cipher){if(!a.default.Crypto)throw new Error("Encryption not enabled; use ably.encryption.js instead");var E=a.default.Crypto.getCipher(f.cipher);return{cipher:E.cipherParams,channelCipher:E.cipher}}return f!=null?f:{}}function C(f){var E=0;return f.name&&(E+=f.name.length),f.clientId&&(E+=f.clientId.length),f.extras&&(E+=JSON.stringify(f.extras).length),f.data&&(E+=S.dataSizeBytes(f.data)),E}var O=function(){function f(){}return f.prototype.toJSON=function(){var E=this.encoding,P=this.data;return P&&a.default.BufferUtils.isBuffer(P)&&(arguments.length>0?(E=E?E+"/base64":"base64",P=a.default.BufferUtils.base64Encode(P)):P=a.default.BufferUtils.toBuffer(P)),{name:this.name,id:this.id,clientId:this.clientId,connectionId:this.connectionId,connectionKey:this.connectionKey,extras:this.extras,encoding:E,data:P}},f.prototype.toString=function(){var E="[Message";return this.name&&(E+="; name="+this.name),this.id&&(E+="; id="+this.id),this.timestamp&&(E+="; timestamp="+this.timestamp),this.clientId&&(E+="; clientId="+this.clientId),this.connectionId&&(E+="; connectionId="+this.connectionId),this.encoding&&(E+="; encoding="+this.encoding),this.extras&&(E+="; extras ="+JSON.stringify(this.extras)),this.data&&(typeof this.data=="string"?E+="; data="+this.data:a.default.BufferUtils.isBuffer(this.data)?E+="; data (buffer)="+a.default.BufferUtils.base64Encode(this.data):E+="; data (json)="+JSON.stringify(this.data)),this.extras&&(E+="; extras="+JSON.stringify(this.extras)),E+="]",E},f.encrypt=function(E,P,y){var d=E.data,h=E.encoding,w=P.channelCipher;h=h?h+"/":"",a.default.BufferUtils.isBuffer(d)||(d=a.default.BufferUtils.utf8Encode(String(d)),h=h+"utf-8/"),w.encrypt(d,function(c,u){if(c){y(c);return}E.data=u,E.encoding=h+"cipher+"+w.algorithm,y(null,E)})},f.encode=function(E,P,y){var d=E.data,h=typeof d=="string"||a.default.BufferUtils.isBuffer(d)||d===null||d===void 0;if(!h)if(S.isObject(d)||S.isArray(d))E.data=JSON.stringify(d),E.encoding=E.encoding?E.encoding+"/json":"json";else throw new v.default("Data type is unsupported",40013,400);P!=null&&P.cipher?f.encrypt(E,P,y):y(null,E)},f.encodeArray=function(E,P,y){for(var d=0,h=0;h<E.length;h++)f.encode(E[h],P,function(w){if(w){y(w);return}d++,d==E.length&&y(null,E)})},f.decode=function(E,P){var y=T(P),d=E.data,h=E.encoding;if(h){var w=h.split("/"),c=void 0,u=w.length,l=E.data,s="";try{for(;(c=u)>0;){var g=w[--u].match(/([-\w]+)(\+([\w-]+))?/);if(!g)break;switch(s=g[1],s){case"base64":l=a.default.BufferUtils.base64Decode(String(l)),c==w.length&&(d=l);continue;case"utf-8":l=a.default.BufferUtils.utf8Decode(l);continue;case"json":l=JSON.parse(l);continue;case"cipher":if(y.channelOptions!=null&&y.channelOptions.cipher&&y.channelOptions.channelCipher){var p=g[3],x=y.channelOptions.channelCipher;if(p!=x.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");l=x.decrypt(l);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!y.plugins||!y.plugins.vcdiff)throw new v.default("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array=="undefined")throw new v.default("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var D=y.baseEncodedPreviousPayload;typeof D=="string"&&(D=a.default.BufferUtils.utf8Encode(D)),D=a.default.BufferUtils.toBuffer(D),l=a.default.BufferUtils.toBuffer(l),l=a.default.BufferUtils.typedArrayToBuffer(y.plugins.vcdiff.decode(l,D)),d=l}catch(k){throw new v.default("Vcdiff delta decode failed with "+k,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(k){var N=k;throw new v.default("Error processing the "+s+" encoding, decoder returned ‘"+N.message+"’",N.code||40013,400)}finally{E.encoding=c<=0?null:w.slice(0,c).join("/"),E.data=l}}y.baseEncodedPreviousPayload=d},f.fromResponseBody=function(E,P,y){y&&(E=S.decodeBody(E,y));for(var d=0;d<E.length;d++){var h=E[d]=f.fromValues(E[d]);try{f.decode(h,P)}catch(w){m.default.logAction(m.default.LOG_ERROR,"Message.fromResponseBody()",w.toString())}}return E},f.fromValues=function(E){return Object.assign(new f,E)},f.fromValuesArray=function(E){for(var P=E.length,y=new Array(P),d=0;d<P;d++)y[d]=f.fromValues(E[d]);return y},f.fromEncoded=function(E,P){var y=f.fromValues(E),d=R(P!=null?P:null);try{f.decode(y,d)}catch(h){m.default.logAction(m.default.LOG_ERROR,"Message.fromEncoded()",h.toString())}return y},f.fromEncodedArray=function(E,P){return E.map(function(y){return f.fromEncoded(y,P)})},f.getMessagesSize=function(E){for(var P,y=0,d=0;d<E.length;d++)P=E[d],y+=P.size||(P.size=C(P));return y},f.serialize=S.encodeBody,f}();r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(4)),v=i.__importDefault(o(9)),S=i.__importDefault(o(16)),T={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18},R=[];Object.keys(T).forEach(function(y){R[T[y]]=y});var C={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19},O=Object.keys(C);C.MODE_ALL=C.PRESENCE|C.PUBLISH|C.SUBSCRIBE|C.PRESENCE_SUBSCRIBE;function f(y){var d=[];if(y)for(var h=0;h<y.length;h++)d.push(y[h].toString());return"[ "+d.join(", ")+" ]"}var E="id channel channelSerial connectionId count msgSerial timestamp".split(" "),P=function(){function y(){var d=this;this.hasFlag=function(h){return(d.flags&C[h])>0}}return y.prototype.setFlag=function(d){return this.flags=this.flags|C[d]},y.prototype.getMode=function(){return this.flags&&this.flags&C.MODE_ALL},y.prototype.encodeModesToFlags=function(d){var h=this;d.forEach(function(w){return h.setFlag(w)})},y.prototype.decodeModesFromFlags=function(){var d=this,h=[];return y.channelModes.forEach(function(w){d.hasFlag(w)&&h.push(w)}),h.length>0?h:void 0},y.fromValues=function(d){return Object.assign(new y,d)},y.Action=T,y.channelModes=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE"],y.ActionName=R,y.serialize=a.encodeBody,y.deserialize=function(d,h){var w=a.decodeBody(d,h);return y.fromDeserialized(w)},y.fromDeserialized=function(d){var h=d.error;h&&(d.error=m.default.fromValues(h));var w=d.messages;if(w)for(var c=0;c<w.length;c++)w[c]=v.default.fromValues(w[c]);var u=d.presence;if(u)for(var c=0;c<u.length;c++)u[c]=S.default.fromValues(u[c],!0);return Object.assign(new y,d)},y.stringify=function(d){var h="[ProtocolMessage";d.action!==void 0&&(h+="; action="+y.ActionName[d.action]||!1);for(var w,c=0;c<E.length;c++)w=E[c],d[w]!==void 0&&(h+="; "+w+"="+d[w]);if(d.messages&&(h+="; messages="+f(v.default.fromValuesArray(d.messages))),d.presence&&(h+="; presence="+f(S.default.fromValuesArray(d.presence))),d.error&&(h+="; error="+m.default.fromValues(d.error).toString()),d.auth&&d.auth.accessToken&&(h+="; token="+d.auth.accessToken),d.flags&&(h+="; flags="+O.filter(d.hasFlag).join(",")),d.params){var u="";a.forInOwnNonNullProperties(d.params,function(l){u.length>0&&(u+="; "),u+=l+"="+d.params[l]}),u.length>0&&(h+="; params=["+u+"]")}return h+="]",h},y}();r.default=P},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){var a=i,m=a.lib,v=m.WordArray,S=a.enc;S.Base64={stringify:function(R){var C=R.words,O=R.sigBytes,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";R.clamp();for(var E=[],P=0;P<O;P+=3)for(var y=C[P>>>2]>>>24-P%4*8&255,d=C[P+1>>>2]>>>24-(P+1)%4*8&255,h=C[P+2>>>2]>>>24-(P+2)%4*8&255,w=y<<16|d<<8|h,c=0;c<4&&P+c*.75<O;c++)E.push(f.charAt(w>>>6*(3-c)&63));var u=f.charAt(64);if(u)for(;E.length%4;)E.push(u);return E.join("")},parse:function(R){var C=R.length,O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=this._reverseMap;if(!f){f=this._reverseMap=[];for(var E=0;E<O.length;E++)f[O.charCodeAt(E)]=E}var P=O.charAt(64);if(P){var y=R.indexOf(P);y!==-1&&(C=y)}return T(R,C,f)}};function T(R,C,O){for(var f=[],E=0,P=0;P<C;P++)if(P%4){var y=O[R.charCodeAt(P-1)]<<P%4*2,d=O[R.charCodeAt(P)]>>>6-P%4*2,h=y|d;f[E>>>2]|=h<<24-E%4*8,E++}return v.create(f,E)}}(),i.enc.Base64})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(10)),v=i.__importDefault(o(26)),S=i.__importDefault(o(2)),T=i.__importDefault(o(8)),R=i.__importDefault(o(21)),C=i.__importDefault(o(18)),O=i.__importDefault(o(4)),f=i.__importDefault(o(22)),E=i.__importDefault(o(3));function P(h){var w=[80015,80017,80030];return h.code?C.default.isTokenErr(h)?!1:a.arrIn(w,h.code)?!0:h.code>=4e4&&h.code<5e4:!1}function y(h){return P(h)?[m.default.fromValues({action:m.default.Action.ERROR,error:h})]:[m.default.fromValues({action:m.default.Action.DISCONNECTED,error:h})]}var d=function(h){i.__extends(w,h);function w(c,u,l){var s=h.call(this,c,u,l,!0)||this;return s.onAuthUpdated=function(g){s.authParams={access_token:g.token}},s.stream="stream"in l?l.stream:!0,s.sendRequest=null,s.recvRequest=null,s.pendingCallback=null,s.pendingItems=null,s}return w.prototype.connect=function(){var c=this;S.default.logAction(S.default.LOG_MINOR,"CometTransport.connect()","starting"),v.default.prototype.connect.call(this);var u=this.params,l=u.options,s=T.default.getHost(l,u.host),g=T.default.getPort(l),p=l.tls?"https://":"http://";this.baseUri=p+s+":"+g+"/comet/";var x=this.baseUri+"connect";S.default.logAction(S.default.LOG_MINOR,"CometTransport.connect()","uri: "+x),this.auth.getAuthParams(function(D,N){if(D){c.disconnect(D);return}if(!c.isDisposed){c.authParams=N;var k=c.params.getConnectParams(N);"stream"in k&&(c.stream=k.stream),S.default.logAction(S.default.LOG_MINOR,"CometTransport.connect()","connectParams:"+a.toQueryString(k));var I=!1,M=c.recvRequest=c.createRequest(x,null,k,null,c.stream?f.default.REQ_RECV_STREAM:f.default.REQ_RECV);M.on("data",function(A){c.recvRequest&&(I||(I=!0,c.emit("preconnect")),c.onData(A))}),M.on("complete",function(A){if(c.recvRequest||(A=A||new O.default("Request cancelled",80003,400)),c.recvRequest=null,!I&&!A&&(I=!0,c.emit("preconnect")),c.onActivity(),A){A.code?c.onData(y(A)):c.disconnect(A);return}E.default.Config.nextTick(function(){c.recv()})}),M.exec()}})},w.prototype.requestClose=function(){S.default.logAction(S.default.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)},w.prototype.requestDisconnect=function(){S.default.logAction(S.default.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)},w.prototype._requestCloseOrDisconnect=function(c){var u=this,l=c?this.closeUri:this.disconnectUri;if(l){var s=this.createRequest(l,null,this.authParams,null,f.default.REQ_SEND);s.on("complete",function(g){g&&(S.default.logAction(S.default.LOG_ERROR,"CometTransport.request"+(c?"Close()":"Disconnect()"),"request returned err = "+a.inspectError(g)),u.finish("disconnected",g))}),s.exec()}},w.prototype.dispose=function(){var c=this;S.default.logAction(S.default.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(S.default.logAction(S.default.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",R.default.disconnected()),E.default.Config.nextTick(function(){c.emit("disposed")}))},w.prototype.onConnect=function(c){var u;if(!this.isDisposed){var l=(u=c.connectionDetails)===null||u===void 0?void 0:u.connectionKey;v.default.prototype.onConnect.call(this,c);var s=this.baseUri+l;S.default.logAction(S.default.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+s),this.sendUri=s+"/send",this.recvUri=s+"/recv",this.closeUri=s+"/close",this.disconnectUri=s+"/disconnect"}},w.prototype.send=function(c){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(c);return}var u=this.pendingItems||[];u.push(c),this.pendingItems=null,this.sendItems(u)},w.prototype.sendAnyPending=function(){var c=this.pendingItems;c&&(this.pendingItems=null,this.sendItems(c))},w.prototype.sendItems=function(c){var u=this,l=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(c),f.default.REQ_SEND);l.on("complete",function(s,g){if(s&&S.default.logAction(S.default.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+a.inspectError(s)),u.sendRequest=null,s){s.code?u.onData(y(s)):u.disconnect(s);return}g&&u.onData(g),u.pendingItems&&E.default.Config.nextTick(function(){u.sendRequest||u.sendAnyPending()})}),l.exec()},w.prototype.recv=function(){var c=this;if(!this.recvRequest&&this.isConnected){var u=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?f.default.REQ_RECV_STREAM:f.default.REQ_RECV_POLL);u.on("data",function(l){c.onData(l)}),u.on("complete",function(l){if(c.recvRequest=null,c.onActivity(),l){l.code?c.onData(y(l)):c.disconnect(l);return}E.default.Config.nextTick(function(){c.recv()})}),u.exec()}},w.prototype.onData=function(c){try{var u=this.decodeResponse(c);if(u&&u.length)for(var l=0;l<u.length;l++)this.onProtocolMessage(m.default.fromDeserialized(u[l]))}catch(s){S.default.logAction(S.default.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+s.stack)}},w.prototype.encodeRequest=function(c){return JSON.stringify(c)},w.prototype.decodeResponse=function(c){return typeof c=="string"?JSON.parse(c):c},w}(v.default);r.default=d},function(n,r){var o;o=function(){return this}();try{o=o||new Function("return this")()}catch(i){typeof window=="object"&&(o=window)}n.exports=o},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.isSuccessCode=void 0;var i;(function(m){m[m.Success=200]="Success",m[m.NoContent=204]="NoContent",m[m.BadRequest=400]="BadRequest",m[m.Unauthorized=401]="Unauthorized",m[m.Forbidden=403]="Forbidden",m[m.RequestTimeout=408]="RequestTimeout",m[m.InternalServerError=500]="InternalServerError"})(i||(i={}));function a(m){return m>=i.Success&&m<i.BadRequest}r.isSuccessCode=a,r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1)),v=i.__importDefault(o(2)),S=i.__importDefault(o(18)),T=i.__importDefault(o(19)),R=o(4),C=i.__importDefault(o(14));function O(h,w,c,u,l){h.http.supportsAuthHeaders?h.auth.getAuthHeaders(function(s,g){s?u(s):l(m.mixin(g,w),c)}):h.auth.getAuthParams(function(s,g){s?u(s):l(w,m.mixin(g,c))})}function f(h,w){return function(c,u,l,s,g){if(c&&!u){h(c);return}if(g===C.default.NoContent){h(c,[],l,!0,g);return}if(!s)try{u=m.decodeBody(u,w)}catch(I){m.isErrorInfoOrPartialErrorInfo(I)?h(I):h(new R.PartialErrorInfo(m.inspectError(I),null));return}if(!u){h(new R.PartialErrorInfo("unenvelope(): Response body is missing",null));return}var p=u,x=p.statusCode,D=p.response,N=p.headers;if(x===void 0){h(c,u,l,!0,g);return}if(x<200||x>=300){var k=D&&D.error||c;k||(k=new Error("Error in unenveloping "+u),k.statusCode=x),h(k,D,N,!0,x);return}h(c,D,N,!0,x)}}function E(h){var w=[];if(h)for(var c in h)w.push(c+"="+h[c]);return w.join("&")}function P(h,w){return h+(w?"?":"")+E(w)}function y(h,w,c,u){return function(l,s,g,p,x){l?v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Received Error; "+P(c,u)+"; Error: "+m.inspectError(l)):v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Received; "+P(c,u)+"; Headers: "+E(g)+"; StatusCode: "+x+"; Body: "+(a.default.BufferUtils.isBuffer(s)?s.toString():s)),h&&h(l,s,g,p,x)}}var d=function(){function h(){}return h.get=function(w,c,u,l,s,g){h.do(T.default.Get,w,c,null,u,l,s,g)},h.delete=function(w,c,u,l,s,g){h.do(T.default.Delete,w,c,null,u,l,s,g)},h.post=function(w,c,u,l,s,g,p){h.do(T.default.Post,w,c,u,l,s,g,p)},h.patch=function(w,c,u,l,s,g,p){h.do(T.default.Patch,w,c,u,l,s,g,p)},h.put=function(w,c,u,l,s,g,p){h.do(T.default.Put,w,c,u,l,s,g,p)},h.do=function(w,c,u,l,s,g,p,x){v.default.shouldLog(v.default.LOG_MICRO)&&(x=y(x,w,u,g)),p&&(x=x&&f(x,p),(g=g||{}).envelope=p);function D(N,k){var I;if(v.default.shouldLog(v.default.LOG_MICRO)&&v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Sending; "+P(u,k)),v.default.shouldLog(v.default.LOG_MICRO)){var M=l;if(((I=N["content-type"])===null||I===void 0?void 0:I.indexOf("msgpack"))>0)try{M=a.default.Config.msgpack.decode(l)}catch(A){v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Sending MsgPack Decoding Error: "+m.inspectError(A))}v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Sending; "+P(u,k)+"; Body: "+M)}c.http.do(w,c,u,N,l,k,function(A,j,U,z,V){if(A&&S.default.isTokenErr(A)){c.auth.authorize(null,null,function(G){if(G){x(G);return}O(c,N,k,x,D)});return}x(A,j,U,z,V)})}O(c,s,g,x,D)},h}();r.default=d},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(2)),m=i.__importDefault(o(3)),v=i.__importDefault(o(9)),S=i.__importStar(o(1));function T(C){return R.Actions.indexOf(C)}var R=function(){function C(){}return C.prototype.isSynthesized=function(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId},C.prototype.parseId=function(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");var O=this.id.split(":");return{connectionId:O[0],msgSerial:parseInt(O[1],10),index:parseInt(O[2],10)}},C.prototype.toJSON=function(){var O=this.data,f=this.encoding;return O&&m.default.BufferUtils.isBuffer(O)&&(arguments.length>0?(f=f?f+"/base64":"base64",O=m.default.BufferUtils.base64Encode(O)):O=m.default.BufferUtils.toBuffer(O)),{id:this.id,clientId:this.clientId,action:T(this.action),data:O,encoding:f,extras:this.extras}},C.prototype.toString=function(){var O="[PresenceMessage";return O+="; action="+this.action,this.id&&(O+="; id="+this.id),this.timestamp&&(O+="; timestamp="+this.timestamp),this.clientId&&(O+="; clientId="+this.clientId),this.connectionId&&(O+="; connectionId="+this.connectionId),this.encoding&&(O+="; encoding="+this.encoding),this.data&&(typeof this.data=="string"?O+="; data="+this.data:m.default.BufferUtils.isBuffer(this.data)?O+="; data (buffer)="+m.default.BufferUtils.base64Encode(this.data):O+="; data (json)="+JSON.stringify(this.data)),this.extras&&(O+="; extras="+JSON.stringify(this.extras)),O+="]",O},C.fromResponseBody=function(O,f,E){var P=[];E&&(O=S.decodeBody(O,E));for(var y=0;y<O.length;y++){var d=P[y]=C.fromValues(O[y],!0);try{C.decode(d,f)}catch(h){a.default.logAction(a.default.LOG_ERROR,"PresenceMessage.fromResponseBody()",h.toString())}}return P},C.fromValues=function(O,f){return f&&(O.action=C.Actions[O.action]),Object.assign(new C,O)},C.fromValuesArray=function(O){for(var f=O.length,E=new Array(f),P=0;P<f;P++)E[P]=C.fromValues(O[P]);return E},C.fromEncoded=function(O,f){var E=C.fromValues(O,!0);try{C.decode(E,f!=null?f:{})}catch(P){a.default.logAction(a.default.LOG_ERROR,"PresenceMessage.fromEncoded()",P.toString())}return E},C.fromEncodedArray=function(O,f){return O.map(function(E){return C.fromEncoded(E,f)})},C.fromData=function(O){return O instanceof C?O:C.fromValues({data:O})},C.Actions=["absent","present","enter","leave","update"],C.encode=v.default.encode,C.decode=v.default.decode,C.getMessagesSize=v.default.getMessagesSize,C}();r.default=R},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importStar(o(1)),v=a.__importDefault(o(7)),S=a.__importStar(o(4)),T=a.__importDefault(o(2)),R=a.__importDefault(o(8)),C=a.__importDefault(o(22)),O=a.__importDefault(o(3));function f(p,x){return m.arrIn(m.allToLowerCase(m.keysArray(x)),"x-ably-errorcode")}function E(p,x){if(f(p,x))return p.error&&S.default.fromValues(p.error)}var P=function(){},y=0,d={},h=typeof i!="undefined"&&i.XDomainRequest;function w(){var p=navigator.userAgent.toString().match(/MSIE\s([\d.]+)/);return p&&Number(p[1])}function c(){var p;return h&&(p=w())&&p===10}function u(p,x){return p.getResponseHeader&&p.getResponseHeader(x)}function l(p){return p.getResponseHeader&&(p.getResponseHeader("transfer-encoding")||!p.getResponseHeader("content-length"))}function s(p){for(var x=m.trim(p.getAllResponseHeaders()).split(`\r
83
- `),D={},N=0;N<x.length;N++){var k=x[N].split(":").map(m.trim);D[k[0].toLowerCase()]=k[1]}return D}var g=function(p){a.__extends(x,p);function x(D,N,k,I,M,A,j){var U=p.call(this)||this;return k=k||{},k.rnd=m.cheapRandStr(),c()&&!k.envelope&&(k.envelope="json"),U.uri=D+m.toQueryString(k),U.headers=N||{},U.body=I,U.method=j?j.toUpperCase():m.isEmptyArg(I)?"GET":"POST",U.requestMode=M,U.timeouts=A,U.timedOut=!1,U.requestComplete=!1,U.id=String(++y),d[U.id]=U,U}return x.createRequest=function(D,N,k,I,M,A,j){var U=A||R.default.TIMEOUTS;return new x(D,N,m.copy(k),I,M,U,j)},x.prototype.complete=function(D,N,k,I,M){this.requestComplete||(this.requestComplete=!0,!D&&N&&this.emit("data",N),this.emit("complete",D,N,k,I,M),this.dispose())},x.prototype.abort=function(){this.dispose()},x.prototype.exec=function(){var D=this,N=this.headers,k=this.requestMode==C.default.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,I=this.timer=setTimeout(function(){D.timedOut=!0,A.abort()},k),M=this.method,A=this.xhr=new XMLHttpRequest,j=N.accept,U=this.body,z="text";if(j?j.indexOf("application/x-msgpack")===0&&(z="arraybuffer"):N.accept="application/json",U){var V=N["content-type"]||(N["content-type"]="application/json");V.indexOf("application/json")>-1&&typeof U!="string"&&(U=JSON.stringify(U))}A.open(M,this.uri,!0),A.responseType=z,"authorization"in N&&(A.withCredentials=!0);for(var G in N)A.setRequestHeader(G,N[G]);var F=function(Z,he,Me,_e){var Ee,Mt=he+" (event type: "+Z.type+")";!((Ee=D==null?void 0:D.xhr)===null||Ee===void 0)&&Ee.statusText&&(Mt+=", current statusText is "+D.xhr.statusText),T.default.logAction(T.default.LOG_ERROR,"Request.on"+Z.type+"()",Mt),D.complete(new S.PartialErrorInfo(Mt,Me,_e))};A.onerror=function(Z){F(Z,"XHR error occurred",null,400)},A.onabort=function(Z){D.timedOut?F(Z,"Request aborted due to request timeout expiring",null,408):F(Z,"Request cancelled",null,400)},A.ontimeout=function(Z){F(Z,"Request timed out",null,408)};var b,L,B,_=0,W=!1,Y=function(){if(clearTimeout(I),B=L<400,L==204){D.complete(null,null,null,null,L);return}b=D.requestMode==C.default.REQ_RECV_STREAM&&B&&l(A)},X=function(){var Z;try{var he=u(A,"content-type"),Me=he?he.indexOf("application/json")>=0:A.responseType=="text";if(Me){var _e=A.responseType==="arraybuffer"?O.default.BufferUtils.utf8Decode(A.response):String(A.responseText);_e.length?Z=JSON.parse(_e):Z=_e,W=!0}else Z=A.response;Z.response!==void 0?(L=Z.statusCode,B=L<400,N=Z.headers,Z=Z.response):N=s(A)}catch(Mt){D.complete(new S.PartialErrorInfo("Malformed response body from server: "+Mt.message,null,400));return}if(B||m.isArray(Z)){D.complete(null,Z,N,W,L);return}var Ee=E(Z,N);Ee||(Ee=new S.PartialErrorInfo("Error response received from server: "+L+" body was: "+O.default.Config.inspect(Z),null,L)),D.complete(Ee,Z,N,W,L)};function te(){for(var Z=A.responseText,he=Z.length-1,Me,_e;_<he&&(Me=Z.indexOf(`
84
- `,_))>-1;)_e=Z.slice(_,Me),_=Me+1,re(_e)}var re=function(Z){try{Z=JSON.parse(Z)}catch(he){D.complete(new S.PartialErrorInfo("Malformed response body from server: "+he.message,null,400));return}D.emit("data",Z)},le=function(){te(),D.streamComplete=!0,O.default.Config.nextTick(function(){D.complete()})};A.onreadystatechange=function(){var Z=A.readyState;Z<3||A.status!==0&&(L===void 0&&(L=A.status,L===1223&&(L=204),Y()),Z==3&&b?te():Z==4&&(b?le():X()))},A.send(U)},x.prototype.dispose=function(){var D=this.xhr;if(D){D.onreadystatechange=D.onerror=D.onabort=D.ontimeout=P,this.xhr=null;var N=this.timer;N&&(clearTimeout(N),this.timer=null),this.requestComplete||D.abort()}delete d[this.id]},x}(v.default);r.default=g}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(2)),m=i.__importStar(o(1)),v=i.__importDefault(o(24)),S=i.__importDefault(o(4)),T=i.__importDefault(o(45)),R=o(11),C=i.__importDefault(o(19)),O=i.__importDefault(o(14)),f=i.__importDefault(o(3)),E=i.__importDefault(o(15)),P=Math.pow(2,17);function y(){}function d(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function h(k){return!!k.connection}function w(k){return m.isErrorInfoOrPartialErrorInfo(k)?(k.code||(k.statusCode===403?k.code=40300:(k.code=40170,k.statusCode=401)),k):new S.default(m.inspectError(k),k.code||40170,k.statusCode||401)}var c=function(k,I){if(f.default.Config.createHmac){var M=f.default.Config.createHmac("SHA256",I);return M.update(k),M.digest("base64")}return(0,R.stringify)((0,T.default)(k,I))};function u(k){if(!k)return"";typeof k=="string"&&(k=JSON.parse(k));var I=Object.create(null),M=m.keysArray(k,!0);if(!M)return"";M.sort();for(var A=0;A<M.length;A++)I[M[A]]=k[M[A]].sort();return JSON.stringify(I)}function l(k){if(k.authCallback)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with authCallback");else if(k.authUrl)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with authUrl");else if(k.key)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(k.tokenDetails)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with supplied token only");else{var I="authOptions must include valid authentication parameters";throw a.default.logAction(a.default.LOG_ERROR,"Auth()",I),new Error(I)}}function s(k){return"useTokenAuth"in k&&!k.useTokenAuth}function g(k){return k.useTokenAuth||!s(k)&&(k.authCallback||k.authUrl||k.token||k.tokenDetails)}function p(k){return!k.key&&!k.authCallback&&!k.authUrl}var x=0;function D(){return x++}var N=function(){function k(I,M){if(this.authOptions={},this.client=I,this.tokenParams=M.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,g(M)){if(M.key&&!c){var A="client-side token request signing not supported";throw a.default.logAction(a.default.LOG_ERROR,"Auth()",A),new Error(A)}p(M)&&a.default.logAction(a.default.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(M.defaultTokenParams,M),l(this.authOptions)}else{if(!M.key){var A="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw a.default.logAction(a.default.LOG_ERROR,"Auth()",A),new S.default(A,40160,401)}a.default.logAction(a.default.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(M)}}return k.prototype.authorize=function(I,M,A){var j=this,U;if(typeof I=="function"&&!A?(A=I,U=I=null):typeof M=="function"&&!A?(A=M,U=null):U=M,!A&&this.client.options.promises)return m.promisify(this,"authorize",arguments);if(U&&U.key&&this.authOptions.key!==U.key)throw new S.default("Unable to update auth options with incompatible key",40102,401);U&&"force"in U&&(a.default.deprecated("The `force` auth option","If you’re using this option to force `authorize()` to fetch a new token even if the current token has not expired, this is no longer necessary, as `authorize()` now always fetches a new token. Update your code to no longer pass the `force` auth option. Note that, in general, passing an auth options argument to `authorize()` will overwrite the library’s stored auth options, which may not be what you want. The library currently contains a special case behavior where passing an auth options object which only contains `{ force: true }` will _not_ overwrite the stored options. This special case behavior will be removed alongside support for the `force` option, so if you’re currently passing `authorize()` an auth options object which only contains `{ force: true }`, you should stop passing it an auth options object entirely."),m.isOnlyPropIn(U,"force")&&(U=null)),this._forceNewToken(I,U,function(z,V){if(z){j.client.connection&&z.statusCode===O.default.Forbidden&&j.client.connection.connectionManager.actOnErrorFromAuthorize(z),A==null||A(z);return}h(j.client)?j.client.connection.connectionManager.onAuthUpdated(V,A||y):A==null||A(null,V)})},k.prototype.authorise=function(I,M,A){a.default.renamedMethod("Auth","authorise","authorize"),this.authorize(I,M,A)},k.prototype._forceNewToken=function(I,M,A){var j=this;this.tokenDetails=null,this._saveTokenOptions(I,M),l(this.authOptions),this._ensureValidAuthCredentials(!0,function(U,z){delete j.tokenParams.timestamp,delete j.authOptions.queryTime,A(U,z)})},k.prototype.requestToken=function(I,M,A){var j=this;if(typeof I=="function"&&!A?(A=I,M=I=null):typeof M=="function"&&!A&&(A=M,M=null),!A&&this.client.options.promises)return m.promisify(this,"requestToken",arguments);M=M||this.authOptions,I=I||m.copy(this.tokenParams);var U=A||y,z,V=this.client;if(M.authCallback)a.default.logAction(a.default.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),z=M.authCallback;else if(M.authUrl)a.default.logAction(a.default.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),z=function(_,W){var Y=m.mixin({accept:"application/json, text/plain"},M.authHeaders),X=M.authMethod&&M.authMethod.toLowerCase()==="post",te,re=M.authUrl.indexOf("?");re>-1&&(te=m.parseQueryString(M.authUrl.slice(re)),M.authUrl=M.authUrl.slice(0,re),X||(M.authParams=m.mixin(te,M.authParams)));var le=m.mixin({},M.authParams||{},_),Z=function(_e,Ee,Mt,qo){var ft;if(_e?a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+m.inspectError(_e)):(ft=Mt["content-type"],a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+ft+"; body: "+m.inspectBody(Ee))),_e||qo)return W(_e,Ee);if(f.default.BufferUtils.isBuffer(Ee)&&(Ee=Ee.toString()),!ft){W(new S.default("authUrl response is missing a content-type header",40170,401));return}var ei=ft.indexOf("application/json")>-1,ws=ft.indexOf("text/plain")>-1||ft.indexOf("application/jwt")>-1;if(!ei&&!ws){W(new S.default("authUrl responded with unacceptable content-type "+ft+", should be either text/plain, application/jwt or application/json",40170,401));return}if(ei){if(Ee.length>P){W(new S.default("authUrl response exceeded max permitted length",40170,401));return}try{Ee=JSON.parse(Ee)}catch(Ss){W(new S.default("Unexpected error processing authURL response; err = "+Ss.message,40170,401));return}}W(null,Ee,ft)};if(a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+M.authUrl+"; Params: "+JSON.stringify(le)+"; method: "+(X?"POST":"GET")),X){var he=Y||{};he["content-type"]="application/x-www-form-urlencoded";var Me=m.toQueryString(le).slice(1);j.client.http.doUri(C.default.Post,V,M.authUrl,he,Me,te,Z)}else j.client.http.doUri(C.default.Get,V,M.authUrl,Y||{},null,le,Z)};else if(M.key)a.default.logAction(a.default.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),z=function(_,W){j.createTokenRequest(_,M,W)};else{var G="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";a.default.logAction(a.default.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),U(new S.default(G,40171,403));return}"capability"in I&&(I.capability=u(I.capability));var F=function(_,W){var Y=_.keyName,X="/keys/"+Y+"/requestToken",te=function(le){return V.baseUri(le)+X},re=m.defaultPostHeaders(j.client.options);M.requestHeaders&&m.mixin(re,M.requestHeaders),a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+X+"; Token params: "+JSON.stringify(_)),j.client.http.do(C.default.Post,V,te,re,JSON.stringify(_),null,W)},b=!1,L=this.client.options.timeouts.realtimeRequestTimeout,B=setTimeout(function(){b=!0;var _="Token request callback timed out after "+L/1e3+" seconds";a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()",_),U(new S.default(_,40170,401))},L);z(I,function(_,W,Y){if(!b){if(clearTimeout(B),_){a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+m.inspectError(_)),U(w(_));return}if(typeof W=="string"){W.length===0?U(new S.default("Token string is empty",40170,401)):W.length>P?U(new S.default("Token string exceeded max permitted length (was "+W.length+" bytes)",40170,401)):W==="undefined"||W==="null"?U(new S.default("Token string was literal null/undefined",40170,401)):W[0]==="{"&&!(Y&&Y.indexOf("application/jwt")>-1)?U(new S.default("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):U(null,{token:W});return}if(typeof W!="object"){var X="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof W;a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()",X),U(new S.default(X,40170,401));return}var te=JSON.stringify(W).length;if(te>P&&!M.suppressMaxLengthCheck){U(new S.default("Token request/details object exceeded max permitted stringified size (was "+te+" bytes)",40170,401));return}if("issued"in W){U(null,W);return}if(!("keyName"in W)){var X="Expected token request callback to call back with a token string, token request object, or token details object";a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()",X),U(new S.default(X,40170,401));return}F(W,function(re,le,Z,he){if(re){a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+m.inspectError(re)),U(w(re));return}he||(le=JSON.parse(le)),a.default.logAction(a.default.LOG_MINOR,"Auth.getToken()","token received"),U(null,le)})}})},k.prototype.createTokenRequest=function(I,M,A){var j=this;if(typeof I=="function"&&!A?(A=I,M=I=null):typeof M=="function"&&!A&&(A=M,M=null),!A&&this.client.options.promises)return m.promisify(this,"createTokenRequest",arguments);M=M||this.authOptions,I=I||m.copy(this.tokenParams);var U=M.key;if(!U){A(new S.default("No key specified",40101,403));return}var z=U.split(":"),V=z[0],G=z[1];if(!G){A(new S.default("Invalid key specified",40101,403));return}if(I.clientId===""){A(new S.default("clientId can’t be an empty string",40012,400));return}"capability"in I&&(I.capability=u(I.capability));var F=m.mixin({keyName:V},I),b=I.clientId||"",L=I.ttl||"",B=I.capability||"";(function(_){if(F.timestamp){_();return}j.getTimestamp(M&&M.queryTime,function(W,Y){if(W){A(W);return}F.timestamp=Y,_()})})(function(){var _=F.nonce||(F.nonce=d()),W=F.timestamp,Y=F.keyName+`
82
+ ***************************************************************************** */var i=function(I,M){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,j){A.__proto__=j}||function(A,j){for(var U in j)Object.prototype.hasOwnProperty.call(j,U)&&(A[U]=j[U])},i(I,M)};function a(I,M){if(typeof M!="function"&&M!==null)throw new TypeError("Class extends value "+String(M)+" is not a constructor or null");i(I,M);function A(){this.constructor=I}I.prototype=M===null?Object.create(M):(A.prototype=M.prototype,new A)}var m=function(){return m=Object.assign||function(M){for(var A,j=1,U=arguments.length;j<U;j++){A=arguments[j];for(var z in A)Object.prototype.hasOwnProperty.call(A,z)&&(M[z]=A[z])}return M},m.apply(this,arguments)};function v(I,M){var A={};for(var j in I)Object.prototype.hasOwnProperty.call(I,j)&&M.indexOf(j)<0&&(A[j]=I[j]);if(I!=null&&typeof Object.getOwnPropertySymbols=="function")for(var U=0,j=Object.getOwnPropertySymbols(I);U<j.length;U++)M.indexOf(j[U])<0&&Object.prototype.propertyIsEnumerable.call(I,j[U])&&(A[j[U]]=I[j[U]]);return A}function S(I,M,A,j){var U=arguments.length,z=U<3?M:j===null?j=Object.getOwnPropertyDescriptor(M,A):j,W;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")z=Reflect.decorate(I,M,A,j);else for(var G=I.length-1;G>=0;G--)(W=I[G])&&(z=(U<3?W(z):U>3?W(M,A,z):W(M,A))||z);return U>3&&z&&Object.defineProperty(M,A,z),z}function T(I,M){return function(A,j){M(A,j,I)}}function R(I,M){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(I,M)}function C(I,M,A,j){function U(z){return z instanceof A?z:new A(function(W){W(z)})}return new(A||(A=Promise))(function(z,W){function G(L){try{b(j.next(L))}catch(B){W(B)}}function F(L){try{b(j.throw(L))}catch(B){W(B)}}function b(L){L.done?z(L.value):U(L.value).then(G,F)}b((j=j.apply(I,M||[])).next())})}function O(I,M){var A={label:0,sent:function(){if(z[0]&1)throw z[1];return z[1]},trys:[],ops:[]},j,U,z,W;return W={next:G(0),throw:G(1),return:G(2)},typeof Symbol=="function"&&(W[Symbol.iterator]=function(){return this}),W;function G(b){return function(L){return F([b,L])}}function F(b){if(j)throw new TypeError("Generator is already executing.");for(;A;)try{if(j=1,U&&(z=b[0]&2?U.return:b[0]?U.throw||((z=U.return)&&z.call(U),0):U.next)&&!(z=z.call(U,b[1])).done)return z;switch(U=0,z&&(b=[b[0]&2,z.value]),b[0]){case 0:case 1:z=b;break;case 4:return A.label++,{value:b[1],done:!1};case 5:A.label++,U=b[1],b=[0];continue;case 7:b=A.ops.pop(),A.trys.pop();continue;default:if(z=A.trys,!(z=z.length>0&&z[z.length-1])&&(b[0]===6||b[0]===2)){A=0;continue}if(b[0]===3&&(!z||b[1]>z[0]&&b[1]<z[3])){A.label=b[1];break}if(b[0]===6&&A.label<z[1]){A.label=z[1],z=b;break}if(z&&A.label<z[2]){A.label=z[2],A.ops.push(b);break}z[2]&&A.ops.pop(),A.trys.pop();continue}b=M.call(I,A)}catch(L){b=[6,L],U=0}finally{j=z=0}if(b[0]&5)throw b[1];return{value:b[0]?b[1]:void 0,done:!0}}}var f=Object.create?function(I,M,A,j){j===void 0&&(j=A),Object.defineProperty(I,j,{enumerable:!0,get:function(){return M[A]}})}:function(I,M,A,j){j===void 0&&(j=A),I[j]=M[A]};function E(I,M){for(var A in I)A!=="default"&&!Object.prototype.hasOwnProperty.call(M,A)&&f(M,I,A)}function P(I){var M=typeof Symbol=="function"&&Symbol.iterator,A=M&&I[M],j=0;if(A)return A.call(I);if(I&&typeof I.length=="number")return{next:function(){return I&&j>=I.length&&(I=void 0),{value:I&&I[j++],done:!I}}};throw new TypeError(M?"Object is not iterable.":"Symbol.iterator is not defined.")}function y(I,M){var A=typeof Symbol=="function"&&I[Symbol.iterator];if(!A)return I;var j=A.call(I),U,z=[],W;try{for(;(M===void 0||M-- >0)&&!(U=j.next()).done;)z.push(U.value)}catch(G){W={error:G}}finally{try{U&&!U.done&&(A=j.return)&&A.call(j)}finally{if(W)throw W.error}}return z}function d(){for(var I=[],M=0;M<arguments.length;M++)I=I.concat(y(arguments[M]));return I}function h(){for(var I=0,M=0,A=arguments.length;M<A;M++)I+=arguments[M].length;for(var j=Array(I),U=0,M=0;M<A;M++)for(var z=arguments[M],W=0,G=z.length;W<G;W++,U++)j[U]=z[W];return j}function w(I,M,A){if(A||arguments.length===2)for(var j=0,U=M.length,z;j<U;j++)(z||!(j in M))&&(z||(z=Array.prototype.slice.call(M,0,j)),z[j]=M[j]);return I.concat(z||Array.prototype.slice.call(M))}function c(I){return this instanceof c?(this.v=I,this):new c(I)}function u(I,M,A){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var j=A.apply(I,M||[]),U,z=[];return U={},W("next"),W("throw"),W("return"),U[Symbol.asyncIterator]=function(){return this},U;function W(_){j[_]&&(U[_]=function(V){return new Promise(function(Y,X){z.push([_,V,Y,X])>1||G(_,V)})})}function G(_,V){try{F(j[_](V))}catch(Y){B(z[0][3],Y)}}function F(_){_.value instanceof c?Promise.resolve(_.value.v).then(b,L):B(z[0][2],_)}function b(_){G("next",_)}function L(_){G("throw",_)}function B(_,V){_(V),z.shift(),z.length&&G(z[0][0],z[0][1])}}function l(I){var M,A;return M={},j("next"),j("throw",function(U){throw U}),j("return"),M[Symbol.iterator]=function(){return this},M;function j(U,z){M[U]=I[U]?function(W){return(A=!A)?{value:c(I[U](W)),done:U==="return"}:z?z(W):W}:z}}function s(I){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var M=I[Symbol.asyncIterator],A;return M?M.call(I):(I=typeof P=="function"?P(I):I[Symbol.iterator](),A={},j("next"),j("throw"),j("return"),A[Symbol.asyncIterator]=function(){return this},A);function j(z){A[z]=I[z]&&function(W){return new Promise(function(G,F){W=I[z](W),U(G,F,W.done,W.value)})}}function U(z,W,G,F){Promise.resolve(F).then(function(b){z({value:b,done:G})},W)}}function g(I,M){return Object.defineProperty?Object.defineProperty(I,"raw",{value:M}):I.raw=M,I}var p=Object.create?function(I,M){Object.defineProperty(I,"default",{enumerable:!0,value:M})}:function(I,M){I.default=M};function x(I){if(I&&I.__esModule)return I;var M={};if(I!=null)for(var A in I)A!=="default"&&Object.prototype.hasOwnProperty.call(I,A)&&f(M,I,A);return p(M,I),M}function D(I){return I&&I.__esModule?I:{default:I}}function N(I,M,A,j){if(A==="a"&&!j)throw new TypeError("Private accessor was defined without a getter");if(typeof M=="function"?I!==M||!j:!M.has(I))throw new TypeError("Cannot read private member from an object whose class did not declare it");return A==="m"?j:A==="a"?j.call(I):j?j.value:M.get(I)}function k(I,M,A,j,U){if(j==="m")throw new TypeError("Private method is not writable");if(j==="a"&&!U)throw new TypeError("Private accessor was defined without a setter");if(typeof M=="function"?I!==M||!U:!M.has(I))throw new TypeError("Cannot write private member to an object whose class did not declare it");return j==="a"?U.call(I,A):U?U.value=A:M.set(I,A),A}},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0}),r.allToUpperCase=r.allToLowerCase=r.encodeBody=r.decodeBody=r.Format=r.promisify=r.trim=r.arrChooseN=r.randomHexString=r.randomString=r.cheapRandStr=r.dataSizeBytes=r.inspectBody=r.inspectError=r.isErrorInfoOrPartialErrorInfo=r.now=r.parseQueryString=r.toQueryString=r.arrPopRandomElement=r.defaultPostHeaders=r.defaultGetHeaders=r.allSame=r.arrEvery=r.arrFilter=r.arrMap=r.safeArrForEach=r.arrForEach=r.forInOwnNonNullProperties=r.valuesArray=r.keysArray=r.arrWithoutValue=r.arrDeleteValue=r.arrIn=r.arrIndexOf=r.arrSubtract=r.arrIntersectOb=r.arrIntersect=r.intersect=r.containsValue=r.inherits=r.prototypicalClone=r.shallowClone=r.isEmptyArg=r.isOnlyPropIn=r.isEmpty=r.isObject=r.ensureArray=r.isArray=r.copy=r.mixin=void 0,r.arrEquals=r.toBase64=r.matchDerivedChannel=r.shallowEquals=r.getGlobalObject=r.getRetryTime=r.getJitterCoefficient=r.getBackoffCoefficient=void 0;var a=o(0),m=a.__importDefault(o(3)),v=a.__importStar(o(8)),S=a.__importDefault(o(4)),T=o(11),R=o(31);function C(H){return Math.floor(Math.random()*H.length)}function O(H){for(var $=[],K=1;K<arguments.length;K++)$[K-1]=arguments[K];for(var ee=0;ee<$.length;ee++){var ie=$[ee];if(!ie)break;var Ve=Object.prototype.hasOwnProperty;for(var Dr in ie)(!Ve||Ve.call(ie,Dr))&&(H[Dr]=ie[Dr])}return H}r.mixin=O;function f(H){return O({},H)}r.copy=f,r.isArray=Array.isArray||function(H){return Object.prototype.toString.call(H)=="[object Array]"};function E(H){return h(H)?[]:(0,r.isArray)(H)?H:[H]}r.ensureArray=E;function P(H){return Object.prototype.toString.call(H)=="[object Object]"}r.isObject=P;function y(H){for(var $ in H)return!1;return!0}r.isEmpty=y;function d(H,$){for(var K in H)if(K!==$)return!1;return!0}r.isOnlyPropIn=d;function h(H){return H==null}r.isEmptyArg=h;function w(H){var $=new Object;for(var K in H)$[K]=H[K];return $}r.shallowClone=w;function c(H,$){var K=function(){function ie(){}return ie}();K.prototype=H;var ee=new K;return $&&O(ee,$),ee}r.prototypicalClone=c;var u=function(H,$){if(m.default.Config.inherits){m.default.Config.inherits(H,$);return}H.super_=$,H.prototype=c($.prototype,{constructor:H})};r.inherits=u;function l(H,$){for(var K in H)if(H[K]==$)return!0;return!1}r.containsValue=l;function s(H,$){return(0,r.isArray)($)?g(H,$):p(H,$)}r.intersect=s;function g(H,$){for(var K=[],ee=0;ee<H.length;ee++){var ie=H[ee];(0,r.arrIndexOf)($,ie)!=-1&&K.push(ie)}return K}r.arrIntersect=g;function p(H,$){for(var K=[],ee=0;ee<H.length;ee++){var ie=H[ee];ie in $&&K.push(ie)}return K}r.arrIntersectOb=p;function x(H,$){for(var K=[],ee=0;ee<H.length;ee++){var ie=H[ee];(0,r.arrIndexOf)($,ie)==-1&&K.push(ie)}return K}r.arrSubtract=x,r.arrIndexOf=Array.prototype.indexOf?function(H,$,K){return H.indexOf($,K)}:function(H,$,K){K=K||0;for(var ee=H.length;K<ee;K++)if(H[K]===$)return K;return-1};function D(H,$){return(0,r.arrIndexOf)(H,$)!==-1}r.arrIn=D;function N(H,$){var K=(0,r.arrIndexOf)(H,$),ee=K!=-1;return ee&&H.splice(K,1),ee}r.arrDeleteValue=N;function k(H,$){var K=H.slice();return N(K,$),K}r.arrWithoutValue=k;function I(H,$){var K=[];for(var ee in H)$&&!Object.prototype.hasOwnProperty.call(H,ee)||K.push(ee);return K}r.keysArray=I;function M(H,$){var K=[];for(var ee in H)$&&!Object.prototype.hasOwnProperty.call(H,ee)||K.push(H[ee]);return K}r.valuesArray=M;function A(H,$){for(var K in H)Object.prototype.hasOwnProperty.call(H,K)&&H[K]&&$(K)}r.forInOwnNonNullProperties=A,r.arrForEach=Array.prototype.forEach?function(H,$){H.forEach($)}:function(H,$){for(var K=H.length,ee=0;ee<K;ee++)$(H[ee],ee,H)};function j(H,$){return(0,r.arrForEach)(H.slice(),$)}r.safeArrForEach=j,r.arrMap=Array.prototype.map?function(H,$){return H.map($)}:function(H,$){for(var K=[],ee=H.length,ie=0;ie<ee;ie++)K.push($(H[ie],ie,H));return K},r.arrFilter=Array.prototype.filter?function(H,$){return H.filter($)}:function(H,$){for(var K=[],ee=H.length,ie=0;ie<ee;ie++)$(H[ie])&&K.push(H[ie]);return K},r.arrEvery=Array.prototype.every?function(H,$){return H.every($)}:function(H,$){for(var K=H.length,ee=0;ee<K;ee++)if(!$(H[ee],ee,H))return!1;return!0};function U(H,$){if(H.length===0)return!0;var K=H[0][$];return(0,r.arrEvery)(H,function(ee){return ee[$]===K})}r.allSame=U;var z={json:"application/json",jsonp:"application/javascript",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack"};function W(H,$){var K=z[$||he.json];return{accept:K,"X-Ably-Version":v.default.protocolVersion.toString(),"Ably-Agent":(0,v.getAgentString)(H)}}r.defaultGetHeaders=W;function G(H,$){var K,ee=K=z[$||he.json];return{accept:ee,"content-type":K,"X-Ably-Version":v.default.protocolVersion.toString(),"Ably-Agent":(0,v.getAgentString)(H)}}r.defaultPostHeaders=G;function F(H){return H.splice(C(H),1)[0]}r.arrPopRandomElement=F;function b(H){var $=[];if(H)for(var K in H)$.push(encodeURIComponent(K)+"="+encodeURIComponent(H[K]));return $.length?"?"+$.join("&"):""}r.toQueryString=b;function L(H){for(var $,K=/([^?&=]+)=?([^&]*)/g,ee={};$=K.exec(H);)ee[decodeURIComponent($[1])]=decodeURIComponent($[2]);return ee}r.parseQueryString=L,r.now=Date.now||function(){return new Date().getTime()};function B(H){return typeof H=="object"&&H!==null&&(H.constructor.name=="ErrorInfo"||H.constructor.name=="PartialErrorInfo")}r.isErrorInfoOrPartialErrorInfo=B;function _(H){var $,K;return H instanceof Error||(($=H==null?void 0:H.constructor)===null||$===void 0?void 0:$.name)==="ErrorInfo"||((K=H==null?void 0:H.constructor)===null||K===void 0?void 0:K.name)==="PartialErrorInfo"?H.toString():m.default.Config.inspect(H)}r.inspectError=_;function V(H){return m.default.BufferUtils.isBuffer(H)?H.toString():typeof H=="string"?H:m.default.Config.inspect(H)}r.inspectBody=V;function Y(H){if(m.default.BufferUtils.isBuffer(H))return m.default.BufferUtils.byteLength(H);if(typeof H=="string")return m.default.Config.stringByteSize(H);throw new Error("Expected input of Utils.dataSizeBytes to be a buffer or string, but was: "+typeof H)}r.dataSizeBytes=Y;function X(){return String(Math.random()).substr(2)}r.cheapRandStr=X;var te=function(H){if(m.default.Config.getRandomValues&&typeof Uint8Array!="undefined"){var $=new Uint8Array(H);return m.default.Config.getRandomValues($),m.default.BufferUtils.base64Encode($)}for(var K=m.default.BufferUtils.base64CharSet,ee=Math.round(H*4/3),ie="",Ve=0;Ve<ee;Ve++)ie+=K[C(K)];return ie};r.randomString=te;var re=function(H){if(m.default.Config.getRandomValues&&typeof Uint8Array!="undefined"){var $=new Uint8Array(H);return m.default.Config.getRandomValues($),m.default.BufferUtils.hexEncode($)}for(var K=m.default.BufferUtils.hexCharSet,ee=H*2,ie="",Ve=0;Ve<ee;Ve++)ie+=K[C(K)];return ie};r.randomHexString=re;function le(H,$){for(var K=Math.min($,H.length),ee=H.slice(),ie=[],Ve=0;Ve<K;Ve++)ie.push(F(ee));return ie}r.arrChooseN=le,r.trim=String.prototype.trim?function(H){return H.trim()}:function(H){return H.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function Z(H,$,K){return new Promise(function(ee,ie){H[$].apply(H,a.__spreadArray(a.__spreadArray([],K,!1),[function(Ve,Dr){Ve?ie(Ve):ee(Dr)}],!1))})}r.promisify=Z;var he;(function(H){H.msgpack="msgpack",H.json="json"})(he=r.Format||(r.Format={}));function Me(H,$){return $=="msgpack"?m.default.Config.msgpack.decode(H):JSON.parse(String(H))}r.decodeBody=Me;function _e(H,$){return $=="msgpack"?m.default.Config.msgpack.encode(H,!0):JSON.stringify(H)}r.encodeBody=_e;function Ee(H){return H.map(function($){return $&&$.toLowerCase()})}r.allToLowerCase=Ee;function Mt(H){return H.map(function($){return $&&$.toUpperCase()})}r.allToUpperCase=Mt;function qo(H){return Math.min((H+2)/3,2)}r.getBackoffCoefficient=qo;function ft(){return 1-Math.random()*.2}r.getJitterCoefficient=ft;function ei(H,$){return H*qo($)*ft()}r.getRetryTime=ei;function ws(){return i||(typeof window!="undefined"?window:self)}r.getGlobalObject=ws;function Ss(H,$){return Object.keys(H).every(function(K){return H[K]===$[K]})&&Object.keys($).every(function(K){return $[K]===H[K]})}r.shallowEquals=Ss;function sp(H){var $=/^(\[([^?]*)(?:(.*))\])?(.+)$/,K=H.match($);if(!K||!K.length||K.length<5)throw new S.default("regex match failed",400,40010);if(K[2])throw new S.default("cannot use a derived option with a ".concat(K[2]," channel"),400,40010);return{qualifierParam:K[3]||"",channelName:K[4]}}r.matchDerivedChannel=sp;function lp(H){return m.default.Config.createHmac?Buffer.from(H,"ascii").toString("base64"):(0,T.stringify)((0,R.parse)(H))}r.toBase64=lp;function up(H,$){return H.length===$.length&&(0,r.arrEvery)(H,function(K,ee){return K===$[ee]})}r.arrEquals=up}).call(this,o(13))},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importDefault(o(3)),v=i||(typeof window!="undefined"?window:self),S;(function(f){f[f.None=0]="None",f[f.Error=1]="Error",f[f.Major=2]="Major",f[f.Minor=3]="Minor",f[f.Micro=4]="Micro"})(S||(S={}));function T(f,E){return"".concat(f).padStart(E?3:2,"0")}function R(f){return m.default.Config.logTimestamps?function(E){var P=new Date;f(T(P.getHours())+":"+T(P.getMinutes())+":"+T(P.getSeconds())+"."+T(P.getMilliseconds(),1)+" "+E)}:f}var C=function(){var f,E,P,y;return typeof Window=="undefined"&&typeof WorkerGlobalScope=="undefined"||typeof((E=(f=v==null?void 0:v.console)===null||f===void 0?void 0:f.log)===null||E===void 0?void 0:E.apply)=="function"?(P=function(){for(var d=[],h=0;h<arguments.length;h++)d[h]=arguments[h];console.log.apply(console,d)},y=console.warn?function(){for(var d=[],h=0;h<arguments.length;h++)d[h]=arguments[h];console.warn.apply(console,d)}:P):v!=null&&v.console.log?P=y=function(){Function.prototype.apply.call(console.log,console,arguments)}:P=y=function(){},[P,y].map(R)},O=function(){function f(){f.logLevel=f.LOG_DEFAULT}return f.initLogHandlers=function(){var E=C(),P=E[0],y=E[1];this.logHandler=P,this.logErrorHandler=y},f.renamedClientOption=function(E,P){f.deprecationWarning("The `".concat(E,"` client option has been renamed to `").concat(P,"`. Please update your code to use `").concat(P,"` instead. `").concat(E,"` will be removed in a future version."))},f.renamedMethod=function(E,P,y){f.deprecationWarning("`".concat(E,"`’s `").concat(P,"` method has been renamed to `").concat(y,"`. Please update your code to use `").concat(y,"` instead. `").concat(P,"` will be removed in a future version."))},f.deprecationWarning=function(E){f.shouldLog(S.Error)&&f.logErrorHandler("Ably: Deprecation warning - ".concat(E))},f.logLevel=S.Error,f.LOG_NONE=S.None,f.LOG_ERROR=S.Error,f.LOG_MAJOR=S.Major,f.LOG_MINOR=S.Minor,f.LOG_MICRO=S.Micro,f.LOG_DEFAULT=S.Error,f.LOG_DEBUG=S.Micro,f.logAction=function(E,P,y){f.shouldLog(E)&&(E===S.Error?f.logErrorHandler:f.logHandler)("Ably: "+P+": "+y)},f.deprecated=function(E,P){f.deprecationWarning("".concat(E," is deprecated and will be removed in a future version. ").concat(P))},f.shouldLog=function(E){return E<=f.logLevel},f.setLog=function(E,P){E!==void 0&&(f.logLevel=E),P!==void 0&&(f.logHandler=f.logErrorHandler=P)},f}();r.default=O}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function a(){}return a}();r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.PartialErrorInfo=void 0;var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1));function v(R){var C="["+R.constructor.name;return R.message&&(C+=": "+R.message),R.statusCode&&(C+="; statusCode="+R.statusCode),R.code&&(C+="; code="+R.code),R.cause&&(C+="; cause="+m.inspectError(R.cause)),R.href&&!(R.message&&R.message.indexOf("help.ably.io")>-1)&&(C+="; see "+R.href+" "),C+="]",C}var S=function(R){i.__extends(C,R);function C(O,f,E,P){var y=R.call(this,O)||this;return typeof Object.setPrototypeOf!="undefined"&&Object.setPrototypeOf(y,C.prototype),y.code=f,y.statusCode=E,y.cause=P,y}return C.prototype.toString=function(){return v(this)},C.fromValues=function(O){var f=O,E=f.message,P=f.code,y=f.statusCode;if(typeof E!="string"||typeof P!="number"||typeof y!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+a.default.Config.inspect(O));var d=Object.assign(new C(E,P,y),O);return d.code&&!d.href&&(d.href="https://help.ably.io/error/"+d.code),d},C}(Error);r.default=S;var T=function(R){i.__extends(C,R);function C(O,f,E,P){var y=R.call(this,O)||this;return typeof Object.setPrototypeOf!="undefined"&&Object.setPrototypeOf(y,C.prototype),y.code=f,y.statusCode=E,y.cause=P,y}return C.prototype.toString=function(){return v(this)},C}(Error);r.PartialErrorInfo=T},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){if(typeof ArrayBuffer=="function"){var a=i,m=a.lib,v=m.WordArray,S=v.init,T=v.init=function(R){if(R instanceof ArrayBuffer&&(R=new Uint8Array(R)),(R instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&R instanceof Uint8ClampedArray||R instanceof Int16Array||R instanceof Uint16Array||R instanceof Int32Array||R instanceof Uint32Array||R instanceof Float32Array||R instanceof Float64Array)&&(R=new Uint8Array(R.buffer,R.byteOffset,R.byteLength)),R instanceof Uint8Array){for(var C=R.byteLength,O=[],f=0;f<C;f++)O[f>>>2]|=R[f]<<24-f%4*8;S.call(this,O,C)}else S.apply(this,arguments)};T.prototype=v}}(),i.lib.WordArray})},function(n,r,o){(function(i){(function(a,m){n.exports=m()})(this,function(){var a=a||function(m,v){var S;if(typeof window!="undefined"&&window.crypto&&(S=window.crypto),!S&&typeof window!="undefined"&&window.msCrypto&&(S=window.msCrypto),!S&&typeof i!="undefined"&&i.crypto&&(S=i.crypto),!S)try{S=o(44)}catch(u){}var T=function(){if(S){if(typeof S.getRandomValues=="function")try{return S.getRandomValues(new Uint32Array(1))[0]}catch(u){}if(typeof S.randomBytes=="function")try{return S.randomBytes(4).readInt32LE()}catch(u){}}throw new Error("Native crypto module could not be used to get secure random number.")},R=Object.create||function(){function u(){}return function(l){var s;return u.prototype=l,s=new u,u.prototype=null,s}}(),C={},O=C.lib={},f=O.Base=function(){return{extend:function(u){var l=R(this);return u&&l.mixIn(u),(!l.hasOwnProperty("init")||this.init===l.init)&&(l.init=function(){l.$super.init.apply(this,arguments)}),l.init.prototype=l,l.$super=this,l},create:function(){var u=this.extend();return u.init.apply(u,arguments),u},init:function(){},mixIn:function(u){for(var l in u)u.hasOwnProperty(l)&&(this[l]=u[l]);u.hasOwnProperty("toString")&&(this.toString=u.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),E=O.WordArray=f.extend({init:function(u,l){u=this.words=u||[],l!=v?this.sigBytes=l:this.sigBytes=u.length*4},toString:function(u){return(u||y).stringify(this)},concat:function(u){var l=this.words,s=u.words,g=this.sigBytes,p=u.sigBytes;if(this.clamp(),g%4)for(var x=0;x<p;x++){var D=s[x>>>2]>>>24-x%4*8&255;l[g+x>>>2]|=D<<24-(g+x)%4*8}else for(var x=0;x<p;x+=4)l[g+x>>>2]=s[x>>>2];return this.sigBytes+=p,this},clamp:function(){var u=this.words,l=this.sigBytes;u[l>>>2]&=4294967295<<32-l%4*8,u.length=m.ceil(l/4)},clone:function(){var u=f.clone.call(this);return u.words=this.words.slice(0),u},random:function(u){for(var l=[],s=0;s<u;s+=4)l.push(T());return new E.init(l,u)}}),P=C.enc={},y=P.Hex={stringify:function(u){for(var l=u.words,s=u.sigBytes,g=[],p=0;p<s;p++){var x=l[p>>>2]>>>24-p%4*8&255;g.push((x>>>4).toString(16)),g.push((x&15).toString(16))}return g.join("")},parse:function(u){for(var l=u.length,s=[],g=0;g<l;g+=2)s[g>>>3]|=parseInt(u.substr(g,2),16)<<24-g%8*4;return new E.init(s,l/2)}},d=P.Latin1={stringify:function(u){for(var l=u.words,s=u.sigBytes,g=[],p=0;p<s;p++){var x=l[p>>>2]>>>24-p%4*8&255;g.push(String.fromCharCode(x))}return g.join("")},parse:function(u){for(var l=u.length,s=[],g=0;g<l;g++)s[g>>>2]|=(u.charCodeAt(g)&255)<<24-g%4*8;return new E.init(s,l)}},h=P.Utf8={stringify:function(u){try{return decodeURIComponent(escape(d.stringify(u)))}catch(l){throw new Error("Malformed UTF-8 data")}},parse:function(u){return d.parse(unescape(encodeURIComponent(u)))}},w=O.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new E.init,this._nDataBytes=0},_append:function(u){typeof u=="string"&&(u=h.parse(u)),this._data.concat(u),this._nDataBytes+=u.sigBytes},_process:function(u){var l,s=this._data,g=s.words,p=s.sigBytes,x=this.blockSize,D=x*4,N=p/D;u?N=m.ceil(N):N=m.max((N|0)-this._minBufferSize,0);var k=N*x,I=m.min(k*4,p);if(k){for(var M=0;M<k;M+=x)this._doProcessBlock(g,M);l=g.splice(0,k),s.sigBytes-=I}return new E.init(l,I)},clone:function(){var u=f.clone.call(this);return u._data=this._data.clone(),u},_minBufferSize:0});O.Hasher=w.extend({cfg:f.extend(),init:function(u){this.cfg=this.cfg.extend(u),this.reset()},reset:function(){w.reset.call(this),this._doReset()},update:function(u){return this._append(u),this._process(),this},finalize:function(u){u&&this._append(u);var l=this._doFinalize();return l},blockSize:16,_createHelper:function(u){return function(l,s){return new u.init(s).finalize(l)}},_createHmacHelper:function(u){return function(l,s){return new c.HMAC.init(u,s).finalize(l)}}});var c=C.algo={};return C}(Math);return a})}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(2)),v=i.__importDefault(o(3));function S(C,O,f){try{O.apply(C,f)}catch(E){m.default.logAction(m.default.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+E+"; stack = "+(E&&E.stack))}}function T(C,O,f){for(var E,P,y,d=0;d<C.length;d++)if(E=C[d],f&&(E=E[f]),a.isArray(E)){for(;(P=a.arrIndexOf(E,O))!==-1;)E.splice(P,1);f&&E.length===0&&delete C[d][f]}else if(a.isObject(E))for(y in E)Object.prototype.hasOwnProperty.call(E,y)&&a.isArray(E[y])&&T([E],O,y)}var R=function(){function C(){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}return C.prototype.on=function(){for(var O=this,f=[],E=0;E<arguments.length;E++)f[E]=arguments[E];if(f.length===1){var P=f[0];if(typeof P=="function")this.any.push(P);else throw new Error("EventListener.on(): Invalid arguments: "+v.default.Config.inspect(f))}if(f.length===2){var y=f[0],d=f[1];if(typeof d!="function")throw new Error("EventListener.on(): Invalid arguments: "+v.default.Config.inspect(f));if(a.isEmptyArg(y))this.any.push(d);else if(a.isArray(y))y.forEach(function(w){O.on(w,d)});else{if(typeof y!="string")throw new Error("EventListener.on(): Invalid arguments: "+v.default.Config.inspect(f));var h=this.events[y]||(this.events[y]=[]);h.push(d)}}},C.prototype.off=function(){for(var O,f=this,E=[],P=0;P<arguments.length;P++)E[P]=arguments[P];if(E.length==0||a.isEmptyArg(E[0])&&a.isEmptyArg(E[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}var y=E[0],d=E[1],h=null,w=null;if(E.length===1||!d)typeof y=="function"?h=y:w=y;else{if(typeof d!="function")throw new Error("EventEmitter.off(): invalid arguments:"+v.default.Config.inspect(E));O=[y,d],w=O[0],h=O[1]}if(h&&a.isEmptyArg(w)){T([this.any,this.events,this.anyOnce,this.eventsOnce],h);return}if(a.isArray(w)){w.forEach(function(c){f.off(c,h)});return}if(typeof w!="string")throw new Error("EventEmitter.off(): invalid arguments:"+v.default.Config.inspect(E));h?T([this.events,this.eventsOnce],h,w):(delete this.events[w],delete this.eventsOnce[w])},C.prototype.listeners=function(O){if(O){var f=this.events[O]||[];return this.eventsOnce[O]&&Array.prototype.push.apply(f,this.eventsOnce[O]),f.length?f:null}return this.any.length?this.any:null},C.prototype.emit=function(O){for(var f=[],E=1;E<arguments.length;E++)f[E-1]=arguments[E];var P={event:O},y=[];this.anyOnce.length&&(Array.prototype.push.apply(y,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(y,this.any);var d=this.eventsOnce[O];d&&(Array.prototype.push.apply(y,d),delete this.eventsOnce[O]);var h=this.events[O];h&&Array.prototype.push.apply(y,h),a.arrForEach(y,function(w){S(P,w,f)})},C.prototype.once=function(){for(var O=this,f=[],E=0;E<arguments.length;E++)f[E]=arguments[E];var P=f.length;if((P===0||P===1&&typeof f[0]!="function")&&v.default.Config.Promise){var y=f[0];return new v.default.Config.Promise(function(l){O.once(y,l)})}var d=f[0],h=f[1];if(f.length===1&&typeof d=="function")this.anyOnce.push(d);else if(a.isEmptyArg(d)){if(typeof h!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));this.anyOnce.push(h)}else if(a.isArray(d)){var w=this,c=function(){var l=Array.prototype.slice.call(arguments);if(a.arrForEach(d,function(s){w.off(s,c)}),typeof h!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));h.apply(this,l)};a.arrForEach(d,function(l){w.on(l,c)})}else{if(typeof d!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));var u=this.eventsOnce[d]||(this.eventsOnce[d]=[]);if(h){if(typeof h!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+v.default.Config.inspect(f));u.push(h)}}},C.prototype.whenState=function(O,f,E){for(var P=this,y=[],d=3;d<arguments.length;d++)y[d-3]=arguments[d];var h={event:O};if(typeof O!="string"||typeof f!="string")throw"whenState requires a valid event String argument";if(typeof E!="function"&&v.default.Config.Promise)return new v.default.Config.Promise(function(w){C.prototype.whenState.apply(P,[O,f,w].concat(y))});O===f?S(h,E,y):this.once(O,E)},C}();r.default=R},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.getDefaults=r.normaliseOptions=r.objectifyOptions=r.getAgentString=r.getHosts=r.getFallbackHosts=r.environmentFallbackHosts=r.getHttpScheme=r.getPort=r.getHost=void 0;var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1)),v=i.__importDefault(o(2)),S=i.__importDefault(o(4)),T=o(43),R="ably-js/"+T.version,C={ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,preferenceConnectTimeout:6e3,parallelUpgradeDelay:6e3},httpMaxRetryCount:3,maxMessageSize:65536,version:T.version,protocolVersion:2,agent:R,getHost:O,getPort:f,getHttpScheme:E,environmentFallbackHosts:P,getFallbackHosts:y,getHosts:d,checkHost:h,objectifyOptions:l,normaliseOptions:s};function O(p,x,D){return D?x=x==p.restHost&&p.realtimeHost||x||p.realtimeHost:x=x||p.restHost,x}r.getHost=O;function f(p,x){return x||p.tls?p.tlsPort:p.port}r.getPort=f;function E(p){return p.tls?"https://":"http://"}r.getHttpScheme=E;function P(p){return[p+"-a-fallback.ably-realtime.com",p+"-b-fallback.ably-realtime.com",p+"-c-fallback.ably-realtime.com",p+"-d-fallback.ably-realtime.com",p+"-e-fallback.ably-realtime.com"]}r.environmentFallbackHosts=P;function y(p){var x=p.fallbackHosts,D=typeof p.httpMaxRetryCount!="undefined"?p.httpMaxRetryCount:C.httpMaxRetryCount;return x?m.arrChooseN(x,D):[]}r.getFallbackHosts=y;function d(p){return[p.restHost].concat(y(p))}r.getHosts=d;function h(p){if(typeof p!="string")throw new S.default("host must be a string; was a "+typeof p,4e4,400);if(!p.length)throw new S.default("host must not be zero-length",4e4,400)}function w(p,x,D){return p.realtimeHost?p.realtimeHost:p.restHost?(v.default.logAction(v.default.LOG_MINOR,"Defaults.normaliseOptions",'restHost is set to "'+p.restHost+'" but realtimeHost is not set, so setting realtimeHost to "'+p.restHost+'" too. If this is not what you want, please set realtimeHost explicitly.'),p.restHost):x?C.REALTIME_HOST:D+"-"+C.REALTIME_HOST}function c(p){var x={};for(var D in C.TIMEOUTS)x[D]=p[D]||C.TIMEOUTS[D];return x}function u(p){var x=C.agent;if(p.agents)for(var D in p.agents)x+=" "+D+"/"+p.agents[D];return x}r.getAgentString=u;function l(p){return typeof p=="string"?p.indexOf(":")==-1?{token:p}:{key:p}:p}r.objectifyOptions=l;function s(p){if(p.host&&(v.default.renamedClientOption("host","restHost"),p.restHost=p.host),p.wsHost&&(v.default.renamedClientOption("wsHost","realtimeHost"),p.realtimeHost=p.wsHost),p.queueEvents&&(v.default.renamedClientOption("queueEvents","queueMessages"),p.queueMessages=p.queueEvents),p.headers&&v.default.deprecated("the `headers` client option",""),p.fallbackHostsUseDefault){if(p.fallbackHosts){var x="fallbackHosts and fallbackHostsUseDefault cannot both be set";throw v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions",x),new S.default(x,4e4,400)}if(p.port||p.tlsPort){var x="fallbackHostsUseDefault cannot be set when port or tlsPort are set";throw v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions",x),new S.default(x,4e4,400)}p.environment?v.default.deprecated("The `fallbackHostsUseDefault` client option","If you’re using this client option to force the library to make use of fallback hosts even though you’ve set the `environment` client option, then this is no longer necessary: remove your usage of the `fallbackHostsUseDefault` client option and the library will then automatically choose the correct fallback hosts to use for the specified environment."):v.default.deprecated("The `fallbackHostsUseDefault` client option","If you’re using this client option to force the library to make use of fallback hosts even though you’re not using the primary Ably environment, then stop using `fallbackHostsUseDefault`, and update your code to either pass the `environment` client option (in which case the library will automatically choose the correct fallback hosts to use for the specified environment), or to pass the `fallbackHosts` client option to specify a custom list of fallback hosts to use (for example, if you’re using a custom CNAME, in which case Ably will have provided you with an explicit list of fallback hosts)."),p.fallbackHosts=C.FALLBACK_HOSTS}p.recover===!0&&(v.default.deprecated("The ability to use a boolean value for the `recover` client option","If you wish for the connection to always be recovered, replace `{ recover: true }` with a function that always passes `true` to its callback: `{ recover: function(lastConnectionDetails, cb) { cb(true); } }`"),p.recover=function(F,b){b(!0)}),typeof p.recover=="function"&&p.closeOnUnload===!0&&(v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),p.recover=void 0),"closeOnUnload"in p||(p.closeOnUnload=!p.recover),p.transports&&m.arrIn(p.transports,"xhr")&&(v.default.deprecationWarning('The "xhr" transport has been renamed to "xhr_streaming". Please update your client options code to use `transports: ["xhr_streaming"]` instead. The ability to use `transports: ["xhr"]` will be removed in a future version.'),m.arrDeleteValue(p.transports,"xhr"),p.transports.push("xhr_streaming")),"queueMessages"in p||(p.queueMessages=!0);var D=p.environment&&String(p.environment).toLowerCase()||C.ENVIRONMENT,N=!D||D==="production";!p.fallbackHosts&&!p.restHost&&!p.realtimeHost&&!p.port&&!p.tlsPort&&(p.fallbackHosts=N?C.FALLBACK_HOSTS:P(D));var k=p.restHost||(N?C.REST_HOST:D+"-"+C.REST_HOST),I=w(p,N,D);m.arrForEach((p.fallbackHosts||[]).concat(k,I),h),p.port=p.port||C.PORT,p.tlsPort=p.tlsPort||C.TLS_PORT,"tls"in p||(p.tls=!0);var M=c(p);if("useBinaryProtocol"in p?p.useBinaryProtocol=a.default.Config.supportsBinary&&p.useBinaryProtocol:p.useBinaryProtocol=a.default.Config.preferBinary,p.clientId){var A=p.headers=p.headers||{};A["X-Ably-ClientId"]=a.default.BufferUtils.base64Encode(a.default.BufferUtils.utf8Encode(p.clientId))}"idempotentRestPublishing"in p||(p.idempotentRestPublishing=!0),p.promises&&!a.default.Config.Promise&&(v.default.logAction(v.default.LOG_ERROR,"Defaults.normaliseOptions","{promises: true} was specified, but no Promise constructor found; disabling promises"),p.promises=!1);var j=null,U=p.connectivityCheckUrl;if(p.connectivityCheckUrl){var z=p.connectivityCheckUrl.split("?"),W=z[0],G=z[1];j=G?m.parseQueryString(G):{},W.indexOf("://")===-1&&(W="https://"+W),U=W}return i.__assign(i.__assign({},p),{useBinaryProtocol:"useBinaryProtocol"in p?a.default.Config.supportsBinary&&p.useBinaryProtocol:a.default.Config.preferBinary,realtimeHost:I,restHost:k,maxMessageSize:p.maxMessageSize||C.maxMessageSize,timeouts:M,connectivityCheckParams:j,connectivityCheckUrl:U})}r.normaliseOptions=s,r.default=C;function g(p){return Object.assign(C,p)}r.getDefaults=g},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(3)),m=i.__importDefault(o(2)),v=i.__importDefault(o(4)),S=i.__importStar(o(1));function T(f){return!f||!f.channelOptions?{channelOptions:f,plugins:{},baseEncodedPreviousPayload:void 0}:f}function R(f){if(f&&f.cipher){if(!a.default.Crypto)throw new Error("Encryption not enabled; use ably.encryption.js instead");var E=a.default.Crypto.getCipher(f.cipher);return{cipher:E.cipherParams,channelCipher:E.cipher}}return f!=null?f:{}}function C(f){var E=0;return f.name&&(E+=f.name.length),f.clientId&&(E+=f.clientId.length),f.extras&&(E+=JSON.stringify(f.extras).length),f.data&&(E+=S.dataSizeBytes(f.data)),E}var O=function(){function f(){}return f.prototype.toJSON=function(){var E=this.encoding,P=this.data;return P&&a.default.BufferUtils.isBuffer(P)&&(arguments.length>0?(E=E?E+"/base64":"base64",P=a.default.BufferUtils.base64Encode(P)):P=a.default.BufferUtils.toBuffer(P)),{name:this.name,id:this.id,clientId:this.clientId,connectionId:this.connectionId,connectionKey:this.connectionKey,extras:this.extras,encoding:E,data:P}},f.prototype.toString=function(){var E="[Message";return this.name&&(E+="; name="+this.name),this.id&&(E+="; id="+this.id),this.timestamp&&(E+="; timestamp="+this.timestamp),this.clientId&&(E+="; clientId="+this.clientId),this.connectionId&&(E+="; connectionId="+this.connectionId),this.encoding&&(E+="; encoding="+this.encoding),this.extras&&(E+="; extras ="+JSON.stringify(this.extras)),this.data&&(typeof this.data=="string"?E+="; data="+this.data:a.default.BufferUtils.isBuffer(this.data)?E+="; data (buffer)="+a.default.BufferUtils.base64Encode(this.data):E+="; data (json)="+JSON.stringify(this.data)),this.extras&&(E+="; extras="+JSON.stringify(this.extras)),E+="]",E},f.encrypt=function(E,P,y){var d=E.data,h=E.encoding,w=P.channelCipher;h=h?h+"/":"",a.default.BufferUtils.isBuffer(d)||(d=a.default.BufferUtils.utf8Encode(String(d)),h=h+"utf-8/"),w.encrypt(d,function(c,u){if(c){y(c);return}E.data=u,E.encoding=h+"cipher+"+w.algorithm,y(null,E)})},f.encode=function(E,P,y){var d=E.data,h=typeof d=="string"||a.default.BufferUtils.isBuffer(d)||d===null||d===void 0;if(!h)if(S.isObject(d)||S.isArray(d))E.data=JSON.stringify(d),E.encoding=E.encoding?E.encoding+"/json":"json";else throw new v.default("Data type is unsupported",40013,400);P!=null&&P.cipher?f.encrypt(E,P,y):y(null,E)},f.encodeArray=function(E,P,y){for(var d=0,h=0;h<E.length;h++)f.encode(E[h],P,function(w){if(w){y(w);return}d++,d==E.length&&y(null,E)})},f.decode=function(E,P){var y=T(P),d=E.data,h=E.encoding;if(h){var w=h.split("/"),c=void 0,u=w.length,l=E.data,s="";try{for(;(c=u)>0;){var g=w[--u].match(/([-\w]+)(\+([\w-]+))?/);if(!g)break;switch(s=g[1],s){case"base64":l=a.default.BufferUtils.base64Decode(String(l)),c==w.length&&(d=l);continue;case"utf-8":l=a.default.BufferUtils.utf8Decode(l);continue;case"json":l=JSON.parse(l);continue;case"cipher":if(y.channelOptions!=null&&y.channelOptions.cipher&&y.channelOptions.channelCipher){var p=g[3],x=y.channelOptions.channelCipher;if(p!=x.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");l=x.decrypt(l);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!y.plugins||!y.plugins.vcdiff)throw new v.default("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array=="undefined")throw new v.default("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var D=y.baseEncodedPreviousPayload;typeof D=="string"&&(D=a.default.BufferUtils.utf8Encode(D)),D=a.default.BufferUtils.toBuffer(D),l=a.default.BufferUtils.toBuffer(l),l=a.default.BufferUtils.typedArrayToBuffer(y.plugins.vcdiff.decode(l,D)),d=l}catch(k){throw new v.default("Vcdiff delta decode failed with "+k,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(k){var N=k;throw new v.default("Error processing the "+s+" encoding, decoder returned ‘"+N.message+"’",N.code||40013,400)}finally{E.encoding=c<=0?null:w.slice(0,c).join("/"),E.data=l}}y.baseEncodedPreviousPayload=d},f.fromResponseBody=function(E,P,y){y&&(E=S.decodeBody(E,y));for(var d=0;d<E.length;d++){var h=E[d]=f.fromValues(E[d]);try{f.decode(h,P)}catch(w){m.default.logAction(m.default.LOG_ERROR,"Message.fromResponseBody()",w.toString())}}return E},f.fromValues=function(E){return Object.assign(new f,E)},f.fromValuesArray=function(E){for(var P=E.length,y=new Array(P),d=0;d<P;d++)y[d]=f.fromValues(E[d]);return y},f.fromEncoded=function(E,P){var y=f.fromValues(E),d=R(P!=null?P:null);try{f.decode(y,d)}catch(h){m.default.logAction(m.default.LOG_ERROR,"Message.fromEncoded()",h.toString())}return y},f.fromEncodedArray=function(E,P){return E.map(function(y){return f.fromEncoded(y,P)})},f.getMessagesSize=function(E){for(var P,y=0,d=0;d<E.length;d++)P=E[d],y+=P.size||(P.size=C(P));return y},f.serialize=S.encodeBody,f}();r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(4)),v=i.__importDefault(o(9)),S=i.__importDefault(o(16)),T={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18},R=[];Object.keys(T).forEach(function(y){R[T[y]]=y});var C={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19},O=Object.keys(C);C.MODE_ALL=C.PRESENCE|C.PUBLISH|C.SUBSCRIBE|C.PRESENCE_SUBSCRIBE;function f(y){var d=[];if(y)for(var h=0;h<y.length;h++)d.push(y[h].toString());return"[ "+d.join(", ")+" ]"}var E="id channel channelSerial connectionId count msgSerial timestamp".split(" "),P=function(){function y(){var d=this;this.hasFlag=function(h){return(d.flags&C[h])>0}}return y.prototype.setFlag=function(d){return this.flags=this.flags|C[d]},y.prototype.getMode=function(){return this.flags&&this.flags&C.MODE_ALL},y.prototype.encodeModesToFlags=function(d){var h=this;d.forEach(function(w){return h.setFlag(w)})},y.prototype.decodeModesFromFlags=function(){var d=this,h=[];return y.channelModes.forEach(function(w){d.hasFlag(w)&&h.push(w)}),h.length>0?h:void 0},y.fromValues=function(d){return Object.assign(new y,d)},y.Action=T,y.channelModes=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE"],y.ActionName=R,y.serialize=a.encodeBody,y.deserialize=function(d,h){var w=a.decodeBody(d,h);return y.fromDeserialized(w)},y.fromDeserialized=function(d){var h=d.error;h&&(d.error=m.default.fromValues(h));var w=d.messages;if(w)for(var c=0;c<w.length;c++)w[c]=v.default.fromValues(w[c]);var u=d.presence;if(u)for(var c=0;c<u.length;c++)u[c]=S.default.fromValues(u[c],!0);return Object.assign(new y,d)},y.stringify=function(d){var h="[ProtocolMessage";d.action!==void 0&&(h+="; action="+y.ActionName[d.action]||!1);for(var w,c=0;c<E.length;c++)w=E[c],d[w]!==void 0&&(h+="; "+w+"="+d[w]);if(d.messages&&(h+="; messages="+f(v.default.fromValuesArray(d.messages))),d.presence&&(h+="; presence="+f(S.default.fromValuesArray(d.presence))),d.error&&(h+="; error="+m.default.fromValues(d.error).toString()),d.auth&&d.auth.accessToken&&(h+="; token="+d.auth.accessToken),d.flags&&(h+="; flags="+O.filter(d.hasFlag).join(",")),d.params){var u="";a.forInOwnNonNullProperties(d.params,function(l){u.length>0&&(u+="; "),u+=l+"="+d.params[l]}),u.length>0&&(h+="; params=["+u+"]")}return h+="]",h},y}();r.default=P},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){var a=i,m=a.lib,v=m.WordArray,S=a.enc;S.Base64={stringify:function(R){var C=R.words,O=R.sigBytes,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";R.clamp();for(var E=[],P=0;P<O;P+=3)for(var y=C[P>>>2]>>>24-P%4*8&255,d=C[P+1>>>2]>>>24-(P+1)%4*8&255,h=C[P+2>>>2]>>>24-(P+2)%4*8&255,w=y<<16|d<<8|h,c=0;c<4&&P+c*.75<O;c++)E.push(f.charAt(w>>>6*(3-c)&63));var u=f.charAt(64);if(u)for(;E.length%4;)E.push(u);return E.join("")},parse:function(R){var C=R.length,O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=this._reverseMap;if(!f){f=this._reverseMap=[];for(var E=0;E<O.length;E++)f[O.charCodeAt(E)]=E}var P=O.charAt(64);if(P){var y=R.indexOf(P);y!==-1&&(C=y)}return T(R,C,f)}};function T(R,C,O){for(var f=[],E=0,P=0;P<C;P++)if(P%4){var y=O[R.charCodeAt(P-1)]<<P%4*2,d=O[R.charCodeAt(P)]>>>6-P%4*2,h=y|d;f[E>>>2]|=h<<24-E%4*8,E++}return v.create(f,E)}}(),i.enc.Base64})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(10)),v=i.__importDefault(o(26)),S=i.__importDefault(o(2)),T=i.__importDefault(o(8)),R=i.__importDefault(o(21)),C=i.__importDefault(o(18)),O=i.__importDefault(o(4)),f=i.__importDefault(o(22)),E=i.__importDefault(o(3));function P(h){var w=[80015,80017,80030];return h.code?C.default.isTokenErr(h)?!1:a.arrIn(w,h.code)?!0:h.code>=4e4&&h.code<5e4:!1}function y(h){return P(h)?[m.default.fromValues({action:m.default.Action.ERROR,error:h})]:[m.default.fromValues({action:m.default.Action.DISCONNECTED,error:h})]}var d=function(h){i.__extends(w,h);function w(c,u,l){var s=h.call(this,c,u,l,!0)||this;return s.onAuthUpdated=function(g){s.authParams={access_token:g.token}},s.stream="stream"in l?l.stream:!0,s.sendRequest=null,s.recvRequest=null,s.pendingCallback=null,s.pendingItems=null,s}return w.prototype.connect=function(){var c=this;S.default.logAction(S.default.LOG_MINOR,"CometTransport.connect()","starting"),v.default.prototype.connect.call(this);var u=this.params,l=u.options,s=T.default.getHost(l,u.host),g=T.default.getPort(l),p=l.tls?"https://":"http://";this.baseUri=p+s+":"+g+"/comet/";var x=this.baseUri+"connect";S.default.logAction(S.default.LOG_MINOR,"CometTransport.connect()","uri: "+x),this.auth.getAuthParams(function(D,N){if(D){c.disconnect(D);return}if(!c.isDisposed){c.authParams=N;var k=c.params.getConnectParams(N);"stream"in k&&(c.stream=k.stream),S.default.logAction(S.default.LOG_MINOR,"CometTransport.connect()","connectParams:"+a.toQueryString(k));var I=!1,M=c.recvRequest=c.createRequest(x,null,k,null,c.stream?f.default.REQ_RECV_STREAM:f.default.REQ_RECV);M.on("data",function(A){c.recvRequest&&(I||(I=!0,c.emit("preconnect")),c.onData(A))}),M.on("complete",function(A){if(c.recvRequest||(A=A||new O.default("Request cancelled",80003,400)),c.recvRequest=null,!I&&!A&&(I=!0,c.emit("preconnect")),c.onActivity(),A){A.code?c.onData(y(A)):c.disconnect(A);return}E.default.Config.nextTick(function(){c.recv()})}),M.exec()}})},w.prototype.requestClose=function(){S.default.logAction(S.default.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)},w.prototype.requestDisconnect=function(){S.default.logAction(S.default.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)},w.prototype._requestCloseOrDisconnect=function(c){var u=this,l=c?this.closeUri:this.disconnectUri;if(l){var s=this.createRequest(l,null,this.authParams,null,f.default.REQ_SEND);s.on("complete",function(g){g&&(S.default.logAction(S.default.LOG_ERROR,"CometTransport.request"+(c?"Close()":"Disconnect()"),"request returned err = "+a.inspectError(g)),u.finish("disconnected",g))}),s.exec()}},w.prototype.dispose=function(){var c=this;S.default.logAction(S.default.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(S.default.logAction(S.default.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",R.default.disconnected()),E.default.Config.nextTick(function(){c.emit("disposed")}))},w.prototype.onConnect=function(c){var u;if(!this.isDisposed){var l=(u=c.connectionDetails)===null||u===void 0?void 0:u.connectionKey;v.default.prototype.onConnect.call(this,c);var s=this.baseUri+l;S.default.logAction(S.default.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+s),this.sendUri=s+"/send",this.recvUri=s+"/recv",this.closeUri=s+"/close",this.disconnectUri=s+"/disconnect"}},w.prototype.send=function(c){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(c);return}var u=this.pendingItems||[];u.push(c),this.pendingItems=null,this.sendItems(u)},w.prototype.sendAnyPending=function(){var c=this.pendingItems;c&&(this.pendingItems=null,this.sendItems(c))},w.prototype.sendItems=function(c){var u=this,l=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(c),f.default.REQ_SEND);l.on("complete",function(s,g){if(s&&S.default.logAction(S.default.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+a.inspectError(s)),u.sendRequest=null,s){s.code?u.onData(y(s)):u.disconnect(s);return}g&&u.onData(g),u.pendingItems&&E.default.Config.nextTick(function(){u.sendRequest||u.sendAnyPending()})}),l.exec()},w.prototype.recv=function(){var c=this;if(!this.recvRequest&&this.isConnected){var u=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?f.default.REQ_RECV_STREAM:f.default.REQ_RECV_POLL);u.on("data",function(l){c.onData(l)}),u.on("complete",function(l){if(c.recvRequest=null,c.onActivity(),l){l.code?c.onData(y(l)):c.disconnect(l);return}E.default.Config.nextTick(function(){c.recv()})}),u.exec()}},w.prototype.onData=function(c){try{var u=this.decodeResponse(c);if(u&&u.length)for(var l=0;l<u.length;l++)this.onProtocolMessage(m.default.fromDeserialized(u[l]))}catch(s){S.default.logAction(S.default.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+s.stack)}},w.prototype.encodeRequest=function(c){return JSON.stringify(c)},w.prototype.decodeResponse=function(c){return typeof c=="string"?JSON.parse(c):c},w}(v.default);r.default=d},function(n,r){var o;o=function(){return this}();try{o=o||new Function("return this")()}catch(i){typeof window=="object"&&(o=window)}n.exports=o},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.isSuccessCode=void 0;var i;(function(m){m[m.Success=200]="Success",m[m.NoContent=204]="NoContent",m[m.BadRequest=400]="BadRequest",m[m.Unauthorized=401]="Unauthorized",m[m.Forbidden=403]="Forbidden",m[m.RequestTimeout=408]="RequestTimeout",m[m.InternalServerError=500]="InternalServerError"})(i||(i={}));function a(m){return m>=i.Success&&m<i.BadRequest}r.isSuccessCode=a,r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1)),v=i.__importDefault(o(2)),S=i.__importDefault(o(18)),T=i.__importDefault(o(19)),R=o(4),C=i.__importDefault(o(14));function O(h,w,c,u,l){h.http.supportsAuthHeaders?h.auth.getAuthHeaders(function(s,g){s?u(s):l(m.mixin(g,w),c)}):h.auth.getAuthParams(function(s,g){s?u(s):l(w,m.mixin(g,c))})}function f(h,w){return function(c,u,l,s,g){if(c&&!u){h(c);return}if(g===C.default.NoContent){h(c,[],l,!0,g);return}if(!s)try{u=m.decodeBody(u,w)}catch(I){m.isErrorInfoOrPartialErrorInfo(I)?h(I):h(new R.PartialErrorInfo(m.inspectError(I),null));return}if(!u){h(new R.PartialErrorInfo("unenvelope(): Response body is missing",null));return}var p=u,x=p.statusCode,D=p.response,N=p.headers;if(x===void 0){h(c,u,l,!0,g);return}if(x<200||x>=300){var k=D&&D.error||c;k||(k=new Error("Error in unenveloping "+u),k.statusCode=x),h(k,D,N,!0,x);return}h(c,D,N,!0,x)}}function E(h){var w=[];if(h)for(var c in h)w.push(c+"="+h[c]);return w.join("&")}function P(h,w){return h+(w?"?":"")+E(w)}function y(h,w,c,u){return function(l,s,g,p,x){l?v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Received Error; "+P(c,u)+"; Error: "+m.inspectError(l)):v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Received; "+P(c,u)+"; Headers: "+E(g)+"; StatusCode: "+x+"; Body: "+(a.default.BufferUtils.isBuffer(s)?s.toString():s)),h&&h(l,s,g,p,x)}}var d=function(){function h(){}return h.get=function(w,c,u,l,s,g){h.do(T.default.Get,w,c,null,u,l,s,g)},h.delete=function(w,c,u,l,s,g){h.do(T.default.Delete,w,c,null,u,l,s,g)},h.post=function(w,c,u,l,s,g,p){h.do(T.default.Post,w,c,u,l,s,g,p)},h.patch=function(w,c,u,l,s,g,p){h.do(T.default.Patch,w,c,u,l,s,g,p)},h.put=function(w,c,u,l,s,g,p){h.do(T.default.Put,w,c,u,l,s,g,p)},h.do=function(w,c,u,l,s,g,p,x){v.default.shouldLog(v.default.LOG_MICRO)&&(x=y(x,w,u,g)),p&&(x=x&&f(x,p),(g=g||{}).envelope=p);function D(N,k){var I;if(v.default.shouldLog(v.default.LOG_MICRO)&&v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Sending; "+P(u,k)),v.default.shouldLog(v.default.LOG_MICRO)){var M=l;if(((I=N["content-type"])===null||I===void 0?void 0:I.indexOf("msgpack"))>0)try{M=a.default.Config.msgpack.decode(l)}catch(A){v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Sending MsgPack Decoding Error: "+m.inspectError(A))}v.default.logAction(v.default.LOG_MICRO,"Resource."+w+"()","Sending; "+P(u,k)+"; Body: "+M)}c.http.do(w,c,u,N,l,k,function(A,j,U,z,W){if(A&&S.default.isTokenErr(A)){c.auth.authorize(null,null,function(G){if(G){x(G);return}O(c,N,k,x,D)});return}x(A,j,U,z,W)})}O(c,s,g,x,D)},h}();r.default=d},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(2)),m=i.__importDefault(o(3)),v=i.__importDefault(o(9)),S=i.__importStar(o(1));function T(C){return R.Actions.indexOf(C)}var R=function(){function C(){}return C.prototype.isSynthesized=function(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId},C.prototype.parseId=function(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");var O=this.id.split(":");return{connectionId:O[0],msgSerial:parseInt(O[1],10),index:parseInt(O[2],10)}},C.prototype.toJSON=function(){var O=this.data,f=this.encoding;return O&&m.default.BufferUtils.isBuffer(O)&&(arguments.length>0?(f=f?f+"/base64":"base64",O=m.default.BufferUtils.base64Encode(O)):O=m.default.BufferUtils.toBuffer(O)),{id:this.id,clientId:this.clientId,action:T(this.action),data:O,encoding:f,extras:this.extras}},C.prototype.toString=function(){var O="[PresenceMessage";return O+="; action="+this.action,this.id&&(O+="; id="+this.id),this.timestamp&&(O+="; timestamp="+this.timestamp),this.clientId&&(O+="; clientId="+this.clientId),this.connectionId&&(O+="; connectionId="+this.connectionId),this.encoding&&(O+="; encoding="+this.encoding),this.data&&(typeof this.data=="string"?O+="; data="+this.data:m.default.BufferUtils.isBuffer(this.data)?O+="; data (buffer)="+m.default.BufferUtils.base64Encode(this.data):O+="; data (json)="+JSON.stringify(this.data)),this.extras&&(O+="; extras="+JSON.stringify(this.extras)),O+="]",O},C.fromResponseBody=function(O,f,E){var P=[];E&&(O=S.decodeBody(O,E));for(var y=0;y<O.length;y++){var d=P[y]=C.fromValues(O[y],!0);try{C.decode(d,f)}catch(h){a.default.logAction(a.default.LOG_ERROR,"PresenceMessage.fromResponseBody()",h.toString())}}return P},C.fromValues=function(O,f){return f&&(O.action=C.Actions[O.action]),Object.assign(new C,O)},C.fromValuesArray=function(O){for(var f=O.length,E=new Array(f),P=0;P<f;P++)E[P]=C.fromValues(O[P]);return E},C.fromEncoded=function(O,f){var E=C.fromValues(O,!0);try{C.decode(E,f!=null?f:{})}catch(P){a.default.logAction(a.default.LOG_ERROR,"PresenceMessage.fromEncoded()",P.toString())}return E},C.fromEncodedArray=function(O,f){return O.map(function(E){return C.fromEncoded(E,f)})},C.fromData=function(O){return O instanceof C?O:C.fromValues({data:O})},C.Actions=["absent","present","enter","leave","update"],C.encode=v.default.encode,C.decode=v.default.decode,C.getMessagesSize=v.default.getMessagesSize,C}();r.default=R},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importStar(o(1)),v=a.__importDefault(o(7)),S=a.__importStar(o(4)),T=a.__importDefault(o(2)),R=a.__importDefault(o(8)),C=a.__importDefault(o(22)),O=a.__importDefault(o(3));function f(p,x){return m.arrIn(m.allToLowerCase(m.keysArray(x)),"x-ably-errorcode")}function E(p,x){if(f(p,x))return p.error&&S.default.fromValues(p.error)}var P=function(){},y=0,d={},h=typeof i!="undefined"&&i.XDomainRequest;function w(){var p=navigator.userAgent.toString().match(/MSIE\s([\d.]+)/);return p&&Number(p[1])}function c(){var p;return h&&(p=w())&&p===10}function u(p,x){return p.getResponseHeader&&p.getResponseHeader(x)}function l(p){return p.getResponseHeader&&(p.getResponseHeader("transfer-encoding")||!p.getResponseHeader("content-length"))}function s(p){for(var x=m.trim(p.getAllResponseHeaders()).split(`\r
83
+ `),D={},N=0;N<x.length;N++){var k=x[N].split(":").map(m.trim);D[k[0].toLowerCase()]=k[1]}return D}var g=function(p){a.__extends(x,p);function x(D,N,k,I,M,A,j){var U=p.call(this)||this;return k=k||{},k.rnd=m.cheapRandStr(),c()&&!k.envelope&&(k.envelope="json"),U.uri=D+m.toQueryString(k),U.headers=N||{},U.body=I,U.method=j?j.toUpperCase():m.isEmptyArg(I)?"GET":"POST",U.requestMode=M,U.timeouts=A,U.timedOut=!1,U.requestComplete=!1,U.id=String(++y),d[U.id]=U,U}return x.createRequest=function(D,N,k,I,M,A,j){var U=A||R.default.TIMEOUTS;return new x(D,N,m.copy(k),I,M,U,j)},x.prototype.complete=function(D,N,k,I,M){this.requestComplete||(this.requestComplete=!0,!D&&N&&this.emit("data",N),this.emit("complete",D,N,k,I,M),this.dispose())},x.prototype.abort=function(){this.dispose()},x.prototype.exec=function(){var D=this,N=this.headers,k=this.requestMode==C.default.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,I=this.timer=setTimeout(function(){D.timedOut=!0,A.abort()},k),M=this.method,A=this.xhr=new XMLHttpRequest,j=N.accept,U=this.body,z="text";if(j?j.indexOf("application/x-msgpack")===0&&(z="arraybuffer"):N.accept="application/json",U){var W=N["content-type"]||(N["content-type"]="application/json");W.indexOf("application/json")>-1&&typeof U!="string"&&(U=JSON.stringify(U))}A.open(M,this.uri,!0),A.responseType=z,"authorization"in N&&(A.withCredentials=!0);for(var G in N)A.setRequestHeader(G,N[G]);var F=function(Z,he,Me,_e){var Ee,Mt=he+" (event type: "+Z.type+")";!((Ee=D==null?void 0:D.xhr)===null||Ee===void 0)&&Ee.statusText&&(Mt+=", current statusText is "+D.xhr.statusText),T.default.logAction(T.default.LOG_ERROR,"Request.on"+Z.type+"()",Mt),D.complete(new S.PartialErrorInfo(Mt,Me,_e))};A.onerror=function(Z){F(Z,"XHR error occurred",null,400)},A.onabort=function(Z){D.timedOut?F(Z,"Request aborted due to request timeout expiring",null,408):F(Z,"Request cancelled",null,400)},A.ontimeout=function(Z){F(Z,"Request timed out",null,408)};var b,L,B,_=0,V=!1,Y=function(){if(clearTimeout(I),B=L<400,L==204){D.complete(null,null,null,null,L);return}b=D.requestMode==C.default.REQ_RECV_STREAM&&B&&l(A)},X=function(){var Z;try{var he=u(A,"content-type"),Me=he?he.indexOf("application/json")>=0:A.responseType=="text";if(Me){var _e=A.responseType==="arraybuffer"?O.default.BufferUtils.utf8Decode(A.response):String(A.responseText);_e.length?Z=JSON.parse(_e):Z=_e,V=!0}else Z=A.response;Z.response!==void 0?(L=Z.statusCode,B=L<400,N=Z.headers,Z=Z.response):N=s(A)}catch(Mt){D.complete(new S.PartialErrorInfo("Malformed response body from server: "+Mt.message,null,400));return}if(B||m.isArray(Z)){D.complete(null,Z,N,V,L);return}var Ee=E(Z,N);Ee||(Ee=new S.PartialErrorInfo("Error response received from server: "+L+" body was: "+O.default.Config.inspect(Z),null,L)),D.complete(Ee,Z,N,V,L)};function te(){for(var Z=A.responseText,he=Z.length-1,Me,_e;_<he&&(Me=Z.indexOf(`
84
+ `,_))>-1;)_e=Z.slice(_,Me),_=Me+1,re(_e)}var re=function(Z){try{Z=JSON.parse(Z)}catch(he){D.complete(new S.PartialErrorInfo("Malformed response body from server: "+he.message,null,400));return}D.emit("data",Z)},le=function(){te(),D.streamComplete=!0,O.default.Config.nextTick(function(){D.complete()})};A.onreadystatechange=function(){var Z=A.readyState;Z<3||A.status!==0&&(L===void 0&&(L=A.status,L===1223&&(L=204),Y()),Z==3&&b?te():Z==4&&(b?le():X()))},A.send(U)},x.prototype.dispose=function(){var D=this.xhr;if(D){D.onreadystatechange=D.onerror=D.onabort=D.ontimeout=P,this.xhr=null;var N=this.timer;N&&(clearTimeout(N),this.timer=null),this.requestComplete||D.abort()}delete d[this.id]},x}(v.default);r.default=g}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(2)),m=i.__importStar(o(1)),v=i.__importDefault(o(24)),S=i.__importDefault(o(4)),T=i.__importDefault(o(45)),R=o(11),C=i.__importDefault(o(19)),O=i.__importDefault(o(14)),f=i.__importDefault(o(3)),E=i.__importDefault(o(15)),P=Math.pow(2,17);function y(){}function d(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function h(k){return!!k.connection}function w(k){return m.isErrorInfoOrPartialErrorInfo(k)?(k.code||(k.statusCode===403?k.code=40300:(k.code=40170,k.statusCode=401)),k):new S.default(m.inspectError(k),k.code||40170,k.statusCode||401)}var c=function(k,I){if(f.default.Config.createHmac){var M=f.default.Config.createHmac("SHA256",I);return M.update(k),M.digest("base64")}return(0,R.stringify)((0,T.default)(k,I))};function u(k){if(!k)return"";typeof k=="string"&&(k=JSON.parse(k));var I=Object.create(null),M=m.keysArray(k,!0);if(!M)return"";M.sort();for(var A=0;A<M.length;A++)I[M[A]]=k[M[A]].sort();return JSON.stringify(I)}function l(k){if(k.authCallback)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with authCallback");else if(k.authUrl)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with authUrl");else if(k.key)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(k.tokenDetails)a.default.logAction(a.default.LOG_MINOR,"Auth()","using token auth with supplied token only");else{var I="authOptions must include valid authentication parameters";throw a.default.logAction(a.default.LOG_ERROR,"Auth()",I),new Error(I)}}function s(k){return"useTokenAuth"in k&&!k.useTokenAuth}function g(k){return k.useTokenAuth||!s(k)&&(k.authCallback||k.authUrl||k.token||k.tokenDetails)}function p(k){return!k.key&&!k.authCallback&&!k.authUrl}var x=0;function D(){return x++}var N=function(){function k(I,M){if(this.authOptions={},this.client=I,this.tokenParams=M.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,g(M)){if(M.key&&!c){var A="client-side token request signing not supported";throw a.default.logAction(a.default.LOG_ERROR,"Auth()",A),new Error(A)}p(M)&&a.default.logAction(a.default.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(M.defaultTokenParams,M),l(this.authOptions)}else{if(!M.key){var A="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw a.default.logAction(a.default.LOG_ERROR,"Auth()",A),new S.default(A,40160,401)}a.default.logAction(a.default.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(M)}}return k.prototype.authorize=function(I,M,A){var j=this,U;if(typeof I=="function"&&!A?(A=I,U=I=null):typeof M=="function"&&!A?(A=M,U=null):U=M,!A&&this.client.options.promises)return m.promisify(this,"authorize",arguments);if(U&&U.key&&this.authOptions.key!==U.key)throw new S.default("Unable to update auth options with incompatible key",40102,401);U&&"force"in U&&(a.default.deprecated("The `force` auth option","If you’re using this option to force `authorize()` to fetch a new token even if the current token has not expired, this is no longer necessary, as `authorize()` now always fetches a new token. Update your code to no longer pass the `force` auth option. Note that, in general, passing an auth options argument to `authorize()` will overwrite the library’s stored auth options, which may not be what you want. The library currently contains a special case behavior where passing an auth options object which only contains `{ force: true }` will _not_ overwrite the stored options. This special case behavior will be removed alongside support for the `force` option, so if you’re currently passing `authorize()` an auth options object which only contains `{ force: true }`, you should stop passing it an auth options object entirely."),m.isOnlyPropIn(U,"force")&&(U=null)),this._forceNewToken(I,U,function(z,W){if(z){j.client.connection&&z.statusCode===O.default.Forbidden&&j.client.connection.connectionManager.actOnErrorFromAuthorize(z),A==null||A(z);return}h(j.client)?j.client.connection.connectionManager.onAuthUpdated(W,A||y):A==null||A(null,W)})},k.prototype.authorise=function(I,M,A){a.default.renamedMethod("Auth","authorise","authorize"),this.authorize(I,M,A)},k.prototype._forceNewToken=function(I,M,A){var j=this;this.tokenDetails=null,this._saveTokenOptions(I,M),l(this.authOptions),this._ensureValidAuthCredentials(!0,function(U,z){delete j.tokenParams.timestamp,delete j.authOptions.queryTime,A(U,z)})},k.prototype.requestToken=function(I,M,A){var j=this;if(typeof I=="function"&&!A?(A=I,M=I=null):typeof M=="function"&&!A&&(A=M,M=null),!A&&this.client.options.promises)return m.promisify(this,"requestToken",arguments);M=M||this.authOptions,I=I||m.copy(this.tokenParams);var U=A||y,z,W=this.client;if(M.authCallback)a.default.logAction(a.default.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),z=M.authCallback;else if(M.authUrl)a.default.logAction(a.default.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),z=function(_,V){var Y=m.mixin({accept:"application/json, text/plain"},M.authHeaders),X=M.authMethod&&M.authMethod.toLowerCase()==="post",te,re=M.authUrl.indexOf("?");re>-1&&(te=m.parseQueryString(M.authUrl.slice(re)),M.authUrl=M.authUrl.slice(0,re),X||(M.authParams=m.mixin(te,M.authParams)));var le=m.mixin({},M.authParams||{},_),Z=function(_e,Ee,Mt,qo){var ft;if(_e?a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+m.inspectError(_e)):(ft=Mt["content-type"],a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+ft+"; body: "+m.inspectBody(Ee))),_e||qo)return V(_e,Ee);if(f.default.BufferUtils.isBuffer(Ee)&&(Ee=Ee.toString()),!ft){V(new S.default("authUrl response is missing a content-type header",40170,401));return}var ei=ft.indexOf("application/json")>-1,ws=ft.indexOf("text/plain")>-1||ft.indexOf("application/jwt")>-1;if(!ei&&!ws){V(new S.default("authUrl responded with unacceptable content-type "+ft+", should be either text/plain, application/jwt or application/json",40170,401));return}if(ei){if(Ee.length>P){V(new S.default("authUrl response exceeded max permitted length",40170,401));return}try{Ee=JSON.parse(Ee)}catch(Ss){V(new S.default("Unexpected error processing authURL response; err = "+Ss.message,40170,401));return}}V(null,Ee,ft)};if(a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+M.authUrl+"; Params: "+JSON.stringify(le)+"; method: "+(X?"POST":"GET")),X){var he=Y||{};he["content-type"]="application/x-www-form-urlencoded";var Me=m.toQueryString(le).slice(1);j.client.http.doUri(C.default.Post,W,M.authUrl,he,Me,te,Z)}else j.client.http.doUri(C.default.Get,W,M.authUrl,Y||{},null,le,Z)};else if(M.key)a.default.logAction(a.default.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),z=function(_,V){j.createTokenRequest(_,M,V)};else{var G="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";a.default.logAction(a.default.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),U(new S.default(G,40171,403));return}"capability"in I&&(I.capability=u(I.capability));var F=function(_,V){var Y=_.keyName,X="/keys/"+Y+"/requestToken",te=function(le){return W.baseUri(le)+X},re=m.defaultPostHeaders(j.client.options);M.requestHeaders&&m.mixin(re,M.requestHeaders),a.default.logAction(a.default.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+X+"; Token params: "+JSON.stringify(_)),j.client.http.do(C.default.Post,W,te,re,JSON.stringify(_),null,V)},b=!1,L=this.client.options.timeouts.realtimeRequestTimeout,B=setTimeout(function(){b=!0;var _="Token request callback timed out after "+L/1e3+" seconds";a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()",_),U(new S.default(_,40170,401))},L);z(I,function(_,V,Y){if(!b){if(clearTimeout(B),_){a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+m.inspectError(_)),U(w(_));return}if(typeof V=="string"){V.length===0?U(new S.default("Token string is empty",40170,401)):V.length>P?U(new S.default("Token string exceeded max permitted length (was "+V.length+" bytes)",40170,401)):V==="undefined"||V==="null"?U(new S.default("Token string was literal null/undefined",40170,401)):V[0]==="{"&&!(Y&&Y.indexOf("application/jwt")>-1)?U(new S.default("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):U(null,{token:V});return}if(typeof V!="object"){var X="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof V;a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()",X),U(new S.default(X,40170,401));return}var te=JSON.stringify(V).length;if(te>P&&!M.suppressMaxLengthCheck){U(new S.default("Token request/details object exceeded max permitted stringified size (was "+te+" bytes)",40170,401));return}if("issued"in V){U(null,V);return}if(!("keyName"in V)){var X="Expected token request callback to call back with a token string, token request object, or token details object";a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()",X),U(new S.default(X,40170,401));return}F(V,function(re,le,Z,he){if(re){a.default.logAction(a.default.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+m.inspectError(re)),U(w(re));return}he||(le=JSON.parse(le)),a.default.logAction(a.default.LOG_MINOR,"Auth.getToken()","token received"),U(null,le)})}})},k.prototype.createTokenRequest=function(I,M,A){var j=this;if(typeof I=="function"&&!A?(A=I,M=I=null):typeof M=="function"&&!A&&(A=M,M=null),!A&&this.client.options.promises)return m.promisify(this,"createTokenRequest",arguments);M=M||this.authOptions,I=I||m.copy(this.tokenParams);var U=M.key;if(!U){A(new S.default("No key specified",40101,403));return}var z=U.split(":"),W=z[0],G=z[1];if(!G){A(new S.default("Invalid key specified",40101,403));return}if(I.clientId===""){A(new S.default("clientId can’t be an empty string",40012,400));return}"capability"in I&&(I.capability=u(I.capability));var F=m.mixin({keyName:W},I),b=I.clientId||"",L=I.ttl||"",B=I.capability||"";(function(_){if(F.timestamp){_();return}j.getTimestamp(M&&M.queryTime,function(V,Y){if(V){A(V);return}F.timestamp=Y,_()})})(function(){var _=F.nonce||(F.nonce=d()),V=F.timestamp,Y=F.keyName+`
85
85
  `+L+`
86
86
  `+B+`
87
87
  `+b+`
88
- `+W+`
88
+ `+V+`
89
89
  `+_+`
90
- `;F.mac=F.mac||c(Y,G),a.default.logAction(a.default.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),A(null,F)})},k.prototype.getAuthParams=function(I){this.method=="basic"?I(null,{key:this.key}):this._ensureValidAuthCredentials(!1,function(M,A){if(M){I(M);return}if(!A)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");I(null,{access_token:A.token})})},k.prototype.getAuthHeaders=function(I){this.method=="basic"?I(null,{authorization:"Basic "+this.basicKey}):this._ensureValidAuthCredentials(!1,function(M,A){if(M){I(M);return}if(!A)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");I(null,{authorization:"Bearer "+m.toBase64(A.token)})})},k.prototype.getTimestamp=function(I,M){!this.isTimeOffsetSet()&&(I||this.authOptions.queryTime)?this.client.time(M):M(null,this.getTimestampUsingOffset())},k.prototype.getTimestampUsingOffset=function(){return m.now()+(this.client.serverTimeOffset||0)},k.prototype.isTimeOffsetSet=function(){return this.client.serverTimeOffset!==null},k.prototype._saveBasicOptions=function(I){this.method="basic",this.key=I.key,this.basicKey=m.toBase64(I.key),this.authOptions=I||{},"clientId"in I&&this._userSetClientId(I.clientId)},k.prototype._saveTokenOptions=function(I,M){this.method="token",I&&(this.tokenParams=I),M&&(M.token&&(M.tokenDetails=typeof M.token=="string"?{token:M.token}:M.token),M.tokenDetails&&(this.tokenDetails=M.tokenDetails),"clientId"in M&&this._userSetClientId(M.clientId),this.authOptions=M)},k.prototype._ensureValidAuthCredentials=function(I,M){var A=this,j=this.tokenDetails;if(j){if(this._tokenClientIdMismatch(j.clientId)){M(new S.default("Mismatch between clientId in token ("+j.clientId+") and current clientId ("+this.clientId+")",40102,403));return}if(!this.isTimeOffsetSet()||!j.expires||j.expires>=this.getTimestampUsingOffset()){a.default.logAction(a.default.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+j.expires),M(null,j);return}a.default.logAction(a.default.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}if((this.waitingForTokenRequest||(this.waitingForTokenRequest=v.default.create())).push(M),!(this.currentTokenRequestId!==null&&!I)){var U=this.currentTokenRequestId=D();this.requestToken(this.tokenParams,this.authOptions,function(z,V){if(A.currentTokenRequestId>U){a.default.logAction(a.default.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one");return}A.currentTokenRequestId=null;var G=A.waitingForTokenRequest||y;if(A.waitingForTokenRequest=null,z){G(z);return}G(null,A.tokenDetails=V)})}},k.prototype._userSetClientId=function(I){if(typeof I=="string"||I===null){if(I==="*")throw new S.default('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);var M=this._uncheckedSetClientId(I);if(M)throw M}else throw new S.default("clientId must be either a string or null",40012,400)},k.prototype._uncheckedSetClientId=function(I){if(this._tokenClientIdMismatch(I)){var M="Unexpected clientId mismatch: client has "+this.clientId+", requested "+I,A=new S.default(M,40102,401);return a.default.logAction(a.default.LOG_ERROR,"Auth._uncheckedSetClientId()",M),A}else return this.clientId=this.tokenParams.clientId=I,null},k.prototype._tokenClientIdMismatch=function(I){return!!(this.clientId&&this.clientId!=="*"&&I&&I!=="*"&&this.clientId!==I)},k.isTokenErr=function(I){return I.code&&I.code>=40140&&I.code<40150},k.prototype.revokeTokens=function(I,M,A){if(g(this.client.options))throw new S.default("Cannot revoke tokens when using token auth",40162,401);var j=this.client.options.keyName,U;if(typeof M=="function"?(A=M,U={}):U=M!=null?M:{},A===void 0){if(this.client.options.promises)return m.promisify(this,"revokeTokens",[I,U]);A=y}var z=A,V=i.__assign({targets:I.map(function(L){return"".concat(L.type,":").concat(L.value)})},U),G=this.client.options.useBinaryProtocol?m.Format.msgpack:m.Format.json,F=m.defaultPostHeaders(this.client.options,G);this.client.options.headers&&m.mixin(F,this.client.options.headers);var b=m.encodeBody(V,G);E.default.post(this.client,"/keys/".concat(j,"/revokeTokens"),b,F,{newBatchResponse:"true"},null,function(L,B,_,W){if(L){z(L);return}var Y=W?B:m.decodeBody(B,G);z(null,Y)})},k}();r.default=N},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i;(function(a){a.Get="get",a.Delete="delete",a.Post="post",a.Put="put",a.Patch="patch"})(i||(i={})),r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.HttpPaginatedResponse=r.PaginatedResult=void 0;var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(2)),v=i.__importDefault(o(15)),S=i.__importDefault(o(14));function T(P){var y=P.match(/^\.\/(\w+)\?(.*)$/);return y&&y[2]&&a.parseQueryString(y[2])}function R(P){typeof P=="string"&&(P=P.split(","));for(var y={},d=0;d<P.length;d++){var h=P[d].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(h){var w=T(h[1]);w&&(y[h[2]]=w)}}return y}function C(P,y,d){return!(d&&(y||typeof P.code=="number"))}var O=function(){function P(y,d,h,w,c,u){this.rest=y,this.path=d,this.headers=h,this.envelope=w!=null?w:null,this.bodyHandler=c,this.useHttpPaginatedResponse=u||!1}return P.prototype.get=function(y,d){var h=this;v.default.get(this.rest,this.path,this.headers,y,this.envelope,function(w,c,u,l,s){h.handlePage(w,c,u,l,s,d)})},P.prototype.delete=function(y,d){var h=this;v.default.delete(this.rest,this.path,this.headers,y,this.envelope,function(w,c,u,l,s){h.handlePage(w,c,u,l,s,d)})},P.prototype.post=function(y,d,h){var w=this;v.default.post(this.rest,this.path,d,this.headers,y,this.envelope,function(c,u,l,s,g){h&&w.handlePage(c,u,l,s,g,h)})},P.prototype.put=function(y,d,h){var w=this;v.default.put(this.rest,this.path,d,this.headers,y,this.envelope,function(c,u,l,s,g){h&&w.handlePage(c,u,l,s,g,h)})},P.prototype.patch=function(y,d,h){var w=this;v.default.patch(this.rest,this.path,d,this.headers,y,this.envelope,function(c,u,l,s,g){h&&w.handlePage(c,u,l,s,g,h)})},P.prototype.handlePage=function(y,d,h,w,c,u){if(y&&C(y,d,this.useHttpPaginatedResponse)){m.default.logAction(m.default.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+a.inspectError(y)),u==null||u(y);return}var l,s,g;try{l=c==S.default.NoContent?[]:this.bodyHandler(d,h||{},w)}catch(p){u==null||u(y||p);return}h&&(s=h.Link||h.link)&&(g=R(s)),this.useHttpPaginatedResponse?u(null,new E(this,l,h||{},c,g,y)):u(null,new f(this,l,g))},P}(),f=function(){function P(y,d,h){var w=this;this.resource=y,this.items=d;var c=this;h&&("first"in h&&(this.first=function(u){if(!u&&c.resource.rest.options.promises)return a.promisify(c,"first",[]);c.get(h.first,u)}),"current"in h&&(this.current=function(u){if(!u&&c.resource.rest.options.promises)return a.promisify(c,"current",[]);c.get(h.current,u)}),this.next=function(u){if(!u&&c.resource.rest.options.promises)return a.promisify(c,"next",[]);"next"in h?c.get(h.next,u):u(null,null)},this.hasNext=function(){return"next"in h},this.isLast=function(){var u;return!(!((u=w.hasNext)===null||u===void 0)&&u.call(w))})}return P.prototype.get=function(y,d){var h=this.resource;v.default.get(h.rest,h.path,h.headers,y,h.envelope,function(w,c,u,l,s){h.handlePage(w,c,u,l,s,d)})},P}();r.PaginatedResult=f;var E=function(P){i.__extends(y,P);function y(d,h,w,c,u,l){var s=P.call(this,d,h,u)||this;return s.statusCode=c,s.success=c<300&&c>=200,s.headers=w,s.errorCode=l&&l.code,s.errorMessage=l&&l.message,s}return y.prototype.toJSON=function(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}},y}(f);r.HttpPaginatedResponse=E,r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.isRetriable=void 0;var i=o(0),a=i.__importDefault(o(4)),m={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},v={disconnected:function(){return a.default.fromValues({statusCode:400,code:m.DISCONNECTED,message:"Connection to server temporarily unavailable"})},suspended:function(){return a.default.fromValues({statusCode:400,code:m.SUSPENDED,message:"Connection to server unavailable"})},failed:function(){return a.default.fromValues({statusCode:400,code:m.FAILED,message:"Connection failed or disconnected by server"})},closing:function(){return a.default.fromValues({statusCode:400,code:m.CLOSING,message:"Connection closing"})},closed:function(){return a.default.fromValues({statusCode:400,code:m.CLOSED,message:"Connection closed"})},unknownConnectionErr:function(){return a.default.fromValues({statusCode:500,code:m.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"})},unknownChannelErr:function(){return a.default.fromValues({statusCode:500,code:m.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})}};function S(T){return!T.statusCode||!T.code||T.statusCode>=500?!0:Object.values(m).includes(T.code)}r.isRetriable=S,r.default=v},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i;(function(a){a[a.REQ_SEND=0]="REQ_SEND",a[a.REQ_RECV=1]="REQ_RECV",a[a.REQ_RECV_POLL=2]="REQ_RECV_POLL",a[a.REQ_RECV_STREAM=3]="REQ_RECV_STREAM"})(i||(i={})),r.default=i},function(n,r,o){(function(i,a){n.exports=a(o(6),o(5),o(58),o(11),o(40),o(32),o(25),o(27),o(28),o(59),o(60))})(this,function(i){return i})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(2)),m=function(){function v(S){this.members=S||[]}return v.prototype.call=function(){for(var S=[],T=0;T<arguments.length;T++)S[T]=arguments[T];for(var R=0,C=this.members;R<C.length;R++){var O=C[R];if(O)try{O.apply(void 0,S)}catch(f){a.default.logAction(a.default.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+f+"; stack = "+f.stack)}}},v.prototype.push=function(){for(var S,T=[],R=0;R<arguments.length;R++)T[R]=arguments[R];(S=this.members).push.apply(S,T)},v.create=function(S){var T=new v(S);return Object.assign(function(){for(var R=[],C=0;C<arguments.length;C++)R[C]=arguments[C];return T.call.apply(T,R)},{push:function(R){return T.push(R)}})},v}();r.default=m},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){(function(){var a=i,m=a.lib,v=m.Base,S=a.enc,T=S.Utf8,R=a.algo;R.HMAC=v.extend({init:function(C,O){C=this._hasher=new C.init,typeof O=="string"&&(O=T.parse(O));var f=C.blockSize,E=f*4;O.sigBytes>E&&(O=C.finalize(O)),O.clamp();for(var P=this._oKey=O.clone(),y=this._iKey=O.clone(),d=P.words,h=y.words,w=0;w<f;w++)d[w]^=1549556828,h[w]^=909522486;P.sigBytes=y.sigBytes=E,this.reset()},reset:function(){var C=this._hasher;C.reset(),C.update(this._iKey)},update:function(C){return this._hasher.update(C),this},finalize:function(C){var O=this._hasher,f=O.finalize(C);O.reset();var E=O.finalize(this._oKey.clone().concat(f));return E}})})()})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(10)),m=i.__importStar(o(1)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(21)),R=i.__importDefault(o(4)),C=i.__importDefault(o(3)),O=a.default.Action,f=a.default.fromValues({action:O.CLOSE}),E=a.default.fromValues({action:O.DISCONNECT}),P=function(y){i.__extends(d,y);function d(h,w,c,u){var l=y.call(this)||this;return u&&(c.format=void 0,c.heartbeats=!0),l.connectionManager=h,h.registerProposedTransport(l),l.auth=w,l.params=c,l.timeouts=c.options.timeouts,l.format=c.format,l.isConnected=!1,l.isFinished=!1,l.isDisposed=!1,l.maxIdleInterval=null,l.idleTimer=null,l.lastActivity=null,l}return d.prototype.connect=function(){},d.prototype.close=function(){this.isConnected&&this.requestClose(),this.finish("closed",T.default.closed())},d.prototype.disconnect=function(h){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",h||T.default.disconnected())},d.prototype.fail=function(h){this.isConnected&&this.requestDisconnect(),this.finish("failed",h||T.default.failed())},d.prototype.finish=function(h,w){var c;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((c=this.idleTimer)!==null&&c!==void 0?c:void 0),this.idleTimer=null,this.emit(h,w),this.dispose())},d.prototype.onProtocolMessage=function(h){switch(S.default.shouldLog(S.default.LOG_MICRO)&&S.default.logAction(S.default.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+a.default.stringify(h)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),h.action){case O.HEARTBEAT:S.default.logAction(S.default.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",h.id);break;case O.CONNECTED:this.onConnect(h),this.emit("connected",h.error,h.connectionId,h.connectionDetails,h);break;case O.CLOSED:this.onClose(h);break;case O.DISCONNECTED:this.onDisconnect(h);break;case O.ACK:this.emit("ack",h.msgSerial,h.count);break;case O.NACK:this.emit("nack",h.msgSerial,h.count,h.error);break;case O.SYNC:this.connectionManager.onChannelMessage(h,this);break;case O.ACTIVATE:break;case O.AUTH:this.auth.authorize(function(w){w&&S.default.logAction(S.default.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+m.inspectError(w))});break;case O.ERROR:if(S.default.logAction(S.default.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+C.default.Config.inspect(h.error)+(h.channel?", channel: "+h.channel:"")),h.channel===void 0){this.onFatalError(h);break}this.connectionManager.onChannelMessage(h,this);break;default:this.connectionManager.onChannelMessage(h,this)}},d.prototype.onConnect=function(h){if(this.isConnected=!0,!h.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");var w=h.connectionDetails.maxIdleInterval;w&&(this.maxIdleInterval=w+this.timeouts.realtimeRequestTimeout,this.onActivity())},d.prototype.onDisconnect=function(h){var w=h&&h.error;S.default.logAction(S.default.LOG_MINOR,"Transport.onDisconnect()","err = "+m.inspectError(w)),this.finish("disconnected",w)},d.prototype.onFatalError=function(h){var w=h&&h.error;S.default.logAction(S.default.LOG_MINOR,"Transport.onFatalError()","err = "+m.inspectError(w)),this.finish("failed",w)},d.prototype.onClose=function(h){var w=h&&h.error;S.default.logAction(S.default.LOG_MINOR,"Transport.onClose()","err = "+m.inspectError(w)),this.finish("closed",w)},d.prototype.requestClose=function(){S.default.logAction(S.default.LOG_MINOR,"Transport.requestClose()",""),this.send(f)},d.prototype.requestDisconnect=function(){S.default.logAction(S.default.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(E)},d.prototype.ping=function(h){var w={action:a.default.Action.HEARTBEAT};h&&(w.id=h),this.send(a.default.fromValues(w))},d.prototype.dispose=function(){S.default.logAction(S.default.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()},d.prototype.onActivity=function(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=m.now(),this.setIdleTimer(this.maxIdleInterval+100))},d.prototype.setIdleTimer=function(h){var w=this;this.idleTimer||(this.idleTimer=setTimeout(function(){w.onIdleTimerExpire()},h))},d.prototype.onIdleTimerExpire=function(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;var h=m.now()-this.lastActivity,w=this.maxIdleInterval-h;if(w<=0){var c="No activity seen from realtime in "+h+"ms; assuming connection has dropped";S.default.logAction(S.default.LOG_ERROR,"Transport.onIdleTimerExpire()",c),this.disconnect(new R.default(c,80003,408))}else this.setIdleTimer(w+100)},d.tryConnect=function(h,w,c,u,l){var s=new h(w,c,u),g,p=function(D){clearTimeout(g),l({event:this.event,error:D})},x=w.options.timeouts.realtimeRequestTimeout;g=setTimeout(function(){s.off(["preconnect","disconnected","failed"]),s.dispose(),p.call({event:"disconnected"},new R.default("Timeout waiting for transport to indicate itself viable",5e4,500))},x),s.on(["failed","disconnected"],p),s.on("preconnect",function(){S.default.logAction(S.default.LOG_MINOR,"Transport.tryConnect()","viable transport "+s),clearTimeout(g),s.off(["failed","disconnected"],p),l(null,s)}),s.connect()},d}(v.default);r.default=P},function(n,r,o){(function(i,a){n.exports=a(o(6),o(40),o(25))})(this,function(i){return function(){var a=i,m=a.lib,v=m.Base,S=m.WordArray,T=a.algo,R=T.MD5,C=T.EvpKDF=v.extend({cfg:v.extend({keySize:128/32,hasher:R,iterations:1}),init:function(O){this.cfg=this.cfg.extend(O)},compute:function(O,f){for(var E,P=this.cfg,y=P.hasher.create(),d=S.create(),h=d.words,w=P.keySize,c=P.iterations;h.length<w;){E&&y.update(E),E=y.update(O).finalize(f),y.reset();for(var u=1;u<c;u++)E=y.finalize(E),y.reset();d.concat(E)}return d.sigBytes=w*4,d}});a.EvpKDF=function(O,f,E){return C.create(E).compute(O,f)}}(),i.EvpKDF})},function(n,r,o){(function(i,a){n.exports=a(o(6),o(27))})(this,function(i){i.lib.Cipher||function(a){var m=i,v=m.lib,S=v.Base,T=v.WordArray,R=v.BufferedBlockAlgorithm,C=m.enc;C.Utf8;var O=C.Base64,f=m.algo,E=f.EvpKDF,P=v.Cipher=R.extend({cfg:S.extend(),createEncryptor:function(N,k){return this.create(this._ENC_XFORM_MODE,N,k)},createDecryptor:function(N,k){return this.create(this._DEC_XFORM_MODE,N,k)},init:function(N,k,I){this.cfg=this.cfg.extend(I),this._xformMode=N,this._key=k,this.reset()},reset:function(){R.reset.call(this),this._doReset()},process:function(N){return this._append(N),this._process()},finalize:function(N){N&&this._append(N);var k=this._doFinalize();return k},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function N(k){return typeof k=="string"?D:g}return function(k){return{encrypt:function(I,M,A){return N(M).encrypt(k,I,M,A)},decrypt:function(I,M,A){return N(M).decrypt(k,I,M,A)}}}}()});v.StreamCipher=P.extend({_doFinalize:function(){var N=this._process(!0);return N},blockSize:1});var y=m.mode={},d=v.BlockCipherMode=S.extend({createEncryptor:function(N,k){return this.Encryptor.create(N,k)},createDecryptor:function(N,k){return this.Decryptor.create(N,k)},init:function(N,k){this._cipher=N,this._iv=k}}),h=y.CBC=function(){var N=d.extend();N.Encryptor=N.extend({processBlock:function(I,M){var A=this._cipher,j=A.blockSize;k.call(this,I,M,j),A.encryptBlock(I,M),this._prevBlock=I.slice(M,M+j)}}),N.Decryptor=N.extend({processBlock:function(I,M){var A=this._cipher,j=A.blockSize,U=I.slice(M,M+j);A.decryptBlock(I,M),k.call(this,I,M,j),this._prevBlock=U}});function k(I,M,A){var j,U=this._iv;U?(j=U,this._iv=a):j=this._prevBlock;for(var z=0;z<A;z++)I[M+z]^=j[z]}return N}(),w=m.pad={},c=w.Pkcs7={pad:function(N,k){for(var I=k*4,M=I-N.sigBytes%I,A=M<<24|M<<16|M<<8|M,j=[],U=0;U<M;U+=4)j.push(A);var z=T.create(j,M);N.concat(z)},unpad:function(N){var k=N.words[N.sigBytes-1>>>2]&255;N.sigBytes-=k}};v.BlockCipher=P.extend({cfg:P.cfg.extend({mode:h,padding:c}),reset:function(){var N;P.reset.call(this);var k=this.cfg,I=k.iv,M=k.mode;this._xformMode==this._ENC_XFORM_MODE?N=M.createEncryptor:(N=M.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==N?this._mode.init(this,I&&I.words):(this._mode=N.call(M,this,I&&I.words),this._mode.__creator=N)},_doProcessBlock:function(N,k){this._mode.processBlock(N,k)},_doFinalize:function(){var N,k=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(k.pad(this._data,this.blockSize),N=this._process(!0)):(N=this._process(!0),k.unpad(N)),N},blockSize:128/32});var u=v.CipherParams=S.extend({init:function(N){this.mixIn(N)},toString:function(N){return(N||this.formatter).stringify(this)}}),l=m.format={},s=l.OpenSSL={stringify:function(N){var k,I=N.ciphertext,M=N.salt;return M?k=T.create([1398893684,1701076831]).concat(M).concat(I):k=I,k.toString(O)},parse:function(N){var k,I=O.parse(N),M=I.words;return M[0]==1398893684&&M[1]==1701076831&&(k=T.create(M.slice(2,4)),M.splice(0,4),I.sigBytes-=16),u.create({ciphertext:I,salt:k})}},g=v.SerializableCipher=S.extend({cfg:S.extend({format:s}),encrypt:function(N,k,I,M){M=this.cfg.extend(M);var A=N.createEncryptor(I,M),j=A.finalize(k),U=A.cfg;return u.create({ciphertext:j,key:I,iv:U.iv,algorithm:N,mode:U.mode,padding:U.padding,blockSize:N.blockSize,formatter:M.format})},decrypt:function(N,k,I,M){M=this.cfg.extend(M),k=this._parse(k,M.format);var A=N.createDecryptor(I,M).finalize(k.ciphertext);return A},_parse:function(N,k){return typeof N=="string"?k.parse(N,this):N}}),p=m.kdf={},x=p.OpenSSL={execute:function(N,k,I,M){M||(M=T.random(64/8));var A=E.create({keySize:k+I}).compute(N,M),j=T.create(A.words.slice(k),I*4);return A.sigBytes=k*4,u.create({key:A,iv:j,salt:M})}},D=v.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:x}),encrypt:function(N,k,I,M){M=this.cfg.extend(M);var A=M.kdf.execute(I,N.keySize,N.ivSize);M.iv=A.iv;var j=g.encrypt.call(this,N,k,A.key,M);return j.mixIn(A),j},decrypt:function(N,k,I,M){M=this.cfg.extend(M),k=this._parse(k,M.format);var A=M.kdf.execute(I,N.keySize,N.ivSize,k.salt);M.iv=A.iv;var j=g.decrypt.call(this,N,k,A.key,M);return j}})}()})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.Request=r.createRequest=void 0;var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(12)),v=i.__importDefault(o(3)),S=i.__importDefault(o(7)),T=o(4),R=i.__importDefault(o(8)),C=i.__importDefault(o(2)),O=i.__importDefault(o(22)),f=a.getGlobalObject(),E=function(){},P=f._ablyjs_jsonp={};P._=function(l){return P["_"+l]||E};var y=1,d="jsonp";function h(l,s,g,p,x,D,N){return D=D||R.default.TIMEOUTS,new c(void 0,l,s,a.copy(g),p,x,D,N)}r.createRequest=h;var w=function(l){i.__extends(s,l);function s(g,p,x){var D=l.call(this,g,p,x)||this;return D.shortName=d,x.stream=!1,D}return s.isAvailable=function(){return v.default.Config.jsonpSupported&&v.default.Config.allowComet},s.prototype.toString=function(){return"JSONPTransport; uri="+this.baseUri+"; isConnected="+this.isConnected},s.prototype.createRequest=function(g,p,x,D,N,k,I){return k=(this===null||this===void 0?void 0:this.timeouts)||k||R.default.TIMEOUTS,h(g,p,x,D,N,k,I)},s}(m.default),c=function(l){i.__extends(s,l);function s(g,p,x,D,N,k,I,M){var A=l.call(this)||this;return g===void 0&&(g=y++),A.id=g,A.uri=p,A.params=D||{},A.params.rnd=a.cheapRandStr(),x&&(x["X-Ably-Version"]&&(A.params.v=x["X-Ably-Version"]),x["X-Ably-Lib"]&&(A.params.lib=x["X-Ably-Lib"])),A.body=N,A.method=M,A.requestMode=k,A.timeouts=I,A.requestComplete=!1,A}return s.prototype.exec=function(){var g=this,p=this.id,x=this.body,D=this.method,N=this.uri,k=this.params;k.callback="_ablyjs_jsonp._("+p+")",k.envelope="jsonp",x&&(k.body=x),D&&D!=="get"&&(k.method=D);var I=this.script=document.createElement("script"),M=N+a.toQueryString(k);I.src=M,I.src.split("/").slice(-1)[0]!==M.split("/").slice(-1)[0]&&C.default.logAction(C.default.LOG_ERROR,"JSONP Request.exec()","Warning: the browser appears to have truncated the script URI. This will likely result in the request failing due to an unparseable body param"),I.async=!0,I.type="text/javascript",I.charset="UTF-8",I.onerror=function(U){g.complete(new T.PartialErrorInfo("JSONP script error (event: "+v.default.Config.inspect(U)+")",null,400))},P["_"+p]=function(U){if(U.statusCode){var z=U.response;if(U.statusCode==204)g.complete(null,null,null,U.statusCode);else if(!z)g.complete(new T.PartialErrorInfo("Invalid server response: no envelope detected",null,500));else if(U.statusCode<400||a.isArray(z))g.complete(null,z,U.headers,U.statusCode);else{var V=z.error||new T.PartialErrorInfo("Error response received from server",null,U.statusCode);g.complete(V)}}else g.complete(null,U)};var A=this.requestMode==O.default.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout;this.timer=setTimeout(this.abort.bind(this),A);var j=document.getElementsByTagName("head")[0];j.insertBefore(I,j.firstChild)},s.prototype.complete=function(g,p,x,D){if(x=x||{},!this.requestComplete){this.requestComplete=!0;var N=void 0;p&&(N=typeof p=="string"?"text/plain":"application/json",x["content-type"]=N,this.emit("data",p)),this.emit("complete",g,p,x,!0,D),this.dispose()}},s.prototype.abort=function(){this.dispose()},s.prototype.dispose=function(){var g=this.timer;g&&(clearTimeout(g),this.timer=null);var p=this.script;p.parentNode&&p.parentNode.removeChild(p),delete P[this.id],this.emit("disposed")},s}(S.default);r.Request=c;function u(l){return f.JSONPTransport=w,w.isAvailable()&&(l.supportedTransports[d]=w),w}r.default=u},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(2)),v=i.__importDefault(o(8)),S=i.__importDefault(o(18)),T=i.__importDefault(o(46)),R=i.__importDefault(o(20)),C=i.__importDefault(o(33)),O=i.__importDefault(o(4)),f=i.__importDefault(o(49)),E=i.__importDefault(o(19)),P=i.__importDefault(o(3)),y=i.__importDefault(o(9)),d=i.__importDefault(o(16)),h=i.__importDefault(o(15)),w=function(){},c=function(){function l(s){if(!s){var g="no options provided";throw m.default.logAction(m.default.LOG_ERROR,"Rest()",g),new Error(g)}var p=v.default.objectifyOptions(s);p.log?(m.default.setLog(p.log.level,p.log.handler),m.default.deprecated("The `log` client option","Equivalent functionality is provided by the `logLevel` and `logHandler` client options. Update your client options code of the form `{ log: { level: logLevel, handler: logHandler } }` to instead be `{ logLevel, logHandler }`.")):m.default.setLog(p.logLevel,p.logHandler),m.default.logAction(m.default.LOG_MICRO,"Rest()","initialized with clientOptions "+P.default.Config.inspect(s));var x=this.options=v.default.normaliseOptions(p);if(x.key){var D=x.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!D){var g="invalid key parameter";throw m.default.logAction(m.default.LOG_ERROR,"Rest()",g),new O.default(g,40400,404)}x.keyName=D[1],x.keySecret=D[2]}if("clientId"in x)if(typeof x.clientId=="string"||x.clientId===null){if(x.clientId==="*")throw new O.default('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new O.default("clientId must be either a string or null",40012,400);m.default.logAction(m.default.LOG_MINOR,"Rest()","started; version = "+v.default.version),this.baseUri=this.authority=function(N){return v.default.getHttpScheme(x)+N+":"+v.default.getPort(x,!1)},this._currentFallback=null,this.serverTimeOffset=null,this.http=new P.default.Http(x),this.auth=new S.default(this,x),this.channels=new u(this),this.push=new T.default(this)}return l.prototype.stats=function(s,g){if(g===void 0)if(typeof s=="function")g=s,s=null;else{if(this.options.promises)return a.promisify(this,"stats",[s]);g=w}var p=a.defaultGetHeaders(this.options),x=this.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,D=this.http.supportsLinkHeaders?void 0:x;this.options.headers&&a.mixin(p,this.options.headers),new R.default(this,"/stats",p,D,function(N,k,I){for(var M=I?N:JSON.parse(N),A=0;A<M.length;A++)M[A]=f.default.fromValues(M[A]);return M}).get(s,g)},l.prototype.time=function(s,g){var p=this;if(g===void 0){if(typeof s=="function")g=s,s=null;else if(this.options.promises)return a.promisify(this,"time",[s])}var x=g||w,D=a.defaultGetHeaders(this.options);this.options.headers&&a.mixin(D,this.options.headers);var N=function(k){return p.authority(k)+"/time"};this.http.do(E.default.Get,this,N,D,null,s,function(k,I,M,A){if(k){x(k);return}A||(I=JSON.parse(I));var j=I[0];if(!j){x(new O.default("Internal error (unexpected result type from GET /time)",5e4,500));return}p.serverTimeOffset=j-a.now(),x(null,j)})},l.prototype.request=function(s,g,p,x,D,N){var k=this.options.useBinaryProtocol,I=k?P.default.Config.msgpack.encode:JSON.stringify,M=k?P.default.Config.msgpack.decode:JSON.parse,A=k?a.Format.msgpack:a.Format.json,j=this.http.supportsLinkHeaders?void 0:A;p=p||{};var U=s.toLowerCase(),z=U=="get"?a.defaultGetHeaders(this.options,A):a.defaultPostHeaders(this.options,A);if(N===void 0){if(this.options.promises)return a.promisify(this,"request",[s,g,p,x,D]);N=w}typeof x!="string"&&(x=I(x)),this.options.headers&&a.mixin(z,this.options.headers),D&&a.mixin(z,D);var V=new R.default(this,g,z,j,function(G,F,b){return a.ensureArray(b?G:M(G))},!0);if(!a.arrIn(P.default.Http.methods,U))throw new O.default("Unsupported method "+U,40500,405);a.arrIn(P.default.Http.methodsWithBody,U)?V[U](p,x,N):V[U](p,N)},l.prototype.batchPublish=function(s,g){if(g===void 0){if(this.options.promises)return a.promisify(this,"batchPublish",[s]);g=w}var p=g,x,D;a.isArray(s)?(x=s,D=!1):(x=[s],D=!0);var N=this.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,k=a.defaultPostHeaders(this.options,N);this.options.headers&&a.mixin(k,this.options.headers);var I=a.encodeBody(x,N);h.default.post(this,"/messages",I,k,{newBatchResponse:"true"},null,function(M,A,j,U){if(M){p(M);return}var z=U?A:a.decodeBody(A,N);D?p(null,z[0]):p(null,z)})},l.prototype.batchPresence=function(s,g){if(g===void 0){if(this.options.promises)return a.promisify(this,"batchPresence",[s]);g=w}var p=g,x=this.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,D=a.defaultPostHeaders(this.options,x);this.options.headers&&a.mixin(D,this.options.headers);var N=s.join(",");h.default.get(this,"/presence",D,{newBatchResponse:"true",channels:N},null,function(k,I,M,A){if(k){p(k);return}var j=A?I:a.decodeBody(I,x);p(null,j)})},l.prototype.setLog=function(s){m.default.setLog(s.level,s.handler)},l.Promise=function(s){return s=v.default.objectifyOptions(s),s.promises=!0,new l(s)},l.Callbacks=l,l.Platform=P.default,l.Message=y.default,l.PresenceMessage=d.default,l}(),u=function(){function l(s){this.rest=s,this.all=Object.create(null)}return l.prototype.get=function(s,g){s=String(s);var p=this.all[s];return p?g&&p.setOptions(g):this.all[s]=p=new C.default(this.rest,s,g),p},l.prototype.release=function(s){delete this.all[String(s)]},l}();r.default=c},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return i.enc.Utf8})},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(a){var m=i,v=m.lib,S=v.WordArray,T=v.Hasher,R=m.algo,C=[],O=[];(function(){function P(w){for(var c=a.sqrt(w),u=2;u<=c;u++)if(!(w%u))return!1;return!0}function y(w){return(w-(w|0))*4294967296|0}for(var d=2,h=0;h<64;)P(d)&&(h<8&&(C[h]=y(a.pow(d,1/2))),O[h]=y(a.pow(d,1/3)),h++),d++})();var f=[],E=R.SHA256=T.extend({_doReset:function(){this._hash=new S.init(C.slice(0))},_doProcessBlock:function(P,y){for(var d=this._hash.words,h=d[0],w=d[1],c=d[2],u=d[3],l=d[4],s=d[5],g=d[6],p=d[7],x=0;x<64;x++){if(x<16)f[x]=P[y+x]|0;else{var D=f[x-15],N=(D<<25|D>>>7)^(D<<14|D>>>18)^D>>>3,k=f[x-2],I=(k<<15|k>>>17)^(k<<13|k>>>19)^k>>>10;f[x]=N+f[x-7]+I+f[x-16]}var M=l&s^~l&g,A=h&w^h&c^w&c,j=(h<<30|h>>>2)^(h<<19|h>>>13)^(h<<10|h>>>22),U=(l<<26|l>>>6)^(l<<21|l>>>11)^(l<<7|l>>>25),z=p+U+M+O[x]+f[x],V=j+A;p=g,g=s,s=l,l=u+z|0,u=c,c=w,w=h,h=z+V|0}d[0]=d[0]+h|0,d[1]=d[1]+w|0,d[2]=d[2]+c|0,d[3]=d[3]+u|0,d[4]=d[4]+l|0,d[5]=d[5]+s|0,d[6]=d[6]+g|0,d[7]=d[7]+p|0},_doFinalize:function(){var P=this._data,y=P.words,d=this._nDataBytes*8,h=P.sigBytes*8;return y[h>>>5]|=128<<24-h%32,y[(h+64>>>9<<4)+14]=a.floor(d/4294967296),y[(h+64>>>9<<4)+15]=d,P.sigBytes=y.length*4,this._process(),this._hash},clone:function(){var P=T.clone.call(this);return P._hash=this._hash.clone(),P}});m.SHA256=T._createHelper(E),m.HmacSHA256=T._createHmacHelper(E)}(Math),i.SHA256})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(7)),v=i.__importDefault(o(2)),S=i.__importDefault(o(34)),T=i.__importDefault(o(9)),R=i.__importDefault(o(4)),C=i.__importDefault(o(20)),O=i.__importDefault(o(15)),f=i.__importDefault(o(3));function E(){}var P=9;function y(w){return a.arrEvery(w,function(c){return!c.id})}function d(w){var c=w||{};if(c.cipher){if(!f.default.Crypto)throw new Error("Encryption not enabled; use ably.encryption.js instead");var u=f.default.Crypto.getCipher(c.cipher);c.cipher=u.cipherParams,c.channelCipher=u.cipher}else"cipher"in c&&(c.cipher=void 0,c.channelCipher=null);return c}var h=function(w){i.__extends(c,w);function c(u,l,s){var g=w.call(this)||this;return v.default.logAction(v.default.LOG_MINOR,"Channel()","started; name = "+l),g.rest=u,g.name=l,g.basePath="/channels/"+encodeURIComponent(l),g.presence=new S.default(g),g.channelOptions=d(s),g}return c.prototype.setOptions=function(u){this.channelOptions=d(u)},c.prototype.history=function(u,l){if(v.default.logAction(v.default.LOG_MICRO,"Channel.history()","channel = "+this.name),l===void 0)if(typeof u=="function")l=u,u=null;else{if(this.rest.options.promises)return a.promisify(this,"history",arguments);l=E}this._history(u,l)},c.prototype._history=function(u,l){var s=this.rest,g=s.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,p=this.rest.http.supportsLinkHeaders?void 0:g,x=a.defaultGetHeaders(s.options,g);s.options.headers&&a.mixin(x,s.options.headers);var D=this.channelOptions;new C.default(s,this.basePath+"/messages",x,p,function(N,k,I){return T.default.fromResponseBody(N,D,I?void 0:g)}).get(u,l)},c.prototype.publish=function(){var u=this,l=arguments.length,s=arguments[0],g=arguments[1],p=arguments[l-1],x,D;if(typeof p!="function"){if(this.rest.options.promises)return a.promisify(this,"publish",arguments);p=E}if(typeof s=="string"||s===null)x=[T.default.fromValues({name:s,data:g})],D=arguments[2];else if(a.isObject(s))x=[T.default.fromValues(s)],D=arguments[1];else if(a.isArray(s))x=T.default.fromValuesArray(s),D=arguments[1];else throw new R.default("The single-argument form of publish() expects a message object or an array of message objects",40013,400);(typeof D!="object"||!D)&&(D={});var N=this.rest,k=N.options,I=k.useBinaryProtocol?a.Format.msgpack:a.Format.json,M=N.options.idempotentRestPublishing,A=a.defaultPostHeaders(N.options,I);if(k.headers&&a.mixin(A,k.headers),M&&y(x)){var j=a.randomString(P);a.arrForEach(x,function(U,z){U.id=j+":"+z.toString()})}T.default.encodeArray(x,this.channelOptions,function(U){if(U){p(U);return}var z=T.default.getMessagesSize(x),V=k.maxMessageSize;if(z>V){p(new R.default("Maximum size of messages that can be published at once exceeded ( was "+z+" bytes; limit is "+V+" bytes)",40009,400));return}u._publish(T.default.serialize(x,I),A,D,p)})},c.prototype._publish=function(u,l,s,g){O.default.post(this.rest,this.basePath+"/messages",u,l,s,null,g)},c.prototype.status=function(u){if(typeof u!="function"&&this.rest.options.promises)return a.promisify(this,"status",[]);var l=this.rest.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,s=a.defaultPostHeaders(this.rest.options,l);O.default.get(this.rest,this.basePath,s,{},l,u||E)},c}(m.default);r.default=h},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(7)),v=i.__importDefault(o(2)),S=i.__importDefault(o(20)),T=i.__importDefault(o(16));function R(){}var C=function(O){i.__extends(f,O);function f(E){var P=O.call(this)||this;return P.channel=E,P.basePath=E.basePath+"/presence",P}return f.prototype.get=function(E,P){if(v.default.logAction(v.default.LOG_MICRO,"Presence.get()","channel = "+this.channel.name),P===void 0)if(typeof E=="function")P=E,E=null;else{if(this.channel.rest.options.promises)return a.promisify(this,"get",arguments);P=R}var y=this.channel.rest,d=y.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,h=this.channel.rest.http.supportsLinkHeaders?void 0:d,w=a.defaultGetHeaders(y.options,d);y.options.headers&&a.mixin(w,y.options.headers);var c=this.channel.channelOptions;new S.default(y,this.basePath,w,h,function(u,l,s){return T.default.fromResponseBody(u,c,s?void 0:d)}).get(E,P)},f.prototype.history=function(E,P){return v.default.logAction(v.default.LOG_MICRO,"Presence.history()","channel = "+this.channel.name),this._history(E,P)},f.prototype._history=function(E,P){if(P===void 0)if(typeof E=="function")P=E,E=null;else{if(this.channel.rest.options.promises)return a.promisify(this,"_history",[E]);P=R}var y=this.channel.rest,d=y.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,h=this.channel.rest.http.supportsLinkHeaders?void 0:d,w=a.defaultGetHeaders(y.options,d);y.options.headers&&a.mixin(w,y.options.headers);var c=this.channel.channelOptions;new S.default(y,this.basePath+"/history",w,h,function(u,l,s){return T.default.fromResponseBody(u,c,s?void 0:d)}).get(E,P)},f}(m.default);r.default=C},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0}),r.TransportParams=void 0;var a=o(0),m=a.__importDefault(o(10)),v=a.__importStar(o(1)),S=a.__importStar(o(52)),T=a.__importStar(o(8)),R=a.__importDefault(o(3)),C=a.__importDefault(o(7)),O=a.__importDefault(o(36)),f=a.__importDefault(o(2)),E=a.__importDefault(o(37)),P=a.__importStar(o(21)),y=a.__importStar(o(4)),d=a.__importDefault(o(18)),h=a.__importDefault(o(9)),w=a.__importDefault(o(24)),c=a.__importDefault(o(53)),u=a.__importDefault(o(26)),l=a.__importDefault(o(14)),s=function(){var G;return typeof R.default.WebStorage!="undefined"&&((G=R.default.WebStorage)===null||G===void 0?void 0:G.localSupported)},g=function(){var G;return typeof R.default.WebStorage!="undefined"&&((G=R.default.WebStorage)===null||G===void 0?void 0:G.sessionSupported)},p=m.default.Action,x=function(){},D="ably-transport-preference",N="ably-connection-recovery";function k(){var G,F;return g()&&((F=(G=R.default.WebStorage)===null||G===void 0?void 0:G.getSession)===null||F===void 0?void 0:F.call(G,N))}function I(G){var F,b;return g()&&((b=(F=R.default.WebStorage)===null||F===void 0?void 0:F.setSession)===null||b===void 0?void 0:b.call(F,N,G))}function M(){var G,F;return g()&&((F=(G=R.default.WebStorage)===null||G===void 0?void 0:G.removeSession)===null||F===void 0?void 0:F.call(G,N))}function A(G,F){return v.arrIndexOf(R.default.Defaults.transportPreferenceOrder,G.shortName)>v.arrIndexOf(R.default.Defaults.transportPreferenceOrder,F.shortName)}function j(G,F,b){var L;if(G.channel!==F.channel||(L=G.action)!==p.PRESENCE&&L!==p.MESSAGE||L!==F.action)return!1;var B=L===p.PRESENCE?"presence":"messages",_=G[B].concat(F[B]),W=h.default.getMessagesSize(_);return W>b||!v.allSame(_,"clientId")||!v.arrEvery(_,function(Y){return!Y.id})?!1:(G[B]=_,!0)}function U(G){try{return JSON.parse(G)}catch(F){return null}}var z=function(){function G(F,b,L,B){this.options=F,this.host=b,this.mode=L,this.connectionKey=B,this.format=F.useBinaryProtocol?v.Format.msgpack:v.Format.json}return G.prototype.getConnectParams=function(F){var b=F?v.copy(F):{},L=this.options;switch(this.mode){case"upgrade":b.upgrade=this.connectionKey;break;case"resume":b.resume=this.connectionKey;break;case"recover":{var B=U(L.recover);B&&(b.recover=B.connectionKey);break}}return L.clientId!==void 0&&(b.clientId=L.clientId),L.echoMessages===!1&&(b.echo="false"),this.format!==void 0&&(b.format=this.format),this.stream!==void 0&&(b.stream=this.stream),this.heartbeats!==void 0&&(b.heartbeats=this.heartbeats),b.v=T.default.protocolVersion,b.agent=(0,T.getAgentString)(this.options),L.transportParams!==void 0&&v.mixin(b,L.transportParams),b},G.prototype.toString=function(){var F="[mode="+this.mode;return this.host&&(F+=",host="+this.host),this.connectionKey&&(F+=",connectionKey="+this.connectionKey),this.format&&(F+=",format="+this.format),F+="]",F},G}();r.TransportParams=z;var V=function(G){a.__extends(F,G);function F(b,L){var B=G.call(this)||this;B.disconnectedRetryCount=0,F.initTransports(),B.realtime=b,B.options=L;var _=L.timeouts,W=_.preferenceConnectTimeout+_.realtimeRequestTimeout;if(B.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:W,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},synchronizing:{state:"connected",terminal:!1,queueEvents:!0,sendEvents:!1,forceQueueEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:_.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:_.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:_.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},B.state=B.states.initialized,B.errorReason=null,B.queuedMessages=new O.default,B.msgSerial=0,B.connectionDetails=void 0,B.connectionId=void 0,B.connectionKey=void 0,B.connectionStateTtl=_.connectionStateTtl,B.maxIdleInterval=null,B.transports=v.intersect(L.transports||T.default.defaultTransports,F.supportedTransports),B.baseTransport=v.intersect(T.default.baseTransportOrder,B.transports)[0],B.upgradeTransports=v.intersect(B.transports,T.default.upgradeTransports),B.transportPreference=null,B.httpHosts=T.default.getHosts(L),B.activeProtocol=null,B.proposedTransports=[],B.pendingTransports=[],B.host=null,B.lastAutoReconnectAttempt=null,B.lastActivity=null,B.forceFallbackHost=!1,B.connectCounter=0,f.default.logAction(f.default.LOG_MINOR,"Realtime.ConnectionManager()","started"),f.default.logAction(f.default.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(L.transports||T.default.defaultTransports)+"]"),f.default.logAction(f.default.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+B.transports+"]"),f.default.logAction(f.default.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+B.httpHosts+"]"),!B.transports.length){var Y="no requested transports available";throw f.default.logAction(f.default.LOG_ERROR,"realtime.ConnectionManager()",Y),new Error(Y)}var X=R.default.Config.addEventListener;return X&&(g()&&typeof L.recover=="function"&&X("beforeunload",B.persistConnection.bind(B)),L.closeOnUnload===!0&&X("beforeunload",function(){f.default.logAction(f.default.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),B.requestState({state:"closing"})}),X("online",function(){B.state==B.states.disconnected||B.state==B.states.suspended?(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),B.requestState({state:"connecting"})):B.state==B.states.connecting&&(B.pendingTransports.forEach(function(te){te.off()}),B.disconnectAllTransports(),B.startConnect())}),X("offline",function(){B.state==B.states.connected&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),B.disconnectAllTransports())})),B}return F.initTransports=function(){(0,c.default)(F),v.arrForEach(R.default.Transports,function(b){b(F)})},F.prototype.createTransportParams=function(b,L){return new z(this.options,b,L,this.connectionKey)},F.prototype.getTransportParams=function(b){var L=this,B=function(_){if(L.connectionKey){_("resume");return}if(typeof L.options.recover=="string"){_("recover");return}var W=L.options.recover,Y=k();if(Y&&typeof W=="function"){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data"),W(Y,function(X){X?(L.options.recover=Y.recoveryKey,_("recover")):_("clean")});return}_("clean")};B(function(_){var W=L.createTransportParams(null,_);if(_==="recover"){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+L.options.recover);var Y=U(L.options.recover);Y&&(L.msgSerial=Y.msgSerial)}else f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+W.toString());b(W)})},F.prototype.tryATransport=function(b,L,B){var _=this;f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+L),u.default.tryConnect(F.supportedTransports[L],this,this.realtime.auth,b,function(W,Y){var X=_.state;if(X==_.states.closing||X==_.states.closed||X==_.states.failed){Y&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+X.state+" while we were attempting the transport; closing "+Y),Y.close()),B(!0);return}if(W){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+L+" "+W.event+", err: "+W.error.toString()),d.default.isTokenErr(W.error)&&!(_.errorReason&&d.default.isTokenErr(_.errorReason))?(_.errorReason=W.error,_.realtime.auth._forceNewToken(null,null,function(te){if(te){_.actOnErrorFromAuthorize(te);return}_.tryATransport(b,L,B)})):W.event==="failed"?(_.notifyState({state:"failed",error:W.error}),B(!0)):W.event==="disconnected"&&((0,P.isRetriable)(W.error)?B(!1):(_.notifyState({state:_.states.connecting.failState,error:W.error}),B(!0)));return}f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+L+"; setting pending"),_.setTransportPending(Y,b),B(null,Y)})},F.prototype.setTransportPending=function(b,L){var B=this,_=L.mode;f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+b+"; mode = "+_),v.arrDeleteValue(this.proposedTransports,b),this.pendingTransports.push(b);var W=R.default.Defaults.transportPreferenceOrder[R.default.Defaults.transportPreferenceOrder.length-1];b.once("connected",function(X,te,re){_=="upgrade"&&B.activeProtocol?b.shortName!==W&&v.arrIn(B.getUpgradePossibilities(),W)&&B.activeProtocol?setTimeout(function(){B.scheduleTransportActivation(X,b,te,re)},B.options.timeouts.parallelUpgradeDelay):B.scheduleTransportActivation(X,b,te,re):(B.activateTransport(X,b,te,re),R.default.Config.nextTick(function(){B.connectImpl(L)})),_==="recover"&&B.options.recover&&(B.options.recover=null,B.unpersistConnection())});var Y=this;b.on(["disconnected","closed","failed"],function(X){Y.deactivateTransport(b,this.event,X)}),this.emit("transport.pending",b)},F.prototype.scheduleTransportActivation=function(b,L,B,_){var W=this,Y=this.activeProtocol&&this.activeProtocol.getTransport(),X=function(){L.disconnect(),v.arrDeleteValue(W.pendingTransports,L)};if(this.state!==this.states.connected&&this.state!==this.states.connecting){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+this.state.state+(this.state===this.states.synchronizing?", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+L.shortName),X();return}if(Y&&!A(L,Y)){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+L.shortName+" is no better than current active transport "+Y.shortName+" - abandoning upgrade"),X();return}f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+L);var te=null;if(!L.isConnected){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+L.shortName+"is no longer connected; abandoning upgrade"),X();return}if(this.state===this.states.connected)f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Currently connected, so temporarily pausing events until the upgrade is complete"),this.state=this.states.synchronizing,te=this.activeProtocol;else if(this.state!==this.states.connecting){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+this.state.state+(this.state===this.states.synchronizing?", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+L.shortName),X();return}f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+L);var re=function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+L),L.send(m.default.fromValues({action:p.ACTIVATE})),W.activateTransport(b,L,B,_),W.state===W.states.synchronizing?(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+L),W.state=W.states.connected):f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, but state is now "+W.state.state+", so leaving unchanged"),W.state.sendEvents&&W.sendQueuedMessages()};te?te.onceIdle(re):re()},F.prototype.activateTransport=function(b,L,B,_){var W=this;f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+L),b&&f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+b),B&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+B),_&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(_)),this.persistTransportPreference(L);var Y=this.state,X=this.states.connected.state;if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+Y.state),Y.state==this.states.closing.state||Y.state==this.states.closed.state||Y.state==this.states.failed.state)return f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),L.disconnect(),!1;if(v.arrDeleteValue(this.pendingTransports,L),!L.isConnected)return f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+L+" since it appears to no longer be connected"),!1;var te=this.activeProtocol;this.activeProtocol=new S.default(L),this.host=L.params.host;var re=_.connectionKey;if(re&&this.connectionKey!=re&&this.setConnection(B,_,!!b),this.onConnectionDetailsUpdate(_,L),R.default.Config.nextTick(function(){L.on("connected",function(Z,he,Me){W.onConnectionDetailsUpdate(Me,L),W.emit("update",new E.default(X,X,null,Z))})}),Y.state===this.states.connected.state?b&&(this.errorReason=this.realtime.connection.errorReason=b,this.emit("update",new E.default(X,X,null,b))):(this.notifyState({state:"connected",error:b}),this.errorReason=this.realtime.connection.errorReason=b||null),this.emit("transport.active",L),te)if(te.messageQueue.count()>0&&f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+te.transport.shortName+", new one is "+L.shortName+") finishing with "+te.messageQueue.count()+" messages still pending"),te.transport===L){var le="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+L.shortName+"; stack = "+new Error().stack;f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()",le)}else te.finish();return v.safeArrForEach(this.pendingTransports,function(Z){if(Z===L){var he="Assumption violated: activating a transport that is still marked as a pending transport; transport = "+L.shortName+"; stack = "+new Error().stack;f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()",he),v.arrDeleteValue(W.pendingTransports,L)}else Z.disconnect()}),v.safeArrForEach(this.proposedTransports,function(Z){Z===L?(f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()","Assumption violated: activating a transport that is still marked as a proposed transport; transport = "+L.shortName+"; stack = "+new Error().stack),v.arrDeleteValue(W.proposedTransports,L)):Z.dispose()}),!0},F.prototype.deactivateTransport=function(b,L,B){var _=this.activeProtocol,W=_&&_.getTransport()===b,Y=v.arrDeleteValue(this.pendingTransports,b),X=v.arrDeleteValue(this.proposedTransports,b),te=this.noTransportsScheduledForActivation();if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+b),f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+L+(W?"; was active":Y?"; was pending":X?"; was proposed":"")+(te?"":"; another transport is scheduled for activation")),B&&B.message&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+B.message),W&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(_.getPendingMessages()),R.default.Config.nextTick(function(){_.clearPendingMessages()}),this.activeProtocol=this.host=null),this.emit("transport.inactive",b),W&&te||W&&L==="failed"||L==="closed"||_===null&&Y&&this.pendingTransports.length===0){if(L==="disconnected"&&B&&B.statusCode>500&&this.httpHosts.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:L,error:B,retryImmediately:!0});return}var re=L==="failed"&&d.default.isTokenErr(B)?"disconnected":L;this.notifyState({state:re,error:B});return}W&&L==="disconnected"&&this.state!==this.states.synchronizing&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.deactivateTransport()","wasActive but another transport is connected and scheduled for activation, so going into the connecting state until it activates"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),this.notifyState({state:"connecting",error:B}))},F.prototype.noTransportsScheduledForActivation=function(){return v.isEmpty(this.pendingTransports)||this.pendingTransports.every(function(b){return!b.isConnected})},F.prototype.setConnection=function(b,L,B){var _=this.connectionId,W=_&&_!==b,Y=!_&&B;(W||Y)&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==b&&f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=b,this.realtime.connection.key=this.connectionKey=L.connectionKey},F.prototype.clearConnection=function(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()},F.prototype.createRecoveryKey=function(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null},F.prototype.checkConnectionStateFreshness=function(){if(!(!this.lastActivity||!this.connectionId)){var b=v.now()-this.lastActivity;b>this.connectionStateTtl+this.maxIdleInterval&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+b+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}},F.prototype.persistConnection=function(){if(g()){var b=this.createRecoveryKey();b&&I({recoveryKey:b,disconnectedAt:v.now(),location:i.location,clientId:this.realtime.auth.clientId})}},F.prototype.unpersistConnection=function(){M()},F.prototype.getError=function(){return this.errorReason||this.getStateError()},F.prototype.getStateError=function(){var b,L;return(L=(b=P.default)[this.state.state])===null||L===void 0?void 0:L.call(b)},F.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents},F.prototype.enactStateChange=function(b){var L=b.current==="failed"?f.default.LOG_ERROR:f.default.LOG_MAJOR;f.default.logAction(L,"Connection state",b.current+(b.reason?"; reason: "+b.reason:"")),f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+b.current+"; reason = "+(b.reason&&b.reason.message));var B=this.state=this.states[b.current];b.reason&&(this.errorReason=b.reason,this.realtime.connection.errorReason=b.reason),(B.terminal||B.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",b)},F.prototype.startTransitionTimer=function(b){var L=this;f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+b.state),this.transitionTimer&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(function(){L.transitionTimer&&(L.transitionTimer=null,f.default.logAction(f.default.LOG_MINOR,"ConnectionManager "+b.state+" timer expired","requesting new state: "+b.failState),L.notifyState({state:b.failState}))},b.retryDelay)},F.prototype.cancelTransitionTimer=function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)},F.prototype.startSuspendTimer=function(){var b=this;this.suspendTimer||(this.suspendTimer=setTimeout(function(){b.suspendTimer&&(b.suspendTimer=null,f.default.logAction(f.default.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),b.states.connecting.failState="suspended",b.notifyState({state:"suspended"}))},this.connectionStateTtl))},F.prototype.checkSuspendTimer=function(b){b!=="disconnected"&&b!=="suspended"&&b!=="connecting"&&this.cancelSuspendTimer()},F.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)},F.prototype.startRetryTimer=function(b){var L=this;this.retryTimer=setTimeout(function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),L.retryTimer=null,L.requestState({state:"connecting"})},b)},F.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)},F.prototype.notifyState=function(b){var L=this,B,_,W=b.state,Y=W==="disconnected"&&(this.state===this.states.connected||this.state===this.states.synchronizing||b.retryImmediately||this.state===this.states.connecting&&b.error&&d.default.isTokenErr(b.error)&&!(this.errorReason&&d.default.isTokenErr(this.errorReason)));if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+W+(Y?"; will retry connection immediately":"")),W!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(b.state),(W==="suspended"||W==="connected")&&(this.disconnectedRetryCount=0),!this.state.terminal)){var X=this.states[b.state],te=X.retryDelay;X.state==="disconnected"&&(this.disconnectedRetryCount++,te=v.getRetryTime(X.retryDelay,this.disconnectedRetryCount));var re=new E.default(this.state.state,X.state,te,b.error||((_=(B=P.default)[X.state])===null||_===void 0?void 0:_.call(B)));if(Y){var le=function(){L.state===L.states.disconnected&&(L.lastAutoReconnectAttempt=v.now(),L.requestState({state:"connecting"}))},Z=this.lastAutoReconnectAttempt&&v.now()-this.lastAutoReconnectAttempt+1;Z&&Z<1e3?(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+Z+"ms ago, waiting another "+(1e3-Z)+"ms before trying again"),setTimeout(le,1e3-Z)):R.default.Config.nextTick(le)}else(W==="disconnected"||W==="suspended")&&this.startRetryTimer(te);(W==="disconnected"&&!Y||W==="suspended"||X.terminal)&&R.default.Config.nextTick(function(){L.disconnectAllTransports()}),W=="connected"&&!this.activeProtocol&&f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(re),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(W,re.reason),this.failQueuedMessages(re.reason))}},F.prototype.requestState=function(b){var L=this,B,_,W=b.state;if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+W+"; current state: "+this.state.state),W!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(W),!(W=="connecting"&&this.state.state=="connected")&&!(W=="closing"&&this.state.state=="closed"))){var Y=this.states[W],X=new E.default(this.state.state,Y.state,null,b.error||((_=(B=P.default)[Y.state])===null||_===void 0?void 0:_.call(B)));this.enactStateChange(X),W=="connecting"&&R.default.Config.nextTick(function(){L.startConnect()}),W=="closing"&&this.closeImpl()}},F.prototype.startConnect=function(){var b=this;if(this.state!==this.states.connecting){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}var L=this.realtime.auth,B=++this.connectCounter,_=function(){b.checkConnectionStateFreshness(),b.getTransportParams(function(Y){if(Y.mode==="recover"&&Y.options.recover){var X=U(Y.options.recover);X&&b.realtime.channels.recoverChannels(X.channelSerials)}B===b.connectCounter&&b.connectImpl(Y,B)})};if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),L.method==="basic")_();else{var W=function(Y){B===b.connectCounter&&(Y?b.actOnErrorFromAuthorize(Y):_())};this.errorReason&&d.default.isTokenErr(this.errorReason)?L._forceNewToken(null,null,W):L._ensureValidAuthCredentials(!1,W)}},F.prototype.connectImpl=function(b,L){var B=this.state.state;B!==this.states.connecting.state&&B!==this.states.connected.state?f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+B):this.pendingTransports.length?f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):B==this.states.connected.state?this.upgradeIfNeeded(b):this.transports.length>1&&this.getTransportPreference()?this.connectPreference(b,L):this.connectBase(b,L)},F.prototype.connectPreference=function(b,L){var B=this,_=this.getTransportPreference(),W=!1;v.arrIn(this.transports,_)||(this.unpersistTransportPreference(),this.connectImpl(b,L)),f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectPreference()","Trying to connect with stored transport preference "+_);var Y=setTimeout(function(){W=!0,B.state.state!==B.states.connected.state&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectPreference()","Shortcircuit connection attempt with "+_+" failed; clearing preference and trying from scratch"),B.disconnectAllTransports(),B.unpersistTransportPreference()),B.connectImpl(b,L)},this.options.timeouts.preferenceConnectTimeout);b.host=this.httpHosts[0],this.tryATransport(b,_,function(X,te){clearTimeout(Y),W&&te?(te.off(),te.disconnect(),v.arrDeleteValue(B.pendingTransports,te)):!te&&!X&&(B.unpersistTransportPreference(),B.connectImpl(b,L))})},F.prototype.connectBase=function(b,L){var B=this,_=function(re){B.notifyState({state:B.states.connecting.failState,error:re})},W=this.httpHosts.slice(),Y=function(re,le){L===B.connectCounter&&!le&&!re&&te()};f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectBase()","Trying to connect with base transport "+this.baseTransport);var X=W.shift();if(!X){_(new y.default("Unable to connect (no available host)",80003,404));return}b.host=X;var te=function(){if(!W.length){_(new y.default("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!B.realtime.http.checkConnectivity){_(new y.PartialErrorInfo("Internal error: Http.checkConnectivity not set",null,500));return}B.realtime.http.checkConnectivity(function(re,le){if(L===B.connectCounter){if(re){_(re);return}if(!le){_(new y.default("Unable to connect (network unreachable)",80003,404));return}b.host=v.arrPopRandomElement(W),B.tryATransport(b,B.baseTransport,Y)}})};if(this.forceFallbackHost&&W.length){this.forceFallbackHost=!1,te();return}this.tryATransport(b,this.baseTransport,Y)},F.prototype.getUpgradePossibilities=function(){var b=this.activeProtocol.getTransport().shortName,L=v.arrIndexOf(this.upgradeTransports,b);return this.upgradeTransports.slice(L+1)},F.prototype.upgradeIfNeeded=function(b){var L=this,B=this.getUpgradePossibilities();f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.upgradeIfNeeded()","upgrade possibilities: "+R.default.Config.inspect(B)),B.length&&v.arrForEach(B,function(_){var W=L.createTransportParams(b.host,"upgrade");L.tryATransport(W,_,x)})},F.prototype.closeImpl=function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),v.safeArrForEach(this.pendingTransports,function(b){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+b),b&&b.close()}),v.safeArrForEach(this.proposedTransports,function(b){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.closeImpl()","Disposing of proposed transport: "+b),b&&b.dispose()}),this.activeProtocol&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})},F.prototype.onAuthUpdated=function(b,L){var B=this,_;switch(this.state.state){case"connected":{if(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport"),(this.pendingTransports.length||this.proposedTransports.length)&&this.state!==this.states.synchronizing){this.disconnectAllTransports(!0);var W=this.activeProtocol.getTransport().params;R.default.Config.nextTick(function(){B.state.state==="connected"&&B.upgradeIfNeeded(W)})}var Y=(_=this.activeProtocol)===null||_===void 0?void 0:_.getTransport();Y&&Y.onAuthUpdated&&Y.onAuthUpdated(b);var X=m.default.fromValues({action:p.AUTH,auth:{accessToken:b.token}});this.send(X);var te=function(){B.off(re),L(null,b)},re=function(Z){Z.current==="failed"&&(B.off(te),B.off(re),L(Z.reason||B.getStateError()))};this.once("connectiondetails",te),this.on("connectionstate",re);break}case"connecting":f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");var le=function(Z){switch(Z.current){case"connected":B.off(le),L(null,b);break;case"failed":case"closed":case"suspended":B.off(le),L(Z.reason||B.getStateError());break}};this.on("connectionstate",le),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}},F.prototype.disconnectAllTransports=function(b){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"+(b?" except the active transport":"")),this.connectCounter++,v.safeArrForEach(this.pendingTransports,function(L){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+L),L&&L.disconnect()}),this.pendingTransports=[],v.safeArrForEach(this.proposedTransports,function(L){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disposing of proposed transport: "+L),L&&L.dispose()}),this.proposedTransports=[],this.activeProtocol&&!b&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())},F.prototype.send=function(b,L,B){B=B||x;var _=this.state;if(_.sendEvents){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new S.PendingMessage(b,B));return}var W=L&&_.queueEvents||_.forceQueueEvents;if(!W){var Y="rejecting event, queueEvent was "+L+", state was "+_.state;f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.send()",Y),B(this.errorReason||new y.default(Y,9e4,400));return}f.default.shouldLog(f.default.LOG_MICRO)&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+m.default.stringify(b)),this.queue(b,B)},F.prototype.sendImpl=function(b){var L=b.message;b.ackRequired&&!b.sendAttempted&&(L.msgSerial=this.msgSerial++);try{this.activeProtocol.send(b)}catch(B){f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+B.stack)}},F.prototype.queue=function(b,L){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.queue()","queueing event");var B=this.queuedMessages.last(),_=this.options.maxMessageSize;B&&!B.sendAttempted&&j(B.message,b,_)?(B.merged||(B.callback=w.default.create([B.callback]),B.merged=!0),B.callback.push(L)):this.queuedMessages.push(new S.PendingMessage(b,L))},F.prototype.sendQueuedMessages=function(){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");for(var b;b=this.queuedMessages.shift();)this.sendImpl(b)},F.prototype.queuePendingMessages=function(b){b&&b.length&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+b.length+" pending messages"),this.queuedMessages.prepend(b))},F.prototype.failQueuedMessages=function(b){var L=this.queuedMessages.count();L>0&&(f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+L+" queued messages, err = "+v.inspectError(b)),this.queuedMessages.completeAllMessages(b))},F.prototype.onChannelMessage=function(b,L){var B=this.activeProtocol&&L===this.activeProtocol.getTransport(),_=v.arrIn(this.pendingTransports,L)&&this.state==this.states.synchronizing;B||_?this.realtime.channels.onChannelMessage(b):v.arrIndexOf([p.ACK,p.NACK,p.ERROR],b.action)>-1?this.realtime.channels.onChannelMessage(b):f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onChannelMessage()","received message "+JSON.stringify(b)+"on defunct transport; discarding")},F.prototype.ping=function(b,L){var B=this;if(b){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.ping()","transport = "+b);var _=function(){b.off("heartbeat",X),L(new y.default("Timeout waiting for heartbeat response",5e4,500))},W=v.now(),Y=v.cheapRandStr(),X=function(he){if(he===Y){b.off("heartbeat",X),clearTimeout(te);var Me=v.now()-W;L(null,Me)}},te=setTimeout(_,this.options.timeouts.realtimeRequestTimeout);b.on("heartbeat",X),b.ping(Y);return}if(this.state.state!=="connected"){L(new y.default("Unable to ping service; not connected",4e4,400));return}var re=!1,le=function(he,Me){B.off("transport.active",Z),re||(re=!0,L(he,Me))},Z=function(){re||(re=!0,R.default.Config.nextTick(function(){B.ping(null,L)}))};this.on("transport.active",Z),this.ping(this.activeProtocol.getTransport(),le)},F.prototype.abort=function(b){this.activeProtocol.getTransport().fail(b)},F.prototype.registerProposedTransport=function(b){this.proposedTransports.push(b)},F.prototype.getTransportPreference=function(){var b,L;return this.transportPreference||s()&&((L=(b=R.default.WebStorage)===null||b===void 0?void 0:b.get)===null||L===void 0?void 0:L.call(b,D))},F.prototype.persistTransportPreference=function(b){var L,B;v.arrIn(T.default.upgradeTransports,b.shortName)&&(this.transportPreference=b.shortName,s()&&((B=(L=R.default.WebStorage)===null||L===void 0?void 0:L.set)===null||B===void 0||B.call(L,D,b.shortName)))},F.prototype.unpersistTransportPreference=function(){var b,L;this.transportPreference=null,s()&&((L=(b=R.default.WebStorage)===null||b===void 0?void 0:b.remove)===null||L===void 0||L.call(b,D))},F.prototype.actOnErrorFromAuthorize=function(b){if(b.code===40171)this.notifyState({state:"failed",error:b});else if(b.code===40102)this.notifyState({state:"failed",error:b});else if(b.statusCode===l.default.Forbidden){var L="Client configured authentication provider returned 403; failing the connection";f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",L),this.notifyState({state:"failed",error:new y.default(L,80019,403,b)})}else{var L="Client configured authentication provider request failed";f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",L),this.notifyState({state:this.state.failState,error:new y.default(L,80019,401,b)})}},F.prototype.onConnectionDetailsUpdate=function(b,L){if(b){this.connectionDetails=b,b.maxMessageSize&&(this.options.maxMessageSize=b.maxMessageSize);var B=b.clientId;if(B){var _=this.realtime.auth._uncheckedSetClientId(B);if(_){f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",_.message),L.fail(_);return}}var W=b.connectionStateTtl;W&&(this.connectionStateTtl=W),this.maxIdleInterval=b.maxIdleInterval,this.emit("connectiondetails",b)}},F.supportedTransports={},F}(C.default);r.default=V}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(7)),m=i.__importDefault(o(2)),v=function(S){i.__extends(T,S);function T(){var R=S.call(this)||this;return R.messages=[],R}return T.prototype.count=function(){return this.messages.length},T.prototype.push=function(R){this.messages.push(R)},T.prototype.shift=function(){return this.messages.shift()},T.prototype.last=function(){return this.messages[this.messages.length-1]},T.prototype.copyAll=function(){return this.messages.slice()},T.prototype.append=function(R){this.messages.push.apply(this.messages,R)},T.prototype.prepend=function(R){this.messages.unshift.apply(this.messages,R)},T.prototype.completeMessages=function(R,C,O){m.default.logAction(m.default.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+R+"; count = "+C),O=O||null;var f=this.messages;if(f.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");var E=f[0];if(E){var P=E.message.msgSerial,y=R+C;if(y>P)for(var d=f.splice(0,y-P),h=0,w=d;h<w.length;h++){var c=w[h];c.callback(O)}f.length==0&&this.emit("idle")}},T.prototype.completeAllMessages=function(R){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,R)},T.prototype.resetSendAttempted=function(){for(var R=0,C=this.messages;R<C.length;R++){var O=C[R];O.sendAttempted=!1}},T.prototype.clear=function(){m.default.logAction(m.default.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")},T}(a.default);r.default=v},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function a(m,v,S,T){this.previous=m,this.current=v,S&&(this.retryIn=S),T&&(this.reason=T)}return a}();r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(10)),m=i.__importDefault(o(7)),v=i.__importStar(o(1)),S=i.__importDefault(o(33)),T=i.__importDefault(o(2)),R=i.__importDefault(o(54)),C=i.__importDefault(o(9)),O=i.__importDefault(o(39)),f=i.__importStar(o(4)),E=i.__importDefault(o(16)),P=i.__importDefault(o(21)),y=a.default.Action,d=function(){};function h(u){if(u&&"params"in u&&!v.isObject(u.params))return new f.default("options.params must be an object",4e4,400);if(u&&"modes"in u){if(!v.isArray(u.modes))return new f.default("options.modes must be an array",4e4,400);for(var l=0;l<u.modes.length;l++){var s=u.modes[l];if(!s||typeof s!="string"||!v.arrIn(a.default.channelModes,String.prototype.toUpperCase.call(s)))return new f.default("Invalid channel mode: "+s,4e4,400)}}}var w=function(u){i.__extends(l,u);function l(s,g,p){var x=u.call(this,s,g,p)||this;return x.retryCount=0,x.history=function(D,N){if(T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name),N===void 0)if(typeof D=="function")N=D,D=null;else{if(this.rest.options.promises)return v.promisify(this,"history",arguments);N=d}if(D&&D.untilAttach){if(this.state!=="attached"){N(new f.default("option untilAttach requires the channel to be attached",4e4,400));return}if(!this.properties.attachSerial){N(new f.default("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400));return}delete D.untilAttach,D.from_serial=this.properties.attachSerial}S.default.prototype._history.call(this,D,N)},x.whenState=function(D,N){return m.default.prototype.whenState.call(x,D,x.state,N)},T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel()","started; name = "+g),x.realtime=s,x.presence=new R.default(x),x.connectionManager=s.connection.connectionManager,x.state="initialized",x.subscriptions=new m.default,x.syncChannelSerial=void 0,x.properties={attachSerial:void 0,channelSerial:void 0},x.setOptions(p),x.errorReason=null,x._requestedFlags=null,x._mode=null,x._attachResume=!1,x._decodingContext={channelOptions:x.channelOptions,plugins:s.options.plugins||{},baseEncodedPreviousPayload:void 0},x._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},x._allChannelChanges=new m.default,x}return l.prototype.invalidStateError=function(){return new f.default("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)},l.processListenerArgs=function(s){return s=Array.prototype.slice.call(s),typeof s[0]=="function"&&s.unshift(null),s[s.length-1]==null&&s.pop(),s},l.prototype.setOptions=function(s,g){var p=this.channelOptions;if(!g&&this.rest.options.promises)return v.promisify(this,"setOptions",arguments);var x=g||function(N){N&&T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.setOptions()","Set options failed: "+N.toString())},D=h(s);if(D){x(D);return}S.default.prototype.setOptions.call(this,s),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(s,p)?(this.attachImpl(),this._allChannelChanges.once(["attached","update","detached","failed"],function(N){switch(this.event){case"update":case"attached":x==null||x(null);return;default:x==null||x(N.reason);return}})):x()},l.prototype._shouldReattachToSetOptions=function(s,g){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(s!=null&&s.params){var p=c(s.params),x=c(g.params);if(Object.keys(p).length!==Object.keys(x).length||!v.shallowEquals(x,p))return!0}return!!(s!=null&&s.modes&&(!g.modes||!v.arrEquals(s.modes,g.modes)))},l.prototype.publish=function(){for(var s=this,g=[],p=0;p<arguments.length;p++)g[p]=arguments[p];var x=g[0],D=g.length,N=g[D-1];if(typeof N!="function"){if(this.realtime.options.promises)return v.promisify(this,"publish",arguments);N=d,++D}if(!this.connectionManager.activeState()){N(this.connectionManager.getError());return}if(D==2)if(v.isObject(x))x=[C.default.fromValues(x)];else if(v.isArray(x))x=C.default.fromValuesArray(x);else throw new f.default("The single-argument form of publish() expects a message object or an array of message objects",40013,400);else x=[C.default.fromValues({name:g[0],data:g[1]})];var k=this.realtime.options.maxMessageSize;C.default.encodeArray(x,this.channelOptions,function(I){if(I){N(I);return}var M=C.default.getMessagesSize(x);if(M>k){N(new f.default("Maximum size of messages that can be published at once exceeded ( was "+M+" bytes; limit is "+k+" bytes)",40009,400));return}s.__publish(x,N)})},l.prototype.__publish=function(s,g){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.publish()","message count = "+s.length);var p=this.state;switch(p){case"failed":case"suspended":g(f.default.fromValues(this.invalidStateError()));break;default:{T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+p);var x=new a.default;x.action=y.MESSAGE,x.channel=this.name,x.messages=s,this.sendMessage(x,g);break}}},l.prototype.onEvent=function(s){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.onEvent()","received message");for(var g=this.subscriptions,p=0;p<s.length;p++){var x=s[p];g.emit(x.name,x)}},l.prototype.attach=function(s,g){var p;if(typeof s=="function"?(g=s,p=null):p=s,!g){if(this.realtime.options.promises)return v.promisify(this,"attach",arguments);g=function(x){x&&T.default.logAction(T.default.LOG_MAJOR,"RealtimeChannel.attach()","Channel attach failed: "+x.toString())}}if(p)T.default.deprecated("The ability to pass an array of channel mode flags as the first argument of `RealtimeChannel.attach()`","To set channel mode flags, populate the `modes` property of the channel options object that you pass to `Channels.get()` or `RealtimeChannel.setOptions()`."),this._requestedFlags=p;else if(this.state==="attached"){g(null,null);return}this._attach(!1,null,g)},l.prototype._attach=function(s,g,p){p||(p=function(D){D&&T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+D.toString())});var x=this.connectionManager;if(!x.activeState()){p(x.getError());return}(this.state!=="attaching"||s)&&this.requestState("attaching",g),this.once(function(D){switch(this.event){case"attached":p==null||p(null,D);break;case"detached":case"suspended":case"failed":p==null||p(D.reason||x.getError()||new f.default("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":p==null||p(new f.default("Attach request superseded by a subsequent detach request",9e4,409));break}})},l.prototype.attachImpl=function(){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");var s=a.default.fromValues({action:y.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this._requestedFlags?s.encodeModesToFlags(this._requestedFlags):this.channelOptions.modes&&s.encodeModesToFlags(v.allToUpperCase(this.channelOptions.modes)),this._attachResume&&s.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(s.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(s,d)},l.prototype.detach=function(s){if(!s){if(this.realtime.options.promises)return v.promisify(this,"detach",arguments);s=d}var g=this.connectionManager;if(!g.activeState()){s(g.getError());return}switch(this.state){case"suspended":this.notifyState("detached"),s();break;case"detached":s();break;case"failed":s(new f.default("Unable to detach; channel state = failed",90001,400));break;default:this.requestState("detaching");case"detaching":this.once(function(p){switch(this.event){case"detached":s();break;case"attached":case"suspended":case"failed":s(p.reason||g.getError()||new f.default("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":s(new f.default("Detach request superseded by a subsequent attach request",9e4,409));break}})}},l.prototype.detachImpl=function(s){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");var g=a.default.fromValues({action:y.DETACH,channel:this.name});this.sendMessage(g,s||d)},l.prototype.subscribe=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];var p=l.processListenerArgs(s),x=p[0],D=p[1],N=p[2];if(!N&&this.realtime.options.promises)return v.promisify(this,"subscribe",[x,D]);if(this.state==="failed"){N==null||N(f.default.fromValues(this.invalidStateError()));return}return x&&typeof x=="object"&&!Array.isArray(x)?this._subscribeFilter(x,D):this.subscriptions.on(x,D),this.attach(N||d)},l.prototype._subscribeFilter=function(s,g){var p=function(x){var D,N,k,I,M,A,j={name:x.name,refTimeserial:(N=(D=x.extras)===null||D===void 0?void 0:D.ref)===null||N===void 0?void 0:N.timeserial,refType:(I=(k=x.extras)===null||k===void 0?void 0:k.ref)===null||I===void 0?void 0:I.type,isRef:!!(!((A=(M=x.extras)===null||M===void 0?void 0:M.ref)===null||A===void 0)&&A.timeserial),clientId:x.clientId};Object.entries(s).find(function(U){var z=U[0],V=U[1];return V!==void 0?j[z]!==V:!1})||g(x)};this._addFilteredSubscription(s,g,p),this.subscriptions.on(p)},l.prototype._addFilteredSubscription=function(s,g,p){var x;if(this.filteredSubscriptions||(this.filteredSubscriptions=new Map),this.filteredSubscriptions.has(g)){var D=this.filteredSubscriptions.get(g);D.set(s,((x=D==null?void 0:D.get(s))===null||x===void 0?void 0:x.concat(p))||[p])}else this.filteredSubscriptions.set(g,new Map([[s,[p]]]))},l.prototype._getAndDeleteFilteredSubscriptions=function(s,g){var p=this;if(!this.filteredSubscriptions)return[];if(!g&&s)return Array.from(this.filteredSubscriptions.entries()).map(function(k){var I,M=k[0],A=k[1],j=A.get(s);return A.delete(s),A.size===0&&((I=p.filteredSubscriptions)===null||I===void 0||I.delete(M)),j}).reduce(function(k,I){var M;return I?(M=k).concat.apply(M,I):k},[]);if(!g||!this.filteredSubscriptions.has(g))return[];var x=this.filteredSubscriptions.get(g);if(!s){var D=Array.from(x.values()).reduce(function(k,I){return k.concat.apply(k,I)},[]);return this.filteredSubscriptions.delete(g),D}var N=x.get(s);return x.delete(s),N||[]},l.prototype.unsubscribe=function(){for(var s=this,g,p=[],x=0;x<arguments.length;x++)p[x]=arguments[x];var D=l.processListenerArgs(p),N=D[0],k=D[1];if(typeof N=="object"&&!k||!((g=this.filteredSubscriptions)===null||g===void 0)&&g.has(k)){this._getAndDeleteFilteredSubscriptions(N,k).forEach(function(I){return s.subscriptions.off(I)});return}this.subscriptions.off(N,k)},l.prototype.sync=function(){switch(this.state){case"initialized":case"detaching":case"detached":throw new f.PartialErrorInfo("Unable to sync to channel; not attached",4e4)}var s=this.connectionManager;if(!s.activeState())throw s.getError();var g=a.default.fromValues({action:y.SYNC,channel:this.name});this.syncChannelSerial&&(g.channelSerial=this.syncChannelSerial),s.send(g)},l.prototype.sendMessage=function(s,g){this.connectionManager.send(s,this.realtime.options.queueMessages,g)},l.prototype.sendPresence=function(s,g){var p=a.default.fromValues({action:y.PRESENCE,channel:this.name,presence:v.isArray(s)?E.default.fromValuesArray(s):[E.default.fromValues(s)]});this.sendMessage(p,g)},l.prototype.onMessage=function(s){(s.action===y.ATTACHED||s.action===y.MESSAGE||s.action===y.PRESENCE)&&this.setChannelSerial(s.channelSerial);var g,p=!1;switch(s.action){case y.ATTACHED:{this.properties.attachSerial=s.channelSerial,this._mode=s.getMode(),this.params=s.params||{};var x=s.decodeModesFromFlags();this.modes=x&&v.allToLowerCase(x)||void 0;var D=s.hasFlag("RESUMED"),N=s.hasFlag("HAS_PRESENCE"),k=s.hasFlag("HAS_BACKLOG");if(this.state==="attached"){D||this.presence.onAttached(N);var I=new O.default(this.state,this.state,D,k,s.error);this._allChannelChanges.emit("update",I),(!D||this.channelOptions.updateOnAttached)&&this.emit("update",I)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",s.error,D,N,k);break}case y.DETACHED:{var M=s.error?f.default.fromValues(s.error):new f.default("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",M):this.state==="attaching"?this.notifyState("suspended",M):this.requestState("attaching",M);break}case y.SYNC:if(p=!0,g=this.syncChannelSerial=s.channelSerial,!s.presence)break;case y.PRESENCE:{for(var A=s.presence,j=s.id,U=s.connectionId,z=s.timestamp,V=this.channelOptions,G=void 0,F=0;F<A.length;F++)try{G=A[F],E.default.decode(G,V),G.connectionId||(G.connectionId=U),G.timestamp||(G.timestamp=z),G.id||(G.id=j+":"+F)}catch(Y){T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()",Y.toString())}this.presence.setPresence(A,p,g);break}case y.MESSAGE:{if(this.state!=="attached"){T.default.logAction(T.default.LOG_MAJOR,"RealtimeChannel.onMessage()",'Message "'+s.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}var b=s.messages,L=b[0],B=b[b.length-1],j=s.id,U=s.connectionId,z=s.timestamp;if(L.extras&&L.extras.delta&&L.extras.delta.from!==this._lastPayload.messageId){var _='Delta message decode failure - previous message not available for message "'+s.id+'" on this channel "'+this.name+'".';T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()",_),this._startDecodeFailureRecovery(new f.default(_,40018,400));break}for(var F=0;F<b.length;F++){var _=b[F];try{C.default.decode(_,this._decodingContext)}catch(Z){switch(T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()",Z.toString()),Z.code){case 40018:this._startDecodeFailureRecovery(Z);return;case 40019:case 40021:this.notifyState("failed",Z);return}}_.connectionId||(_.connectionId=U),_.timestamp||(_.timestamp=z),_.id||(_.id=j+":"+F)}this._lastPayload.messageId=B.id,this._lastPayload.protocolMessageChannelSerial=s.channelSerial,this.onEvent(b);break}case y.ERROR:{var W=s.error;W&&W.code==80016?this.checkPendingState():this.notifyState("failed",f.default.fromValues(W));break}default:T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()","Fatal protocol error: unrecognised action ("+s.action+")"),this.connectionManager.abort(P.default.unknownChannelErr())}},l.prototype._startDecodeFailureRecovery=function(s){var g=this;this._lastPayload.decodeFailureRecoveryInProgress||(T.default.logAction(T.default.LOG_MAJOR,"RealtimeChannel.onMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,s,function(){g._lastPayload.decodeFailureRecoveryInProgress=!1}))},l.prototype.onAttached=function(){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)},l.prototype.notifyState=function(s,g,p,x,D){if(T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+s),this.clearStateTimer(),v.arrIn(["detached","suspended","failed"],s)&&(this.properties.channelSerial=null),s!==this.state){this.presence.actOnChannelState(s,x,g),s==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),g&&(this.errorReason=g);var N=new O.default(this.state,s,p,D,g),k=s==="failed"?T.default.LOG_ERROR:T.default.LOG_MAJOR;T.default.logAction(k,'Channel state for channel "'+this.name+'"',s+(g?"; reason: "+g:"")),s!=="attaching"&&s!=="suspended"&&(this.retryCount=0),s==="attached"&&this.onAttached(),s==="attached"?this._attachResume=!0:(s==="detaching"||s==="failed")&&(this._attachResume=!1),this.state=s,this._allChannelChanges.emit(s,N),this.emit(s,N)}},l.prototype.requestState=function(s,g){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+s),this.notifyState(s,g),this.checkPendingState()},l.prototype.checkPendingState=function(){var s=this.connectionManager.state;if(!(s.sendEvents||s.forceQueueEvents)){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break}},l.prototype.timeoutPendingState=function(){switch(this.state){case"attaching":{var s=new f.default("Channel attach timed out",90007,408);this.notifyState("suspended",s);break}case"detaching":{var s=new f.default("Channel detach timed out",90007,408);this.notifyState("attached",s);break}default:this.checkPendingState();break}},l.prototype.startStateTimerIfNotRunning=function(){var s=this;this.stateTimer||(this.stateTimer=setTimeout(function(){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),s.stateTimer=null,s.timeoutPendingState()},this.realtime.options.timeouts.realtimeRequestTimeout))},l.prototype.clearStateTimer=function(){var s=this.stateTimer;s&&(clearTimeout(s),this.stateTimer=null)},l.prototype.startRetryTimer=function(){var s=this;if(!this.retryTimer){this.retryCount++;var g=v.getRetryTime(this.realtime.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(function(){s.state==="suspended"&&s.connectionManager.state.sendEvents&&(s.retryTimer=null,T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),s.requestState("attaching"))},g)}},l.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)},l.prototype.getReleaseErr=function(){var s=this.state;return s==="initialized"||s==="detached"||s==="failed"?null:new f.default("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+s,90001,400)},l.prototype.setChannelSerial=function(s){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+s+"; previous = "+this.properties.channelSerial),s&&(this.properties.channelSerial=s)},l}(S.default);function c(u){var l=u||{};l.agent;var s=i.__rest(l,["agent"]);return s}r.default=w},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function a(m,v,S,T,R){this.previous=m,this.current=v,v==="attached"&&(this.resumed=S,this.hasBacklog=T),R&&(this.reason=R)}return a}();r.default=i},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){var a=i,m=a.lib,v=m.WordArray,S=m.Hasher,T=a.algo,R=[],C=T.SHA1=S.extend({_doReset:function(){this._hash=new v.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(O,f){for(var E=this._hash.words,P=E[0],y=E[1],d=E[2],h=E[3],w=E[4],c=0;c<80;c++){if(c<16)R[c]=O[f+c]|0;else{var u=R[c-3]^R[c-8]^R[c-14]^R[c-16];R[c]=u<<1|u>>>31}var l=(P<<5|P>>>27)+w+R[c];c<20?l+=(y&d|~y&h)+1518500249:c<40?l+=(y^d^h)+1859775393:c<60?l+=(y&d|y&h|d&h)-1894007588:l+=(y^d^h)-899497514,w=h,h=d,d=y<<30|y>>>2,y=P,P=l}E[0]=E[0]+P|0,E[1]=E[1]+y|0,E[2]=E[2]+d|0,E[3]=E[3]+h|0,E[4]=E[4]+w|0},_doFinalize:function(){var O=this._data,f=O.words,E=this._nDataBytes*8,P=O.sigBytes*8;return f[P>>>5]|=128<<24-P%32,f[(P+64>>>9<<4)+14]=Math.floor(E/4294967296),f[(P+64>>>9<<4)+15]=E,O.sigBytes=f.length*4,this._process(),this._hash},clone:function(){var O=S.clone.call(this);return O._hash=this._hash.clone(),O}});a.SHA1=S._createHelper(C),a.HmacSHA1=S._createHmacHelper(C)}(),i.SHA1})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});function i(c){if(c===void 0)return"undefined";var u,l;if(c instanceof ArrayBuffer?(l="ArrayBuffer",u=new DataView(c)):c instanceof DataView&&(l="DataView",u=c),!u)return JSON.stringify(c);for(var s=[],g=0;g<c.byteLength;g++){if(g>20){s.push("...");break}var p=u.getUint8(g).toString(16);p.length===1&&(p="0"+p),s.push(p)}return"<"+l+" "+s.join(" ")+">"}function a(c,u,l){for(var s=0,g=l.length;s<g;s++){var p=l.charCodeAt(s);if(p<128){c.setUint8(u++,p>>>0&127|0);continue}if(p<2048){c.setUint8(u++,p>>>6&31|192),c.setUint8(u++,p>>>0&63|128);continue}if(p<65536){c.setUint8(u++,p>>>12&15|224),c.setUint8(u++,p>>>6&63|128),c.setUint8(u++,p>>>0&63|128);continue}if(p<1114112){c.setUint8(u++,p>>>18&7|240),c.setUint8(u++,p>>>12&63|128),c.setUint8(u++,p>>>6&63|128),c.setUint8(u++,p>>>0&63|128);continue}throw new Error("bad codepoint "+p)}}function m(c,u,l){for(var s="",g=u,p=u+l;g<p;g++){var x=c.getUint8(g);if(!(x&128)){s+=String.fromCharCode(x);continue}if((x&224)===192){s+=String.fromCharCode((x&15)<<6|c.getUint8(++g)&63);continue}if((x&240)===224){s+=String.fromCharCode((x&15)<<12|(c.getUint8(++g)&63)<<6|(c.getUint8(++g)&63)<<0);continue}if((x&248)===240){s+=String.fromCharCode((x&7)<<18|(c.getUint8(++g)&63)<<12|(c.getUint8(++g)&63)<<6|(c.getUint8(++g)&63)<<0);continue}throw new Error("Invalid byte "+x.toString(16))}return s}function v(c){for(var u=0,l=0,s=c.length;l<s;l++){var g=c.charCodeAt(l);if(g<128){u+=1;continue}if(g<2048){u+=2;continue}if(g<65536){u+=3;continue}if(g<1114112){u+=4;continue}throw new Error("bad codepoint "+g)}return u}function S(c,u){var l=w(c,u);if(l!==0){var s=new ArrayBuffer(l),g=new DataView(s);return h(c,g,0,u),s}}var T=65536*65536,R=1/T;function C(c,u){return u=u||0,c.getInt32(u)*T+c.getUint32(u+4)}function O(c,u){return u=u||0,c.getUint32(u)*T+c.getUint32(u+4)}function f(c,u,l){l<9223372036854776e3?(c.setInt32(u,Math.floor(l*R)),c.setInt32(u+4,l&-1)):(c.setUint32(u,2147483647),c.setUint32(u+4,2147483647))}function E(c,u,l){l<18446744073709552e3?(c.setUint32(u,Math.floor(l*R)),c.setInt32(u+4,l&-1)):(c.setUint32(u,4294967295),c.setUint32(u+4,4294967295))}var P=function(){function c(u,l){var s=this;this.map=function(g){for(var p={},x=0;x<g;x++){var D=s.parse();p[D]=s.parse()}return p},this.bin=function(g){var p=new ArrayBuffer(g);return new Uint8Array(p).set(new Uint8Array(s.view.buffer,s.offset,g),0),s.offset+=g,p},this.buf=this.bin,this.str=function(g){var p=m(s.view,s.offset,g);return s.offset+=g,p},this.array=function(g){for(var p=new Array(g),x=0;x<g;x++)p[x]=s.parse();return p},this.ext=function(g){return s.offset+=g,{type:s.view.getInt8(s.offset),data:s.buf(g)}},this.parse=function(){var g=s.view.getUint8(s.offset),p,x;if(!(g&128))return s.offset++,g;if((g&240)===128)return x=g&15,s.offset++,s.map(x);if((g&240)===144)return x=g&15,s.offset++,s.array(x);if((g&224)===160)return x=g&31,s.offset++,s.str(x);if((g&224)===224)return p=s.view.getInt8(s.offset),s.offset++,p;switch(g){case 192:return s.offset++,null;case 193:s.offset++;return;case 194:return s.offset++,!1;case 195:return s.offset++,!0;case 196:return x=s.view.getUint8(s.offset+1),s.offset+=2,s.bin(x);case 197:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.bin(x);case 198:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.bin(x);case 199:return x=s.view.getUint8(s.offset+1),s.offset+=2,s.ext(x);case 200:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.ext(x);case 201:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.ext(x);case 202:return p=s.view.getFloat32(s.offset+1),s.offset+=5,p;case 203:return p=s.view.getFloat64(s.offset+1),s.offset+=9,p;case 204:return p=s.view.getUint8(s.offset+1),s.offset+=2,p;case 205:return p=s.view.getUint16(s.offset+1),s.offset+=3,p;case 206:return p=s.view.getUint32(s.offset+1),s.offset+=5,p;case 207:return p=O(s.view,s.offset+1),s.offset+=9,p;case 208:return p=s.view.getInt8(s.offset+1),s.offset+=2,p;case 209:return p=s.view.getInt16(s.offset+1),s.offset+=3,p;case 210:return p=s.view.getInt32(s.offset+1),s.offset+=5,p;case 211:return p=C(s.view,s.offset+1),s.offset+=9,p;case 212:return x=1,s.offset++,s.ext(x);case 213:return x=2,s.offset++,s.ext(x);case 214:return x=4,s.offset++,s.ext(x);case 215:return x=8,s.offset++,s.ext(x);case 216:return x=16,s.offset++,s.ext(x);case 217:return x=s.view.getUint8(s.offset+1),s.offset+=2,s.str(x);case 218:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.str(x);case 219:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.str(x);case 220:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.array(x);case 221:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.array(x);case 222:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.map(x);case 223:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.map(x)}throw new Error("Unknown type 0x"+g.toString(16))},this.offset=l||0,this.view=u}return c}();function y(c){var u=new DataView(c),l=new P(u),s=l.parse();if(l.offset!==c.byteLength)throw new Error(c.byteLength-l.offset+" trailing bytes");return s}function d(c,u){return Object.keys(c).filter(function(l){var s=c[l],g=typeof s;return(!u||s!=null)&&(g!=="function"||!!s.toJSON)})}function h(c,u,l,s){var g=typeof c;if(typeof c=="string"){var p=v(c);if(p<32)return u.setUint8(l,p|160),a(u,l+1,c),1+p;if(p<256)return u.setUint8(l,217),u.setUint8(l+1,p),a(u,l+2,c),2+p;if(p<65536)return u.setUint8(l,218),u.setUint16(l+1,p),a(u,l+3,c),3+p;if(p<4294967296)return u.setUint8(l,219),u.setUint32(l+1,p),a(u,l+5,c),5+p}if(ArrayBuffer.isView&&ArrayBuffer.isView(c)&&(c=c.buffer),c instanceof ArrayBuffer){var x=c.byteLength;if(x<256)return u.setUint8(l,196),u.setUint8(l+1,x),new Uint8Array(u.buffer).set(new Uint8Array(c),l+2),2+x;if(x<65536)return u.setUint8(l,197),u.setUint16(l+1,x),new Uint8Array(u.buffer).set(new Uint8Array(c),l+3),3+x;if(x<4294967296)return u.setUint8(l,198),u.setUint32(l+1,x),new Uint8Array(u.buffer).set(new Uint8Array(c),l+5),5+x}if(typeof c=="number"){if(Math.floor(c)!==c)return u.setUint8(l,203),u.setFloat64(l+1,c),9;if(c>=0){if(c<128)return u.setUint8(l,c),1;if(c<256)return u.setUint8(l,204),u.setUint8(l+1,c),2;if(c<65536)return u.setUint8(l,205),u.setUint16(l+1,c),3;if(c<4294967296)return u.setUint8(l,206),u.setUint32(l+1,c),5;if(c<18446744073709552e3)return u.setUint8(l,207),E(u,l+1,c),9;throw new Error("Number too big 0x"+c.toString(16))}if(c>=-32)return u.setInt8(l,c),1;if(c>=-128)return u.setUint8(l,208),u.setInt8(l+1,c),2;if(c>=-32768)return u.setUint8(l,209),u.setInt16(l+1,c),3;if(c>=-2147483648)return u.setUint8(l,210),u.setInt32(l+1,c),5;if(c>=-9223372036854776e3)return u.setUint8(l,211),f(u,l+1,c),9;throw new Error("Number too small -0x"+(-c).toString(16).substr(1))}if(g==="undefined")return s?0:(u.setUint8(l,212),u.setUint8(l+1,0),u.setUint8(l+2,0),3);if(c===null)return s?0:(u.setUint8(l,192),1);if(g==="boolean")return u.setUint8(l,c?195:194),1;if(typeof c.toJSON=="function")return h(c.toJSON(),u,l,s);if(g==="object"){var D,N=0,k=void 0,I=Array.isArray(c);if(I?D=c.length:(k=d(c,s),D=k.length),D<16?(u.setUint8(l,D|(I?144:128)),N=1):D<65536?(u.setUint8(l,I?220:222),u.setUint16(l+1,D),N=3):D<4294967296&&(u.setUint8(l,I?221:223),u.setUint32(l+1,D),N=5),I)for(var M=0;M<D;M++)N+=h(c[M],u,l+N,s);else if(k)for(var M=0;M<D;M++){var A=k[M];N+=h(A,u,l+N),N+=h(c[A],u,l+N,s)}return N}if(g==="function")return 0;throw new Error("Unknown type "+g)}function w(c,u){var l=typeof c;if(l==="string"){var s=v(c);if(s<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(c)&&(c=c.buffer),c instanceof ArrayBuffer){var g=c.byteLength;if(g<256)return 2+g;if(g<65536)return 3+g;if(g<4294967296)return 5+g}if(typeof c=="number"){if(Math.floor(c)!==c)return 9;if(c>=0){if(c<128)return 1;if(c<256)return 2;if(c<65536)return 3;if(c<4294967296)return 5;if(c<18446744073709552e3)return 9;throw new Error("Number too big 0x"+c.toString(16))}if(c>=-32)return 1;if(c>=-128)return 2;if(c>=-32768)return 3;if(c>=-2147483648)return 5;if(c>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+c.toString(16).substr(1))}if(l==="boolean")return 1;if(c===null)return u?0:1;if(c===void 0)return u?0:3;if(typeof c.toJSON=="function")return w(c.toJSON(),u);if(l==="object"){var p,x=0;if(Array.isArray(c)){p=c.length;for(var D=0;D<p;D++)x+=w(c[D],u)}else{var N=d(c,u);p=N.length;for(var D=0;D<p;D++){var k=N[D];x+=w(k)+w(c[k],u)}}if(p<16)return 1+x;if(p<65536)return 3+x;if(p<4294967296)return 5+x;throw new Error("Array or object too long 0x"+p.toString(16))}if(l==="function")return 0;throw new Error("Unknown type "+l)}r.default={encode:S,decode:y,inspect:i,utf8Write:a,utf8Read:m,utf8ByteCount:v}},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(30)),m=i.__importDefault(o(50)),v=i.__importDefault(o(3)),S=i.__importDefault(o(4)),T=i.__importDefault(o(55)),R=i.__importDefault(o(57)),C=i.__importDefault(o(62)),O=i.__importDefault(o(64)),f=i.__importDefault(o(68)),E=i.__importDefault(o(2)),P=o(8),y=i.__importDefault(o(65)),d=i.__importDefault(o(66)),h=i.__importDefault(o(41)),w=(0,R.default)(O.default,T.default);v.default.Crypto=w,v.default.BufferUtils=T.default,v.default.Http=C.default,v.default.Config=O.default,v.default.Transports=f.default,v.default.WebStorage=y.default,a.default.Crypto=w,m.default.Crypto=w,E.default.initLogHandlers(),v.default.Defaults=(0,P.getDefaults)(d.default),v.default.Config.agent&&(v.default.Defaults.agent+=" "+v.default.Config.agent),v.default.Config.noUpgrade&&(v.default.Defaults.upgradeTransports=[]),r.default={ErrorInfo:S.default,Rest:a.default,Realtime:m.default,msgpack:h.default}},function(n){n.exports=JSON.parse('{"name":"ably","description":"Realtime client library for Ably, the realtime messaging service","version":"1.2.50","license":"Apache-2.0","bugs":{"url":"https://github.com/ably/ably-js/issues","email":"support@ably.com"},"main":"./build/ably-node.js","typings":"./ably.d.ts","react-native":{"./build/ably-node.js":"./build/ably-reactnative.js"},"browser":{"./build/ably-node.js":"./build/ably-commonjs.js"},"files":["build/**","ably.d.ts","callbacks.d.ts","callbacks.js","promises.d.ts","promises.js","resources/**","src/**","react/**"],"dependencies":{"@ably/msgpack-js":"^0.4.0","got":"^11.8.5","ws":"^8.14.2"},"peerDependencies":{"react":">=16.8.0","react-dom":">=16.8.0"},"peerDependenciesMeta":{"react":{"optional":true},"react-dom":{"optional":true}},"devDependencies":{"@ably/vcdiff-decoder":"1.0.4","@arethetypeswrong/cli":"^0.13.1","@babel/preset-env":"^7.23.6","@testing-library/react":"^13.3.0","@types/crypto-js":"^4.0.1","@types/jmespath":"^0.15.2","@types/node":"^15.0.0","@types/request":"^2.48.7","@types/ws":"^8.2.0","@typescript-eslint/eslint-plugin":"^5.14.0","@typescript-eslint/parser":"^5.14.0","@vitejs/plugin-react":"^1.3.2","async":"ably-forks/async#requirejs","aws-sdk":"^2.1413.0","babel-loader":"^8.3.0","chai":"^4.2.0","copy-webpack-plugin":"^6.4.1","cors":"^2.8.5","crypto-js":"ably-forks/crypto-js#crypto-lite","eslint":"^7.13.0","eslint-plugin-import":"^2.28.0","eslint-plugin-jsdoc":"^40.0.0","eslint-plugin-react":"^7.32.2","eslint-plugin-react-hooks":"^4.6.0","eslint-plugin-security":"^1.4.0","express":"^4.17.1","glob":"~4.4","google-closure-compiler":"^20180610.0.1","grunt":"^1.6.1","grunt-bump":"^0.3.1","grunt-cli":"~1.2.0","grunt-closure-tools":"^1.0.0","grunt-contrib-concat":"~0.5","grunt-shell":"~1.1","grunt-webpack":"^4.0.2","hexy":"~0.2","jmespath":"^0.16.0","jsdom":"^20.0.0","kexec":"ably-forks/node-kexec#update-for-node-12","minimist":"^1.2.5","mocha":"^8.1.3","mocha-junit-reporter":"^2.2.1","null-loader":"^4.0.1","playwright":"^1.39.0","prettier":"^2.5.1","react":">=18.1.0","react-dom":">=18.1.0","requirejs":"~2.1","shelljs":"~0.8","source-map-explorer":"^2.5.2","ts-loader":"^8.2.0","tsconfig-paths-webpack-plugin":"^4.0.1","tslib":"^2.3.1","typedoc":"^0.23.8","typescript":"^4.6.4","vite":"^4.4.9","vitest":"^0.18.0","webpack":"^4.44.2","webpack-cli":"^4.2.0","webpack-node-externals":"^3.0.0"},"engines":{"node":">=5.10.x"},"repository":"ably/ably-js","jspm":{"registry":"npm","directories":{"lib":"build"},"main":"ably"},"scripts":{"start:react":"npx vite serve","grunt":"grunt","test":"grunt test","test:node":"grunt test:node","test:node:skip-build":"grunt mocha","test:webserver":"grunt test:webserver","test:playwright":"node test/support/runPlaywrightTests.js","test:react":"vitest run","concat":"grunt concat","build":"grunt build:all && npm run build:react","build:node":"grunt build:node","build:browser":"grunt build:browser","build:react":"npm run build:react:mjs && npm run build:react:cjs && cp src/platform/react-hooks/res/package.react.json react/package.json","build:react:mjs":"tsc --project src/platform/react-hooks/tsconfig.mjs.json && cp src/platform/react-hooks/res/package.mjs.json react/mjs/package.json","build:react:cjs":"tsc --project src/platform/react-hooks/tsconfig.cjs.json && cp src/platform/react-hooks/res/package.cjs.json react/cjs/package.json","requirejs":"grunt requirejs","lint":"eslint .","lint:fix":"eslint --fix .","check-closure-compiler":"grunt check-closure-compiler","prepare":"npm run build","format":"prettier --write --ignore-path .gitignore --ignore-path .prettierignore src test ably.d.ts webpack.config.js Gruntfile.js scripts/cdn_deploy.js docs/chrome-mv3.md","format:check":"prettier --check --ignore-path .gitignore --ignore-path .prettierignore src test ably.d.ts webpack.config.js Gruntfile.js scripts/cdn_deploy.js","sourcemap":"source-map-explorer build/ably.min.js","sourcemap:noencryption":"source-map-explorer build/ably.noencryption.min.js","docs":"typedoc --entryPoints ably.d.ts --out docs/generated/default --readme docs/landing-pages/default.md && typedoc --entryPoints promises.d.ts --out docs/generated/promises --name \\"ably (Promise-based)\\" --readme docs/landing-pages/promises.md && cp docs/landing-pages/choose-library.html docs/generated/index.html"}}')},function(n,r){},function(n,r,o){(function(i,a){n.exports=a(o(6),o(32),o(25))})(this,function(i){return i.HmacSHA256})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(47)),v=i.__importDefault(o(15)),S=i.__importDefault(o(20)),T=i.__importDefault(o(4)),R=i.__importDefault(o(48)),C=function(){},O=function(){function y(d){this.rest=d,this.admin=new f(d)}return y}(),f=function(){function y(d){this.rest=d,this.deviceRegistrations=new E(d),this.channelSubscriptions=new P(d)}return y.prototype.publish=function(d,h,w){var c=this.rest,u=c.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,l=a.defaultPostHeaders(c.options,u),s={},g=a.mixin({recipient:d},h);if(typeof w!="function"){if(this.rest.options.promises)return a.promisify(this,"publish",arguments);w=C}c.options.headers&&a.mixin(l,c.options.headers),c.options.pushFullWait&&a.mixin(s,{fullWait:"true"});var p=a.encodeBody(g,u);v.default.post(c,"/push/publish",p,l,s,null,function(x){return w(x)})},y}(),E=function(){function y(d){this.rest=d}return y.prototype.save=function(d,h){var w=this.rest,c=m.default.fromValues(d),u=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,l=a.defaultPostHeaders(w.options,u),s={};if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"save",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),w.options.pushFullWait&&a.mixin(s,{fullWait:"true"});var g=a.encodeBody(c,u);v.default.put(w,"/push/deviceRegistrations/"+encodeURIComponent(d.id),g,l,s,null,function(p,x,D,N){h(p,p?void 0:m.default.fromResponseBody(x,N?void 0:u))})},y.prototype.get=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c),l=d.id||d;if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"get",arguments);h=C}if(typeof l!="string"||!l.length){h(new T.default("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400));return}w.options.headers&&a.mixin(u,w.options.headers),v.default.get(w,"/push/deviceRegistrations/"+encodeURIComponent(l),u,{},null,function(s,g,p,x){h(s,s?void 0:m.default.fromResponseBody(g,x?void 0:c))})},y.prototype.list=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=this.rest.http.supportsLinkHeaders?void 0:c,l=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"list",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),new S.default(w,"/push/deviceRegistrations",l,u,function(s,g,p){return m.default.fromResponseBody(s,p?void 0:c)}).get(d,h)},y.prototype.remove=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c),l={},s=d.id||d;if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"remove",arguments);h=C}if(typeof s!="string"||!s.length){h(new T.default("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400));return}w.options.headers&&a.mixin(u,w.options.headers),w.options.pushFullWait&&a.mixin(l,{fullWait:"true"}),v.default.delete(w,"/push/deviceRegistrations/"+encodeURIComponent(s),u,l,null,function(g){return h(g)})},y.prototype.removeWhere=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"removeWhere",arguments);h=C}w.options.headers&&a.mixin(u,w.options.headers),w.options.pushFullWait&&a.mixin(d,{fullWait:"true"}),v.default.delete(w,"/push/deviceRegistrations",u,d,null,function(l){return h(l)})},y}(),P=function(){function y(d){this.remove=y.prototype.removeWhere,this.rest=d}return y.prototype.save=function(d,h){var w=this.rest,c=R.default.fromValues(d),u=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,l=a.defaultPostHeaders(w.options,u),s={};if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"save",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),w.options.pushFullWait&&a.mixin(s,{fullWait:"true"});var g=a.encodeBody(c,u);v.default.post(w,"/push/channelSubscriptions",g,l,s,null,function(p,x,D,N){h(p,!p&&R.default.fromResponseBody(x,N?void 0:u))})},y.prototype.list=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=this.rest.http.supportsLinkHeaders?void 0:c,l=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"list",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),new S.default(w,"/push/channelSubscriptions",l,u,function(s,g,p){return R.default.fromResponseBody(s,p?void 0:c)}).get(d,h)},y.prototype.removeWhere=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"removeWhere",arguments);h=C}w.options.headers&&a.mixin(u,w.options.headers),w.options.pushFullWait&&a.mixin(d,{fullWait:"true"}),v.default.delete(w,"/push/channelSubscriptions",u,d,null,function(l){return h(l)})},y.prototype.listChannels=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=this.rest.http.supportsLinkHeaders?void 0:c,l=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"listChannels",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),w.options.pushFullWait&&a.mixin(d,{fullWait:"true"}),new S.default(w,"/push/channels",l,u,function(s,g,p){for(var x=!p&&c?a.decodeBody(s,c):s,D=0;D<x.length;D++)x[D]=String(x[D]);return x}).get(d,h)},y}();r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(4)),v;(function(R){R.Phone="phone",R.Tablet="tablet",R.Desktop="desktop",R.TV="tv",R.Watch="watch",R.Car="car",R.Embedded="embedded",R.Other="other"})(v||(v={}));var S;(function(R){R.Android="android",R.IOS="ios",R.Browser="browser"})(S||(S={}));var T=function(){function R(){}return R.prototype.toJSON=function(){var C,O,f;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(C=this.push)===null||C===void 0?void 0:C.recipient,state:(O=this.push)===null||O===void 0?void 0:O.state,error:(f=this.push)===null||f===void 0?void 0:f.error}}},R.prototype.toString=function(){var C,O,f,E,P="[DeviceDetails";return this.id&&(P+="; id="+this.id),this.platform&&(P+="; platform="+this.platform),this.formFactor&&(P+="; formFactor="+this.formFactor),this.clientId&&(P+="; clientId="+this.clientId),this.metadata&&(P+="; metadata="+this.metadata),this.deviceIdentityToken&&(P+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),!((C=this.push)===null||C===void 0)&&C.recipient&&(P+="; push.recipient="+JSON.stringify(this.push.recipient)),!((O=this.push)===null||O===void 0)&&O.state&&(P+="; push.state="+this.push.state),!((f=this.push)===null||f===void 0)&&f.error&&(P+="; push.error="+JSON.stringify(this.push.error)),!((E=this.push)===null||E===void 0)&&E.metadata&&(P+="; push.metadata="+this.push.metadata),P+="]",P},R.fromResponseBody=function(C,O){return O&&(C=a.decodeBody(C,O)),a.isArray(C)?R.fromValuesArray(C):R.fromValues(C)},R.fromValues=function(C){return C.error=C.error&&m.default.fromValues(C.error),Object.assign(new R,C)},R.fromValuesArray=function(C){for(var O=C.length,f=new Array(O),E=0;E<O;E++)f[E]=R.fromValues(C[E]);return f},R.toRequestBody=a.encodeBody,R}();r.default=T},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=function(){function v(){}return v.prototype.toJSON=function(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}},v.prototype.toString=function(){var S="[PushChannelSubscription";return this.channel&&(S+="; channel="+this.channel),this.deviceId&&(S+="; deviceId="+this.deviceId),this.clientId&&(S+="; clientId="+this.clientId),S+="]",S},v.fromResponseBody=function(S,T){return T&&(S=a.decodeBody(S,T)),a.isArray(S)?v.fromValuesArray(S):v.fromValues(S)},v.fromValues=function(S){return Object.assign(new v,S)},v.fromValuesArray=function(S){for(var T=S.length,R=new Array(T),C=0;C<T;C++)R[C]=v.fromValues(S[C]);return R},v.toRequestBody=a.encodeBody,v}();r.default=m},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=function(){function w(c){this.count=c&&c.count||0,this.data=c&&c.data||0,this.uncompressedData=c&&c.uncompressedData||0,this.failed=c&&c.failed||0,this.refused=c&&c.refused||0}return w}(),v=function(w){i.__extends(c,w);function c(u){var l=w.call(this,u)||this;return u&&u.category&&(l.category={},a.forInOwnNonNullProperties(u.category,function(s){l.category[s]=new m(u.category[s])})),l}return c}(m),S=function(){function w(c){this.peak=c&&c.peak||0,this.min=c&&c.min||0,this.mean=c&&c.mean||0,this.opened=c&&c.opened||0,this.refused=c&&c.refused||0}return w}(),T=function(){function w(c){this.succeeded=c&&c.succeeded||0,this.failed=c&&c.failed||0,this.refused=c&&c.refused||0}return w}(),R=function(){function w(c){this.plain=new S(c&&c.plain),this.tls=new S(c&&c.tls),this.all=new S(c&&c.all)}return w}(),C=function(){function w(c){this.messages=new v(c&&c.messages),this.presence=new v(c&&c.presence),this.all=new v(c&&c.all)}return w}(),O=function(){function w(c){this.realtime=new C(c&&c.realtime),this.rest=new C(c&&c.rest),this.webhook=new C(c&&c.webhook),this.sharedQueue=new C(c&&c.sharedQueue),this.externalQueue=new C(c&&c.externalQueue),this.httpEvent=new C(c&&c.httpEvent),this.push=new C(c&&c.push),this.all=new C(c&&c.all)}return w}(),f=function(){function w(c){this.all=new C(c&&c.all),this.inbound=new O(c&&c.inbound),this.outbound=new O(c&&c.outbound)}return w}(),E=function(){function w(c){this.all=new C(c&&c.all),this.producerPaid=new f(c&&c.producerPaid),this.consumerPaid=new f(c&&c.consumerPaid)}return w}(),P=function(){function w(c){this.messages=c&&c.messages||0;var u=c&&c.notifications;this.notifications={invalid:u&&u.invalid||0,attempted:u&&u.attempted||0,successful:u&&u.successful||0,failed:u&&u.failed||0},this.directPublishes=c&&c.directPublishes||0}return w}(),y=function(){function w(c){this.succeeded=c&&c.succeeded||0,this.skipped=c&&c.skipped||0,this.failed=c&&c.failed||0}return w}(),d=function(){function w(c){var u=this;this.delta=void 0,c&&c.delta&&(this.delta={},a.forInOwnNonNullProperties(c.delta,function(l){u.delta[l]=new y(c.delta[l])}))}return w}(),h=function(w){i.__extends(c,w);function c(u){var l=w.call(this,u)||this;return l.persisted=new C(u&&u.persisted),l.connections=new R(u&&u.connections),l.channels=new S(u&&u.channels),l.apiRequests=new T(u&&u.apiRequests),l.tokenRequests=new T(u&&u.tokenRequests),l.xchgProducer=new E(u&&u.xchgProducer),l.xchgConsumer=new E(u&&u.xchgConsumer),l.push=new P(u&&u.pushStats),l.processed=new d(u&&u.processed),l.inProgress=u&&u.inProgress||void 0,l.unit=u&&u.unit||void 0,l.intervalId=u&&u.intervalId||void 0,l}return c.fromValues=function(u){return new c(u)},c}(f);r.default=h},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(30)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(51)),R=i.__importDefault(o(38)),C=i.__importDefault(o(8)),O=i.__importDefault(o(4)),f=i.__importDefault(o(10)),E=i.__importDefault(o(35)),P=i.__importDefault(o(3)),y=i.__importDefault(o(9)),d=function(w){i.__extends(c,w);function c(u){var l=w.call(this,u)||this;return S.default.logAction(S.default.LOG_MINOR,"Realtime()",""),l.connection=new T.default(l,l.options),l.channels=new h(l),u.autoConnect!==!1&&l.connect(),l}return c.prototype.connect=function(){S.default.logAction(S.default.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()},c.prototype.close=function(){S.default.logAction(S.default.LOG_MINOR,"Realtime.close()",""),this.connection.close()},c.Promise=function(u){return u=C.default.objectifyOptions(u),u.promises=!0,new c(u)},c.Callbacks=c,c.Utils=a,c.ConnectionManager=E.default,c.Platform=P.default,c.ProtocolMessage=f.default,c.Message=y.default,c}(m.default),h=function(w){i.__extends(c,w);function c(u){var l=w.call(this)||this;return l.realtime=u,l.all=Object.create(null),u.connection.connectionManager.on("transport.active",function(){l.onTransportActive()}),l}return c.prototype.channelSerials=function(){for(var u={},l=0,s=a.keysArray(this.all,!0);l<s.length;l++){var g=s[l],p=this.all[g];p.properties.channelSerial&&(u[g]=p.properties.channelSerial)}return u},c.prototype.recoverChannels=function(u){for(var l=0,s=a.keysArray(u,!0);l<s.length;l++){var g=s[l],p=this.get(g);p.properties.channelSerial=u[g]}},c.prototype.onChannelMessage=function(u){var l=u.channel;if(l===void 0){S.default.logAction(S.default.LOG_ERROR,"Channels.onChannelMessage()","received event unspecified channel, action = "+u.action);return}var s=this.all[l];if(!s){S.default.logAction(S.default.LOG_ERROR,"Channels.onChannelMessage()","received event for non-existent channel: "+l);return}s.onMessage(u)},c.prototype.onTransportActive=function(){for(var u in this.all){var l=this.all[u];l.state==="attaching"||l.state==="detaching"?l.checkPendingState():l.state==="suspended"?l._attach(!1,null):l.state==="attached"&&l.requestState("attaching")}},c.prototype.propogateConnectionInterruption=function(u,l){var s={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},g=["attaching","attached","detaching","suspended"],p=s[u];for(var x in this.all){var D=this.all[x];a.arrIn(g,D.state)&&D.notifyState(p,l)}},c.prototype.get=function(u,l){u=String(u);var s=this.all[u];if(!s)s=this.all[u]=new R.default(this.realtime,u,l);else if(l){if(s._shouldReattachToSetOptions(l,s.channelOptions))throw new O.default("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);s.setOptions(l)}return s},c.prototype.getDerived=function(u,l,s){if(l.filter){var g=a.toBase64(l.filter),p=a.matchDerivedChannel(u);u="[filter=".concat(g).concat(p.qualifierParam,"]").concat(p.channelName)}return this.get(u,s)},c.prototype.release=function(u){u=String(u);var l=this.all[u];if(l){var s=l.getReleaseErr();if(s)throw s;delete this.all[u]}},c}(v.default);r.default=d},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(7)),v=i.__importDefault(o(35)),S=i.__importDefault(o(2)),T=i.__importDefault(o(37)),R=i.__importDefault(o(3));function C(){}var O=function(f){i.__extends(E,f);function E(P,y){var d=f.call(this)||this;return d.whenState=function(h,w){return m.default.prototype.whenState.call(d,h,d.state,w,new T.default(void 0,h))},d.ably=P,d.connectionManager=new v.default(P,y),d.state=d.connectionManager.state.state,d.key=void 0,d.id=void 0,d.errorReason=null,d.connectionManager.on("connectionstate",function(h){var w=d.state=h.current;R.default.Config.nextTick(function(){d.emit(w,h)})}),d.connectionManager.on("update",function(h){R.default.Config.nextTick(function(){d.emit("update",h)})}),d}return E.prototype.connect=function(){S.default.logAction(S.default.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})},E.prototype.ping=function(P){if(S.default.logAction(S.default.LOG_MINOR,"Connection.ping()",""),!P){if(this.ably.options.promises)return a.promisify(this,"ping",arguments);P=C}this.connectionManager.ping(null,P)},E.prototype.close=function(){S.default.logAction(S.default.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})},Object.defineProperty(E.prototype,"recoveryKey",{get:function(){return this.createRecoveryKey()},enumerable:!1,configurable:!0}),E.prototype.createRecoveryKey=function(){return this.connectionManager.createRecoveryKey()},E}(m.default);r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.PendingMessage=void 0;var i=o(0),a=i.__importDefault(o(10)),m=i.__importStar(o(1)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(36)),R=i.__importDefault(o(4)),C=a.default.Action,O=function(){function E(P,y){this.message=P,this.callback=y,this.merged=!1;var d=P.action;this.sendAttempted=!1,this.ackRequired=d==C.MESSAGE||d==C.PRESENCE}return E}();r.PendingMessage=O;var f=function(E){i.__extends(P,E);function P(y){var d=E.call(this)||this;return d.transport=y,d.messageQueue=new T.default,y.on("ack",function(h,w){d.onAck(h,w)}),y.on("nack",function(h,w,c){d.onNack(h,w,c)}),d}return P.prototype.onAck=function(y,d){S.default.logAction(S.default.LOG_MICRO,"Protocol.onAck()","serial = "+y+"; count = "+d),this.messageQueue.completeMessages(y,d)},P.prototype.onNack=function(y,d,h){S.default.logAction(S.default.LOG_ERROR,"Protocol.onNack()","serial = "+y+"; count = "+d+"; err = "+m.inspectError(h)),h||(h=new R.default("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(y,d,h)},P.prototype.onceIdle=function(y){var d=this.messageQueue;if(d.count()===0){y();return}d.once("idle",y)},P.prototype.send=function(y){y.ackRequired&&this.messageQueue.push(y),S.default.shouldLog(S.default.LOG_MICRO)&&S.default.logAction(S.default.LOG_MICRO,"Protocol.send()","sending msg; "+a.default.stringify(y.message)),y.sendAttempted=!0,this.transport.send(y.message)},P.prototype.getTransport=function(){return this.transport},P.prototype.getPendingMessages=function(){return this.messageQueue.copyAll()},P.prototype.clearPendingMessages=function(){return this.messageQueue.clear()},P.prototype.finish=function(){var y=this.transport;this.onceIdle(function(){y.disconnect()})},P}(v.default);r.default=f},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1)),v=i.__importDefault(o(26)),S=i.__importDefault(o(8)),T=i.__importDefault(o(2)),R=i.__importDefault(o(10)),C=i.__importDefault(o(4)),O="web_socket";function f(y){return!!y.on}var E=function(y){i.__extends(d,y);function d(h,w,c){var u=y.call(this,h,w,c)||this;return u.shortName=O,c.heartbeats=a.default.Config.useProtocolHeartbeats,u.wsHost=S.default.getHost(c.options,c.host,!0),u}return d.isAvailable=function(){return!!a.default.Config.WebSocket},d.prototype.createWebSocket=function(h,w){return this.uri=h+m.toQueryString(w),new a.default.Config.WebSocket(this.uri)},d.prototype.toString=function(){return"WebSocketTransport; uri="+this.uri},d.prototype.connect=function(){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.connect()","starting"),v.default.prototype.connect.call(this);var h=this,w=this.params,c=w.options,u=c.tls?"wss://":"ws://",l=u+this.wsHost+":"+S.default.getPort(c)+"/";T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.connect()","uri: "+l),this.auth.getAuthParams(function(s,g){if(!h.isDisposed){var p="";for(var x in g)p+=" "+x+": "+g[x]+";";if(T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+p+" err: "+s),s){h.disconnect(s);return}var D=w.getConnectParams(g);try{var N=h.wsConnection=h.createWebSocket(l,D);N.binaryType=a.default.Config.binaryType,N.onopen=function(){h.onWsOpen()},N.onclose=function(k){h.onWsClose(k)},N.onmessage=function(k){h.onWsData(k.data)},N.onerror=function(k){h.onWsError(k)},f(N)&&N.on("ping",function(){h.onActivity()})}catch(k){T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(k.stack||k.message)),h.disconnect(k)}}})},d.prototype.send=function(h){var w=this.wsConnection;if(!w){T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{w.send(R.default.serialize(h,this.params.format))}catch(u){var c="Exception from ws connection when trying to send: "+m.inspectError(u);T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.send()",c),this.finish("disconnected",new C.default(c,5e4,500))}},d.prototype.onWsData=function(h){T.default.logAction(T.default.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+h.length+"; type = "+typeof h);try{this.onProtocolMessage(R.default.deserialize(h,this.format))}catch(w){T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+w.stack)}},d.prototype.onWsOpen=function(){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")},d.prototype.onWsClose=function(h){var w,c;if(typeof h=="object"?(c=h.code,w=h.wasClean||c===1e3):(c=h,w=c==1e3),delete this.wsConnection,w){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");var u=new C.default("Websocket closed",80003,400);this.finish("disconnected",u)}else{var l="Unclean disconnection of WebSocket ; code = "+c,u=new C.default(l,80003,400);T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",u)}this.emit("disposed")},d.prototype.onWsError=function(h){var w=this;T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+h.message),a.default.Config.nextTick(function(){w.disconnect(Error(h.message))})},d.prototype.dispose=function(){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;var h=this.wsConnection;h&&(h.onmessage=function(){},delete this.wsConnection,a.default.Config.nextTick(function(){if(T.default.logAction(T.default.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!h)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");h.close()}))},d}(v.default);function P(y){return E.isAvailable()&&(y.supportedTransports[O]=E),E}r.default=P},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(34)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(16)),R=i.__importStar(o(4)),C=i.__importDefault(o(38)),O=i.__importDefault(o(24)),f=i.__importDefault(o(39)),E=function(){};function P(u){return u.channel.realtime.auth.clientId}function y(u){var l=u.channel.realtime,s=l.auth.clientId;return(!s||s==="*")&&l.connection.state==="connected"}function d(u,l,s){switch(u.state){case"attached":case"suspended":s();break;case"initialized":case"detached":case"detaching":case"attaching":u.attach(function(g){g?l(g):s()});break;default:l(R.default.fromValues(u.invalidStateError()))}}function h(u,l){if(u.isSynthesized()||l.isSynthesized())return u.timestamp>=l.timestamp;var s=u.parseId(),g=l.parseId();return s.msgSerial===g.msgSerial?s.index>g.index:s.msgSerial>g.msgSerial}var w=function(u){i.__extends(l,u);function l(s){var g=u.call(this,s)||this;return g.channel=s,g.syncComplete=!1,g.members=new c(g,function(p){return p.clientId+":"+p.connectionId}),g._myMembers=new c(g,function(p){return p.clientId}),g.subscriptions=new v.default,g.pendingPresence=[],g}return l.prototype.enter=function(s,g){if(y(this))throw new R.default("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"enter",g)},l.prototype.update=function(s,g){if(y(this))throw new R.default("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"update",g)},l.prototype.enterClient=function(s,g,p){return this._enterOrUpdateClient(void 0,s,g,"enter",p)},l.prototype.updateClient=function(s,g,p){return this._enterOrUpdateClient(void 0,s,g,"update",p)},l.prototype._enterOrUpdateClient=function(s,g,p,x,D){var N=this;if(!D)if(typeof p=="function")D=p,p=null;else{if(this.channel.realtime.options.promises)return a.promisify(this,"_enterOrUpdateClient",[s,g,p,x]);D=E}var k=this.channel;if(!k.connectionManager.activeState()){D(k.connectionManager.getError());return}S.default.logAction(S.default.LOG_MICRO,"RealtimePresence."+x+"Client()","channel = "+k.name+", id = "+s+", client = "+(g||"(implicit) "+P(this)));var I=T.default.fromData(p);I.action=x,s&&(I.id=s),g&&(I.clientId=g),T.default.encode(I,k.channelOptions,function(M){if(M){D(M);return}switch(k.state){case"attached":k.sendPresence(I,D);break;case"initialized":case"detached":k.attach();case"attaching":N.pendingPresence.push({presence:I,callback:D});break;default:M=new R.PartialErrorInfo("Unable to "+x+" presence channel while in "+k.state+" state",90001),M.code=90001,D(M)}})},l.prototype.leave=function(s,g){if(y(this))throw new R.default("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,s,g)},l.prototype.leaveClient=function(s,g,p){if(!p)if(typeof g=="function")p=g,g=null;else{if(this.channel.realtime.options.promises)return a.promisify(this,"leaveClient",[s,g]);p=E}var x=this.channel;if(!x.connectionManager.activeState()){p==null||p(x.connectionManager.getError());return}S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+s);var D=T.default.fromData(g);switch(D.action="leave",s&&(D.clientId=s),x.state){case"attached":x.sendPresence(D,p);break;case"attaching":this.pendingPresence.push({presence:D,callback:p});break;case"initialized":case"failed":{var N=new R.PartialErrorInfo("Unable to leave presence channel (incompatible state)",90001);p==null||p(N);break}default:p==null||p(x.invalidStateError())}},l.prototype.get=function(s,g){var p=this,x=Array.prototype.slice.call(arguments);x.length==1&&typeof x[0]=="function"&&x.unshift(null),s=x[0],g=x[1];var D=!s||("waitForSync"in s?s.waitForSync:!0);if(!g){if(this.channel.realtime.options.promises)return a.promisify(this,"get",x);g=E}function N(k){g(null,s?k.list(s):k.values())}if(this.channel.state==="suspended"){D?g(R.default.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):N(this.members);return}d(this.channel,g,function(){var k=p.members;D?k.waitSync(function(){N(k)}):N(k)})},l.prototype.history=function(s,g){if(S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name),g===void 0)if(typeof s=="function")g=s,s=null;else{if(this.channel.realtime.options.promises)return a.promisify(this,"history",arguments);g=E}s&&s.untilAttach&&(this.channel.state==="attached"?(delete s.untilAttach,s.from_serial=this.channel.properties.attachSerial):g(new R.default("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400))),m.default.prototype._history.call(this,s,g)},l.prototype.setPresence=function(s,g,p){S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+s.length+" participants; syncChannelSerial = "+p);var x,D,N=this.members,k=this._myMembers,I=[],M=this.channel.connectionManager.connectionId;g&&(this.members.startSync(),p&&(D=p.match(/^[\w-]+:(.*)$/))&&(x=D[1]));for(var A=0;A<s.length;A++){var j=T.default.fromValues(s[A]);switch(j.action){case"leave":N.remove(j)&&I.push(j),j.connectionId===M&&!j.isSynthesized()&&k.remove(j);break;case"enter":case"present":case"update":N.put(j)&&I.push(j),j.connectionId===M&&k.put(j);break}}g&&!x&&(N.endSync(),this.channel.syncChannelSerial=null);for(var A=0;A<I.length;A++){var j=I[A];this.subscriptions.emit(j.action,j)}},l.prototype.onAttached=function(s){S.default.logAction(S.default.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+s),s?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();var g=this.pendingPresence,p=g.length;if(p){this.pendingPresence=[];var x=[],D=O.default.create();S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.onAttached","sending "+p+" queued presence messages");for(var N=0;N<p;N++){var k=g[N];x.push(k.presence),D.push(k.callback)}this.channel.sendPresence(x,D)}},l.prototype.actOnChannelState=function(s,g,p){switch(s){case"attached":this.onAttached(g);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(p);break}},l.prototype.failPendingPresence=function(s){if(this.pendingPresence.length){S.default.logAction(S.default.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+a.inspectError(s));for(var g=0;g<this.pendingPresence.length;g++)try{this.pendingPresence[g].callback(s)}catch(p){}this.pendingPresence=[]}},l.prototype._clearMyMembers=function(){this._myMembers.clear()},l.prototype._ensureMyMembersPresent=function(){var s=this,g=this._myMembers,p=function(N){if(N){var k="Presence auto-re-enter failed: "+N.toString(),I=new R.default(k,91004,400);S.default.logAction(S.default.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()",k);var M=new f.default(s.channel.state,s.channel.state,!0,!1,I);s.channel.emit("update",M)}};for(var x in g.map){var D=g.map[x];S.default.logAction(S.default.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+D.clientId+'" into the presence set'),this._enterOrUpdateClient(D.id,D.clientId,D.data,"enter",p)}},l.prototype._synthesizeLeaves=function(s){var g=this.subscriptions;a.arrForEach(s,function(p){var x=T.default.fromValues({action:"leave",connectionId:p.connectionId,clientId:p.clientId,data:p.data,encoding:p.encoding,timestamp:a.now()});g.emit("leave",x)})},l.prototype.on=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];S.default.renamedMethod("RealtimePresence","on","subscribe"),this.subscribe.apply(this,s)},l.prototype.off=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];S.default.renamedMethod("RealtimePresence","off","unsubscribe"),this.unsubscribe.apply(this,s)},l.prototype.subscribe=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];var p=C.default.processListenerArgs(s),x=p[0],D=p[1],N=p[2],k=this.channel;if(!N){if(this.channel.realtime.options.promises)return a.promisify(this,"subscribe",[x,D]);N=E}if(k.state==="failed"){N(R.default.fromValues(k.invalidStateError()));return}this.subscriptions.on(x,D),k.attach(N)},l.prototype.unsubscribe=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];var p=C.default.processListenerArgs(s),x=p[0],D=p[1];this.subscriptions.off(x,D)},l}(m.default),c=function(u){i.__extends(l,u);function l(s,g){var p=u.call(this)||this;return p.presence=s,p.map=Object.create(null),p.syncInProgress=!1,p.residualMembers=null,p.memberKey=g,p}return l.prototype.get=function(s){return this.map[s]},l.prototype.getClient=function(s){var g=this.map,p=[];for(var x in g){var D=g[x];D.clientId==s&&D.action!="absent"&&p.push(D)}return p},l.prototype.list=function(s){var g=this.map,p=s&&s.clientId,x=s&&s.connectionId,D=[];for(var N in g){var k=g[N];k.action!=="absent"&&(p&&p!=k.clientId||x&&x!=k.connectionId||D.push(k))}return D},l.prototype.put=function(s){(s.action==="enter"||s.action==="update")&&(s=T.default.fromValues(s),s.action="present");var g=this.map,p=this.memberKey(s);this.residualMembers&&delete this.residualMembers[p];var x=g[p];return x&&!h(s,x)?!1:(g[p]=s,!0)},l.prototype.values=function(){var s=this.map,g=[];for(var p in s){var x=s[p];x.action!="absent"&&g.push(x)}return g},l.prototype.remove=function(s){var g=this.map,p=this.memberKey(s),x=g[p];return x&&!h(s,x)?!1:(this.syncInProgress?(s=T.default.fromValues(s),s.action="absent",g[p]=s):delete g[p],!0)},l.prototype.startSync=function(){var s=this.map,g=this.syncInProgress;S.default.logAction(S.default.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+g),this.syncInProgress||(this.residualMembers=a.copy(s),this.setInProgress(!0))},l.prototype.endSync=function(){var s=this.map,g=this.syncInProgress;if(S.default.logAction(S.default.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+g),g){for(var p in s){var x=s[p];x.action==="absent"&&delete s[p]}this.presence._synthesizeLeaves(a.valuesArray(this.residualMembers));for(var p in this.residualMembers)delete s[p];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")},l.prototype.waitSync=function(s){var g=this.syncInProgress;if(S.default.logAction(S.default.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+g),!g){s();return}this.once("sync",s)},l.prototype.clear=function(){this.map={},this.setInProgress(!1),this.residualMembers=null},l.prototype.setInProgress=function(s){S.default.logAction(S.default.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+s),this.syncInProgress=s,this.presence.syncComplete=!s},l}(v.default);r.default=w},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=o(56),m=o(31),v=o(11),S=i.__importDefault(o(5)),T=i.__importDefault(o(3)),R=function(){function C(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}return C.prototype.isWordArray=function(O){return O!=null&&O.sigBytes!==void 0},C.prototype.isArrayBuffer=function(O){return O!=null&&O.constructor===ArrayBuffer},C.prototype.isTypedArray=function(O){return!!ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(O)},C.prototype.uint8ViewToBase64=function(O){for(var f="",E=this.base64CharSet,P=O.byteLength,y=P%3,d=P-y,h,w,c,u,l,s=0;s<d;s=s+3)l=O[s]<<16|O[s+1]<<8|O[s+2],h=(l&16515072)>>18,w=(l&258048)>>12,c=(l&4032)>>6,u=l&63,f+=E[h]+E[w]+E[c]+E[u];return y==1?(l=O[d],h=(l&252)>>2,w=(l&3)<<4,f+=E[h]+E[w]+"=="):y==2&&(l=O[d]<<8|O[d+1],h=(l&64512)>>10,w=(l&1008)>>4,c=(l&15)<<2,f+=E[h]+E[w]+E[c]+"="),f},C.prototype.base64ToArrayBuffer=function(O){for(var f=atob==null?void 0:atob(O),E=f.length,P=new Uint8Array(E),y=0;y<E;y++){var d=f.charCodeAt(y);P[y]=d}return P.buffer},C.prototype.isBuffer=function(O){return this.isArrayBuffer(O)||this.isWordArray(O)||this.isTypedArray(O)},C.prototype.toBuffer=function(O){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(this.isArrayBuffer(O))return new Uint8Array(O);if(this.isTypedArray(O))return new Uint8Array(O.buffer);if(this.isWordArray(O)){for(var f=new ArrayBuffer(O.sigBytes),E=new Uint8Array(f),P=0;P<O.sigBytes;P++)E[P]=O.words[P>>>2]>>>24-P%4*8&255;return E}throw new Error("BufferUtils.toBuffer expected an arraybuffer, typed array, or CryptoJS wordarray")},C.prototype.toArrayBuffer=function(O){return this.isArrayBuffer(O)?O:this.toBuffer(O).buffer},C.prototype.toWordArray=function(O){return this.isTypedArray(O)&&(O=O.buffer),this.isWordArray(O)?O:S.default.create(O)},C.prototype.base64Encode=function(O){return this.isWordArray(O)?(0,v.stringify)(O):this.uint8ViewToBase64(this.toBuffer(O))},C.prototype.base64Decode=function(O){return ArrayBuffer&&T.default.Config.atob?this.base64ToArrayBuffer(O):(0,v.parse)(O)},C.prototype.hexEncode=function(O){return(0,a.stringify)(this.toWordArray(O))},C.prototype.hexDecode=function(O){var f=(0,a.parse)(O);return ArrayBuffer?this.toArrayBuffer(f):f},C.prototype.utf8Encode=function(O){return T.default.Config.TextEncoder?new T.default.Config.TextEncoder().encode(O).buffer:(0,m.parse)(O)},C.prototype.utf8Decode=function(O){if(!this.isBuffer(O))throw new Error("Expected input of utf8decode to be an arraybuffer, typed array, or CryptoJS wordarray");return TextDecoder&&!this.isWordArray(O)?new TextDecoder().decode(O):(O=this.toWordArray(O),(0,m.stringify)(O))},C.prototype.bufferCompare=function(O,f){if(!O)return-1;if(!f)return 1;var E=this.toWordArray(O),P=this.toWordArray(f);E.clamp(),P.clamp();var y=E.sigBytes-P.sigBytes;if(y!=0)return y;for(var d=E.words,h=P.words,w=0;w<d.length;w++)if(y=d[w]-h[w],y!=0)return y;return 0},C.prototype.byteLength=function(O){return this.isArrayBuffer(O)||this.isTypedArray(O)?O.byteLength:this.isWordArray(O)?O.sigBytes:-1},C.prototype.typedArrayToBuffer=function(O){return O.buffer},C}();r.default=new R},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return i.enc.Hex})},function(n,r,o){o.r(r);var i=o(5),a=o.n(i),m=o(11),v=o(23),S=o.n(v),T=o(2),R=o.n(T),C=o(4),O=o.n(C),f=function(E,P){var y="aes",d=256,h="cbc",w=16,c=4,u=4294967296,l=2147483648,s;if(E.getRandomWordArray)s=E.getRandomWordArray;else if(typeof Uint32Array!="undefined"&&E.getRandomValues){var g=new Uint32Array(c);s=function(A,j){var U=A/4,z=U==c?g:new Uint32Array(U);E.getRandomValues(z,function(V){typeof j!="undefined"&&j(V,P.toWordArray(z))})}}else s=function(A,j){R.a.logAction(R.a.LOG_MAJOR,"Ably.Crypto.generateRandom()","Warning: the browser you are using does not support secure cryptographically secure randomness generation; falling back to insecure Math.random()");for(var U=A/4,z=new Array(U),V=0;V<U;V++)z[V]=Math.floor(Math.random()*u)-l;j(null,a.a.create(z))};function p(A){return A+w&-16}function x(A){if(A.algorithm==="aes"&&A.mode==="cbc"){if(A.keyLength===128||A.keyLength===256)return;throw new Error("Unsupported key length "+A.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function D(A){return A.replace("_","/").replace("-","+")}var N=[a.a.create([269488144,269488144,269488144,269488144],16),a.a.create([16777216],1),a.a.create([33685504],2),a.a.create([50529024],3),a.a.create([67372036],4),a.a.create([84215045,83886080],5),a.a.create([101058054,101056512],6),a.a.create([117901063,117901056],7),a.a.create([134744072,134744072],8),a.a.create([151587081,151587081,150994944],9),a.a.create([168430090,168430090,168427520],10),a.a.create([185273099,185273099,185273088],11),a.a.create([202116108,202116108,202116108],12),a.a.create([218959117,218959117,218959117,218103808],13),a.a.create([235802126,235802126,235802126,235798528],14),a.a.create([252645135,252645135,252645135,252645135],15),a.a.create([269488144,269488144,269488144,269488144],16)];function k(){}function I(){this.algorithm=null,this.keyLength=null,this.mode=null,this.key=null}k.CipherParams=I,k.getDefaultParams=function(A){var j;if(typeof A=="function"||typeof A=="string"){if(R.a.deprecated("The ability to pass a callback to `Crypto.getDefaultParams()`","This method now directly returns its result, instead of returning it asynchronously via a callback. Please update your code so that it uses the return value of this method instead of passing a callback."),typeof A=="function")R.a.deprecated("The ability to call `Crypto.getDefaultParams()` without specifying an encryption key","Please update your code so that it instead passes an object whose `key` property contains an encryption key. That is, replace `Crypto.getDefaultParams()` with `Crypto.getDefaultParams({ key })`, where `key` is an encryption key that you have generated (for example from the `Crypto.generateRandomKey()` method)."),k.generateRandomKey(function(z){A(null,k.getDefaultParams({key:z}))});else if(typeof arguments[1]=="function")R.a.deprecated("The ability to pass the encryption key as the first argument of `Crypto.getDefaultParams()`","Please update your code so that it instead passes an object whose `key` property contains the key. That is, replace `Crypto.getDefaultParams(key)` with `Crypto.getDefaultParams({ key })`."),arguments[1](null,k.getDefaultParams({key:A}));else throw new Error("Invalid arguments for Crypto.getDefaultParams");return}if(!A.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof A.key=="string"?j=Object(m.parse)(D(A.key)):j=P.toWordArray(A.key);var U=new I;if(U.key=j,U.algorithm=A.algorithm||y,U.keyLength=j.words.length*(4*8),U.mode=A.mode||h,A.keyLength&&A.keyLength!==U.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+A.keyLength+" was specified, but the key actually has length "+U.keyLength);return x(U),U},k.generateRandomKey=function(A,j){arguments.length==1&&typeof A=="function"&&(j=A,A=void 0),s((A||d)/8,function(U,z){j!==void 0&&j(U?O.a.fromValues(U):null,z)})},k.getCipher=function(A){var j=A instanceof I?A:k.getDefaultParams(A);return{cipherParams:j,cipher:new M(j,c,A.iv)}};function M(A,j,U){this.algorithm=A.algorithm+"-"+String(A.keyLength)+"-"+A.mode,this.cjsAlgorithm=A.algorithm.toUpperCase().replace(/-\d+$/,""),this.key=P.toWordArray(A.key),U&&(this.iv=P.toWordArray(U).clone()),this.blockLengthWords=j}return M.prototype.encrypt=function(A,j){R.a.logAction(R.a.LOG_MICRO,"CBCCipher.encrypt()",""),A=P.toWordArray(A);var U=A.sigBytes,z=p(U),V=this,G=function(){V.getIv(function(F,b){if(F){j(F);return}var L=V.encryptCipher.process(A.concat(N[z-U])),B=b.concat(L);j(null,B)})};this.encryptCipher?G():this.iv?(this.encryptCipher=S.a.algo[this.cjsAlgorithm].createEncryptor(this.key,{iv:this.iv}),G()):s(w,function(F,b){if(F){j(F);return}V.encryptCipher=S.a.algo[V.cjsAlgorithm].createEncryptor(V.key,{iv:b}),V.iv=b,G()})},M.prototype.decrypt=function(A){R.a.logAction(R.a.LOG_MICRO,"CBCCipher.decrypt()",""),A=P.toWordArray(A);var j=this.blockLengthWords,U=A.words,z=a.a.create(U.slice(0,j)),V=a.a.create(U.slice(j)),G=S.a.algo[this.cjsAlgorithm].createDecryptor(this.key,{iv:z}),F=G.process(V),b=G.finalize();return G.reset(),b&&b.sigBytes&&F.concat(b),F},M.prototype.getIv=function(A){if(this.iv){var j=this.iv;this.iv=null,A(null,j);return}var U=this;s(w,function(z,V){if(z){A(z);return}A(null,U.encryptCipher.process(V))})},k};r.default=f},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){var a=i,m=a.lib,v=m.WordArray,S=a.enc;S.Utf16=S.Utf16BE={stringify:function(R){for(var C=R.words,O=R.sigBytes,f=[],E=0;E<O;E+=2){var P=C[E>>>2]>>>16-E%4*8&65535;f.push(String.fromCharCode(P))}return f.join("")},parse:function(R){for(var C=R.length,O=[],f=0;f<C;f++)O[f>>>1]|=R.charCodeAt(f)<<16-f%2*16;return v.create(O,C*2)}},S.Utf16LE={stringify:function(R){for(var C=R.words,O=R.sigBytes,f=[],E=0;E<O;E+=2){var P=T(C[E>>>2]>>>16-E%4*8&65535);f.push(String.fromCharCode(P))}return f.join("")},parse:function(R){for(var C=R.length,O=[],f=0;f<C;f++)O[f>>>1]|=T(R.charCodeAt(f)<<16-f%2*16);return v.create(O,C*2)}};function T(R){return R<<8&4278255360|R>>>8&16711935}}(),i.enc.Utf16})},function(n,r,o){(function(i,a){n.exports=a(o(6),o(28))})(this,function(i){return function(a){var m=i,v=m.lib,S=v.CipherParams,T=m.enc,R=T.Hex,C=m.format;C.Hex={stringify:function(O){return O.ciphertext.toString(R)},parse:function(O){var f=R.parse(O);return S.create({ciphertext:f})}}}(),i.format.Hex})},function(n,r,o){(function(i,a){n.exports=a(o(6),o(11),o(61),o(27),o(28))})(this,function(i){return function(){var a=i,m=a.lib,v=m.BlockCipher,S=a.algo,T=[],R=[],C=[],O=[],f=[],E=[],P=[],y=[],d=[],h=[];(function(){for(var u=[],l=0;l<256;l++)l<128?u[l]=l<<1:u[l]=l<<1^283;for(var s=0,g=0,l=0;l<256;l++){var p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^p&255^99,T[s]=p,R[p]=s;var x=u[s],D=u[x],N=u[D],k=u[p]*257^p*16843008;C[s]=k<<24|k>>>8,O[s]=k<<16|k>>>16,f[s]=k<<8|k>>>24,E[s]=k;var k=N*16843009^D*65537^x*257^s*16843008;P[p]=k<<24|k>>>8,y[p]=k<<16|k>>>16,d[p]=k<<8|k>>>24,h[p]=k,s?(s=x^u[u[u[N^x]]],g^=u[u[g]]):s=g=1}})();var w=[0,1,2,4,8,16,32,64,128,27,54],c=S.AES=v.extend({_doReset:function(){var u;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var l=this._keyPriorReset=this._key,s=l.words,g=l.sigBytes/4,p=this._nRounds=g+6,x=(p+1)*4,D=this._keySchedule=[],N=0;N<x;N++)N<g?D[N]=s[N]:(u=D[N-1],N%g?g>6&&N%g==4&&(u=T[u>>>24]<<24|T[u>>>16&255]<<16|T[u>>>8&255]<<8|T[u&255]):(u=u<<8|u>>>24,u=T[u>>>24]<<24|T[u>>>16&255]<<16|T[u>>>8&255]<<8|T[u&255],u^=w[N/g|0]<<24),D[N]=D[N-g]^u);for(var k=this._invKeySchedule=[],I=0;I<x;I++){var N=x-I;if(I%4)var u=D[N];else var u=D[N-4];I<4||N<=4?k[I]=u:k[I]=P[T[u>>>24]]^y[T[u>>>16&255]]^d[T[u>>>8&255]]^h[T[u&255]]}}},encryptBlock:function(u,l){this._doCryptBlock(u,l,this._keySchedule,C,O,f,E,T)},decryptBlock:function(u,l){var s=u[l+1];u[l+1]=u[l+3],u[l+3]=s,this._doCryptBlock(u,l,this._invKeySchedule,P,y,d,h,R);var s=u[l+1];u[l+1]=u[l+3],u[l+3]=s},_doCryptBlock:function(u,l,s,g,p,x,D,N){for(var k=this._nRounds,I=u[l]^s[0],M=u[l+1]^s[1],A=u[l+2]^s[2],j=u[l+3]^s[3],U=4,z=1;z<k;z++){var V=g[I>>>24]^p[M>>>16&255]^x[A>>>8&255]^D[j&255]^s[U++],G=g[M>>>24]^p[A>>>16&255]^x[j>>>8&255]^D[I&255]^s[U++],F=g[A>>>24]^p[j>>>16&255]^x[I>>>8&255]^D[M&255]^s[U++],b=g[j>>>24]^p[I>>>16&255]^x[M>>>8&255]^D[A&255]^s[U++];I=V,M=G,A=F,j=b}var V=(N[I>>>24]<<24|N[M>>>16&255]<<16|N[A>>>8&255]<<8|N[j&255])^s[U++],G=(N[M>>>24]<<24|N[A>>>16&255]<<16|N[j>>>8&255]<<8|N[I&255])^s[U++],F=(N[A>>>24]<<24|N[j>>>16&255]<<16|N[I>>>8&255]<<8|N[M&255])^s[U++],b=(N[j>>>24]<<24|N[I>>>16&255]<<16|N[M>>>8&255]<<8|N[A&255])^s[U++];u[l]=V,u[l+1]=G,u[l+2]=F,u[l+3]=b},keySize:256/32});a.AES=v._createHelper(c)}(),i.AES})},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(a){var m=i,v=m.lib,S=v.WordArray,T=v.Hasher,R=m.algo,C=[];(function(){for(var d=0;d<64;d++)C[d]=a.abs(a.sin(d+1))*4294967296|0})();var O=R.MD5=T.extend({_doReset:function(){this._hash=new S.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(d,h){for(var w=0;w<16;w++){var c=h+w,u=d[c];d[c]=(u<<8|u>>>24)&16711935|(u<<24|u>>>8)&4278255360}var l=this._hash.words,s=d[h+0],g=d[h+1],p=d[h+2],x=d[h+3],D=d[h+4],N=d[h+5],k=d[h+6],I=d[h+7],M=d[h+8],A=d[h+9],j=d[h+10],U=d[h+11],z=d[h+12],V=d[h+13],G=d[h+14],F=d[h+15],b=l[0],L=l[1],B=l[2],_=l[3];b=f(b,L,B,_,s,7,C[0]),_=f(_,b,L,B,g,12,C[1]),B=f(B,_,b,L,p,17,C[2]),L=f(L,B,_,b,x,22,C[3]),b=f(b,L,B,_,D,7,C[4]),_=f(_,b,L,B,N,12,C[5]),B=f(B,_,b,L,k,17,C[6]),L=f(L,B,_,b,I,22,C[7]),b=f(b,L,B,_,M,7,C[8]),_=f(_,b,L,B,A,12,C[9]),B=f(B,_,b,L,j,17,C[10]),L=f(L,B,_,b,U,22,C[11]),b=f(b,L,B,_,z,7,C[12]),_=f(_,b,L,B,V,12,C[13]),B=f(B,_,b,L,G,17,C[14]),L=f(L,B,_,b,F,22,C[15]),b=E(b,L,B,_,g,5,C[16]),_=E(_,b,L,B,k,9,C[17]),B=E(B,_,b,L,U,14,C[18]),L=E(L,B,_,b,s,20,C[19]),b=E(b,L,B,_,N,5,C[20]),_=E(_,b,L,B,j,9,C[21]),B=E(B,_,b,L,F,14,C[22]),L=E(L,B,_,b,D,20,C[23]),b=E(b,L,B,_,A,5,C[24]),_=E(_,b,L,B,G,9,C[25]),B=E(B,_,b,L,x,14,C[26]),L=E(L,B,_,b,M,20,C[27]),b=E(b,L,B,_,V,5,C[28]),_=E(_,b,L,B,p,9,C[29]),B=E(B,_,b,L,I,14,C[30]),L=E(L,B,_,b,z,20,C[31]),b=P(b,L,B,_,N,4,C[32]),_=P(_,b,L,B,M,11,C[33]),B=P(B,_,b,L,U,16,C[34]),L=P(L,B,_,b,G,23,C[35]),b=P(b,L,B,_,g,4,C[36]),_=P(_,b,L,B,D,11,C[37]),B=P(B,_,b,L,I,16,C[38]),L=P(L,B,_,b,j,23,C[39]),b=P(b,L,B,_,V,4,C[40]),_=P(_,b,L,B,s,11,C[41]),B=P(B,_,b,L,x,16,C[42]),L=P(L,B,_,b,k,23,C[43]),b=P(b,L,B,_,A,4,C[44]),_=P(_,b,L,B,z,11,C[45]),B=P(B,_,b,L,F,16,C[46]),L=P(L,B,_,b,p,23,C[47]),b=y(b,L,B,_,s,6,C[48]),_=y(_,b,L,B,I,10,C[49]),B=y(B,_,b,L,G,15,C[50]),L=y(L,B,_,b,N,21,C[51]),b=y(b,L,B,_,z,6,C[52]),_=y(_,b,L,B,x,10,C[53]),B=y(B,_,b,L,j,15,C[54]),L=y(L,B,_,b,g,21,C[55]),b=y(b,L,B,_,M,6,C[56]),_=y(_,b,L,B,F,10,C[57]),B=y(B,_,b,L,k,15,C[58]),L=y(L,B,_,b,V,21,C[59]),b=y(b,L,B,_,D,6,C[60]),_=y(_,b,L,B,U,10,C[61]),B=y(B,_,b,L,p,15,C[62]),L=y(L,B,_,b,A,21,C[63]),l[0]=l[0]+b|0,l[1]=l[1]+L|0,l[2]=l[2]+B|0,l[3]=l[3]+_|0},_doFinalize:function(){var d=this._data,h=d.words,w=this._nDataBytes*8,c=d.sigBytes*8;h[c>>>5]|=128<<24-c%32;var u=a.floor(w/4294967296),l=w;h[(c+64>>>9<<4)+15]=(u<<8|u>>>24)&16711935|(u<<24|u>>>8)&4278255360,h[(c+64>>>9<<4)+14]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360,d.sigBytes=(h.length+1)*4,this._process();for(var s=this._hash,g=s.words,p=0;p<4;p++){var x=g[p];g[p]=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360}return s},clone:function(){var d=T.clone.call(this);return d._hash=this._hash.clone(),d}});function f(d,h,w,c,u,l,s){var g=d+(h&w|~h&c)+u+s;return(g<<l|g>>>32-l)+h}function E(d,h,w,c,u,l,s){var g=d+(h&c|w&~c)+u+s;return(g<<l|g>>>32-l)+h}function P(d,h,w,c,u,l,s){var g=d+(h^w^c)+u+s;return(g<<l|g>>>32-l)+h}function y(d,h,w,c,u,l,s){var g=d+(w^(h|~c))+u+s;return(g<<l|g>>>32-l)+h}m.MD5=T._createHelper(O),m.HmacMD5=T._createHmacHelper(O)}(Math),i.MD5})},function(n,r,o){var i;Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importDefault(o(3)),v=a.__importStar(o(1)),S=a.__importDefault(o(8)),T=o(4),R=a.__importDefault(o(19)),C=a.__importDefault(o(17)),O=a.__importDefault(o(22)),f=a.__importDefault(o(2)),E=o(29),P=a.__importDefault(o(63)),y=o(14);function d(c){var u=c.statusCode;return u===408&&!c.code||u===400&&!c.code||u>=500&&u<=504}function h(c){var u=c.connection,l=u&&u.connectionManager.host;return l?[l].concat(S.default.getFallbackHosts(c.options)):S.default.getHosts(c.options)}var w=(i=function(){function c(u){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this._getHosts=h,this.options=u||{};var l=this.options.connectivityCheckUrl||S.default.connectivityCheckUrl,s=this.options.connectivityCheckParams,g=!this.options.connectivityCheckUrl;m.default.Config.xhrSupported?(this.supportsAuthHeaders=!0,this.Request=function(p,x,D,N,k,I,M){var A=C.default.createRequest(D,N,k,I,O.default.REQ_SEND,x&&x.options.timeouts,p);return A.once("complete",M),A.exec(),A},this.options.disableConnectivityCheck?this.checkConnectivity=function(p){p(null,!0)}:this.checkConnectivity=function(p){f.default.logAction(f.default.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+l),this.doUri(R.default.Get,null,l,null,null,s,function(x,D,N,k,I){var M=!1;g?M=!x&&(D==null?void 0:D.replace(/\n/,""))=="yes":M=!x&&(0,y.isSuccessCode)(I),f.default.logAction(f.default.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+M),p(null,M)})}):m.default.Config.jsonpSupported?(this.Request=function(p,x,D,N,k,I,M){var A=(0,E.createRequest)(D,N,k,I,O.default.REQ_SEND,x&&x.options.timeouts,p);return A.once("complete",M),m.default.Config.nextTick(function(){A.exec()}),A},this.options.disableConnectivityCheck?this.checkConnectivity=function(p){p(null,!0)}:this.checkConnectivity=function(p){var x=this,D=S.default.jsonpInternetUpUrl;if(this.checksInProgress){this.checksInProgress.push(p);return}this.checksInProgress=[p],f.default.logAction(f.default.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+D);var N=new E.Request("isTheInternetUp",D,null,null,null,O.default.REQ_SEND,S.default.TIMEOUTS);N.once("complete",function(k,I){var M=!k&&I;f.default.logAction(f.default.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+M);for(var A=0;A<x.checksInProgress.length;A++)x.checksInProgress[A](null,M);x.checksInProgress=null}),m.default.Config.nextTick(function(){N.exec()})}):m.default.Config.fetchSupported?(this.supportsAuthHeaders=!0,this.Request=P.default,this.checkConnectivity=function(p){f.default.logAction(f.default.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+l),this.doUri(R.default.Get,null,l,null,null,null,function(x,D){var N=!x&&(D==null?void 0:D.replace(/\n/,""))=="yes";f.default.logAction(f.default.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+N),p(null,N)})}):this.Request=function(p,x,D,N,k,I,M){M(new T.PartialErrorInfo("no supported HTTP transports available",null,400),null)}}return c.prototype.do=function(u,l,s,g,p,x,D){var N=this,k=typeof s=="function"?s:function(j){return l.baseUri(j)+s},I=l._currentFallback;if(I)if(I.validUntil>v.now()){if(!this.Request){D==null||D(new T.PartialErrorInfo("Request invoked before assigned to",null,500));return}this.Request(u,l,k(I.host),g,x,p,function(j){for(var U=[],z=1;z<arguments.length;z++)U[z-1]=arguments[z];if(j&&d(j)){l._currentFallback=null,N.do(u,l,s,g,p,x,D);return}D==null||D.apply(void 0,a.__spreadArray([j],U,!1))});return}else l._currentFallback=null;var M=h(l);if(M.length===1){this.doUri(u,l,k(M[0]),g,p,x,D);return}var A=function(j,U){var z=j.shift();N.doUri(u,l,k(z),g,p,x,function(V){for(var G=[],F=1;F<arguments.length;F++)G[F-1]=arguments[F];if(V&&d(V)&&j.length){A(j,!0);return}U&&(l._currentFallback={host:z,validUntil:v.now()+l.options.timeouts.fallbackRetryTimeout}),D==null||D.apply(void 0,a.__spreadArray([V],G,!1))})};A(M)},c.prototype.doUri=function(u,l,s,g,p,x,D){if(!this.Request){D(new T.PartialErrorInfo("Request invoked before assigned to",null,500));return}this.Request(u,l,s,g,x,p,D)},c}(),i.methods=[R.default.Get,R.default.Delete,R.default.Post,R.default.Put,R.default.Patch],i.methodsWithoutBody=[R.default.Get,R.default.Delete],i.methodsWithBody=[R.default.Post,R.default.Put,R.default.Patch],i);r.default=w},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(4)),m=i.__importDefault(o(3)),v=i.__importDefault(o(8)),S=i.__importStar(o(1)),T=o(1);function R(f,E){return!!E.get("x-ably-errorcode")}function C(f,E){if(R(f,E))return f.error&&a.default.fromValues(f.error)}function O(f,E,P,y,d,h,w){var c=new Headers(y||{}),u=f?f.toUpperCase():S.isEmptyArg(h)?"GET":"POST",l=new AbortController,s=setTimeout(function(){l.abort(),w(new a.PartialErrorInfo("Request timed out",null,408))},E?E.options.timeouts.httpRequestTimeout:v.default.TIMEOUTS.httpRequestTimeout),g={method:u,headers:c,body:h};m.default.Config.isWebworker||(g.credentials=c.has("authorization")?"include":"same-origin"),(0,T.getGlobalObject)().fetch(P+"?"+new URLSearchParams(d||{}),g).then(function(p){clearTimeout(s);var x=p.headers.get("Content-Type"),D;x&&x.indexOf("application/x-msgpack")>-1?D=p.arrayBuffer():x&&x.indexOf("application/json")>-1?D=p.json():D=p.text(),D.then(function(N){var k=!!x&&x.indexOf("application/x-msgpack")===-1;if(p.ok)w(null,N,p.headers,k,p.status);else{var I=C(N,p.headers)||new a.PartialErrorInfo("Error response received from server: "+p.status+" body was: "+m.default.Config.inspect(N),null,p.status);w(I,N,p.headers,k,p.status)}})}).catch(function(p){clearTimeout(s),w(p)})}r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(41)),m=i.__importStar(o(1)),v=m.getGlobalObject();typeof Window=="undefined"&&typeof WorkerGlobalScope=="undefined"&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function S(){var O=v.location;return!v.WebSocket||!O||!O.origin||O.origin.indexOf("http")>-1}var T=v.navigator&&v.navigator.userAgent.toString(),R=v.location&&v.location.href,C={agent:"browser",logTimestamps:!0,userAgent:T,currentUrl:R,noUpgrade:T&&!!T.match(/MSIE\s8\.0/),binaryType:"arraybuffer",WebSocket:v.WebSocket,fetchSupported:!!v.fetch,xhrSupported:v.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,jsonpSupported:typeof document!="undefined",allowComet:S(),streamingSupported:!0,useProtocolHeartbeats:!0,createHmac:null,msgpack:a.default,supportsBinary:!!v.TextDecoder,preferBinary:!1,ArrayBuffer:v.ArrayBuffer,atob:v.atob,nextTick:typeof v.setImmediate!="undefined"?v.setImmediate.bind(v):function(O){setTimeout(O,0)},addEventListener:v.addEventListener,inspect:JSON.stringify,stringByteSize:function(O){return v.TextDecoder&&new v.TextEncoder().encode(O).length||O.length},TextEncoder:v.TextEncoder,TextDecoder:v.TextDecoder,Promise:v.Promise,getRandomValues:function(O){if(O!==void 0)return function(f,E){O.getRandomValues(f),E&&E(null)}}(v.crypto||msCrypto)};r.default=C},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importStar(o(1)),v="ablyjs-storage-test",S=function(){function T(){try{i.sessionStorage.setItem(v,v),i.sessionStorage.removeItem(v),this.sessionSupported=!0}catch(R){this.sessionSupported=!1}try{i.localStorage.setItem(v,v),i.localStorage.removeItem(v),this.localSupported=!0}catch(R){this.localSupported=!1}}return T.prototype.get=function(R){return this._get(R,!1)},T.prototype.getSession=function(R){return this._get(R,!0)},T.prototype.remove=function(R){return this._remove(R,!1)},T.prototype.removeSession=function(R){return this._remove(R,!0)},T.prototype.set=function(R,C,O){return this._set(R,C,O,!1)},T.prototype.setSession=function(R,C,O){return this._set(R,C,O,!0)},T.prototype._set=function(R,C,O,f){var E={value:C};return O&&(E.expires=m.now()+O),this.storageInterface(f).setItem(R,JSON.stringify(E))},T.prototype._get=function(R,C){if(C&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!C&&!this.localSupported)throw new Error("Local Storage not supported");var O=this.storageInterface(C).getItem(R);if(!O)return null;var f=JSON.parse(O);return f.expires&&f.expires<m.now()?(this.storageInterface(C).removeItem(R),null):f.value},T.prototype._remove=function(R,C){return this.storageInterface(C).removeItem(R)},T.prototype.storageInterface=function(R){return R?i.sessionStorage:i.localStorage},T}();r.default=new S}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(67)),m={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",jsonpInternetUpUrl:"https://internet-up.ably-realtime.com/is-the-internet-up-0-9.js",defaultTransports:[a.default.XhrPolling,a.default.XhrStreaming,a.default.JsonP,a.default.WebSocket],baseTransportOrder:[a.default.XhrPolling,a.default.XhrStreaming,a.default.JsonP,a.default.WebSocket],transportPreferenceOrder:[a.default.JsonP,a.default.XhrPolling,a.default.XhrStreaming,a.default.WebSocket],upgradeTransports:[a.default.XhrStreaming,a.default.WebSocket]};r.default=m},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i;(function(a){a.WebSocket="web_socket",a.Comet="comet",a.XhrStreaming="xhr_streaming",a.XhrPolling="xhr_polling",a.JsonP="jsonp"})(i||(i={})),r.default=i},function(n,r,o){o.r(r);var i=o(29),a=o.n(i),m=o(1),v=o(3),S=o.n(v),T=o(12),R=o.n(T),C=o(17),O=o.n(C),f=function(d){var h="xhr_polling";function w(c,u,l){l.stream=!1,R.a.call(this,c,u,l),this.shortName=h}return m.inherits(w,R.a),w.isAvailable=function(){return S.a.Config.xhrSupported&&S.a.Config.allowComet},w.prototype.toString=function(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected},w.prototype.createRequest=function(c,u,l,s,g){return O.a.createRequest(c,u,l,s,g,this.timeouts)},typeof d!="undefined"&&w.isAvailable()&&(d.supportedTransports[h]=w),w},E=f,P=function(d){var h="xhr_streaming";function w(c,u,l){R.a.call(this,c,u,l),this.shortName=h}return m.inherits(w,R.a),w.isAvailable=function(){return S.a.Config.xhrSupported&&S.a.Config.streamingSupported&&S.a.Config.allowComet},w.prototype.toString=function(){return"XHRStreamingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected},w.prototype.createRequest=function(c,u,l,s,g){return O.a.createRequest(c,u,l,s,g,this.timeouts)},typeof d!="undefined"&&w.isAvailable()&&(d.supportedTransports[h]=w),w},y=P;r.default=[a.a,E,y]}]).default})})(Zc);var Qh=Zc.exports;const Jh=Oe(Qh),ys=(e,t,n,r,o)=>dt(this,null,function*(){try{const i=new Jh.Realtime({token:e.token,clientId:e.clientId});i.connection.on("connected",()=>{o==null||o("connected")}),i.connection.on("failed",v=>{console.error("[❌ ABLY CONNECTION FAILED]",v),o==null||o("failed")}),i.connection.on("disconnected",()=>{o==null||o("disconnected")});const a=`room:${t}:${n}`,m=i.channels.get(a);return m.subscribe("messages",v=>{var S;try{const T=(S=v.data)==null?void 0:S.message;if(T&&T.role==="employee"){const R={id:T.id||Xt(),text:T.content||"",sender:"bot",timestamp:T.createdAt?new Date(T.createdAt):new Date};r(R)}}catch(T){console.error("[❌ MESSAGE PARSING ERROR]",T)}}),{client:i,channel:m}}catch(i){throw console.error("[❌ ABLY INITIALIZATION ERROR]",i),i}}),Yh=(e,t)=>dt(this,null,function*(){try{const n=Xc(),r=yield fetch(`${n}?conversationId=${e}&chatbotUid=${t}`);return r.ok?yield r.json():(console.error("Failed to fetch conversation data:",r.statusText),null)}catch(n){return console.error("[❌ ABLY TOKEN FETCH ERROR]",n),null}}),Xh=e=>{e&&e.close()},qc=()=>({id:Xt(),text:"Lo siento, hubo un problema con la conexión. Esta es una respuesta de demostración.",sender:"bot",timestamp:new Date}),Zh=(e,t,n,r)=>{const o=Kh(t,e),i={id:e,senderId:r||"unknown",createdAt:new Date().toISOString(),chatbotActivated:!0,updatedAt:new Date().toISOString(),source:"IFRAME",website:typeof window!="undefined"?window.location.origin:"",messages:o};return{conversationId:e,conversation:i,chatbotUid:n.apiKey}},qh=e=>dt(this,null,function*(){try{const t=Wh(),n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return n.ok?yield n.json():(console.error("WebChat: API request failed:",n.status,n.statusText),null)}catch(t){return console.error("WebChat: Error sending message to API:",t),null}}),ep=e=>e&&e.content?{id:e.id||Xt(),text:e.content,sender:"bot",timestamp:new Date}:null,tp=e=>`¡Hola! Soy ${e||"tu asistente"}, ¿En qué te puedo ayudar?
90
+ `;F.mac=F.mac||c(Y,G),a.default.logAction(a.default.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),A(null,F)})},k.prototype.getAuthParams=function(I){this.method=="basic"?I(null,{key:this.key}):this._ensureValidAuthCredentials(!1,function(M,A){if(M){I(M);return}if(!A)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");I(null,{access_token:A.token})})},k.prototype.getAuthHeaders=function(I){this.method=="basic"?I(null,{authorization:"Basic "+this.basicKey}):this._ensureValidAuthCredentials(!1,function(M,A){if(M){I(M);return}if(!A)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");I(null,{authorization:"Bearer "+m.toBase64(A.token)})})},k.prototype.getTimestamp=function(I,M){!this.isTimeOffsetSet()&&(I||this.authOptions.queryTime)?this.client.time(M):M(null,this.getTimestampUsingOffset())},k.prototype.getTimestampUsingOffset=function(){return m.now()+(this.client.serverTimeOffset||0)},k.prototype.isTimeOffsetSet=function(){return this.client.serverTimeOffset!==null},k.prototype._saveBasicOptions=function(I){this.method="basic",this.key=I.key,this.basicKey=m.toBase64(I.key),this.authOptions=I||{},"clientId"in I&&this._userSetClientId(I.clientId)},k.prototype._saveTokenOptions=function(I,M){this.method="token",I&&(this.tokenParams=I),M&&(M.token&&(M.tokenDetails=typeof M.token=="string"?{token:M.token}:M.token),M.tokenDetails&&(this.tokenDetails=M.tokenDetails),"clientId"in M&&this._userSetClientId(M.clientId),this.authOptions=M)},k.prototype._ensureValidAuthCredentials=function(I,M){var A=this,j=this.tokenDetails;if(j){if(this._tokenClientIdMismatch(j.clientId)){M(new S.default("Mismatch between clientId in token ("+j.clientId+") and current clientId ("+this.clientId+")",40102,403));return}if(!this.isTimeOffsetSet()||!j.expires||j.expires>=this.getTimestampUsingOffset()){a.default.logAction(a.default.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+j.expires),M(null,j);return}a.default.logAction(a.default.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}if((this.waitingForTokenRequest||(this.waitingForTokenRequest=v.default.create())).push(M),!(this.currentTokenRequestId!==null&&!I)){var U=this.currentTokenRequestId=D();this.requestToken(this.tokenParams,this.authOptions,function(z,W){if(A.currentTokenRequestId>U){a.default.logAction(a.default.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one");return}A.currentTokenRequestId=null;var G=A.waitingForTokenRequest||y;if(A.waitingForTokenRequest=null,z){G(z);return}G(null,A.tokenDetails=W)})}},k.prototype._userSetClientId=function(I){if(typeof I=="string"||I===null){if(I==="*")throw new S.default('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);var M=this._uncheckedSetClientId(I);if(M)throw M}else throw new S.default("clientId must be either a string or null",40012,400)},k.prototype._uncheckedSetClientId=function(I){if(this._tokenClientIdMismatch(I)){var M="Unexpected clientId mismatch: client has "+this.clientId+", requested "+I,A=new S.default(M,40102,401);return a.default.logAction(a.default.LOG_ERROR,"Auth._uncheckedSetClientId()",M),A}else return this.clientId=this.tokenParams.clientId=I,null},k.prototype._tokenClientIdMismatch=function(I){return!!(this.clientId&&this.clientId!=="*"&&I&&I!=="*"&&this.clientId!==I)},k.isTokenErr=function(I){return I.code&&I.code>=40140&&I.code<40150},k.prototype.revokeTokens=function(I,M,A){if(g(this.client.options))throw new S.default("Cannot revoke tokens when using token auth",40162,401);var j=this.client.options.keyName,U;if(typeof M=="function"?(A=M,U={}):U=M!=null?M:{},A===void 0){if(this.client.options.promises)return m.promisify(this,"revokeTokens",[I,U]);A=y}var z=A,W=i.__assign({targets:I.map(function(L){return"".concat(L.type,":").concat(L.value)})},U),G=this.client.options.useBinaryProtocol?m.Format.msgpack:m.Format.json,F=m.defaultPostHeaders(this.client.options,G);this.client.options.headers&&m.mixin(F,this.client.options.headers);var b=m.encodeBody(W,G);E.default.post(this.client,"/keys/".concat(j,"/revokeTokens"),b,F,{newBatchResponse:"true"},null,function(L,B,_,V){if(L){z(L);return}var Y=V?B:m.decodeBody(B,G);z(null,Y)})},k}();r.default=N},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i;(function(a){a.Get="get",a.Delete="delete",a.Post="post",a.Put="put",a.Patch="patch"})(i||(i={})),r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.HttpPaginatedResponse=r.PaginatedResult=void 0;var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(2)),v=i.__importDefault(o(15)),S=i.__importDefault(o(14));function T(P){var y=P.match(/^\.\/(\w+)\?(.*)$/);return y&&y[2]&&a.parseQueryString(y[2])}function R(P){typeof P=="string"&&(P=P.split(","));for(var y={},d=0;d<P.length;d++){var h=P[d].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(h){var w=T(h[1]);w&&(y[h[2]]=w)}}return y}function C(P,y,d){return!(d&&(y||typeof P.code=="number"))}var O=function(){function P(y,d,h,w,c,u){this.rest=y,this.path=d,this.headers=h,this.envelope=w!=null?w:null,this.bodyHandler=c,this.useHttpPaginatedResponse=u||!1}return P.prototype.get=function(y,d){var h=this;v.default.get(this.rest,this.path,this.headers,y,this.envelope,function(w,c,u,l,s){h.handlePage(w,c,u,l,s,d)})},P.prototype.delete=function(y,d){var h=this;v.default.delete(this.rest,this.path,this.headers,y,this.envelope,function(w,c,u,l,s){h.handlePage(w,c,u,l,s,d)})},P.prototype.post=function(y,d,h){var w=this;v.default.post(this.rest,this.path,d,this.headers,y,this.envelope,function(c,u,l,s,g){h&&w.handlePage(c,u,l,s,g,h)})},P.prototype.put=function(y,d,h){var w=this;v.default.put(this.rest,this.path,d,this.headers,y,this.envelope,function(c,u,l,s,g){h&&w.handlePage(c,u,l,s,g,h)})},P.prototype.patch=function(y,d,h){var w=this;v.default.patch(this.rest,this.path,d,this.headers,y,this.envelope,function(c,u,l,s,g){h&&w.handlePage(c,u,l,s,g,h)})},P.prototype.handlePage=function(y,d,h,w,c,u){if(y&&C(y,d,this.useHttpPaginatedResponse)){m.default.logAction(m.default.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+a.inspectError(y)),u==null||u(y);return}var l,s,g;try{l=c==S.default.NoContent?[]:this.bodyHandler(d,h||{},w)}catch(p){u==null||u(y||p);return}h&&(s=h.Link||h.link)&&(g=R(s)),this.useHttpPaginatedResponse?u(null,new E(this,l,h||{},c,g,y)):u(null,new f(this,l,g))},P}(),f=function(){function P(y,d,h){var w=this;this.resource=y,this.items=d;var c=this;h&&("first"in h&&(this.first=function(u){if(!u&&c.resource.rest.options.promises)return a.promisify(c,"first",[]);c.get(h.first,u)}),"current"in h&&(this.current=function(u){if(!u&&c.resource.rest.options.promises)return a.promisify(c,"current",[]);c.get(h.current,u)}),this.next=function(u){if(!u&&c.resource.rest.options.promises)return a.promisify(c,"next",[]);"next"in h?c.get(h.next,u):u(null,null)},this.hasNext=function(){return"next"in h},this.isLast=function(){var u;return!(!((u=w.hasNext)===null||u===void 0)&&u.call(w))})}return P.prototype.get=function(y,d){var h=this.resource;v.default.get(h.rest,h.path,h.headers,y,h.envelope,function(w,c,u,l,s){h.handlePage(w,c,u,l,s,d)})},P}();r.PaginatedResult=f;var E=function(P){i.__extends(y,P);function y(d,h,w,c,u,l){var s=P.call(this,d,h,u)||this;return s.statusCode=c,s.success=c<300&&c>=200,s.headers=w,s.errorCode=l&&l.code,s.errorMessage=l&&l.message,s}return y.prototype.toJSON=function(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}},y}(f);r.HttpPaginatedResponse=E,r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.isRetriable=void 0;var i=o(0),a=i.__importDefault(o(4)),m={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},v={disconnected:function(){return a.default.fromValues({statusCode:400,code:m.DISCONNECTED,message:"Connection to server temporarily unavailable"})},suspended:function(){return a.default.fromValues({statusCode:400,code:m.SUSPENDED,message:"Connection to server unavailable"})},failed:function(){return a.default.fromValues({statusCode:400,code:m.FAILED,message:"Connection failed or disconnected by server"})},closing:function(){return a.default.fromValues({statusCode:400,code:m.CLOSING,message:"Connection closing"})},closed:function(){return a.default.fromValues({statusCode:400,code:m.CLOSED,message:"Connection closed"})},unknownConnectionErr:function(){return a.default.fromValues({statusCode:500,code:m.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"})},unknownChannelErr:function(){return a.default.fromValues({statusCode:500,code:m.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})}};function S(T){return!T.statusCode||!T.code||T.statusCode>=500?!0:Object.values(m).includes(T.code)}r.isRetriable=S,r.default=v},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i;(function(a){a[a.REQ_SEND=0]="REQ_SEND",a[a.REQ_RECV=1]="REQ_RECV",a[a.REQ_RECV_POLL=2]="REQ_RECV_POLL",a[a.REQ_RECV_STREAM=3]="REQ_RECV_STREAM"})(i||(i={})),r.default=i},function(n,r,o){(function(i,a){n.exports=a(o(6),o(5),o(58),o(11),o(40),o(32),o(25),o(27),o(28),o(59),o(60))})(this,function(i){return i})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(2)),m=function(){function v(S){this.members=S||[]}return v.prototype.call=function(){for(var S=[],T=0;T<arguments.length;T++)S[T]=arguments[T];for(var R=0,C=this.members;R<C.length;R++){var O=C[R];if(O)try{O.apply(void 0,S)}catch(f){a.default.logAction(a.default.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+f+"; stack = "+f.stack)}}},v.prototype.push=function(){for(var S,T=[],R=0;R<arguments.length;R++)T[R]=arguments[R];(S=this.members).push.apply(S,T)},v.create=function(S){var T=new v(S);return Object.assign(function(){for(var R=[],C=0;C<arguments.length;C++)R[C]=arguments[C];return T.call.apply(T,R)},{push:function(R){return T.push(R)}})},v}();r.default=m},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){(function(){var a=i,m=a.lib,v=m.Base,S=a.enc,T=S.Utf8,R=a.algo;R.HMAC=v.extend({init:function(C,O){C=this._hasher=new C.init,typeof O=="string"&&(O=T.parse(O));var f=C.blockSize,E=f*4;O.sigBytes>E&&(O=C.finalize(O)),O.clamp();for(var P=this._oKey=O.clone(),y=this._iKey=O.clone(),d=P.words,h=y.words,w=0;w<f;w++)d[w]^=1549556828,h[w]^=909522486;P.sigBytes=y.sigBytes=E,this.reset()},reset:function(){var C=this._hasher;C.reset(),C.update(this._iKey)},update:function(C){return this._hasher.update(C),this},finalize:function(C){var O=this._hasher,f=O.finalize(C);O.reset();var E=O.finalize(this._oKey.clone().concat(f));return E}})})()})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(10)),m=i.__importStar(o(1)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(21)),R=i.__importDefault(o(4)),C=i.__importDefault(o(3)),O=a.default.Action,f=a.default.fromValues({action:O.CLOSE}),E=a.default.fromValues({action:O.DISCONNECT}),P=function(y){i.__extends(d,y);function d(h,w,c,u){var l=y.call(this)||this;return u&&(c.format=void 0,c.heartbeats=!0),l.connectionManager=h,h.registerProposedTransport(l),l.auth=w,l.params=c,l.timeouts=c.options.timeouts,l.format=c.format,l.isConnected=!1,l.isFinished=!1,l.isDisposed=!1,l.maxIdleInterval=null,l.idleTimer=null,l.lastActivity=null,l}return d.prototype.connect=function(){},d.prototype.close=function(){this.isConnected&&this.requestClose(),this.finish("closed",T.default.closed())},d.prototype.disconnect=function(h){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",h||T.default.disconnected())},d.prototype.fail=function(h){this.isConnected&&this.requestDisconnect(),this.finish("failed",h||T.default.failed())},d.prototype.finish=function(h,w){var c;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((c=this.idleTimer)!==null&&c!==void 0?c:void 0),this.idleTimer=null,this.emit(h,w),this.dispose())},d.prototype.onProtocolMessage=function(h){switch(S.default.shouldLog(S.default.LOG_MICRO)&&S.default.logAction(S.default.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+a.default.stringify(h)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),h.action){case O.HEARTBEAT:S.default.logAction(S.default.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",h.id);break;case O.CONNECTED:this.onConnect(h),this.emit("connected",h.error,h.connectionId,h.connectionDetails,h);break;case O.CLOSED:this.onClose(h);break;case O.DISCONNECTED:this.onDisconnect(h);break;case O.ACK:this.emit("ack",h.msgSerial,h.count);break;case O.NACK:this.emit("nack",h.msgSerial,h.count,h.error);break;case O.SYNC:this.connectionManager.onChannelMessage(h,this);break;case O.ACTIVATE:break;case O.AUTH:this.auth.authorize(function(w){w&&S.default.logAction(S.default.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+m.inspectError(w))});break;case O.ERROR:if(S.default.logAction(S.default.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+C.default.Config.inspect(h.error)+(h.channel?", channel: "+h.channel:"")),h.channel===void 0){this.onFatalError(h);break}this.connectionManager.onChannelMessage(h,this);break;default:this.connectionManager.onChannelMessage(h,this)}},d.prototype.onConnect=function(h){if(this.isConnected=!0,!h.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");var w=h.connectionDetails.maxIdleInterval;w&&(this.maxIdleInterval=w+this.timeouts.realtimeRequestTimeout,this.onActivity())},d.prototype.onDisconnect=function(h){var w=h&&h.error;S.default.logAction(S.default.LOG_MINOR,"Transport.onDisconnect()","err = "+m.inspectError(w)),this.finish("disconnected",w)},d.prototype.onFatalError=function(h){var w=h&&h.error;S.default.logAction(S.default.LOG_MINOR,"Transport.onFatalError()","err = "+m.inspectError(w)),this.finish("failed",w)},d.prototype.onClose=function(h){var w=h&&h.error;S.default.logAction(S.default.LOG_MINOR,"Transport.onClose()","err = "+m.inspectError(w)),this.finish("closed",w)},d.prototype.requestClose=function(){S.default.logAction(S.default.LOG_MINOR,"Transport.requestClose()",""),this.send(f)},d.prototype.requestDisconnect=function(){S.default.logAction(S.default.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(E)},d.prototype.ping=function(h){var w={action:a.default.Action.HEARTBEAT};h&&(w.id=h),this.send(a.default.fromValues(w))},d.prototype.dispose=function(){S.default.logAction(S.default.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()},d.prototype.onActivity=function(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=m.now(),this.setIdleTimer(this.maxIdleInterval+100))},d.prototype.setIdleTimer=function(h){var w=this;this.idleTimer||(this.idleTimer=setTimeout(function(){w.onIdleTimerExpire()},h))},d.prototype.onIdleTimerExpire=function(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;var h=m.now()-this.lastActivity,w=this.maxIdleInterval-h;if(w<=0){var c="No activity seen from realtime in "+h+"ms; assuming connection has dropped";S.default.logAction(S.default.LOG_ERROR,"Transport.onIdleTimerExpire()",c),this.disconnect(new R.default(c,80003,408))}else this.setIdleTimer(w+100)},d.tryConnect=function(h,w,c,u,l){var s=new h(w,c,u),g,p=function(D){clearTimeout(g),l({event:this.event,error:D})},x=w.options.timeouts.realtimeRequestTimeout;g=setTimeout(function(){s.off(["preconnect","disconnected","failed"]),s.dispose(),p.call({event:"disconnected"},new R.default("Timeout waiting for transport to indicate itself viable",5e4,500))},x),s.on(["failed","disconnected"],p),s.on("preconnect",function(){S.default.logAction(S.default.LOG_MINOR,"Transport.tryConnect()","viable transport "+s),clearTimeout(g),s.off(["failed","disconnected"],p),l(null,s)}),s.connect()},d}(v.default);r.default=P},function(n,r,o){(function(i,a){n.exports=a(o(6),o(40),o(25))})(this,function(i){return function(){var a=i,m=a.lib,v=m.Base,S=m.WordArray,T=a.algo,R=T.MD5,C=T.EvpKDF=v.extend({cfg:v.extend({keySize:128/32,hasher:R,iterations:1}),init:function(O){this.cfg=this.cfg.extend(O)},compute:function(O,f){for(var E,P=this.cfg,y=P.hasher.create(),d=S.create(),h=d.words,w=P.keySize,c=P.iterations;h.length<w;){E&&y.update(E),E=y.update(O).finalize(f),y.reset();for(var u=1;u<c;u++)E=y.finalize(E),y.reset();d.concat(E)}return d.sigBytes=w*4,d}});a.EvpKDF=function(O,f,E){return C.create(E).compute(O,f)}}(),i.EvpKDF})},function(n,r,o){(function(i,a){n.exports=a(o(6),o(27))})(this,function(i){i.lib.Cipher||function(a){var m=i,v=m.lib,S=v.Base,T=v.WordArray,R=v.BufferedBlockAlgorithm,C=m.enc;C.Utf8;var O=C.Base64,f=m.algo,E=f.EvpKDF,P=v.Cipher=R.extend({cfg:S.extend(),createEncryptor:function(N,k){return this.create(this._ENC_XFORM_MODE,N,k)},createDecryptor:function(N,k){return this.create(this._DEC_XFORM_MODE,N,k)},init:function(N,k,I){this.cfg=this.cfg.extend(I),this._xformMode=N,this._key=k,this.reset()},reset:function(){R.reset.call(this),this._doReset()},process:function(N){return this._append(N),this._process()},finalize:function(N){N&&this._append(N);var k=this._doFinalize();return k},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function N(k){return typeof k=="string"?D:g}return function(k){return{encrypt:function(I,M,A){return N(M).encrypt(k,I,M,A)},decrypt:function(I,M,A){return N(M).decrypt(k,I,M,A)}}}}()});v.StreamCipher=P.extend({_doFinalize:function(){var N=this._process(!0);return N},blockSize:1});var y=m.mode={},d=v.BlockCipherMode=S.extend({createEncryptor:function(N,k){return this.Encryptor.create(N,k)},createDecryptor:function(N,k){return this.Decryptor.create(N,k)},init:function(N,k){this._cipher=N,this._iv=k}}),h=y.CBC=function(){var N=d.extend();N.Encryptor=N.extend({processBlock:function(I,M){var A=this._cipher,j=A.blockSize;k.call(this,I,M,j),A.encryptBlock(I,M),this._prevBlock=I.slice(M,M+j)}}),N.Decryptor=N.extend({processBlock:function(I,M){var A=this._cipher,j=A.blockSize,U=I.slice(M,M+j);A.decryptBlock(I,M),k.call(this,I,M,j),this._prevBlock=U}});function k(I,M,A){var j,U=this._iv;U?(j=U,this._iv=a):j=this._prevBlock;for(var z=0;z<A;z++)I[M+z]^=j[z]}return N}(),w=m.pad={},c=w.Pkcs7={pad:function(N,k){for(var I=k*4,M=I-N.sigBytes%I,A=M<<24|M<<16|M<<8|M,j=[],U=0;U<M;U+=4)j.push(A);var z=T.create(j,M);N.concat(z)},unpad:function(N){var k=N.words[N.sigBytes-1>>>2]&255;N.sigBytes-=k}};v.BlockCipher=P.extend({cfg:P.cfg.extend({mode:h,padding:c}),reset:function(){var N;P.reset.call(this);var k=this.cfg,I=k.iv,M=k.mode;this._xformMode==this._ENC_XFORM_MODE?N=M.createEncryptor:(N=M.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==N?this._mode.init(this,I&&I.words):(this._mode=N.call(M,this,I&&I.words),this._mode.__creator=N)},_doProcessBlock:function(N,k){this._mode.processBlock(N,k)},_doFinalize:function(){var N,k=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(k.pad(this._data,this.blockSize),N=this._process(!0)):(N=this._process(!0),k.unpad(N)),N},blockSize:128/32});var u=v.CipherParams=S.extend({init:function(N){this.mixIn(N)},toString:function(N){return(N||this.formatter).stringify(this)}}),l=m.format={},s=l.OpenSSL={stringify:function(N){var k,I=N.ciphertext,M=N.salt;return M?k=T.create([1398893684,1701076831]).concat(M).concat(I):k=I,k.toString(O)},parse:function(N){var k,I=O.parse(N),M=I.words;return M[0]==1398893684&&M[1]==1701076831&&(k=T.create(M.slice(2,4)),M.splice(0,4),I.sigBytes-=16),u.create({ciphertext:I,salt:k})}},g=v.SerializableCipher=S.extend({cfg:S.extend({format:s}),encrypt:function(N,k,I,M){M=this.cfg.extend(M);var A=N.createEncryptor(I,M),j=A.finalize(k),U=A.cfg;return u.create({ciphertext:j,key:I,iv:U.iv,algorithm:N,mode:U.mode,padding:U.padding,blockSize:N.blockSize,formatter:M.format})},decrypt:function(N,k,I,M){M=this.cfg.extend(M),k=this._parse(k,M.format);var A=N.createDecryptor(I,M).finalize(k.ciphertext);return A},_parse:function(N,k){return typeof N=="string"?k.parse(N,this):N}}),p=m.kdf={},x=p.OpenSSL={execute:function(N,k,I,M){M||(M=T.random(64/8));var A=E.create({keySize:k+I}).compute(N,M),j=T.create(A.words.slice(k),I*4);return A.sigBytes=k*4,u.create({key:A,iv:j,salt:M})}},D=v.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:x}),encrypt:function(N,k,I,M){M=this.cfg.extend(M);var A=M.kdf.execute(I,N.keySize,N.ivSize);M.iv=A.iv;var j=g.encrypt.call(this,N,k,A.key,M);return j.mixIn(A),j},decrypt:function(N,k,I,M){M=this.cfg.extend(M),k=this._parse(k,M.format);var A=M.kdf.execute(I,N.keySize,N.ivSize,k.salt);M.iv=A.iv;var j=g.decrypt.call(this,N,k,A.key,M);return j}})}()})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.Request=r.createRequest=void 0;var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(12)),v=i.__importDefault(o(3)),S=i.__importDefault(o(7)),T=o(4),R=i.__importDefault(o(8)),C=i.__importDefault(o(2)),O=i.__importDefault(o(22)),f=a.getGlobalObject(),E=function(){},P=f._ablyjs_jsonp={};P._=function(l){return P["_"+l]||E};var y=1,d="jsonp";function h(l,s,g,p,x,D,N){return D=D||R.default.TIMEOUTS,new c(void 0,l,s,a.copy(g),p,x,D,N)}r.createRequest=h;var w=function(l){i.__extends(s,l);function s(g,p,x){var D=l.call(this,g,p,x)||this;return D.shortName=d,x.stream=!1,D}return s.isAvailable=function(){return v.default.Config.jsonpSupported&&v.default.Config.allowComet},s.prototype.toString=function(){return"JSONPTransport; uri="+this.baseUri+"; isConnected="+this.isConnected},s.prototype.createRequest=function(g,p,x,D,N,k,I){return k=(this===null||this===void 0?void 0:this.timeouts)||k||R.default.TIMEOUTS,h(g,p,x,D,N,k,I)},s}(m.default),c=function(l){i.__extends(s,l);function s(g,p,x,D,N,k,I,M){var A=l.call(this)||this;return g===void 0&&(g=y++),A.id=g,A.uri=p,A.params=D||{},A.params.rnd=a.cheapRandStr(),x&&(x["X-Ably-Version"]&&(A.params.v=x["X-Ably-Version"]),x["X-Ably-Lib"]&&(A.params.lib=x["X-Ably-Lib"])),A.body=N,A.method=M,A.requestMode=k,A.timeouts=I,A.requestComplete=!1,A}return s.prototype.exec=function(){var g=this,p=this.id,x=this.body,D=this.method,N=this.uri,k=this.params;k.callback="_ablyjs_jsonp._("+p+")",k.envelope="jsonp",x&&(k.body=x),D&&D!=="get"&&(k.method=D);var I=this.script=document.createElement("script"),M=N+a.toQueryString(k);I.src=M,I.src.split("/").slice(-1)[0]!==M.split("/").slice(-1)[0]&&C.default.logAction(C.default.LOG_ERROR,"JSONP Request.exec()","Warning: the browser appears to have truncated the script URI. This will likely result in the request failing due to an unparseable body param"),I.async=!0,I.type="text/javascript",I.charset="UTF-8",I.onerror=function(U){g.complete(new T.PartialErrorInfo("JSONP script error (event: "+v.default.Config.inspect(U)+")",null,400))},P["_"+p]=function(U){if(U.statusCode){var z=U.response;if(U.statusCode==204)g.complete(null,null,null,U.statusCode);else if(!z)g.complete(new T.PartialErrorInfo("Invalid server response: no envelope detected",null,500));else if(U.statusCode<400||a.isArray(z))g.complete(null,z,U.headers,U.statusCode);else{var W=z.error||new T.PartialErrorInfo("Error response received from server",null,U.statusCode);g.complete(W)}}else g.complete(null,U)};var A=this.requestMode==O.default.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout;this.timer=setTimeout(this.abort.bind(this),A);var j=document.getElementsByTagName("head")[0];j.insertBefore(I,j.firstChild)},s.prototype.complete=function(g,p,x,D){if(x=x||{},!this.requestComplete){this.requestComplete=!0;var N=void 0;p&&(N=typeof p=="string"?"text/plain":"application/json",x["content-type"]=N,this.emit("data",p)),this.emit("complete",g,p,x,!0,D),this.dispose()}},s.prototype.abort=function(){this.dispose()},s.prototype.dispose=function(){var g=this.timer;g&&(clearTimeout(g),this.timer=null);var p=this.script;p.parentNode&&p.parentNode.removeChild(p),delete P[this.id],this.emit("disposed")},s}(S.default);r.Request=c;function u(l){return f.JSONPTransport=w,w.isAvailable()&&(l.supportedTransports[d]=w),w}r.default=u},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(2)),v=i.__importDefault(o(8)),S=i.__importDefault(o(18)),T=i.__importDefault(o(46)),R=i.__importDefault(o(20)),C=i.__importDefault(o(33)),O=i.__importDefault(o(4)),f=i.__importDefault(o(49)),E=i.__importDefault(o(19)),P=i.__importDefault(o(3)),y=i.__importDefault(o(9)),d=i.__importDefault(o(16)),h=i.__importDefault(o(15)),w=function(){},c=function(){function l(s){if(!s){var g="no options provided";throw m.default.logAction(m.default.LOG_ERROR,"Rest()",g),new Error(g)}var p=v.default.objectifyOptions(s);p.log?(m.default.setLog(p.log.level,p.log.handler),m.default.deprecated("The `log` client option","Equivalent functionality is provided by the `logLevel` and `logHandler` client options. Update your client options code of the form `{ log: { level: logLevel, handler: logHandler } }` to instead be `{ logLevel, logHandler }`.")):m.default.setLog(p.logLevel,p.logHandler),m.default.logAction(m.default.LOG_MICRO,"Rest()","initialized with clientOptions "+P.default.Config.inspect(s));var x=this.options=v.default.normaliseOptions(p);if(x.key){var D=x.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!D){var g="invalid key parameter";throw m.default.logAction(m.default.LOG_ERROR,"Rest()",g),new O.default(g,40400,404)}x.keyName=D[1],x.keySecret=D[2]}if("clientId"in x)if(typeof x.clientId=="string"||x.clientId===null){if(x.clientId==="*")throw new O.default('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new O.default("clientId must be either a string or null",40012,400);m.default.logAction(m.default.LOG_MINOR,"Rest()","started; version = "+v.default.version),this.baseUri=this.authority=function(N){return v.default.getHttpScheme(x)+N+":"+v.default.getPort(x,!1)},this._currentFallback=null,this.serverTimeOffset=null,this.http=new P.default.Http(x),this.auth=new S.default(this,x),this.channels=new u(this),this.push=new T.default(this)}return l.prototype.stats=function(s,g){if(g===void 0)if(typeof s=="function")g=s,s=null;else{if(this.options.promises)return a.promisify(this,"stats",[s]);g=w}var p=a.defaultGetHeaders(this.options),x=this.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,D=this.http.supportsLinkHeaders?void 0:x;this.options.headers&&a.mixin(p,this.options.headers),new R.default(this,"/stats",p,D,function(N,k,I){for(var M=I?N:JSON.parse(N),A=0;A<M.length;A++)M[A]=f.default.fromValues(M[A]);return M}).get(s,g)},l.prototype.time=function(s,g){var p=this;if(g===void 0){if(typeof s=="function")g=s,s=null;else if(this.options.promises)return a.promisify(this,"time",[s])}var x=g||w,D=a.defaultGetHeaders(this.options);this.options.headers&&a.mixin(D,this.options.headers);var N=function(k){return p.authority(k)+"/time"};this.http.do(E.default.Get,this,N,D,null,s,function(k,I,M,A){if(k){x(k);return}A||(I=JSON.parse(I));var j=I[0];if(!j){x(new O.default("Internal error (unexpected result type from GET /time)",5e4,500));return}p.serverTimeOffset=j-a.now(),x(null,j)})},l.prototype.request=function(s,g,p,x,D,N){var k=this.options.useBinaryProtocol,I=k?P.default.Config.msgpack.encode:JSON.stringify,M=k?P.default.Config.msgpack.decode:JSON.parse,A=k?a.Format.msgpack:a.Format.json,j=this.http.supportsLinkHeaders?void 0:A;p=p||{};var U=s.toLowerCase(),z=U=="get"?a.defaultGetHeaders(this.options,A):a.defaultPostHeaders(this.options,A);if(N===void 0){if(this.options.promises)return a.promisify(this,"request",[s,g,p,x,D]);N=w}typeof x!="string"&&(x=I(x)),this.options.headers&&a.mixin(z,this.options.headers),D&&a.mixin(z,D);var W=new R.default(this,g,z,j,function(G,F,b){return a.ensureArray(b?G:M(G))},!0);if(!a.arrIn(P.default.Http.methods,U))throw new O.default("Unsupported method "+U,40500,405);a.arrIn(P.default.Http.methodsWithBody,U)?W[U](p,x,N):W[U](p,N)},l.prototype.batchPublish=function(s,g){if(g===void 0){if(this.options.promises)return a.promisify(this,"batchPublish",[s]);g=w}var p=g,x,D;a.isArray(s)?(x=s,D=!1):(x=[s],D=!0);var N=this.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,k=a.defaultPostHeaders(this.options,N);this.options.headers&&a.mixin(k,this.options.headers);var I=a.encodeBody(x,N);h.default.post(this,"/messages",I,k,{newBatchResponse:"true"},null,function(M,A,j,U){if(M){p(M);return}var z=U?A:a.decodeBody(A,N);D?p(null,z[0]):p(null,z)})},l.prototype.batchPresence=function(s,g){if(g===void 0){if(this.options.promises)return a.promisify(this,"batchPresence",[s]);g=w}var p=g,x=this.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,D=a.defaultPostHeaders(this.options,x);this.options.headers&&a.mixin(D,this.options.headers);var N=s.join(",");h.default.get(this,"/presence",D,{newBatchResponse:"true",channels:N},null,function(k,I,M,A){if(k){p(k);return}var j=A?I:a.decodeBody(I,x);p(null,j)})},l.prototype.setLog=function(s){m.default.setLog(s.level,s.handler)},l.Promise=function(s){return s=v.default.objectifyOptions(s),s.promises=!0,new l(s)},l.Callbacks=l,l.Platform=P.default,l.Message=y.default,l.PresenceMessage=d.default,l}(),u=function(){function l(s){this.rest=s,this.all=Object.create(null)}return l.prototype.get=function(s,g){s=String(s);var p=this.all[s];return p?g&&p.setOptions(g):this.all[s]=p=new C.default(this.rest,s,g),p},l.prototype.release=function(s){delete this.all[String(s)]},l}();r.default=c},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return i.enc.Utf8})},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(a){var m=i,v=m.lib,S=v.WordArray,T=v.Hasher,R=m.algo,C=[],O=[];(function(){function P(w){for(var c=a.sqrt(w),u=2;u<=c;u++)if(!(w%u))return!1;return!0}function y(w){return(w-(w|0))*4294967296|0}for(var d=2,h=0;h<64;)P(d)&&(h<8&&(C[h]=y(a.pow(d,1/2))),O[h]=y(a.pow(d,1/3)),h++),d++})();var f=[],E=R.SHA256=T.extend({_doReset:function(){this._hash=new S.init(C.slice(0))},_doProcessBlock:function(P,y){for(var d=this._hash.words,h=d[0],w=d[1],c=d[2],u=d[3],l=d[4],s=d[5],g=d[6],p=d[7],x=0;x<64;x++){if(x<16)f[x]=P[y+x]|0;else{var D=f[x-15],N=(D<<25|D>>>7)^(D<<14|D>>>18)^D>>>3,k=f[x-2],I=(k<<15|k>>>17)^(k<<13|k>>>19)^k>>>10;f[x]=N+f[x-7]+I+f[x-16]}var M=l&s^~l&g,A=h&w^h&c^w&c,j=(h<<30|h>>>2)^(h<<19|h>>>13)^(h<<10|h>>>22),U=(l<<26|l>>>6)^(l<<21|l>>>11)^(l<<7|l>>>25),z=p+U+M+O[x]+f[x],W=j+A;p=g,g=s,s=l,l=u+z|0,u=c,c=w,w=h,h=z+W|0}d[0]=d[0]+h|0,d[1]=d[1]+w|0,d[2]=d[2]+c|0,d[3]=d[3]+u|0,d[4]=d[4]+l|0,d[5]=d[5]+s|0,d[6]=d[6]+g|0,d[7]=d[7]+p|0},_doFinalize:function(){var P=this._data,y=P.words,d=this._nDataBytes*8,h=P.sigBytes*8;return y[h>>>5]|=128<<24-h%32,y[(h+64>>>9<<4)+14]=a.floor(d/4294967296),y[(h+64>>>9<<4)+15]=d,P.sigBytes=y.length*4,this._process(),this._hash},clone:function(){var P=T.clone.call(this);return P._hash=this._hash.clone(),P}});m.SHA256=T._createHelper(E),m.HmacSHA256=T._createHmacHelper(E)}(Math),i.SHA256})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(7)),v=i.__importDefault(o(2)),S=i.__importDefault(o(34)),T=i.__importDefault(o(9)),R=i.__importDefault(o(4)),C=i.__importDefault(o(20)),O=i.__importDefault(o(15)),f=i.__importDefault(o(3));function E(){}var P=9;function y(w){return a.arrEvery(w,function(c){return!c.id})}function d(w){var c=w||{};if(c.cipher){if(!f.default.Crypto)throw new Error("Encryption not enabled; use ably.encryption.js instead");var u=f.default.Crypto.getCipher(c.cipher);c.cipher=u.cipherParams,c.channelCipher=u.cipher}else"cipher"in c&&(c.cipher=void 0,c.channelCipher=null);return c}var h=function(w){i.__extends(c,w);function c(u,l,s){var g=w.call(this)||this;return v.default.logAction(v.default.LOG_MINOR,"Channel()","started; name = "+l),g.rest=u,g.name=l,g.basePath="/channels/"+encodeURIComponent(l),g.presence=new S.default(g),g.channelOptions=d(s),g}return c.prototype.setOptions=function(u){this.channelOptions=d(u)},c.prototype.history=function(u,l){if(v.default.logAction(v.default.LOG_MICRO,"Channel.history()","channel = "+this.name),l===void 0)if(typeof u=="function")l=u,u=null;else{if(this.rest.options.promises)return a.promisify(this,"history",arguments);l=E}this._history(u,l)},c.prototype._history=function(u,l){var s=this.rest,g=s.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,p=this.rest.http.supportsLinkHeaders?void 0:g,x=a.defaultGetHeaders(s.options,g);s.options.headers&&a.mixin(x,s.options.headers);var D=this.channelOptions;new C.default(s,this.basePath+"/messages",x,p,function(N,k,I){return T.default.fromResponseBody(N,D,I?void 0:g)}).get(u,l)},c.prototype.publish=function(){var u=this,l=arguments.length,s=arguments[0],g=arguments[1],p=arguments[l-1],x,D;if(typeof p!="function"){if(this.rest.options.promises)return a.promisify(this,"publish",arguments);p=E}if(typeof s=="string"||s===null)x=[T.default.fromValues({name:s,data:g})],D=arguments[2];else if(a.isObject(s))x=[T.default.fromValues(s)],D=arguments[1];else if(a.isArray(s))x=T.default.fromValuesArray(s),D=arguments[1];else throw new R.default("The single-argument form of publish() expects a message object or an array of message objects",40013,400);(typeof D!="object"||!D)&&(D={});var N=this.rest,k=N.options,I=k.useBinaryProtocol?a.Format.msgpack:a.Format.json,M=N.options.idempotentRestPublishing,A=a.defaultPostHeaders(N.options,I);if(k.headers&&a.mixin(A,k.headers),M&&y(x)){var j=a.randomString(P);a.arrForEach(x,function(U,z){U.id=j+":"+z.toString()})}T.default.encodeArray(x,this.channelOptions,function(U){if(U){p(U);return}var z=T.default.getMessagesSize(x),W=k.maxMessageSize;if(z>W){p(new R.default("Maximum size of messages that can be published at once exceeded ( was "+z+" bytes; limit is "+W+" bytes)",40009,400));return}u._publish(T.default.serialize(x,I),A,D,p)})},c.prototype._publish=function(u,l,s,g){O.default.post(this.rest,this.basePath+"/messages",u,l,s,null,g)},c.prototype.status=function(u){if(typeof u!="function"&&this.rest.options.promises)return a.promisify(this,"status",[]);var l=this.rest.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,s=a.defaultPostHeaders(this.rest.options,l);O.default.get(this.rest,this.basePath,s,{},l,u||E)},c}(m.default);r.default=h},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(7)),v=i.__importDefault(o(2)),S=i.__importDefault(o(20)),T=i.__importDefault(o(16));function R(){}var C=function(O){i.__extends(f,O);function f(E){var P=O.call(this)||this;return P.channel=E,P.basePath=E.basePath+"/presence",P}return f.prototype.get=function(E,P){if(v.default.logAction(v.default.LOG_MICRO,"Presence.get()","channel = "+this.channel.name),P===void 0)if(typeof E=="function")P=E,E=null;else{if(this.channel.rest.options.promises)return a.promisify(this,"get",arguments);P=R}var y=this.channel.rest,d=y.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,h=this.channel.rest.http.supportsLinkHeaders?void 0:d,w=a.defaultGetHeaders(y.options,d);y.options.headers&&a.mixin(w,y.options.headers);var c=this.channel.channelOptions;new S.default(y,this.basePath,w,h,function(u,l,s){return T.default.fromResponseBody(u,c,s?void 0:d)}).get(E,P)},f.prototype.history=function(E,P){return v.default.logAction(v.default.LOG_MICRO,"Presence.history()","channel = "+this.channel.name),this._history(E,P)},f.prototype._history=function(E,P){if(P===void 0)if(typeof E=="function")P=E,E=null;else{if(this.channel.rest.options.promises)return a.promisify(this,"_history",[E]);P=R}var y=this.channel.rest,d=y.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,h=this.channel.rest.http.supportsLinkHeaders?void 0:d,w=a.defaultGetHeaders(y.options,d);y.options.headers&&a.mixin(w,y.options.headers);var c=this.channel.channelOptions;new S.default(y,this.basePath+"/history",w,h,function(u,l,s){return T.default.fromResponseBody(u,c,s?void 0:d)}).get(E,P)},f}(m.default);r.default=C},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0}),r.TransportParams=void 0;var a=o(0),m=a.__importDefault(o(10)),v=a.__importStar(o(1)),S=a.__importStar(o(52)),T=a.__importStar(o(8)),R=a.__importDefault(o(3)),C=a.__importDefault(o(7)),O=a.__importDefault(o(36)),f=a.__importDefault(o(2)),E=a.__importDefault(o(37)),P=a.__importStar(o(21)),y=a.__importStar(o(4)),d=a.__importDefault(o(18)),h=a.__importDefault(o(9)),w=a.__importDefault(o(24)),c=a.__importDefault(o(53)),u=a.__importDefault(o(26)),l=a.__importDefault(o(14)),s=function(){var G;return typeof R.default.WebStorage!="undefined"&&((G=R.default.WebStorage)===null||G===void 0?void 0:G.localSupported)},g=function(){var G;return typeof R.default.WebStorage!="undefined"&&((G=R.default.WebStorage)===null||G===void 0?void 0:G.sessionSupported)},p=m.default.Action,x=function(){},D="ably-transport-preference",N="ably-connection-recovery";function k(){var G,F;return g()&&((F=(G=R.default.WebStorage)===null||G===void 0?void 0:G.getSession)===null||F===void 0?void 0:F.call(G,N))}function I(G){var F,b;return g()&&((b=(F=R.default.WebStorage)===null||F===void 0?void 0:F.setSession)===null||b===void 0?void 0:b.call(F,N,G))}function M(){var G,F;return g()&&((F=(G=R.default.WebStorage)===null||G===void 0?void 0:G.removeSession)===null||F===void 0?void 0:F.call(G,N))}function A(G,F){return v.arrIndexOf(R.default.Defaults.transportPreferenceOrder,G.shortName)>v.arrIndexOf(R.default.Defaults.transportPreferenceOrder,F.shortName)}function j(G,F,b){var L;if(G.channel!==F.channel||(L=G.action)!==p.PRESENCE&&L!==p.MESSAGE||L!==F.action)return!1;var B=L===p.PRESENCE?"presence":"messages",_=G[B].concat(F[B]),V=h.default.getMessagesSize(_);return V>b||!v.allSame(_,"clientId")||!v.arrEvery(_,function(Y){return!Y.id})?!1:(G[B]=_,!0)}function U(G){try{return JSON.parse(G)}catch(F){return null}}var z=function(){function G(F,b,L,B){this.options=F,this.host=b,this.mode=L,this.connectionKey=B,this.format=F.useBinaryProtocol?v.Format.msgpack:v.Format.json}return G.prototype.getConnectParams=function(F){var b=F?v.copy(F):{},L=this.options;switch(this.mode){case"upgrade":b.upgrade=this.connectionKey;break;case"resume":b.resume=this.connectionKey;break;case"recover":{var B=U(L.recover);B&&(b.recover=B.connectionKey);break}}return L.clientId!==void 0&&(b.clientId=L.clientId),L.echoMessages===!1&&(b.echo="false"),this.format!==void 0&&(b.format=this.format),this.stream!==void 0&&(b.stream=this.stream),this.heartbeats!==void 0&&(b.heartbeats=this.heartbeats),b.v=T.default.protocolVersion,b.agent=(0,T.getAgentString)(this.options),L.transportParams!==void 0&&v.mixin(b,L.transportParams),b},G.prototype.toString=function(){var F="[mode="+this.mode;return this.host&&(F+=",host="+this.host),this.connectionKey&&(F+=",connectionKey="+this.connectionKey),this.format&&(F+=",format="+this.format),F+="]",F},G}();r.TransportParams=z;var W=function(G){a.__extends(F,G);function F(b,L){var B=G.call(this)||this;B.disconnectedRetryCount=0,F.initTransports(),B.realtime=b,B.options=L;var _=L.timeouts,V=_.preferenceConnectTimeout+_.realtimeRequestTimeout;if(B.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:V,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},synchronizing:{state:"connected",terminal:!1,queueEvents:!0,sendEvents:!1,forceQueueEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:_.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:_.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:_.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},B.state=B.states.initialized,B.errorReason=null,B.queuedMessages=new O.default,B.msgSerial=0,B.connectionDetails=void 0,B.connectionId=void 0,B.connectionKey=void 0,B.connectionStateTtl=_.connectionStateTtl,B.maxIdleInterval=null,B.transports=v.intersect(L.transports||T.default.defaultTransports,F.supportedTransports),B.baseTransport=v.intersect(T.default.baseTransportOrder,B.transports)[0],B.upgradeTransports=v.intersect(B.transports,T.default.upgradeTransports),B.transportPreference=null,B.httpHosts=T.default.getHosts(L),B.activeProtocol=null,B.proposedTransports=[],B.pendingTransports=[],B.host=null,B.lastAutoReconnectAttempt=null,B.lastActivity=null,B.forceFallbackHost=!1,B.connectCounter=0,f.default.logAction(f.default.LOG_MINOR,"Realtime.ConnectionManager()","started"),f.default.logAction(f.default.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(L.transports||T.default.defaultTransports)+"]"),f.default.logAction(f.default.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+B.transports+"]"),f.default.logAction(f.default.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+B.httpHosts+"]"),!B.transports.length){var Y="no requested transports available";throw f.default.logAction(f.default.LOG_ERROR,"realtime.ConnectionManager()",Y),new Error(Y)}var X=R.default.Config.addEventListener;return X&&(g()&&typeof L.recover=="function"&&X("beforeunload",B.persistConnection.bind(B)),L.closeOnUnload===!0&&X("beforeunload",function(){f.default.logAction(f.default.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),B.requestState({state:"closing"})}),X("online",function(){B.state==B.states.disconnected||B.state==B.states.suspended?(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),B.requestState({state:"connecting"})):B.state==B.states.connecting&&(B.pendingTransports.forEach(function(te){te.off()}),B.disconnectAllTransports(),B.startConnect())}),X("offline",function(){B.state==B.states.connected&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),B.disconnectAllTransports())})),B}return F.initTransports=function(){(0,c.default)(F),v.arrForEach(R.default.Transports,function(b){b(F)})},F.prototype.createTransportParams=function(b,L){return new z(this.options,b,L,this.connectionKey)},F.prototype.getTransportParams=function(b){var L=this,B=function(_){if(L.connectionKey){_("resume");return}if(typeof L.options.recover=="string"){_("recover");return}var V=L.options.recover,Y=k();if(Y&&typeof V=="function"){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data"),V(Y,function(X){X?(L.options.recover=Y.recoveryKey,_("recover")):_("clean")});return}_("clean")};B(function(_){var V=L.createTransportParams(null,_);if(_==="recover"){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+L.options.recover);var Y=U(L.options.recover);Y&&(L.msgSerial=Y.msgSerial)}else f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+V.toString());b(V)})},F.prototype.tryATransport=function(b,L,B){var _=this;f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+L),u.default.tryConnect(F.supportedTransports[L],this,this.realtime.auth,b,function(V,Y){var X=_.state;if(X==_.states.closing||X==_.states.closed||X==_.states.failed){Y&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+X.state+" while we were attempting the transport; closing "+Y),Y.close()),B(!0);return}if(V){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+L+" "+V.event+", err: "+V.error.toString()),d.default.isTokenErr(V.error)&&!(_.errorReason&&d.default.isTokenErr(_.errorReason))?(_.errorReason=V.error,_.realtime.auth._forceNewToken(null,null,function(te){if(te){_.actOnErrorFromAuthorize(te);return}_.tryATransport(b,L,B)})):V.event==="failed"?(_.notifyState({state:"failed",error:V.error}),B(!0)):V.event==="disconnected"&&((0,P.isRetriable)(V.error)?B(!1):(_.notifyState({state:_.states.connecting.failState,error:V.error}),B(!0)));return}f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+L+"; setting pending"),_.setTransportPending(Y,b),B(null,Y)})},F.prototype.setTransportPending=function(b,L){var B=this,_=L.mode;f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+b+"; mode = "+_),v.arrDeleteValue(this.proposedTransports,b),this.pendingTransports.push(b);var V=R.default.Defaults.transportPreferenceOrder[R.default.Defaults.transportPreferenceOrder.length-1];b.once("connected",function(X,te,re){_=="upgrade"&&B.activeProtocol?b.shortName!==V&&v.arrIn(B.getUpgradePossibilities(),V)&&B.activeProtocol?setTimeout(function(){B.scheduleTransportActivation(X,b,te,re)},B.options.timeouts.parallelUpgradeDelay):B.scheduleTransportActivation(X,b,te,re):(B.activateTransport(X,b,te,re),R.default.Config.nextTick(function(){B.connectImpl(L)})),_==="recover"&&B.options.recover&&(B.options.recover=null,B.unpersistConnection())});var Y=this;b.on(["disconnected","closed","failed"],function(X){Y.deactivateTransport(b,this.event,X)}),this.emit("transport.pending",b)},F.prototype.scheduleTransportActivation=function(b,L,B,_){var V=this,Y=this.activeProtocol&&this.activeProtocol.getTransport(),X=function(){L.disconnect(),v.arrDeleteValue(V.pendingTransports,L)};if(this.state!==this.states.connected&&this.state!==this.states.connecting){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+this.state.state+(this.state===this.states.synchronizing?", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+L.shortName),X();return}if(Y&&!A(L,Y)){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+L.shortName+" is no better than current active transport "+Y.shortName+" - abandoning upgrade"),X();return}f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+L);var te=null;if(!L.isConnected){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+L.shortName+"is no longer connected; abandoning upgrade"),X();return}if(this.state===this.states.connected)f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Currently connected, so temporarily pausing events until the upgrade is complete"),this.state=this.states.synchronizing,te=this.activeProtocol;else if(this.state!==this.states.connecting){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+this.state.state+(this.state===this.states.synchronizing?", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+L.shortName),X();return}f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+L);var re=function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+L),L.send(m.default.fromValues({action:p.ACTIVATE})),V.activateTransport(b,L,B,_),V.state===V.states.synchronizing?(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+L),V.state=V.states.connected):f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, but state is now "+V.state.state+", so leaving unchanged"),V.state.sendEvents&&V.sendQueuedMessages()};te?te.onceIdle(re):re()},F.prototype.activateTransport=function(b,L,B,_){var V=this;f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+L),b&&f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+b),B&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+B),_&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(_)),this.persistTransportPreference(L);var Y=this.state,X=this.states.connected.state;if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+Y.state),Y.state==this.states.closing.state||Y.state==this.states.closed.state||Y.state==this.states.failed.state)return f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),L.disconnect(),!1;if(v.arrDeleteValue(this.pendingTransports,L),!L.isConnected)return f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+L+" since it appears to no longer be connected"),!1;var te=this.activeProtocol;this.activeProtocol=new S.default(L),this.host=L.params.host;var re=_.connectionKey;if(re&&this.connectionKey!=re&&this.setConnection(B,_,!!b),this.onConnectionDetailsUpdate(_,L),R.default.Config.nextTick(function(){L.on("connected",function(Z,he,Me){V.onConnectionDetailsUpdate(Me,L),V.emit("update",new E.default(X,X,null,Z))})}),Y.state===this.states.connected.state?b&&(this.errorReason=this.realtime.connection.errorReason=b,this.emit("update",new E.default(X,X,null,b))):(this.notifyState({state:"connected",error:b}),this.errorReason=this.realtime.connection.errorReason=b||null),this.emit("transport.active",L),te)if(te.messageQueue.count()>0&&f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+te.transport.shortName+", new one is "+L.shortName+") finishing with "+te.messageQueue.count()+" messages still pending"),te.transport===L){var le="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+L.shortName+"; stack = "+new Error().stack;f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()",le)}else te.finish();return v.safeArrForEach(this.pendingTransports,function(Z){if(Z===L){var he="Assumption violated: activating a transport that is still marked as a pending transport; transport = "+L.shortName+"; stack = "+new Error().stack;f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()",he),v.arrDeleteValue(V.pendingTransports,L)}else Z.disconnect()}),v.safeArrForEach(this.proposedTransports,function(Z){Z===L?(f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.activateTransport()","Assumption violated: activating a transport that is still marked as a proposed transport; transport = "+L.shortName+"; stack = "+new Error().stack),v.arrDeleteValue(V.proposedTransports,L)):Z.dispose()}),!0},F.prototype.deactivateTransport=function(b,L,B){var _=this.activeProtocol,V=_&&_.getTransport()===b,Y=v.arrDeleteValue(this.pendingTransports,b),X=v.arrDeleteValue(this.proposedTransports,b),te=this.noTransportsScheduledForActivation();if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+b),f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+L+(V?"; was active":Y?"; was pending":X?"; was proposed":"")+(te?"":"; another transport is scheduled for activation")),B&&B.message&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+B.message),V&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(_.getPendingMessages()),R.default.Config.nextTick(function(){_.clearPendingMessages()}),this.activeProtocol=this.host=null),this.emit("transport.inactive",b),V&&te||V&&L==="failed"||L==="closed"||_===null&&Y&&this.pendingTransports.length===0){if(L==="disconnected"&&B&&B.statusCode>500&&this.httpHosts.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:L,error:B,retryImmediately:!0});return}var re=L==="failed"&&d.default.isTokenErr(B)?"disconnected":L;this.notifyState({state:re,error:B});return}V&&L==="disconnected"&&this.state!==this.states.synchronizing&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.deactivateTransport()","wasActive but another transport is connected and scheduled for activation, so going into the connecting state until it activates"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),this.notifyState({state:"connecting",error:B}))},F.prototype.noTransportsScheduledForActivation=function(){return v.isEmpty(this.pendingTransports)||this.pendingTransports.every(function(b){return!b.isConnected})},F.prototype.setConnection=function(b,L,B){var _=this.connectionId,V=_&&_!==b,Y=!_&&B;(V||Y)&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==b&&f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=b,this.realtime.connection.key=this.connectionKey=L.connectionKey},F.prototype.clearConnection=function(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()},F.prototype.createRecoveryKey=function(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null},F.prototype.checkConnectionStateFreshness=function(){if(!(!this.lastActivity||!this.connectionId)){var b=v.now()-this.lastActivity;b>this.connectionStateTtl+this.maxIdleInterval&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+b+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}},F.prototype.persistConnection=function(){if(g()){var b=this.createRecoveryKey();b&&I({recoveryKey:b,disconnectedAt:v.now(),location:i.location,clientId:this.realtime.auth.clientId})}},F.prototype.unpersistConnection=function(){M()},F.prototype.getError=function(){return this.errorReason||this.getStateError()},F.prototype.getStateError=function(){var b,L;return(L=(b=P.default)[this.state.state])===null||L===void 0?void 0:L.call(b)},F.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents},F.prototype.enactStateChange=function(b){var L=b.current==="failed"?f.default.LOG_ERROR:f.default.LOG_MAJOR;f.default.logAction(L,"Connection state",b.current+(b.reason?"; reason: "+b.reason:"")),f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+b.current+"; reason = "+(b.reason&&b.reason.message));var B=this.state=this.states[b.current];b.reason&&(this.errorReason=b.reason,this.realtime.connection.errorReason=b.reason),(B.terminal||B.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",b)},F.prototype.startTransitionTimer=function(b){var L=this;f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+b.state),this.transitionTimer&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(function(){L.transitionTimer&&(L.transitionTimer=null,f.default.logAction(f.default.LOG_MINOR,"ConnectionManager "+b.state+" timer expired","requesting new state: "+b.failState),L.notifyState({state:b.failState}))},b.retryDelay)},F.prototype.cancelTransitionTimer=function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)},F.prototype.startSuspendTimer=function(){var b=this;this.suspendTimer||(this.suspendTimer=setTimeout(function(){b.suspendTimer&&(b.suspendTimer=null,f.default.logAction(f.default.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),b.states.connecting.failState="suspended",b.notifyState({state:"suspended"}))},this.connectionStateTtl))},F.prototype.checkSuspendTimer=function(b){b!=="disconnected"&&b!=="suspended"&&b!=="connecting"&&this.cancelSuspendTimer()},F.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)},F.prototype.startRetryTimer=function(b){var L=this;this.retryTimer=setTimeout(function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),L.retryTimer=null,L.requestState({state:"connecting"})},b)},F.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)},F.prototype.notifyState=function(b){var L=this,B,_,V=b.state,Y=V==="disconnected"&&(this.state===this.states.connected||this.state===this.states.synchronizing||b.retryImmediately||this.state===this.states.connecting&&b.error&&d.default.isTokenErr(b.error)&&!(this.errorReason&&d.default.isTokenErr(this.errorReason)));if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+V+(Y?"; will retry connection immediately":"")),V!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(b.state),(V==="suspended"||V==="connected")&&(this.disconnectedRetryCount=0),!this.state.terminal)){var X=this.states[b.state],te=X.retryDelay;X.state==="disconnected"&&(this.disconnectedRetryCount++,te=v.getRetryTime(X.retryDelay,this.disconnectedRetryCount));var re=new E.default(this.state.state,X.state,te,b.error||((_=(B=P.default)[X.state])===null||_===void 0?void 0:_.call(B)));if(Y){var le=function(){L.state===L.states.disconnected&&(L.lastAutoReconnectAttempt=v.now(),L.requestState({state:"connecting"}))},Z=this.lastAutoReconnectAttempt&&v.now()-this.lastAutoReconnectAttempt+1;Z&&Z<1e3?(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+Z+"ms ago, waiting another "+(1e3-Z)+"ms before trying again"),setTimeout(le,1e3-Z)):R.default.Config.nextTick(le)}else(V==="disconnected"||V==="suspended")&&this.startRetryTimer(te);(V==="disconnected"&&!Y||V==="suspended"||X.terminal)&&R.default.Config.nextTick(function(){L.disconnectAllTransports()}),V=="connected"&&!this.activeProtocol&&f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(re),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(V,re.reason),this.failQueuedMessages(re.reason))}},F.prototype.requestState=function(b){var L=this,B,_,V=b.state;if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+V+"; current state: "+this.state.state),V!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(V),!(V=="connecting"&&this.state.state=="connected")&&!(V=="closing"&&this.state.state=="closed"))){var Y=this.states[V],X=new E.default(this.state.state,Y.state,null,b.error||((_=(B=P.default)[Y.state])===null||_===void 0?void 0:_.call(B)));this.enactStateChange(X),V=="connecting"&&R.default.Config.nextTick(function(){L.startConnect()}),V=="closing"&&this.closeImpl()}},F.prototype.startConnect=function(){var b=this;if(this.state!==this.states.connecting){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}var L=this.realtime.auth,B=++this.connectCounter,_=function(){b.checkConnectionStateFreshness(),b.getTransportParams(function(Y){if(Y.mode==="recover"&&Y.options.recover){var X=U(Y.options.recover);X&&b.realtime.channels.recoverChannels(X.channelSerials)}B===b.connectCounter&&b.connectImpl(Y,B)})};if(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),L.method==="basic")_();else{var V=function(Y){B===b.connectCounter&&(Y?b.actOnErrorFromAuthorize(Y):_())};this.errorReason&&d.default.isTokenErr(this.errorReason)?L._forceNewToken(null,null,V):L._ensureValidAuthCredentials(!1,V)}},F.prototype.connectImpl=function(b,L){var B=this.state.state;B!==this.states.connecting.state&&B!==this.states.connected.state?f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+B):this.pendingTransports.length?f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):B==this.states.connected.state?this.upgradeIfNeeded(b):this.transports.length>1&&this.getTransportPreference()?this.connectPreference(b,L):this.connectBase(b,L)},F.prototype.connectPreference=function(b,L){var B=this,_=this.getTransportPreference(),V=!1;v.arrIn(this.transports,_)||(this.unpersistTransportPreference(),this.connectImpl(b,L)),f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectPreference()","Trying to connect with stored transport preference "+_);var Y=setTimeout(function(){V=!0,B.state.state!==B.states.connected.state&&(f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectPreference()","Shortcircuit connection attempt with "+_+" failed; clearing preference and trying from scratch"),B.disconnectAllTransports(),B.unpersistTransportPreference()),B.connectImpl(b,L)},this.options.timeouts.preferenceConnectTimeout);b.host=this.httpHosts[0],this.tryATransport(b,_,function(X,te){clearTimeout(Y),V&&te?(te.off(),te.disconnect(),v.arrDeleteValue(B.pendingTransports,te)):!te&&!X&&(B.unpersistTransportPreference(),B.connectImpl(b,L))})},F.prototype.connectBase=function(b,L){var B=this,_=function(re){B.notifyState({state:B.states.connecting.failState,error:re})},V=this.httpHosts.slice(),Y=function(re,le){L===B.connectCounter&&!le&&!re&&te()};f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.connectBase()","Trying to connect with base transport "+this.baseTransport);var X=V.shift();if(!X){_(new y.default("Unable to connect (no available host)",80003,404));return}b.host=X;var te=function(){if(!V.length){_(new y.default("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!B.realtime.http.checkConnectivity){_(new y.PartialErrorInfo("Internal error: Http.checkConnectivity not set",null,500));return}B.realtime.http.checkConnectivity(function(re,le){if(L===B.connectCounter){if(re){_(re);return}if(!le){_(new y.default("Unable to connect (network unreachable)",80003,404));return}b.host=v.arrPopRandomElement(V),B.tryATransport(b,B.baseTransport,Y)}})};if(this.forceFallbackHost&&V.length){this.forceFallbackHost=!1,te();return}this.tryATransport(b,this.baseTransport,Y)},F.prototype.getUpgradePossibilities=function(){var b=this.activeProtocol.getTransport().shortName,L=v.arrIndexOf(this.upgradeTransports,b);return this.upgradeTransports.slice(L+1)},F.prototype.upgradeIfNeeded=function(b){var L=this,B=this.getUpgradePossibilities();f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.upgradeIfNeeded()","upgrade possibilities: "+R.default.Config.inspect(B)),B.length&&v.arrForEach(B,function(_){var V=L.createTransportParams(b.host,"upgrade");L.tryATransport(V,_,x)})},F.prototype.closeImpl=function(){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),v.safeArrForEach(this.pendingTransports,function(b){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+b),b&&b.close()}),v.safeArrForEach(this.proposedTransports,function(b){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.closeImpl()","Disposing of proposed transport: "+b),b&&b.dispose()}),this.activeProtocol&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})},F.prototype.onAuthUpdated=function(b,L){var B=this,_;switch(this.state.state){case"connected":{if(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport"),(this.pendingTransports.length||this.proposedTransports.length)&&this.state!==this.states.synchronizing){this.disconnectAllTransports(!0);var V=this.activeProtocol.getTransport().params;R.default.Config.nextTick(function(){B.state.state==="connected"&&B.upgradeIfNeeded(V)})}var Y=(_=this.activeProtocol)===null||_===void 0?void 0:_.getTransport();Y&&Y.onAuthUpdated&&Y.onAuthUpdated(b);var X=m.default.fromValues({action:p.AUTH,auth:{accessToken:b.token}});this.send(X);var te=function(){B.off(re),L(null,b)},re=function(Z){Z.current==="failed"&&(B.off(te),B.off(re),L(Z.reason||B.getStateError()))};this.once("connectiondetails",te),this.on("connectionstate",re);break}case"connecting":f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");var le=function(Z){switch(Z.current){case"connected":B.off(le),L(null,b);break;case"failed":case"closed":case"suspended":B.off(le),L(Z.reason||B.getStateError());break}};this.on("connectionstate",le),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}},F.prototype.disconnectAllTransports=function(b){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"+(b?" except the active transport":"")),this.connectCounter++,v.safeArrForEach(this.pendingTransports,function(L){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+L),L&&L.disconnect()}),this.pendingTransports=[],v.safeArrForEach(this.proposedTransports,function(L){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disposing of proposed transport: "+L),L&&L.dispose()}),this.proposedTransports=[],this.activeProtocol&&!b&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())},F.prototype.send=function(b,L,B){B=B||x;var _=this.state;if(_.sendEvents){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new S.PendingMessage(b,B));return}var V=L&&_.queueEvents||_.forceQueueEvents;if(!V){var Y="rejecting event, queueEvent was "+L+", state was "+_.state;f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.send()",Y),B(this.errorReason||new y.default(Y,9e4,400));return}f.default.shouldLog(f.default.LOG_MICRO)&&f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+m.default.stringify(b)),this.queue(b,B)},F.prototype.sendImpl=function(b){var L=b.message;b.ackRequired&&!b.sendAttempted&&(L.msgSerial=this.msgSerial++);try{this.activeProtocol.send(b)}catch(B){f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+B.stack)}},F.prototype.queue=function(b,L){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.queue()","queueing event");var B=this.queuedMessages.last(),_=this.options.maxMessageSize;B&&!B.sendAttempted&&j(B.message,b,_)?(B.merged||(B.callback=w.default.create([B.callback]),B.merged=!0),B.callback.push(L)):this.queuedMessages.push(new S.PendingMessage(b,L))},F.prototype.sendQueuedMessages=function(){f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");for(var b;b=this.queuedMessages.shift();)this.sendImpl(b)},F.prototype.queuePendingMessages=function(b){b&&b.length&&(f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+b.length+" pending messages"),this.queuedMessages.prepend(b))},F.prototype.failQueuedMessages=function(b){var L=this.queuedMessages.count();L>0&&(f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+L+" queued messages, err = "+v.inspectError(b)),this.queuedMessages.completeAllMessages(b))},F.prototype.onChannelMessage=function(b,L){var B=this.activeProtocol&&L===this.activeProtocol.getTransport(),_=v.arrIn(this.pendingTransports,L)&&this.state==this.states.synchronizing;B||_?this.realtime.channels.onChannelMessage(b):v.arrIndexOf([p.ACK,p.NACK,p.ERROR],b.action)>-1?this.realtime.channels.onChannelMessage(b):f.default.logAction(f.default.LOG_MICRO,"ConnectionManager.onChannelMessage()","received message "+JSON.stringify(b)+"on defunct transport; discarding")},F.prototype.ping=function(b,L){var B=this;if(b){f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.ping()","transport = "+b);var _=function(){b.off("heartbeat",X),L(new y.default("Timeout waiting for heartbeat response",5e4,500))},V=v.now(),Y=v.cheapRandStr(),X=function(he){if(he===Y){b.off("heartbeat",X),clearTimeout(te);var Me=v.now()-V;L(null,Me)}},te=setTimeout(_,this.options.timeouts.realtimeRequestTimeout);b.on("heartbeat",X),b.ping(Y);return}if(this.state.state!=="connected"){L(new y.default("Unable to ping service; not connected",4e4,400));return}var re=!1,le=function(he,Me){B.off("transport.active",Z),re||(re=!0,L(he,Me))},Z=function(){re||(re=!0,R.default.Config.nextTick(function(){B.ping(null,L)}))};this.on("transport.active",Z),this.ping(this.activeProtocol.getTransport(),le)},F.prototype.abort=function(b){this.activeProtocol.getTransport().fail(b)},F.prototype.registerProposedTransport=function(b){this.proposedTransports.push(b)},F.prototype.getTransportPreference=function(){var b,L;return this.transportPreference||s()&&((L=(b=R.default.WebStorage)===null||b===void 0?void 0:b.get)===null||L===void 0?void 0:L.call(b,D))},F.prototype.persistTransportPreference=function(b){var L,B;v.arrIn(T.default.upgradeTransports,b.shortName)&&(this.transportPreference=b.shortName,s()&&((B=(L=R.default.WebStorage)===null||L===void 0?void 0:L.set)===null||B===void 0||B.call(L,D,b.shortName)))},F.prototype.unpersistTransportPreference=function(){var b,L;this.transportPreference=null,s()&&((L=(b=R.default.WebStorage)===null||b===void 0?void 0:b.remove)===null||L===void 0||L.call(b,D))},F.prototype.actOnErrorFromAuthorize=function(b){if(b.code===40171)this.notifyState({state:"failed",error:b});else if(b.code===40102)this.notifyState({state:"failed",error:b});else if(b.statusCode===l.default.Forbidden){var L="Client configured authentication provider returned 403; failing the connection";f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",L),this.notifyState({state:"failed",error:new y.default(L,80019,403,b)})}else{var L="Client configured authentication provider request failed";f.default.logAction(f.default.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",L),this.notifyState({state:this.state.failState,error:new y.default(L,80019,401,b)})}},F.prototype.onConnectionDetailsUpdate=function(b,L){if(b){this.connectionDetails=b,b.maxMessageSize&&(this.options.maxMessageSize=b.maxMessageSize);var B=b.clientId;if(B){var _=this.realtime.auth._uncheckedSetClientId(B);if(_){f.default.logAction(f.default.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",_.message),L.fail(_);return}}var V=b.connectionStateTtl;V&&(this.connectionStateTtl=V),this.maxIdleInterval=b.maxIdleInterval,this.emit("connectiondetails",b)}},F.supportedTransports={},F}(C.default);r.default=W}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(7)),m=i.__importDefault(o(2)),v=function(S){i.__extends(T,S);function T(){var R=S.call(this)||this;return R.messages=[],R}return T.prototype.count=function(){return this.messages.length},T.prototype.push=function(R){this.messages.push(R)},T.prototype.shift=function(){return this.messages.shift()},T.prototype.last=function(){return this.messages[this.messages.length-1]},T.prototype.copyAll=function(){return this.messages.slice()},T.prototype.append=function(R){this.messages.push.apply(this.messages,R)},T.prototype.prepend=function(R){this.messages.unshift.apply(this.messages,R)},T.prototype.completeMessages=function(R,C,O){m.default.logAction(m.default.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+R+"; count = "+C),O=O||null;var f=this.messages;if(f.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");var E=f[0];if(E){var P=E.message.msgSerial,y=R+C;if(y>P)for(var d=f.splice(0,y-P),h=0,w=d;h<w.length;h++){var c=w[h];c.callback(O)}f.length==0&&this.emit("idle")}},T.prototype.completeAllMessages=function(R){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,R)},T.prototype.resetSendAttempted=function(){for(var R=0,C=this.messages;R<C.length;R++){var O=C[R];O.sendAttempted=!1}},T.prototype.clear=function(){m.default.logAction(m.default.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")},T}(a.default);r.default=v},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function a(m,v,S,T){this.previous=m,this.current=v,S&&(this.retryIn=S),T&&(this.reason=T)}return a}();r.default=i},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(10)),m=i.__importDefault(o(7)),v=i.__importStar(o(1)),S=i.__importDefault(o(33)),T=i.__importDefault(o(2)),R=i.__importDefault(o(54)),C=i.__importDefault(o(9)),O=i.__importDefault(o(39)),f=i.__importStar(o(4)),E=i.__importDefault(o(16)),P=i.__importDefault(o(21)),y=a.default.Action,d=function(){};function h(u){if(u&&"params"in u&&!v.isObject(u.params))return new f.default("options.params must be an object",4e4,400);if(u&&"modes"in u){if(!v.isArray(u.modes))return new f.default("options.modes must be an array",4e4,400);for(var l=0;l<u.modes.length;l++){var s=u.modes[l];if(!s||typeof s!="string"||!v.arrIn(a.default.channelModes,String.prototype.toUpperCase.call(s)))return new f.default("Invalid channel mode: "+s,4e4,400)}}}var w=function(u){i.__extends(l,u);function l(s,g,p){var x=u.call(this,s,g,p)||this;return x.retryCount=0,x.history=function(D,N){if(T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name),N===void 0)if(typeof D=="function")N=D,D=null;else{if(this.rest.options.promises)return v.promisify(this,"history",arguments);N=d}if(D&&D.untilAttach){if(this.state!=="attached"){N(new f.default("option untilAttach requires the channel to be attached",4e4,400));return}if(!this.properties.attachSerial){N(new f.default("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400));return}delete D.untilAttach,D.from_serial=this.properties.attachSerial}S.default.prototype._history.call(this,D,N)},x.whenState=function(D,N){return m.default.prototype.whenState.call(x,D,x.state,N)},T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel()","started; name = "+g),x.realtime=s,x.presence=new R.default(x),x.connectionManager=s.connection.connectionManager,x.state="initialized",x.subscriptions=new m.default,x.syncChannelSerial=void 0,x.properties={attachSerial:void 0,channelSerial:void 0},x.setOptions(p),x.errorReason=null,x._requestedFlags=null,x._mode=null,x._attachResume=!1,x._decodingContext={channelOptions:x.channelOptions,plugins:s.options.plugins||{},baseEncodedPreviousPayload:void 0},x._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},x._allChannelChanges=new m.default,x}return l.prototype.invalidStateError=function(){return new f.default("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)},l.processListenerArgs=function(s){return s=Array.prototype.slice.call(s),typeof s[0]=="function"&&s.unshift(null),s[s.length-1]==null&&s.pop(),s},l.prototype.setOptions=function(s,g){var p=this.channelOptions;if(!g&&this.rest.options.promises)return v.promisify(this,"setOptions",arguments);var x=g||function(N){N&&T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.setOptions()","Set options failed: "+N.toString())},D=h(s);if(D){x(D);return}S.default.prototype.setOptions.call(this,s),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(s,p)?(this.attachImpl(),this._allChannelChanges.once(["attached","update","detached","failed"],function(N){switch(this.event){case"update":case"attached":x==null||x(null);return;default:x==null||x(N.reason);return}})):x()},l.prototype._shouldReattachToSetOptions=function(s,g){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(s!=null&&s.params){var p=c(s.params),x=c(g.params);if(Object.keys(p).length!==Object.keys(x).length||!v.shallowEquals(x,p))return!0}return!!(s!=null&&s.modes&&(!g.modes||!v.arrEquals(s.modes,g.modes)))},l.prototype.publish=function(){for(var s=this,g=[],p=0;p<arguments.length;p++)g[p]=arguments[p];var x=g[0],D=g.length,N=g[D-1];if(typeof N!="function"){if(this.realtime.options.promises)return v.promisify(this,"publish",arguments);N=d,++D}if(!this.connectionManager.activeState()){N(this.connectionManager.getError());return}if(D==2)if(v.isObject(x))x=[C.default.fromValues(x)];else if(v.isArray(x))x=C.default.fromValuesArray(x);else throw new f.default("The single-argument form of publish() expects a message object or an array of message objects",40013,400);else x=[C.default.fromValues({name:g[0],data:g[1]})];var k=this.realtime.options.maxMessageSize;C.default.encodeArray(x,this.channelOptions,function(I){if(I){N(I);return}var M=C.default.getMessagesSize(x);if(M>k){N(new f.default("Maximum size of messages that can be published at once exceeded ( was "+M+" bytes; limit is "+k+" bytes)",40009,400));return}s.__publish(x,N)})},l.prototype.__publish=function(s,g){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.publish()","message count = "+s.length);var p=this.state;switch(p){case"failed":case"suspended":g(f.default.fromValues(this.invalidStateError()));break;default:{T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+p);var x=new a.default;x.action=y.MESSAGE,x.channel=this.name,x.messages=s,this.sendMessage(x,g);break}}},l.prototype.onEvent=function(s){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.onEvent()","received message");for(var g=this.subscriptions,p=0;p<s.length;p++){var x=s[p];g.emit(x.name,x)}},l.prototype.attach=function(s,g){var p;if(typeof s=="function"?(g=s,p=null):p=s,!g){if(this.realtime.options.promises)return v.promisify(this,"attach",arguments);g=function(x){x&&T.default.logAction(T.default.LOG_MAJOR,"RealtimeChannel.attach()","Channel attach failed: "+x.toString())}}if(p)T.default.deprecated("The ability to pass an array of channel mode flags as the first argument of `RealtimeChannel.attach()`","To set channel mode flags, populate the `modes` property of the channel options object that you pass to `Channels.get()` or `RealtimeChannel.setOptions()`."),this._requestedFlags=p;else if(this.state==="attached"){g(null,null);return}this._attach(!1,null,g)},l.prototype._attach=function(s,g,p){p||(p=function(D){D&&T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+D.toString())});var x=this.connectionManager;if(!x.activeState()){p(x.getError());return}(this.state!=="attaching"||s)&&this.requestState("attaching",g),this.once(function(D){switch(this.event){case"attached":p==null||p(null,D);break;case"detached":case"suspended":case"failed":p==null||p(D.reason||x.getError()||new f.default("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":p==null||p(new f.default("Attach request superseded by a subsequent detach request",9e4,409));break}})},l.prototype.attachImpl=function(){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");var s=a.default.fromValues({action:y.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this._requestedFlags?s.encodeModesToFlags(this._requestedFlags):this.channelOptions.modes&&s.encodeModesToFlags(v.allToUpperCase(this.channelOptions.modes)),this._attachResume&&s.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(s.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(s,d)},l.prototype.detach=function(s){if(!s){if(this.realtime.options.promises)return v.promisify(this,"detach",arguments);s=d}var g=this.connectionManager;if(!g.activeState()){s(g.getError());return}switch(this.state){case"suspended":this.notifyState("detached"),s();break;case"detached":s();break;case"failed":s(new f.default("Unable to detach; channel state = failed",90001,400));break;default:this.requestState("detaching");case"detaching":this.once(function(p){switch(this.event){case"detached":s();break;case"attached":case"suspended":case"failed":s(p.reason||g.getError()||new f.default("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":s(new f.default("Detach request superseded by a subsequent attach request",9e4,409));break}})}},l.prototype.detachImpl=function(s){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");var g=a.default.fromValues({action:y.DETACH,channel:this.name});this.sendMessage(g,s||d)},l.prototype.subscribe=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];var p=l.processListenerArgs(s),x=p[0],D=p[1],N=p[2];if(!N&&this.realtime.options.promises)return v.promisify(this,"subscribe",[x,D]);if(this.state==="failed"){N==null||N(f.default.fromValues(this.invalidStateError()));return}return x&&typeof x=="object"&&!Array.isArray(x)?this._subscribeFilter(x,D):this.subscriptions.on(x,D),this.attach(N||d)},l.prototype._subscribeFilter=function(s,g){var p=function(x){var D,N,k,I,M,A,j={name:x.name,refTimeserial:(N=(D=x.extras)===null||D===void 0?void 0:D.ref)===null||N===void 0?void 0:N.timeserial,refType:(I=(k=x.extras)===null||k===void 0?void 0:k.ref)===null||I===void 0?void 0:I.type,isRef:!!(!((A=(M=x.extras)===null||M===void 0?void 0:M.ref)===null||A===void 0)&&A.timeserial),clientId:x.clientId};Object.entries(s).find(function(U){var z=U[0],W=U[1];return W!==void 0?j[z]!==W:!1})||g(x)};this._addFilteredSubscription(s,g,p),this.subscriptions.on(p)},l.prototype._addFilteredSubscription=function(s,g,p){var x;if(this.filteredSubscriptions||(this.filteredSubscriptions=new Map),this.filteredSubscriptions.has(g)){var D=this.filteredSubscriptions.get(g);D.set(s,((x=D==null?void 0:D.get(s))===null||x===void 0?void 0:x.concat(p))||[p])}else this.filteredSubscriptions.set(g,new Map([[s,[p]]]))},l.prototype._getAndDeleteFilteredSubscriptions=function(s,g){var p=this;if(!this.filteredSubscriptions)return[];if(!g&&s)return Array.from(this.filteredSubscriptions.entries()).map(function(k){var I,M=k[0],A=k[1],j=A.get(s);return A.delete(s),A.size===0&&((I=p.filteredSubscriptions)===null||I===void 0||I.delete(M)),j}).reduce(function(k,I){var M;return I?(M=k).concat.apply(M,I):k},[]);if(!g||!this.filteredSubscriptions.has(g))return[];var x=this.filteredSubscriptions.get(g);if(!s){var D=Array.from(x.values()).reduce(function(k,I){return k.concat.apply(k,I)},[]);return this.filteredSubscriptions.delete(g),D}var N=x.get(s);return x.delete(s),N||[]},l.prototype.unsubscribe=function(){for(var s=this,g,p=[],x=0;x<arguments.length;x++)p[x]=arguments[x];var D=l.processListenerArgs(p),N=D[0],k=D[1];if(typeof N=="object"&&!k||!((g=this.filteredSubscriptions)===null||g===void 0)&&g.has(k)){this._getAndDeleteFilteredSubscriptions(N,k).forEach(function(I){return s.subscriptions.off(I)});return}this.subscriptions.off(N,k)},l.prototype.sync=function(){switch(this.state){case"initialized":case"detaching":case"detached":throw new f.PartialErrorInfo("Unable to sync to channel; not attached",4e4)}var s=this.connectionManager;if(!s.activeState())throw s.getError();var g=a.default.fromValues({action:y.SYNC,channel:this.name});this.syncChannelSerial&&(g.channelSerial=this.syncChannelSerial),s.send(g)},l.prototype.sendMessage=function(s,g){this.connectionManager.send(s,this.realtime.options.queueMessages,g)},l.prototype.sendPresence=function(s,g){var p=a.default.fromValues({action:y.PRESENCE,channel:this.name,presence:v.isArray(s)?E.default.fromValuesArray(s):[E.default.fromValues(s)]});this.sendMessage(p,g)},l.prototype.onMessage=function(s){(s.action===y.ATTACHED||s.action===y.MESSAGE||s.action===y.PRESENCE)&&this.setChannelSerial(s.channelSerial);var g,p=!1;switch(s.action){case y.ATTACHED:{this.properties.attachSerial=s.channelSerial,this._mode=s.getMode(),this.params=s.params||{};var x=s.decodeModesFromFlags();this.modes=x&&v.allToLowerCase(x)||void 0;var D=s.hasFlag("RESUMED"),N=s.hasFlag("HAS_PRESENCE"),k=s.hasFlag("HAS_BACKLOG");if(this.state==="attached"){D||this.presence.onAttached(N);var I=new O.default(this.state,this.state,D,k,s.error);this._allChannelChanges.emit("update",I),(!D||this.channelOptions.updateOnAttached)&&this.emit("update",I)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",s.error,D,N,k);break}case y.DETACHED:{var M=s.error?f.default.fromValues(s.error):new f.default("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",M):this.state==="attaching"?this.notifyState("suspended",M):this.requestState("attaching",M);break}case y.SYNC:if(p=!0,g=this.syncChannelSerial=s.channelSerial,!s.presence)break;case y.PRESENCE:{for(var A=s.presence,j=s.id,U=s.connectionId,z=s.timestamp,W=this.channelOptions,G=void 0,F=0;F<A.length;F++)try{G=A[F],E.default.decode(G,W),G.connectionId||(G.connectionId=U),G.timestamp||(G.timestamp=z),G.id||(G.id=j+":"+F)}catch(Y){T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()",Y.toString())}this.presence.setPresence(A,p,g);break}case y.MESSAGE:{if(this.state!=="attached"){T.default.logAction(T.default.LOG_MAJOR,"RealtimeChannel.onMessage()",'Message "'+s.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}var b=s.messages,L=b[0],B=b[b.length-1],j=s.id,U=s.connectionId,z=s.timestamp;if(L.extras&&L.extras.delta&&L.extras.delta.from!==this._lastPayload.messageId){var _='Delta message decode failure - previous message not available for message "'+s.id+'" on this channel "'+this.name+'".';T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()",_),this._startDecodeFailureRecovery(new f.default(_,40018,400));break}for(var F=0;F<b.length;F++){var _=b[F];try{C.default.decode(_,this._decodingContext)}catch(Z){switch(T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()",Z.toString()),Z.code){case 40018:this._startDecodeFailureRecovery(Z);return;case 40019:case 40021:this.notifyState("failed",Z);return}}_.connectionId||(_.connectionId=U),_.timestamp||(_.timestamp=z),_.id||(_.id=j+":"+F)}this._lastPayload.messageId=B.id,this._lastPayload.protocolMessageChannelSerial=s.channelSerial,this.onEvent(b);break}case y.ERROR:{var V=s.error;V&&V.code==80016?this.checkPendingState():this.notifyState("failed",f.default.fromValues(V));break}default:T.default.logAction(T.default.LOG_ERROR,"RealtimeChannel.onMessage()","Fatal protocol error: unrecognised action ("+s.action+")"),this.connectionManager.abort(P.default.unknownChannelErr())}},l.prototype._startDecodeFailureRecovery=function(s){var g=this;this._lastPayload.decodeFailureRecoveryInProgress||(T.default.logAction(T.default.LOG_MAJOR,"RealtimeChannel.onMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,s,function(){g._lastPayload.decodeFailureRecoveryInProgress=!1}))},l.prototype.onAttached=function(){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)},l.prototype.notifyState=function(s,g,p,x,D){if(T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+s),this.clearStateTimer(),v.arrIn(["detached","suspended","failed"],s)&&(this.properties.channelSerial=null),s!==this.state){this.presence.actOnChannelState(s,x,g),s==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),g&&(this.errorReason=g);var N=new O.default(this.state,s,p,D,g),k=s==="failed"?T.default.LOG_ERROR:T.default.LOG_MAJOR;T.default.logAction(k,'Channel state for channel "'+this.name+'"',s+(g?"; reason: "+g:"")),s!=="attaching"&&s!=="suspended"&&(this.retryCount=0),s==="attached"&&this.onAttached(),s==="attached"?this._attachResume=!0:(s==="detaching"||s==="failed")&&(this._attachResume=!1),this.state=s,this._allChannelChanges.emit(s,N),this.emit(s,N)}},l.prototype.requestState=function(s,g){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+s),this.notifyState(s,g),this.checkPendingState()},l.prototype.checkPendingState=function(){var s=this.connectionManager.state;if(!(s.sendEvents||s.forceQueueEvents)){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break}},l.prototype.timeoutPendingState=function(){switch(this.state){case"attaching":{var s=new f.default("Channel attach timed out",90007,408);this.notifyState("suspended",s);break}case"detaching":{var s=new f.default("Channel detach timed out",90007,408);this.notifyState("attached",s);break}default:this.checkPendingState();break}},l.prototype.startStateTimerIfNotRunning=function(){var s=this;this.stateTimer||(this.stateTimer=setTimeout(function(){T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),s.stateTimer=null,s.timeoutPendingState()},this.realtime.options.timeouts.realtimeRequestTimeout))},l.prototype.clearStateTimer=function(){var s=this.stateTimer;s&&(clearTimeout(s),this.stateTimer=null)},l.prototype.startRetryTimer=function(){var s=this;if(!this.retryTimer){this.retryCount++;var g=v.getRetryTime(this.realtime.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(function(){s.state==="suspended"&&s.connectionManager.state.sendEvents&&(s.retryTimer=null,T.default.logAction(T.default.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),s.requestState("attaching"))},g)}},l.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)},l.prototype.getReleaseErr=function(){var s=this.state;return s==="initialized"||s==="detached"||s==="failed"?null:new f.default("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+s,90001,400)},l.prototype.setChannelSerial=function(s){T.default.logAction(T.default.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+s+"; previous = "+this.properties.channelSerial),s&&(this.properties.channelSerial=s)},l}(S.default);function c(u){var l=u||{};l.agent;var s=i.__rest(l,["agent"]);return s}r.default=w},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=function(){function a(m,v,S,T,R){this.previous=m,this.current=v,v==="attached"&&(this.resumed=S,this.hasBacklog=T),R&&(this.reason=R)}return a}();r.default=i},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){var a=i,m=a.lib,v=m.WordArray,S=m.Hasher,T=a.algo,R=[],C=T.SHA1=S.extend({_doReset:function(){this._hash=new v.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(O,f){for(var E=this._hash.words,P=E[0],y=E[1],d=E[2],h=E[3],w=E[4],c=0;c<80;c++){if(c<16)R[c]=O[f+c]|0;else{var u=R[c-3]^R[c-8]^R[c-14]^R[c-16];R[c]=u<<1|u>>>31}var l=(P<<5|P>>>27)+w+R[c];c<20?l+=(y&d|~y&h)+1518500249:c<40?l+=(y^d^h)+1859775393:c<60?l+=(y&d|y&h|d&h)-1894007588:l+=(y^d^h)-899497514,w=h,h=d,d=y<<30|y>>>2,y=P,P=l}E[0]=E[0]+P|0,E[1]=E[1]+y|0,E[2]=E[2]+d|0,E[3]=E[3]+h|0,E[4]=E[4]+w|0},_doFinalize:function(){var O=this._data,f=O.words,E=this._nDataBytes*8,P=O.sigBytes*8;return f[P>>>5]|=128<<24-P%32,f[(P+64>>>9<<4)+14]=Math.floor(E/4294967296),f[(P+64>>>9<<4)+15]=E,O.sigBytes=f.length*4,this._process(),this._hash},clone:function(){var O=S.clone.call(this);return O._hash=this._hash.clone(),O}});a.SHA1=S._createHelper(C),a.HmacSHA1=S._createHmacHelper(C)}(),i.SHA1})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});function i(c){if(c===void 0)return"undefined";var u,l;if(c instanceof ArrayBuffer?(l="ArrayBuffer",u=new DataView(c)):c instanceof DataView&&(l="DataView",u=c),!u)return JSON.stringify(c);for(var s=[],g=0;g<c.byteLength;g++){if(g>20){s.push("...");break}var p=u.getUint8(g).toString(16);p.length===1&&(p="0"+p),s.push(p)}return"<"+l+" "+s.join(" ")+">"}function a(c,u,l){for(var s=0,g=l.length;s<g;s++){var p=l.charCodeAt(s);if(p<128){c.setUint8(u++,p>>>0&127|0);continue}if(p<2048){c.setUint8(u++,p>>>6&31|192),c.setUint8(u++,p>>>0&63|128);continue}if(p<65536){c.setUint8(u++,p>>>12&15|224),c.setUint8(u++,p>>>6&63|128),c.setUint8(u++,p>>>0&63|128);continue}if(p<1114112){c.setUint8(u++,p>>>18&7|240),c.setUint8(u++,p>>>12&63|128),c.setUint8(u++,p>>>6&63|128),c.setUint8(u++,p>>>0&63|128);continue}throw new Error("bad codepoint "+p)}}function m(c,u,l){for(var s="",g=u,p=u+l;g<p;g++){var x=c.getUint8(g);if(!(x&128)){s+=String.fromCharCode(x);continue}if((x&224)===192){s+=String.fromCharCode((x&15)<<6|c.getUint8(++g)&63);continue}if((x&240)===224){s+=String.fromCharCode((x&15)<<12|(c.getUint8(++g)&63)<<6|(c.getUint8(++g)&63)<<0);continue}if((x&248)===240){s+=String.fromCharCode((x&7)<<18|(c.getUint8(++g)&63)<<12|(c.getUint8(++g)&63)<<6|(c.getUint8(++g)&63)<<0);continue}throw new Error("Invalid byte "+x.toString(16))}return s}function v(c){for(var u=0,l=0,s=c.length;l<s;l++){var g=c.charCodeAt(l);if(g<128){u+=1;continue}if(g<2048){u+=2;continue}if(g<65536){u+=3;continue}if(g<1114112){u+=4;continue}throw new Error("bad codepoint "+g)}return u}function S(c,u){var l=w(c,u);if(l!==0){var s=new ArrayBuffer(l),g=new DataView(s);return h(c,g,0,u),s}}var T=65536*65536,R=1/T;function C(c,u){return u=u||0,c.getInt32(u)*T+c.getUint32(u+4)}function O(c,u){return u=u||0,c.getUint32(u)*T+c.getUint32(u+4)}function f(c,u,l){l<9223372036854776e3?(c.setInt32(u,Math.floor(l*R)),c.setInt32(u+4,l&-1)):(c.setUint32(u,2147483647),c.setUint32(u+4,2147483647))}function E(c,u,l){l<18446744073709552e3?(c.setUint32(u,Math.floor(l*R)),c.setInt32(u+4,l&-1)):(c.setUint32(u,4294967295),c.setUint32(u+4,4294967295))}var P=function(){function c(u,l){var s=this;this.map=function(g){for(var p={},x=0;x<g;x++){var D=s.parse();p[D]=s.parse()}return p},this.bin=function(g){var p=new ArrayBuffer(g);return new Uint8Array(p).set(new Uint8Array(s.view.buffer,s.offset,g),0),s.offset+=g,p},this.buf=this.bin,this.str=function(g){var p=m(s.view,s.offset,g);return s.offset+=g,p},this.array=function(g){for(var p=new Array(g),x=0;x<g;x++)p[x]=s.parse();return p},this.ext=function(g){return s.offset+=g,{type:s.view.getInt8(s.offset),data:s.buf(g)}},this.parse=function(){var g=s.view.getUint8(s.offset),p,x;if(!(g&128))return s.offset++,g;if((g&240)===128)return x=g&15,s.offset++,s.map(x);if((g&240)===144)return x=g&15,s.offset++,s.array(x);if((g&224)===160)return x=g&31,s.offset++,s.str(x);if((g&224)===224)return p=s.view.getInt8(s.offset),s.offset++,p;switch(g){case 192:return s.offset++,null;case 193:s.offset++;return;case 194:return s.offset++,!1;case 195:return s.offset++,!0;case 196:return x=s.view.getUint8(s.offset+1),s.offset+=2,s.bin(x);case 197:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.bin(x);case 198:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.bin(x);case 199:return x=s.view.getUint8(s.offset+1),s.offset+=2,s.ext(x);case 200:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.ext(x);case 201:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.ext(x);case 202:return p=s.view.getFloat32(s.offset+1),s.offset+=5,p;case 203:return p=s.view.getFloat64(s.offset+1),s.offset+=9,p;case 204:return p=s.view.getUint8(s.offset+1),s.offset+=2,p;case 205:return p=s.view.getUint16(s.offset+1),s.offset+=3,p;case 206:return p=s.view.getUint32(s.offset+1),s.offset+=5,p;case 207:return p=O(s.view,s.offset+1),s.offset+=9,p;case 208:return p=s.view.getInt8(s.offset+1),s.offset+=2,p;case 209:return p=s.view.getInt16(s.offset+1),s.offset+=3,p;case 210:return p=s.view.getInt32(s.offset+1),s.offset+=5,p;case 211:return p=C(s.view,s.offset+1),s.offset+=9,p;case 212:return x=1,s.offset++,s.ext(x);case 213:return x=2,s.offset++,s.ext(x);case 214:return x=4,s.offset++,s.ext(x);case 215:return x=8,s.offset++,s.ext(x);case 216:return x=16,s.offset++,s.ext(x);case 217:return x=s.view.getUint8(s.offset+1),s.offset+=2,s.str(x);case 218:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.str(x);case 219:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.str(x);case 220:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.array(x);case 221:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.array(x);case 222:return x=s.view.getUint16(s.offset+1),s.offset+=3,s.map(x);case 223:return x=s.view.getUint32(s.offset+1),s.offset+=5,s.map(x)}throw new Error("Unknown type 0x"+g.toString(16))},this.offset=l||0,this.view=u}return c}();function y(c){var u=new DataView(c),l=new P(u),s=l.parse();if(l.offset!==c.byteLength)throw new Error(c.byteLength-l.offset+" trailing bytes");return s}function d(c,u){return Object.keys(c).filter(function(l){var s=c[l],g=typeof s;return(!u||s!=null)&&(g!=="function"||!!s.toJSON)})}function h(c,u,l,s){var g=typeof c;if(typeof c=="string"){var p=v(c);if(p<32)return u.setUint8(l,p|160),a(u,l+1,c),1+p;if(p<256)return u.setUint8(l,217),u.setUint8(l+1,p),a(u,l+2,c),2+p;if(p<65536)return u.setUint8(l,218),u.setUint16(l+1,p),a(u,l+3,c),3+p;if(p<4294967296)return u.setUint8(l,219),u.setUint32(l+1,p),a(u,l+5,c),5+p}if(ArrayBuffer.isView&&ArrayBuffer.isView(c)&&(c=c.buffer),c instanceof ArrayBuffer){var x=c.byteLength;if(x<256)return u.setUint8(l,196),u.setUint8(l+1,x),new Uint8Array(u.buffer).set(new Uint8Array(c),l+2),2+x;if(x<65536)return u.setUint8(l,197),u.setUint16(l+1,x),new Uint8Array(u.buffer).set(new Uint8Array(c),l+3),3+x;if(x<4294967296)return u.setUint8(l,198),u.setUint32(l+1,x),new Uint8Array(u.buffer).set(new Uint8Array(c),l+5),5+x}if(typeof c=="number"){if(Math.floor(c)!==c)return u.setUint8(l,203),u.setFloat64(l+1,c),9;if(c>=0){if(c<128)return u.setUint8(l,c),1;if(c<256)return u.setUint8(l,204),u.setUint8(l+1,c),2;if(c<65536)return u.setUint8(l,205),u.setUint16(l+1,c),3;if(c<4294967296)return u.setUint8(l,206),u.setUint32(l+1,c),5;if(c<18446744073709552e3)return u.setUint8(l,207),E(u,l+1,c),9;throw new Error("Number too big 0x"+c.toString(16))}if(c>=-32)return u.setInt8(l,c),1;if(c>=-128)return u.setUint8(l,208),u.setInt8(l+1,c),2;if(c>=-32768)return u.setUint8(l,209),u.setInt16(l+1,c),3;if(c>=-2147483648)return u.setUint8(l,210),u.setInt32(l+1,c),5;if(c>=-9223372036854776e3)return u.setUint8(l,211),f(u,l+1,c),9;throw new Error("Number too small -0x"+(-c).toString(16).substr(1))}if(g==="undefined")return s?0:(u.setUint8(l,212),u.setUint8(l+1,0),u.setUint8(l+2,0),3);if(c===null)return s?0:(u.setUint8(l,192),1);if(g==="boolean")return u.setUint8(l,c?195:194),1;if(typeof c.toJSON=="function")return h(c.toJSON(),u,l,s);if(g==="object"){var D,N=0,k=void 0,I=Array.isArray(c);if(I?D=c.length:(k=d(c,s),D=k.length),D<16?(u.setUint8(l,D|(I?144:128)),N=1):D<65536?(u.setUint8(l,I?220:222),u.setUint16(l+1,D),N=3):D<4294967296&&(u.setUint8(l,I?221:223),u.setUint32(l+1,D),N=5),I)for(var M=0;M<D;M++)N+=h(c[M],u,l+N,s);else if(k)for(var M=0;M<D;M++){var A=k[M];N+=h(A,u,l+N),N+=h(c[A],u,l+N,s)}return N}if(g==="function")return 0;throw new Error("Unknown type "+g)}function w(c,u){var l=typeof c;if(l==="string"){var s=v(c);if(s<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(c)&&(c=c.buffer),c instanceof ArrayBuffer){var g=c.byteLength;if(g<256)return 2+g;if(g<65536)return 3+g;if(g<4294967296)return 5+g}if(typeof c=="number"){if(Math.floor(c)!==c)return 9;if(c>=0){if(c<128)return 1;if(c<256)return 2;if(c<65536)return 3;if(c<4294967296)return 5;if(c<18446744073709552e3)return 9;throw new Error("Number too big 0x"+c.toString(16))}if(c>=-32)return 1;if(c>=-128)return 2;if(c>=-32768)return 3;if(c>=-2147483648)return 5;if(c>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+c.toString(16).substr(1))}if(l==="boolean")return 1;if(c===null)return u?0:1;if(c===void 0)return u?0:3;if(typeof c.toJSON=="function")return w(c.toJSON(),u);if(l==="object"){var p,x=0;if(Array.isArray(c)){p=c.length;for(var D=0;D<p;D++)x+=w(c[D],u)}else{var N=d(c,u);p=N.length;for(var D=0;D<p;D++){var k=N[D];x+=w(k)+w(c[k],u)}}if(p<16)return 1+x;if(p<65536)return 3+x;if(p<4294967296)return 5+x;throw new Error("Array or object too long 0x"+p.toString(16))}if(l==="function")return 0;throw new Error("Unknown type "+l)}r.default={encode:S,decode:y,inspect:i,utf8Write:a,utf8Read:m,utf8ByteCount:v}},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(30)),m=i.__importDefault(o(50)),v=i.__importDefault(o(3)),S=i.__importDefault(o(4)),T=i.__importDefault(o(55)),R=i.__importDefault(o(57)),C=i.__importDefault(o(62)),O=i.__importDefault(o(64)),f=i.__importDefault(o(68)),E=i.__importDefault(o(2)),P=o(8),y=i.__importDefault(o(65)),d=i.__importDefault(o(66)),h=i.__importDefault(o(41)),w=(0,R.default)(O.default,T.default);v.default.Crypto=w,v.default.BufferUtils=T.default,v.default.Http=C.default,v.default.Config=O.default,v.default.Transports=f.default,v.default.WebStorage=y.default,a.default.Crypto=w,m.default.Crypto=w,E.default.initLogHandlers(),v.default.Defaults=(0,P.getDefaults)(d.default),v.default.Config.agent&&(v.default.Defaults.agent+=" "+v.default.Config.agent),v.default.Config.noUpgrade&&(v.default.Defaults.upgradeTransports=[]),r.default={ErrorInfo:S.default,Rest:a.default,Realtime:m.default,msgpack:h.default}},function(n){n.exports=JSON.parse('{"name":"ably","description":"Realtime client library for Ably, the realtime messaging service","version":"1.2.50","license":"Apache-2.0","bugs":{"url":"https://github.com/ably/ably-js/issues","email":"support@ably.com"},"main":"./build/ably-node.js","typings":"./ably.d.ts","react-native":{"./build/ably-node.js":"./build/ably-reactnative.js"},"browser":{"./build/ably-node.js":"./build/ably-commonjs.js"},"files":["build/**","ably.d.ts","callbacks.d.ts","callbacks.js","promises.d.ts","promises.js","resources/**","src/**","react/**"],"dependencies":{"@ably/msgpack-js":"^0.4.0","got":"^11.8.5","ws":"^8.14.2"},"peerDependencies":{"react":">=16.8.0","react-dom":">=16.8.0"},"peerDependenciesMeta":{"react":{"optional":true},"react-dom":{"optional":true}},"devDependencies":{"@ably/vcdiff-decoder":"1.0.4","@arethetypeswrong/cli":"^0.13.1","@babel/preset-env":"^7.23.6","@testing-library/react":"^13.3.0","@types/crypto-js":"^4.0.1","@types/jmespath":"^0.15.2","@types/node":"^15.0.0","@types/request":"^2.48.7","@types/ws":"^8.2.0","@typescript-eslint/eslint-plugin":"^5.14.0","@typescript-eslint/parser":"^5.14.0","@vitejs/plugin-react":"^1.3.2","async":"ably-forks/async#requirejs","aws-sdk":"^2.1413.0","babel-loader":"^8.3.0","chai":"^4.2.0","copy-webpack-plugin":"^6.4.1","cors":"^2.8.5","crypto-js":"ably-forks/crypto-js#crypto-lite","eslint":"^7.13.0","eslint-plugin-import":"^2.28.0","eslint-plugin-jsdoc":"^40.0.0","eslint-plugin-react":"^7.32.2","eslint-plugin-react-hooks":"^4.6.0","eslint-plugin-security":"^1.4.0","express":"^4.17.1","glob":"~4.4","google-closure-compiler":"^20180610.0.1","grunt":"^1.6.1","grunt-bump":"^0.3.1","grunt-cli":"~1.2.0","grunt-closure-tools":"^1.0.0","grunt-contrib-concat":"~0.5","grunt-shell":"~1.1","grunt-webpack":"^4.0.2","hexy":"~0.2","jmespath":"^0.16.0","jsdom":"^20.0.0","kexec":"ably-forks/node-kexec#update-for-node-12","minimist":"^1.2.5","mocha":"^8.1.3","mocha-junit-reporter":"^2.2.1","null-loader":"^4.0.1","playwright":"^1.39.0","prettier":"^2.5.1","react":">=18.1.0","react-dom":">=18.1.0","requirejs":"~2.1","shelljs":"~0.8","source-map-explorer":"^2.5.2","ts-loader":"^8.2.0","tsconfig-paths-webpack-plugin":"^4.0.1","tslib":"^2.3.1","typedoc":"^0.23.8","typescript":"^4.6.4","vite":"^4.4.9","vitest":"^0.18.0","webpack":"^4.44.2","webpack-cli":"^4.2.0","webpack-node-externals":"^3.0.0"},"engines":{"node":">=5.10.x"},"repository":"ably/ably-js","jspm":{"registry":"npm","directories":{"lib":"build"},"main":"ably"},"scripts":{"start:react":"npx vite serve","grunt":"grunt","test":"grunt test","test:node":"grunt test:node","test:node:skip-build":"grunt mocha","test:webserver":"grunt test:webserver","test:playwright":"node test/support/runPlaywrightTests.js","test:react":"vitest run","concat":"grunt concat","build":"grunt build:all && npm run build:react","build:node":"grunt build:node","build:browser":"grunt build:browser","build:react":"npm run build:react:mjs && npm run build:react:cjs && cp src/platform/react-hooks/res/package.react.json react/package.json","build:react:mjs":"tsc --project src/platform/react-hooks/tsconfig.mjs.json && cp src/platform/react-hooks/res/package.mjs.json react/mjs/package.json","build:react:cjs":"tsc --project src/platform/react-hooks/tsconfig.cjs.json && cp src/platform/react-hooks/res/package.cjs.json react/cjs/package.json","requirejs":"grunt requirejs","lint":"eslint .","lint:fix":"eslint --fix .","check-closure-compiler":"grunt check-closure-compiler","prepare":"npm run build","format":"prettier --write --ignore-path .gitignore --ignore-path .prettierignore src test ably.d.ts webpack.config.js Gruntfile.js scripts/cdn_deploy.js docs/chrome-mv3.md","format:check":"prettier --check --ignore-path .gitignore --ignore-path .prettierignore src test ably.d.ts webpack.config.js Gruntfile.js scripts/cdn_deploy.js","sourcemap":"source-map-explorer build/ably.min.js","sourcemap:noencryption":"source-map-explorer build/ably.noencryption.min.js","docs":"typedoc --entryPoints ably.d.ts --out docs/generated/default --readme docs/landing-pages/default.md && typedoc --entryPoints promises.d.ts --out docs/generated/promises --name \\"ably (Promise-based)\\" --readme docs/landing-pages/promises.md && cp docs/landing-pages/choose-library.html docs/generated/index.html"}}')},function(n,r){},function(n,r,o){(function(i,a){n.exports=a(o(6),o(32),o(25))})(this,function(i){return i.HmacSHA256})},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(47)),v=i.__importDefault(o(15)),S=i.__importDefault(o(20)),T=i.__importDefault(o(4)),R=i.__importDefault(o(48)),C=function(){},O=function(){function y(d){this.rest=d,this.admin=new f(d)}return y}(),f=function(){function y(d){this.rest=d,this.deviceRegistrations=new E(d),this.channelSubscriptions=new P(d)}return y.prototype.publish=function(d,h,w){var c=this.rest,u=c.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,l=a.defaultPostHeaders(c.options,u),s={},g=a.mixin({recipient:d},h);if(typeof w!="function"){if(this.rest.options.promises)return a.promisify(this,"publish",arguments);w=C}c.options.headers&&a.mixin(l,c.options.headers),c.options.pushFullWait&&a.mixin(s,{fullWait:"true"});var p=a.encodeBody(g,u);v.default.post(c,"/push/publish",p,l,s,null,function(x){return w(x)})},y}(),E=function(){function y(d){this.rest=d}return y.prototype.save=function(d,h){var w=this.rest,c=m.default.fromValues(d),u=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,l=a.defaultPostHeaders(w.options,u),s={};if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"save",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),w.options.pushFullWait&&a.mixin(s,{fullWait:"true"});var g=a.encodeBody(c,u);v.default.put(w,"/push/deviceRegistrations/"+encodeURIComponent(d.id),g,l,s,null,function(p,x,D,N){h(p,p?void 0:m.default.fromResponseBody(x,N?void 0:u))})},y.prototype.get=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c),l=d.id||d;if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"get",arguments);h=C}if(typeof l!="string"||!l.length){h(new T.default("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400));return}w.options.headers&&a.mixin(u,w.options.headers),v.default.get(w,"/push/deviceRegistrations/"+encodeURIComponent(l),u,{},null,function(s,g,p,x){h(s,s?void 0:m.default.fromResponseBody(g,x?void 0:c))})},y.prototype.list=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=this.rest.http.supportsLinkHeaders?void 0:c,l=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"list",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),new S.default(w,"/push/deviceRegistrations",l,u,function(s,g,p){return m.default.fromResponseBody(s,p?void 0:c)}).get(d,h)},y.prototype.remove=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c),l={},s=d.id||d;if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"remove",arguments);h=C}if(typeof s!="string"||!s.length){h(new T.default("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400));return}w.options.headers&&a.mixin(u,w.options.headers),w.options.pushFullWait&&a.mixin(l,{fullWait:"true"}),v.default.delete(w,"/push/deviceRegistrations/"+encodeURIComponent(s),u,l,null,function(g){return h(g)})},y.prototype.removeWhere=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"removeWhere",arguments);h=C}w.options.headers&&a.mixin(u,w.options.headers),w.options.pushFullWait&&a.mixin(d,{fullWait:"true"}),v.default.delete(w,"/push/deviceRegistrations",u,d,null,function(l){return h(l)})},y}(),P=function(){function y(d){this.remove=y.prototype.removeWhere,this.rest=d}return y.prototype.save=function(d,h){var w=this.rest,c=R.default.fromValues(d),u=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,l=a.defaultPostHeaders(w.options,u),s={};if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"save",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),w.options.pushFullWait&&a.mixin(s,{fullWait:"true"});var g=a.encodeBody(c,u);v.default.post(w,"/push/channelSubscriptions",g,l,s,null,function(p,x,D,N){h(p,!p&&R.default.fromResponseBody(x,N?void 0:u))})},y.prototype.list=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=this.rest.http.supportsLinkHeaders?void 0:c,l=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"list",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),new S.default(w,"/push/channelSubscriptions",l,u,function(s,g,p){return R.default.fromResponseBody(s,p?void 0:c)}).get(d,h)},y.prototype.removeWhere=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"removeWhere",arguments);h=C}w.options.headers&&a.mixin(u,w.options.headers),w.options.pushFullWait&&a.mixin(d,{fullWait:"true"}),v.default.delete(w,"/push/channelSubscriptions",u,d,null,function(l){return h(l)})},y.prototype.listChannels=function(d,h){var w=this.rest,c=w.options.useBinaryProtocol?a.Format.msgpack:a.Format.json,u=this.rest.http.supportsLinkHeaders?void 0:c,l=a.defaultGetHeaders(w.options,c);if(typeof h!="function"){if(this.rest.options.promises)return a.promisify(this,"listChannels",arguments);h=C}w.options.headers&&a.mixin(l,w.options.headers),w.options.pushFullWait&&a.mixin(d,{fullWait:"true"}),new S.default(w,"/push/channels",l,u,function(s,g,p){for(var x=!p&&c?a.decodeBody(s,c):s,D=0;D<x.length;D++)x[D]=String(x[D]);return x}).get(d,h)},y}();r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(4)),v;(function(R){R.Phone="phone",R.Tablet="tablet",R.Desktop="desktop",R.TV="tv",R.Watch="watch",R.Car="car",R.Embedded="embedded",R.Other="other"})(v||(v={}));var S;(function(R){R.Android="android",R.IOS="ios",R.Browser="browser"})(S||(S={}));var T=function(){function R(){}return R.prototype.toJSON=function(){var C,O,f;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(C=this.push)===null||C===void 0?void 0:C.recipient,state:(O=this.push)===null||O===void 0?void 0:O.state,error:(f=this.push)===null||f===void 0?void 0:f.error}}},R.prototype.toString=function(){var C,O,f,E,P="[DeviceDetails";return this.id&&(P+="; id="+this.id),this.platform&&(P+="; platform="+this.platform),this.formFactor&&(P+="; formFactor="+this.formFactor),this.clientId&&(P+="; clientId="+this.clientId),this.metadata&&(P+="; metadata="+this.metadata),this.deviceIdentityToken&&(P+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),!((C=this.push)===null||C===void 0)&&C.recipient&&(P+="; push.recipient="+JSON.stringify(this.push.recipient)),!((O=this.push)===null||O===void 0)&&O.state&&(P+="; push.state="+this.push.state),!((f=this.push)===null||f===void 0)&&f.error&&(P+="; push.error="+JSON.stringify(this.push.error)),!((E=this.push)===null||E===void 0)&&E.metadata&&(P+="; push.metadata="+this.push.metadata),P+="]",P},R.fromResponseBody=function(C,O){return O&&(C=a.decodeBody(C,O)),a.isArray(C)?R.fromValuesArray(C):R.fromValues(C)},R.fromValues=function(C){return C.error=C.error&&m.default.fromValues(C.error),Object.assign(new R,C)},R.fromValuesArray=function(C){for(var O=C.length,f=new Array(O),E=0;E<O;E++)f[E]=R.fromValues(C[E]);return f},R.toRequestBody=a.encodeBody,R}();r.default=T},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=function(){function v(){}return v.prototype.toJSON=function(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}},v.prototype.toString=function(){var S="[PushChannelSubscription";return this.channel&&(S+="; channel="+this.channel),this.deviceId&&(S+="; deviceId="+this.deviceId),this.clientId&&(S+="; clientId="+this.clientId),S+="]",S},v.fromResponseBody=function(S,T){return T&&(S=a.decodeBody(S,T)),a.isArray(S)?v.fromValuesArray(S):v.fromValues(S)},v.fromValues=function(S){return Object.assign(new v,S)},v.fromValuesArray=function(S){for(var T=S.length,R=new Array(T),C=0;C<T;C++)R[C]=v.fromValues(S[C]);return R},v.toRequestBody=a.encodeBody,v}();r.default=m},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=function(){function w(c){this.count=c&&c.count||0,this.data=c&&c.data||0,this.uncompressedData=c&&c.uncompressedData||0,this.failed=c&&c.failed||0,this.refused=c&&c.refused||0}return w}(),v=function(w){i.__extends(c,w);function c(u){var l=w.call(this,u)||this;return u&&u.category&&(l.category={},a.forInOwnNonNullProperties(u.category,function(s){l.category[s]=new m(u.category[s])})),l}return c}(m),S=function(){function w(c){this.peak=c&&c.peak||0,this.min=c&&c.min||0,this.mean=c&&c.mean||0,this.opened=c&&c.opened||0,this.refused=c&&c.refused||0}return w}(),T=function(){function w(c){this.succeeded=c&&c.succeeded||0,this.failed=c&&c.failed||0,this.refused=c&&c.refused||0}return w}(),R=function(){function w(c){this.plain=new S(c&&c.plain),this.tls=new S(c&&c.tls),this.all=new S(c&&c.all)}return w}(),C=function(){function w(c){this.messages=new v(c&&c.messages),this.presence=new v(c&&c.presence),this.all=new v(c&&c.all)}return w}(),O=function(){function w(c){this.realtime=new C(c&&c.realtime),this.rest=new C(c&&c.rest),this.webhook=new C(c&&c.webhook),this.sharedQueue=new C(c&&c.sharedQueue),this.externalQueue=new C(c&&c.externalQueue),this.httpEvent=new C(c&&c.httpEvent),this.push=new C(c&&c.push),this.all=new C(c&&c.all)}return w}(),f=function(){function w(c){this.all=new C(c&&c.all),this.inbound=new O(c&&c.inbound),this.outbound=new O(c&&c.outbound)}return w}(),E=function(){function w(c){this.all=new C(c&&c.all),this.producerPaid=new f(c&&c.producerPaid),this.consumerPaid=new f(c&&c.consumerPaid)}return w}(),P=function(){function w(c){this.messages=c&&c.messages||0;var u=c&&c.notifications;this.notifications={invalid:u&&u.invalid||0,attempted:u&&u.attempted||0,successful:u&&u.successful||0,failed:u&&u.failed||0},this.directPublishes=c&&c.directPublishes||0}return w}(),y=function(){function w(c){this.succeeded=c&&c.succeeded||0,this.skipped=c&&c.skipped||0,this.failed=c&&c.failed||0}return w}(),d=function(){function w(c){var u=this;this.delta=void 0,c&&c.delta&&(this.delta={},a.forInOwnNonNullProperties(c.delta,function(l){u.delta[l]=new y(c.delta[l])}))}return w}(),h=function(w){i.__extends(c,w);function c(u){var l=w.call(this,u)||this;return l.persisted=new C(u&&u.persisted),l.connections=new R(u&&u.connections),l.channels=new S(u&&u.channels),l.apiRequests=new T(u&&u.apiRequests),l.tokenRequests=new T(u&&u.tokenRequests),l.xchgProducer=new E(u&&u.xchgProducer),l.xchgConsumer=new E(u&&u.xchgConsumer),l.push=new P(u&&u.pushStats),l.processed=new d(u&&u.processed),l.inProgress=u&&u.inProgress||void 0,l.unit=u&&u.unit||void 0,l.intervalId=u&&u.intervalId||void 0,l}return c.fromValues=function(u){return new c(u)},c}(f);r.default=h},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(30)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(51)),R=i.__importDefault(o(38)),C=i.__importDefault(o(8)),O=i.__importDefault(o(4)),f=i.__importDefault(o(10)),E=i.__importDefault(o(35)),P=i.__importDefault(o(3)),y=i.__importDefault(o(9)),d=function(w){i.__extends(c,w);function c(u){var l=w.call(this,u)||this;return S.default.logAction(S.default.LOG_MINOR,"Realtime()",""),l.connection=new T.default(l,l.options),l.channels=new h(l),u.autoConnect!==!1&&l.connect(),l}return c.prototype.connect=function(){S.default.logAction(S.default.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()},c.prototype.close=function(){S.default.logAction(S.default.LOG_MINOR,"Realtime.close()",""),this.connection.close()},c.Promise=function(u){return u=C.default.objectifyOptions(u),u.promises=!0,new c(u)},c.Callbacks=c,c.Utils=a,c.ConnectionManager=E.default,c.Platform=P.default,c.ProtocolMessage=f.default,c.Message=y.default,c}(m.default),h=function(w){i.__extends(c,w);function c(u){var l=w.call(this)||this;return l.realtime=u,l.all=Object.create(null),u.connection.connectionManager.on("transport.active",function(){l.onTransportActive()}),l}return c.prototype.channelSerials=function(){for(var u={},l=0,s=a.keysArray(this.all,!0);l<s.length;l++){var g=s[l],p=this.all[g];p.properties.channelSerial&&(u[g]=p.properties.channelSerial)}return u},c.prototype.recoverChannels=function(u){for(var l=0,s=a.keysArray(u,!0);l<s.length;l++){var g=s[l],p=this.get(g);p.properties.channelSerial=u[g]}},c.prototype.onChannelMessage=function(u){var l=u.channel;if(l===void 0){S.default.logAction(S.default.LOG_ERROR,"Channels.onChannelMessage()","received event unspecified channel, action = "+u.action);return}var s=this.all[l];if(!s){S.default.logAction(S.default.LOG_ERROR,"Channels.onChannelMessage()","received event for non-existent channel: "+l);return}s.onMessage(u)},c.prototype.onTransportActive=function(){for(var u in this.all){var l=this.all[u];l.state==="attaching"||l.state==="detaching"?l.checkPendingState():l.state==="suspended"?l._attach(!1,null):l.state==="attached"&&l.requestState("attaching")}},c.prototype.propogateConnectionInterruption=function(u,l){var s={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},g=["attaching","attached","detaching","suspended"],p=s[u];for(var x in this.all){var D=this.all[x];a.arrIn(g,D.state)&&D.notifyState(p,l)}},c.prototype.get=function(u,l){u=String(u);var s=this.all[u];if(!s)s=this.all[u]=new R.default(this.realtime,u,l);else if(l){if(s._shouldReattachToSetOptions(l,s.channelOptions))throw new O.default("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);s.setOptions(l)}return s},c.prototype.getDerived=function(u,l,s){if(l.filter){var g=a.toBase64(l.filter),p=a.matchDerivedChannel(u);u="[filter=".concat(g).concat(p.qualifierParam,"]").concat(p.channelName)}return this.get(u,s)},c.prototype.release=function(u){u=String(u);var l=this.all[u];if(l){var s=l.getReleaseErr();if(s)throw s;delete this.all[u]}},c}(v.default);r.default=d},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(7)),v=i.__importDefault(o(35)),S=i.__importDefault(o(2)),T=i.__importDefault(o(37)),R=i.__importDefault(o(3));function C(){}var O=function(f){i.__extends(E,f);function E(P,y){var d=f.call(this)||this;return d.whenState=function(h,w){return m.default.prototype.whenState.call(d,h,d.state,w,new T.default(void 0,h))},d.ably=P,d.connectionManager=new v.default(P,y),d.state=d.connectionManager.state.state,d.key=void 0,d.id=void 0,d.errorReason=null,d.connectionManager.on("connectionstate",function(h){var w=d.state=h.current;R.default.Config.nextTick(function(){d.emit(w,h)})}),d.connectionManager.on("update",function(h){R.default.Config.nextTick(function(){d.emit("update",h)})}),d}return E.prototype.connect=function(){S.default.logAction(S.default.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})},E.prototype.ping=function(P){if(S.default.logAction(S.default.LOG_MINOR,"Connection.ping()",""),!P){if(this.ably.options.promises)return a.promisify(this,"ping",arguments);P=C}this.connectionManager.ping(null,P)},E.prototype.close=function(){S.default.logAction(S.default.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})},Object.defineProperty(E.prototype,"recoveryKey",{get:function(){return this.createRecoveryKey()},enumerable:!1,configurable:!0}),E.prototype.createRecoveryKey=function(){return this.connectionManager.createRecoveryKey()},E}(m.default);r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0}),r.PendingMessage=void 0;var i=o(0),a=i.__importDefault(o(10)),m=i.__importStar(o(1)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(36)),R=i.__importDefault(o(4)),C=a.default.Action,O=function(){function E(P,y){this.message=P,this.callback=y,this.merged=!1;var d=P.action;this.sendAttempted=!1,this.ackRequired=d==C.MESSAGE||d==C.PRESENCE}return E}();r.PendingMessage=O;var f=function(E){i.__extends(P,E);function P(y){var d=E.call(this)||this;return d.transport=y,d.messageQueue=new T.default,y.on("ack",function(h,w){d.onAck(h,w)}),y.on("nack",function(h,w,c){d.onNack(h,w,c)}),d}return P.prototype.onAck=function(y,d){S.default.logAction(S.default.LOG_MICRO,"Protocol.onAck()","serial = "+y+"; count = "+d),this.messageQueue.completeMessages(y,d)},P.prototype.onNack=function(y,d,h){S.default.logAction(S.default.LOG_ERROR,"Protocol.onNack()","serial = "+y+"; count = "+d+"; err = "+m.inspectError(h)),h||(h=new R.default("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(y,d,h)},P.prototype.onceIdle=function(y){var d=this.messageQueue;if(d.count()===0){y();return}d.once("idle",y)},P.prototype.send=function(y){y.ackRequired&&this.messageQueue.push(y),S.default.shouldLog(S.default.LOG_MICRO)&&S.default.logAction(S.default.LOG_MICRO,"Protocol.send()","sending msg; "+a.default.stringify(y.message)),y.sendAttempted=!0,this.transport.send(y.message)},P.prototype.getTransport=function(){return this.transport},P.prototype.getPendingMessages=function(){return this.messageQueue.copyAll()},P.prototype.clearPendingMessages=function(){return this.messageQueue.clear()},P.prototype.finish=function(){var y=this.transport;this.onceIdle(function(){y.disconnect()})},P}(v.default);r.default=f},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(3)),m=i.__importStar(o(1)),v=i.__importDefault(o(26)),S=i.__importDefault(o(8)),T=i.__importDefault(o(2)),R=i.__importDefault(o(10)),C=i.__importDefault(o(4)),O="web_socket";function f(y){return!!y.on}var E=function(y){i.__extends(d,y);function d(h,w,c){var u=y.call(this,h,w,c)||this;return u.shortName=O,c.heartbeats=a.default.Config.useProtocolHeartbeats,u.wsHost=S.default.getHost(c.options,c.host,!0),u}return d.isAvailable=function(){return!!a.default.Config.WebSocket},d.prototype.createWebSocket=function(h,w){return this.uri=h+m.toQueryString(w),new a.default.Config.WebSocket(this.uri)},d.prototype.toString=function(){return"WebSocketTransport; uri="+this.uri},d.prototype.connect=function(){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.connect()","starting"),v.default.prototype.connect.call(this);var h=this,w=this.params,c=w.options,u=c.tls?"wss://":"ws://",l=u+this.wsHost+":"+S.default.getPort(c)+"/";T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.connect()","uri: "+l),this.auth.getAuthParams(function(s,g){if(!h.isDisposed){var p="";for(var x in g)p+=" "+x+": "+g[x]+";";if(T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+p+" err: "+s),s){h.disconnect(s);return}var D=w.getConnectParams(g);try{var N=h.wsConnection=h.createWebSocket(l,D);N.binaryType=a.default.Config.binaryType,N.onopen=function(){h.onWsOpen()},N.onclose=function(k){h.onWsClose(k)},N.onmessage=function(k){h.onWsData(k.data)},N.onerror=function(k){h.onWsError(k)},f(N)&&N.on("ping",function(){h.onActivity()})}catch(k){T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(k.stack||k.message)),h.disconnect(k)}}})},d.prototype.send=function(h){var w=this.wsConnection;if(!w){T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{w.send(R.default.serialize(h,this.params.format))}catch(u){var c="Exception from ws connection when trying to send: "+m.inspectError(u);T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.send()",c),this.finish("disconnected",new C.default(c,5e4,500))}},d.prototype.onWsData=function(h){T.default.logAction(T.default.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+h.length+"; type = "+typeof h);try{this.onProtocolMessage(R.default.deserialize(h,this.format))}catch(w){T.default.logAction(T.default.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+w.stack)}},d.prototype.onWsOpen=function(){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")},d.prototype.onWsClose=function(h){var w,c;if(typeof h=="object"?(c=h.code,w=h.wasClean||c===1e3):(c=h,w=c==1e3),delete this.wsConnection,w){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");var u=new C.default("Websocket closed",80003,400);this.finish("disconnected",u)}else{var l="Unclean disconnection of WebSocket ; code = "+c,u=new C.default(l,80003,400);T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",u)}this.emit("disposed")},d.prototype.onWsError=function(h){var w=this;T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+h.message),a.default.Config.nextTick(function(){w.disconnect(Error(h.message))})},d.prototype.dispose=function(){T.default.logAction(T.default.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;var h=this.wsConnection;h&&(h.onmessage=function(){},delete this.wsConnection,a.default.Config.nextTick(function(){if(T.default.logAction(T.default.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!h)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");h.close()}))},d}(v.default);function P(y){return E.isAvailable()&&(y.supportedTransports[O]=E),E}r.default=P},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(1)),m=i.__importDefault(o(34)),v=i.__importDefault(o(7)),S=i.__importDefault(o(2)),T=i.__importDefault(o(16)),R=i.__importStar(o(4)),C=i.__importDefault(o(38)),O=i.__importDefault(o(24)),f=i.__importDefault(o(39)),E=function(){};function P(u){return u.channel.realtime.auth.clientId}function y(u){var l=u.channel.realtime,s=l.auth.clientId;return(!s||s==="*")&&l.connection.state==="connected"}function d(u,l,s){switch(u.state){case"attached":case"suspended":s();break;case"initialized":case"detached":case"detaching":case"attaching":u.attach(function(g){g?l(g):s()});break;default:l(R.default.fromValues(u.invalidStateError()))}}function h(u,l){if(u.isSynthesized()||l.isSynthesized())return u.timestamp>=l.timestamp;var s=u.parseId(),g=l.parseId();return s.msgSerial===g.msgSerial?s.index>g.index:s.msgSerial>g.msgSerial}var w=function(u){i.__extends(l,u);function l(s){var g=u.call(this,s)||this;return g.channel=s,g.syncComplete=!1,g.members=new c(g,function(p){return p.clientId+":"+p.connectionId}),g._myMembers=new c(g,function(p){return p.clientId}),g.subscriptions=new v.default,g.pendingPresence=[],g}return l.prototype.enter=function(s,g){if(y(this))throw new R.default("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"enter",g)},l.prototype.update=function(s,g){if(y(this))throw new R.default("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"update",g)},l.prototype.enterClient=function(s,g,p){return this._enterOrUpdateClient(void 0,s,g,"enter",p)},l.prototype.updateClient=function(s,g,p){return this._enterOrUpdateClient(void 0,s,g,"update",p)},l.prototype._enterOrUpdateClient=function(s,g,p,x,D){var N=this;if(!D)if(typeof p=="function")D=p,p=null;else{if(this.channel.realtime.options.promises)return a.promisify(this,"_enterOrUpdateClient",[s,g,p,x]);D=E}var k=this.channel;if(!k.connectionManager.activeState()){D(k.connectionManager.getError());return}S.default.logAction(S.default.LOG_MICRO,"RealtimePresence."+x+"Client()","channel = "+k.name+", id = "+s+", client = "+(g||"(implicit) "+P(this)));var I=T.default.fromData(p);I.action=x,s&&(I.id=s),g&&(I.clientId=g),T.default.encode(I,k.channelOptions,function(M){if(M){D(M);return}switch(k.state){case"attached":k.sendPresence(I,D);break;case"initialized":case"detached":k.attach();case"attaching":N.pendingPresence.push({presence:I,callback:D});break;default:M=new R.PartialErrorInfo("Unable to "+x+" presence channel while in "+k.state+" state",90001),M.code=90001,D(M)}})},l.prototype.leave=function(s,g){if(y(this))throw new R.default("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,s,g)},l.prototype.leaveClient=function(s,g,p){if(!p)if(typeof g=="function")p=g,g=null;else{if(this.channel.realtime.options.promises)return a.promisify(this,"leaveClient",[s,g]);p=E}var x=this.channel;if(!x.connectionManager.activeState()){p==null||p(x.connectionManager.getError());return}S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+s);var D=T.default.fromData(g);switch(D.action="leave",s&&(D.clientId=s),x.state){case"attached":x.sendPresence(D,p);break;case"attaching":this.pendingPresence.push({presence:D,callback:p});break;case"initialized":case"failed":{var N=new R.PartialErrorInfo("Unable to leave presence channel (incompatible state)",90001);p==null||p(N);break}default:p==null||p(x.invalidStateError())}},l.prototype.get=function(s,g){var p=this,x=Array.prototype.slice.call(arguments);x.length==1&&typeof x[0]=="function"&&x.unshift(null),s=x[0],g=x[1];var D=!s||("waitForSync"in s?s.waitForSync:!0);if(!g){if(this.channel.realtime.options.promises)return a.promisify(this,"get",x);g=E}function N(k){g(null,s?k.list(s):k.values())}if(this.channel.state==="suspended"){D?g(R.default.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):N(this.members);return}d(this.channel,g,function(){var k=p.members;D?k.waitSync(function(){N(k)}):N(k)})},l.prototype.history=function(s,g){if(S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name),g===void 0)if(typeof s=="function")g=s,s=null;else{if(this.channel.realtime.options.promises)return a.promisify(this,"history",arguments);g=E}s&&s.untilAttach&&(this.channel.state==="attached"?(delete s.untilAttach,s.from_serial=this.channel.properties.attachSerial):g(new R.default("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400))),m.default.prototype._history.call(this,s,g)},l.prototype.setPresence=function(s,g,p){S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+s.length+" participants; syncChannelSerial = "+p);var x,D,N=this.members,k=this._myMembers,I=[],M=this.channel.connectionManager.connectionId;g&&(this.members.startSync(),p&&(D=p.match(/^[\w-]+:(.*)$/))&&(x=D[1]));for(var A=0;A<s.length;A++){var j=T.default.fromValues(s[A]);switch(j.action){case"leave":N.remove(j)&&I.push(j),j.connectionId===M&&!j.isSynthesized()&&k.remove(j);break;case"enter":case"present":case"update":N.put(j)&&I.push(j),j.connectionId===M&&k.put(j);break}}g&&!x&&(N.endSync(),this.channel.syncChannelSerial=null);for(var A=0;A<I.length;A++){var j=I[A];this.subscriptions.emit(j.action,j)}},l.prototype.onAttached=function(s){S.default.logAction(S.default.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+s),s?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();var g=this.pendingPresence,p=g.length;if(p){this.pendingPresence=[];var x=[],D=O.default.create();S.default.logAction(S.default.LOG_MICRO,"RealtimePresence.onAttached","sending "+p+" queued presence messages");for(var N=0;N<p;N++){var k=g[N];x.push(k.presence),D.push(k.callback)}this.channel.sendPresence(x,D)}},l.prototype.actOnChannelState=function(s,g,p){switch(s){case"attached":this.onAttached(g);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(p);break}},l.prototype.failPendingPresence=function(s){if(this.pendingPresence.length){S.default.logAction(S.default.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+a.inspectError(s));for(var g=0;g<this.pendingPresence.length;g++)try{this.pendingPresence[g].callback(s)}catch(p){}this.pendingPresence=[]}},l.prototype._clearMyMembers=function(){this._myMembers.clear()},l.prototype._ensureMyMembersPresent=function(){var s=this,g=this._myMembers,p=function(N){if(N){var k="Presence auto-re-enter failed: "+N.toString(),I=new R.default(k,91004,400);S.default.logAction(S.default.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()",k);var M=new f.default(s.channel.state,s.channel.state,!0,!1,I);s.channel.emit("update",M)}};for(var x in g.map){var D=g.map[x];S.default.logAction(S.default.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+D.clientId+'" into the presence set'),this._enterOrUpdateClient(D.id,D.clientId,D.data,"enter",p)}},l.prototype._synthesizeLeaves=function(s){var g=this.subscriptions;a.arrForEach(s,function(p){var x=T.default.fromValues({action:"leave",connectionId:p.connectionId,clientId:p.clientId,data:p.data,encoding:p.encoding,timestamp:a.now()});g.emit("leave",x)})},l.prototype.on=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];S.default.renamedMethod("RealtimePresence","on","subscribe"),this.subscribe.apply(this,s)},l.prototype.off=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];S.default.renamedMethod("RealtimePresence","off","unsubscribe"),this.unsubscribe.apply(this,s)},l.prototype.subscribe=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];var p=C.default.processListenerArgs(s),x=p[0],D=p[1],N=p[2],k=this.channel;if(!N){if(this.channel.realtime.options.promises)return a.promisify(this,"subscribe",[x,D]);N=E}if(k.state==="failed"){N(R.default.fromValues(k.invalidStateError()));return}this.subscriptions.on(x,D),k.attach(N)},l.prototype.unsubscribe=function(){for(var s=[],g=0;g<arguments.length;g++)s[g]=arguments[g];var p=C.default.processListenerArgs(s),x=p[0],D=p[1];this.subscriptions.off(x,D)},l}(m.default),c=function(u){i.__extends(l,u);function l(s,g){var p=u.call(this)||this;return p.presence=s,p.map=Object.create(null),p.syncInProgress=!1,p.residualMembers=null,p.memberKey=g,p}return l.prototype.get=function(s){return this.map[s]},l.prototype.getClient=function(s){var g=this.map,p=[];for(var x in g){var D=g[x];D.clientId==s&&D.action!="absent"&&p.push(D)}return p},l.prototype.list=function(s){var g=this.map,p=s&&s.clientId,x=s&&s.connectionId,D=[];for(var N in g){var k=g[N];k.action!=="absent"&&(p&&p!=k.clientId||x&&x!=k.connectionId||D.push(k))}return D},l.prototype.put=function(s){(s.action==="enter"||s.action==="update")&&(s=T.default.fromValues(s),s.action="present");var g=this.map,p=this.memberKey(s);this.residualMembers&&delete this.residualMembers[p];var x=g[p];return x&&!h(s,x)?!1:(g[p]=s,!0)},l.prototype.values=function(){var s=this.map,g=[];for(var p in s){var x=s[p];x.action!="absent"&&g.push(x)}return g},l.prototype.remove=function(s){var g=this.map,p=this.memberKey(s),x=g[p];return x&&!h(s,x)?!1:(this.syncInProgress?(s=T.default.fromValues(s),s.action="absent",g[p]=s):delete g[p],!0)},l.prototype.startSync=function(){var s=this.map,g=this.syncInProgress;S.default.logAction(S.default.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+g),this.syncInProgress||(this.residualMembers=a.copy(s),this.setInProgress(!0))},l.prototype.endSync=function(){var s=this.map,g=this.syncInProgress;if(S.default.logAction(S.default.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+g),g){for(var p in s){var x=s[p];x.action==="absent"&&delete s[p]}this.presence._synthesizeLeaves(a.valuesArray(this.residualMembers));for(var p in this.residualMembers)delete s[p];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")},l.prototype.waitSync=function(s){var g=this.syncInProgress;if(S.default.logAction(S.default.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+g),!g){s();return}this.once("sync",s)},l.prototype.clear=function(){this.map={},this.setInProgress(!1),this.residualMembers=null},l.prototype.setInProgress=function(s){S.default.logAction(S.default.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+s),this.syncInProgress=s,this.presence.syncComplete=!s},l}(v.default);r.default=w},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=o(56),m=o(31),v=o(11),S=i.__importDefault(o(5)),T=i.__importDefault(o(3)),R=function(){function C(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}return C.prototype.isWordArray=function(O){return O!=null&&O.sigBytes!==void 0},C.prototype.isArrayBuffer=function(O){return O!=null&&O.constructor===ArrayBuffer},C.prototype.isTypedArray=function(O){return!!ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(O)},C.prototype.uint8ViewToBase64=function(O){for(var f="",E=this.base64CharSet,P=O.byteLength,y=P%3,d=P-y,h,w,c,u,l,s=0;s<d;s=s+3)l=O[s]<<16|O[s+1]<<8|O[s+2],h=(l&16515072)>>18,w=(l&258048)>>12,c=(l&4032)>>6,u=l&63,f+=E[h]+E[w]+E[c]+E[u];return y==1?(l=O[d],h=(l&252)>>2,w=(l&3)<<4,f+=E[h]+E[w]+"=="):y==2&&(l=O[d]<<8|O[d+1],h=(l&64512)>>10,w=(l&1008)>>4,c=(l&15)<<2,f+=E[h]+E[w]+E[c]+"="),f},C.prototype.base64ToArrayBuffer=function(O){for(var f=atob==null?void 0:atob(O),E=f.length,P=new Uint8Array(E),y=0;y<E;y++){var d=f.charCodeAt(y);P[y]=d}return P.buffer},C.prototype.isBuffer=function(O){return this.isArrayBuffer(O)||this.isWordArray(O)||this.isTypedArray(O)},C.prototype.toBuffer=function(O){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(this.isArrayBuffer(O))return new Uint8Array(O);if(this.isTypedArray(O))return new Uint8Array(O.buffer);if(this.isWordArray(O)){for(var f=new ArrayBuffer(O.sigBytes),E=new Uint8Array(f),P=0;P<O.sigBytes;P++)E[P]=O.words[P>>>2]>>>24-P%4*8&255;return E}throw new Error("BufferUtils.toBuffer expected an arraybuffer, typed array, or CryptoJS wordarray")},C.prototype.toArrayBuffer=function(O){return this.isArrayBuffer(O)?O:this.toBuffer(O).buffer},C.prototype.toWordArray=function(O){return this.isTypedArray(O)&&(O=O.buffer),this.isWordArray(O)?O:S.default.create(O)},C.prototype.base64Encode=function(O){return this.isWordArray(O)?(0,v.stringify)(O):this.uint8ViewToBase64(this.toBuffer(O))},C.prototype.base64Decode=function(O){return ArrayBuffer&&T.default.Config.atob?this.base64ToArrayBuffer(O):(0,v.parse)(O)},C.prototype.hexEncode=function(O){return(0,a.stringify)(this.toWordArray(O))},C.prototype.hexDecode=function(O){var f=(0,a.parse)(O);return ArrayBuffer?this.toArrayBuffer(f):f},C.prototype.utf8Encode=function(O){return T.default.Config.TextEncoder?new T.default.Config.TextEncoder().encode(O).buffer:(0,m.parse)(O)},C.prototype.utf8Decode=function(O){if(!this.isBuffer(O))throw new Error("Expected input of utf8decode to be an arraybuffer, typed array, or CryptoJS wordarray");return TextDecoder&&!this.isWordArray(O)?new TextDecoder().decode(O):(O=this.toWordArray(O),(0,m.stringify)(O))},C.prototype.bufferCompare=function(O,f){if(!O)return-1;if(!f)return 1;var E=this.toWordArray(O),P=this.toWordArray(f);E.clamp(),P.clamp();var y=E.sigBytes-P.sigBytes;if(y!=0)return y;for(var d=E.words,h=P.words,w=0;w<d.length;w++)if(y=d[w]-h[w],y!=0)return y;return 0},C.prototype.byteLength=function(O){return this.isArrayBuffer(O)||this.isTypedArray(O)?O.byteLength:this.isWordArray(O)?O.sigBytes:-1},C.prototype.typedArrayToBuffer=function(O){return O.buffer},C}();r.default=new R},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return i.enc.Hex})},function(n,r,o){o.r(r);var i=o(5),a=o.n(i),m=o(11),v=o(23),S=o.n(v),T=o(2),R=o.n(T),C=o(4),O=o.n(C),f=function(E,P){var y="aes",d=256,h="cbc",w=16,c=4,u=4294967296,l=2147483648,s;if(E.getRandomWordArray)s=E.getRandomWordArray;else if(typeof Uint32Array!="undefined"&&E.getRandomValues){var g=new Uint32Array(c);s=function(A,j){var U=A/4,z=U==c?g:new Uint32Array(U);E.getRandomValues(z,function(W){typeof j!="undefined"&&j(W,P.toWordArray(z))})}}else s=function(A,j){R.a.logAction(R.a.LOG_MAJOR,"Ably.Crypto.generateRandom()","Warning: the browser you are using does not support secure cryptographically secure randomness generation; falling back to insecure Math.random()");for(var U=A/4,z=new Array(U),W=0;W<U;W++)z[W]=Math.floor(Math.random()*u)-l;j(null,a.a.create(z))};function p(A){return A+w&-16}function x(A){if(A.algorithm==="aes"&&A.mode==="cbc"){if(A.keyLength===128||A.keyLength===256)return;throw new Error("Unsupported key length "+A.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function D(A){return A.replace("_","/").replace("-","+")}var N=[a.a.create([269488144,269488144,269488144,269488144],16),a.a.create([16777216],1),a.a.create([33685504],2),a.a.create([50529024],3),a.a.create([67372036],4),a.a.create([84215045,83886080],5),a.a.create([101058054,101056512],6),a.a.create([117901063,117901056],7),a.a.create([134744072,134744072],8),a.a.create([151587081,151587081,150994944],9),a.a.create([168430090,168430090,168427520],10),a.a.create([185273099,185273099,185273088],11),a.a.create([202116108,202116108,202116108],12),a.a.create([218959117,218959117,218959117,218103808],13),a.a.create([235802126,235802126,235802126,235798528],14),a.a.create([252645135,252645135,252645135,252645135],15),a.a.create([269488144,269488144,269488144,269488144],16)];function k(){}function I(){this.algorithm=null,this.keyLength=null,this.mode=null,this.key=null}k.CipherParams=I,k.getDefaultParams=function(A){var j;if(typeof A=="function"||typeof A=="string"){if(R.a.deprecated("The ability to pass a callback to `Crypto.getDefaultParams()`","This method now directly returns its result, instead of returning it asynchronously via a callback. Please update your code so that it uses the return value of this method instead of passing a callback."),typeof A=="function")R.a.deprecated("The ability to call `Crypto.getDefaultParams()` without specifying an encryption key","Please update your code so that it instead passes an object whose `key` property contains an encryption key. That is, replace `Crypto.getDefaultParams()` with `Crypto.getDefaultParams({ key })`, where `key` is an encryption key that you have generated (for example from the `Crypto.generateRandomKey()` method)."),k.generateRandomKey(function(z){A(null,k.getDefaultParams({key:z}))});else if(typeof arguments[1]=="function")R.a.deprecated("The ability to pass the encryption key as the first argument of `Crypto.getDefaultParams()`","Please update your code so that it instead passes an object whose `key` property contains the key. That is, replace `Crypto.getDefaultParams(key)` with `Crypto.getDefaultParams({ key })`."),arguments[1](null,k.getDefaultParams({key:A}));else throw new Error("Invalid arguments for Crypto.getDefaultParams");return}if(!A.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof A.key=="string"?j=Object(m.parse)(D(A.key)):j=P.toWordArray(A.key);var U=new I;if(U.key=j,U.algorithm=A.algorithm||y,U.keyLength=j.words.length*(4*8),U.mode=A.mode||h,A.keyLength&&A.keyLength!==U.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+A.keyLength+" was specified, but the key actually has length "+U.keyLength);return x(U),U},k.generateRandomKey=function(A,j){arguments.length==1&&typeof A=="function"&&(j=A,A=void 0),s((A||d)/8,function(U,z){j!==void 0&&j(U?O.a.fromValues(U):null,z)})},k.getCipher=function(A){var j=A instanceof I?A:k.getDefaultParams(A);return{cipherParams:j,cipher:new M(j,c,A.iv)}};function M(A,j,U){this.algorithm=A.algorithm+"-"+String(A.keyLength)+"-"+A.mode,this.cjsAlgorithm=A.algorithm.toUpperCase().replace(/-\d+$/,""),this.key=P.toWordArray(A.key),U&&(this.iv=P.toWordArray(U).clone()),this.blockLengthWords=j}return M.prototype.encrypt=function(A,j){R.a.logAction(R.a.LOG_MICRO,"CBCCipher.encrypt()",""),A=P.toWordArray(A);var U=A.sigBytes,z=p(U),W=this,G=function(){W.getIv(function(F,b){if(F){j(F);return}var L=W.encryptCipher.process(A.concat(N[z-U])),B=b.concat(L);j(null,B)})};this.encryptCipher?G():this.iv?(this.encryptCipher=S.a.algo[this.cjsAlgorithm].createEncryptor(this.key,{iv:this.iv}),G()):s(w,function(F,b){if(F){j(F);return}W.encryptCipher=S.a.algo[W.cjsAlgorithm].createEncryptor(W.key,{iv:b}),W.iv=b,G()})},M.prototype.decrypt=function(A){R.a.logAction(R.a.LOG_MICRO,"CBCCipher.decrypt()",""),A=P.toWordArray(A);var j=this.blockLengthWords,U=A.words,z=a.a.create(U.slice(0,j)),W=a.a.create(U.slice(j)),G=S.a.algo[this.cjsAlgorithm].createDecryptor(this.key,{iv:z}),F=G.process(W),b=G.finalize();return G.reset(),b&&b.sigBytes&&F.concat(b),F},M.prototype.getIv=function(A){if(this.iv){var j=this.iv;this.iv=null,A(null,j);return}var U=this;s(w,function(z,W){if(z){A(z);return}A(null,U.encryptCipher.process(W))})},k};r.default=f},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(){var a=i,m=a.lib,v=m.WordArray,S=a.enc;S.Utf16=S.Utf16BE={stringify:function(R){for(var C=R.words,O=R.sigBytes,f=[],E=0;E<O;E+=2){var P=C[E>>>2]>>>16-E%4*8&65535;f.push(String.fromCharCode(P))}return f.join("")},parse:function(R){for(var C=R.length,O=[],f=0;f<C;f++)O[f>>>1]|=R.charCodeAt(f)<<16-f%2*16;return v.create(O,C*2)}},S.Utf16LE={stringify:function(R){for(var C=R.words,O=R.sigBytes,f=[],E=0;E<O;E+=2){var P=T(C[E>>>2]>>>16-E%4*8&65535);f.push(String.fromCharCode(P))}return f.join("")},parse:function(R){for(var C=R.length,O=[],f=0;f<C;f++)O[f>>>1]|=T(R.charCodeAt(f)<<16-f%2*16);return v.create(O,C*2)}};function T(R){return R<<8&4278255360|R>>>8&16711935}}(),i.enc.Utf16})},function(n,r,o){(function(i,a){n.exports=a(o(6),o(28))})(this,function(i){return function(a){var m=i,v=m.lib,S=v.CipherParams,T=m.enc,R=T.Hex,C=m.format;C.Hex={stringify:function(O){return O.ciphertext.toString(R)},parse:function(O){var f=R.parse(O);return S.create({ciphertext:f})}}}(),i.format.Hex})},function(n,r,o){(function(i,a){n.exports=a(o(6),o(11),o(61),o(27),o(28))})(this,function(i){return function(){var a=i,m=a.lib,v=m.BlockCipher,S=a.algo,T=[],R=[],C=[],O=[],f=[],E=[],P=[],y=[],d=[],h=[];(function(){for(var u=[],l=0;l<256;l++)l<128?u[l]=l<<1:u[l]=l<<1^283;for(var s=0,g=0,l=0;l<256;l++){var p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^p&255^99,T[s]=p,R[p]=s;var x=u[s],D=u[x],N=u[D],k=u[p]*257^p*16843008;C[s]=k<<24|k>>>8,O[s]=k<<16|k>>>16,f[s]=k<<8|k>>>24,E[s]=k;var k=N*16843009^D*65537^x*257^s*16843008;P[p]=k<<24|k>>>8,y[p]=k<<16|k>>>16,d[p]=k<<8|k>>>24,h[p]=k,s?(s=x^u[u[u[N^x]]],g^=u[u[g]]):s=g=1}})();var w=[0,1,2,4,8,16,32,64,128,27,54],c=S.AES=v.extend({_doReset:function(){var u;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var l=this._keyPriorReset=this._key,s=l.words,g=l.sigBytes/4,p=this._nRounds=g+6,x=(p+1)*4,D=this._keySchedule=[],N=0;N<x;N++)N<g?D[N]=s[N]:(u=D[N-1],N%g?g>6&&N%g==4&&(u=T[u>>>24]<<24|T[u>>>16&255]<<16|T[u>>>8&255]<<8|T[u&255]):(u=u<<8|u>>>24,u=T[u>>>24]<<24|T[u>>>16&255]<<16|T[u>>>8&255]<<8|T[u&255],u^=w[N/g|0]<<24),D[N]=D[N-g]^u);for(var k=this._invKeySchedule=[],I=0;I<x;I++){var N=x-I;if(I%4)var u=D[N];else var u=D[N-4];I<4||N<=4?k[I]=u:k[I]=P[T[u>>>24]]^y[T[u>>>16&255]]^d[T[u>>>8&255]]^h[T[u&255]]}}},encryptBlock:function(u,l){this._doCryptBlock(u,l,this._keySchedule,C,O,f,E,T)},decryptBlock:function(u,l){var s=u[l+1];u[l+1]=u[l+3],u[l+3]=s,this._doCryptBlock(u,l,this._invKeySchedule,P,y,d,h,R);var s=u[l+1];u[l+1]=u[l+3],u[l+3]=s},_doCryptBlock:function(u,l,s,g,p,x,D,N){for(var k=this._nRounds,I=u[l]^s[0],M=u[l+1]^s[1],A=u[l+2]^s[2],j=u[l+3]^s[3],U=4,z=1;z<k;z++){var W=g[I>>>24]^p[M>>>16&255]^x[A>>>8&255]^D[j&255]^s[U++],G=g[M>>>24]^p[A>>>16&255]^x[j>>>8&255]^D[I&255]^s[U++],F=g[A>>>24]^p[j>>>16&255]^x[I>>>8&255]^D[M&255]^s[U++],b=g[j>>>24]^p[I>>>16&255]^x[M>>>8&255]^D[A&255]^s[U++];I=W,M=G,A=F,j=b}var W=(N[I>>>24]<<24|N[M>>>16&255]<<16|N[A>>>8&255]<<8|N[j&255])^s[U++],G=(N[M>>>24]<<24|N[A>>>16&255]<<16|N[j>>>8&255]<<8|N[I&255])^s[U++],F=(N[A>>>24]<<24|N[j>>>16&255]<<16|N[I>>>8&255]<<8|N[M&255])^s[U++],b=(N[j>>>24]<<24|N[I>>>16&255]<<16|N[M>>>8&255]<<8|N[A&255])^s[U++];u[l]=W,u[l+1]=G,u[l+2]=F,u[l+3]=b},keySize:256/32});a.AES=v._createHelper(c)}(),i.AES})},function(n,r,o){(function(i,a){n.exports=a(o(6))})(this,function(i){return function(a){var m=i,v=m.lib,S=v.WordArray,T=v.Hasher,R=m.algo,C=[];(function(){for(var d=0;d<64;d++)C[d]=a.abs(a.sin(d+1))*4294967296|0})();var O=R.MD5=T.extend({_doReset:function(){this._hash=new S.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(d,h){for(var w=0;w<16;w++){var c=h+w,u=d[c];d[c]=(u<<8|u>>>24)&16711935|(u<<24|u>>>8)&4278255360}var l=this._hash.words,s=d[h+0],g=d[h+1],p=d[h+2],x=d[h+3],D=d[h+4],N=d[h+5],k=d[h+6],I=d[h+7],M=d[h+8],A=d[h+9],j=d[h+10],U=d[h+11],z=d[h+12],W=d[h+13],G=d[h+14],F=d[h+15],b=l[0],L=l[1],B=l[2],_=l[3];b=f(b,L,B,_,s,7,C[0]),_=f(_,b,L,B,g,12,C[1]),B=f(B,_,b,L,p,17,C[2]),L=f(L,B,_,b,x,22,C[3]),b=f(b,L,B,_,D,7,C[4]),_=f(_,b,L,B,N,12,C[5]),B=f(B,_,b,L,k,17,C[6]),L=f(L,B,_,b,I,22,C[7]),b=f(b,L,B,_,M,7,C[8]),_=f(_,b,L,B,A,12,C[9]),B=f(B,_,b,L,j,17,C[10]),L=f(L,B,_,b,U,22,C[11]),b=f(b,L,B,_,z,7,C[12]),_=f(_,b,L,B,W,12,C[13]),B=f(B,_,b,L,G,17,C[14]),L=f(L,B,_,b,F,22,C[15]),b=E(b,L,B,_,g,5,C[16]),_=E(_,b,L,B,k,9,C[17]),B=E(B,_,b,L,U,14,C[18]),L=E(L,B,_,b,s,20,C[19]),b=E(b,L,B,_,N,5,C[20]),_=E(_,b,L,B,j,9,C[21]),B=E(B,_,b,L,F,14,C[22]),L=E(L,B,_,b,D,20,C[23]),b=E(b,L,B,_,A,5,C[24]),_=E(_,b,L,B,G,9,C[25]),B=E(B,_,b,L,x,14,C[26]),L=E(L,B,_,b,M,20,C[27]),b=E(b,L,B,_,W,5,C[28]),_=E(_,b,L,B,p,9,C[29]),B=E(B,_,b,L,I,14,C[30]),L=E(L,B,_,b,z,20,C[31]),b=P(b,L,B,_,N,4,C[32]),_=P(_,b,L,B,M,11,C[33]),B=P(B,_,b,L,U,16,C[34]),L=P(L,B,_,b,G,23,C[35]),b=P(b,L,B,_,g,4,C[36]),_=P(_,b,L,B,D,11,C[37]),B=P(B,_,b,L,I,16,C[38]),L=P(L,B,_,b,j,23,C[39]),b=P(b,L,B,_,W,4,C[40]),_=P(_,b,L,B,s,11,C[41]),B=P(B,_,b,L,x,16,C[42]),L=P(L,B,_,b,k,23,C[43]),b=P(b,L,B,_,A,4,C[44]),_=P(_,b,L,B,z,11,C[45]),B=P(B,_,b,L,F,16,C[46]),L=P(L,B,_,b,p,23,C[47]),b=y(b,L,B,_,s,6,C[48]),_=y(_,b,L,B,I,10,C[49]),B=y(B,_,b,L,G,15,C[50]),L=y(L,B,_,b,N,21,C[51]),b=y(b,L,B,_,z,6,C[52]),_=y(_,b,L,B,x,10,C[53]),B=y(B,_,b,L,j,15,C[54]),L=y(L,B,_,b,g,21,C[55]),b=y(b,L,B,_,M,6,C[56]),_=y(_,b,L,B,F,10,C[57]),B=y(B,_,b,L,k,15,C[58]),L=y(L,B,_,b,W,21,C[59]),b=y(b,L,B,_,D,6,C[60]),_=y(_,b,L,B,U,10,C[61]),B=y(B,_,b,L,p,15,C[62]),L=y(L,B,_,b,A,21,C[63]),l[0]=l[0]+b|0,l[1]=l[1]+L|0,l[2]=l[2]+B|0,l[3]=l[3]+_|0},_doFinalize:function(){var d=this._data,h=d.words,w=this._nDataBytes*8,c=d.sigBytes*8;h[c>>>5]|=128<<24-c%32;var u=a.floor(w/4294967296),l=w;h[(c+64>>>9<<4)+15]=(u<<8|u>>>24)&16711935|(u<<24|u>>>8)&4278255360,h[(c+64>>>9<<4)+14]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360,d.sigBytes=(h.length+1)*4,this._process();for(var s=this._hash,g=s.words,p=0;p<4;p++){var x=g[p];g[p]=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360}return s},clone:function(){var d=T.clone.call(this);return d._hash=this._hash.clone(),d}});function f(d,h,w,c,u,l,s){var g=d+(h&w|~h&c)+u+s;return(g<<l|g>>>32-l)+h}function E(d,h,w,c,u,l,s){var g=d+(h&c|w&~c)+u+s;return(g<<l|g>>>32-l)+h}function P(d,h,w,c,u,l,s){var g=d+(h^w^c)+u+s;return(g<<l|g>>>32-l)+h}function y(d,h,w,c,u,l,s){var g=d+(w^(h|~c))+u+s;return(g<<l|g>>>32-l)+h}m.MD5=T._createHelper(O),m.HmacMD5=T._createHmacHelper(O)}(Math),i.MD5})},function(n,r,o){var i;Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importDefault(o(3)),v=a.__importStar(o(1)),S=a.__importDefault(o(8)),T=o(4),R=a.__importDefault(o(19)),C=a.__importDefault(o(17)),O=a.__importDefault(o(22)),f=a.__importDefault(o(2)),E=o(29),P=a.__importDefault(o(63)),y=o(14);function d(c){var u=c.statusCode;return u===408&&!c.code||u===400&&!c.code||u>=500&&u<=504}function h(c){var u=c.connection,l=u&&u.connectionManager.host;return l?[l].concat(S.default.getFallbackHosts(c.options)):S.default.getHosts(c.options)}var w=(i=function(){function c(u){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this._getHosts=h,this.options=u||{};var l=this.options.connectivityCheckUrl||S.default.connectivityCheckUrl,s=this.options.connectivityCheckParams,g=!this.options.connectivityCheckUrl;m.default.Config.xhrSupported?(this.supportsAuthHeaders=!0,this.Request=function(p,x,D,N,k,I,M){var A=C.default.createRequest(D,N,k,I,O.default.REQ_SEND,x&&x.options.timeouts,p);return A.once("complete",M),A.exec(),A},this.options.disableConnectivityCheck?this.checkConnectivity=function(p){p(null,!0)}:this.checkConnectivity=function(p){f.default.logAction(f.default.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+l),this.doUri(R.default.Get,null,l,null,null,s,function(x,D,N,k,I){var M=!1;g?M=!x&&(D==null?void 0:D.replace(/\n/,""))=="yes":M=!x&&(0,y.isSuccessCode)(I),f.default.logAction(f.default.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+M),p(null,M)})}):m.default.Config.jsonpSupported?(this.Request=function(p,x,D,N,k,I,M){var A=(0,E.createRequest)(D,N,k,I,O.default.REQ_SEND,x&&x.options.timeouts,p);return A.once("complete",M),m.default.Config.nextTick(function(){A.exec()}),A},this.options.disableConnectivityCheck?this.checkConnectivity=function(p){p(null,!0)}:this.checkConnectivity=function(p){var x=this,D=S.default.jsonpInternetUpUrl;if(this.checksInProgress){this.checksInProgress.push(p);return}this.checksInProgress=[p],f.default.logAction(f.default.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+D);var N=new E.Request("isTheInternetUp",D,null,null,null,O.default.REQ_SEND,S.default.TIMEOUTS);N.once("complete",function(k,I){var M=!k&&I;f.default.logAction(f.default.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+M);for(var A=0;A<x.checksInProgress.length;A++)x.checksInProgress[A](null,M);x.checksInProgress=null}),m.default.Config.nextTick(function(){N.exec()})}):m.default.Config.fetchSupported?(this.supportsAuthHeaders=!0,this.Request=P.default,this.checkConnectivity=function(p){f.default.logAction(f.default.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+l),this.doUri(R.default.Get,null,l,null,null,null,function(x,D){var N=!x&&(D==null?void 0:D.replace(/\n/,""))=="yes";f.default.logAction(f.default.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+N),p(null,N)})}):this.Request=function(p,x,D,N,k,I,M){M(new T.PartialErrorInfo("no supported HTTP transports available",null,400),null)}}return c.prototype.do=function(u,l,s,g,p,x,D){var N=this,k=typeof s=="function"?s:function(j){return l.baseUri(j)+s},I=l._currentFallback;if(I)if(I.validUntil>v.now()){if(!this.Request){D==null||D(new T.PartialErrorInfo("Request invoked before assigned to",null,500));return}this.Request(u,l,k(I.host),g,x,p,function(j){for(var U=[],z=1;z<arguments.length;z++)U[z-1]=arguments[z];if(j&&d(j)){l._currentFallback=null,N.do(u,l,s,g,p,x,D);return}D==null||D.apply(void 0,a.__spreadArray([j],U,!1))});return}else l._currentFallback=null;var M=h(l);if(M.length===1){this.doUri(u,l,k(M[0]),g,p,x,D);return}var A=function(j,U){var z=j.shift();N.doUri(u,l,k(z),g,p,x,function(W){for(var G=[],F=1;F<arguments.length;F++)G[F-1]=arguments[F];if(W&&d(W)&&j.length){A(j,!0);return}U&&(l._currentFallback={host:z,validUntil:v.now()+l.options.timeouts.fallbackRetryTimeout}),D==null||D.apply(void 0,a.__spreadArray([W],G,!1))})};A(M)},c.prototype.doUri=function(u,l,s,g,p,x,D){if(!this.Request){D(new T.PartialErrorInfo("Request invoked before assigned to",null,500));return}this.Request(u,l,s,g,x,p,D)},c}(),i.methods=[R.default.Get,R.default.Delete,R.default.Post,R.default.Put,R.default.Patch],i.methodsWithoutBody=[R.default.Get,R.default.Delete],i.methodsWithBody=[R.default.Post,R.default.Put,R.default.Patch],i);r.default=w},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importStar(o(4)),m=i.__importDefault(o(3)),v=i.__importDefault(o(8)),S=i.__importStar(o(1)),T=o(1);function R(f,E){return!!E.get("x-ably-errorcode")}function C(f,E){if(R(f,E))return f.error&&a.default.fromValues(f.error)}function O(f,E,P,y,d,h,w){var c=new Headers(y||{}),u=f?f.toUpperCase():S.isEmptyArg(h)?"GET":"POST",l=new AbortController,s=setTimeout(function(){l.abort(),w(new a.PartialErrorInfo("Request timed out",null,408))},E?E.options.timeouts.httpRequestTimeout:v.default.TIMEOUTS.httpRequestTimeout),g={method:u,headers:c,body:h};m.default.Config.isWebworker||(g.credentials=c.has("authorization")?"include":"same-origin"),(0,T.getGlobalObject)().fetch(P+"?"+new URLSearchParams(d||{}),g).then(function(p){clearTimeout(s);var x=p.headers.get("Content-Type"),D;x&&x.indexOf("application/x-msgpack")>-1?D=p.arrayBuffer():x&&x.indexOf("application/json")>-1?D=p.json():D=p.text(),D.then(function(N){var k=!!x&&x.indexOf("application/x-msgpack")===-1;if(p.ok)w(null,N,p.headers,k,p.status);else{var I=C(N,p.headers)||new a.PartialErrorInfo("Error response received from server: "+p.status+" body was: "+m.default.Config.inspect(N),null,p.status);w(I,N,p.headers,k,p.status)}})}).catch(function(p){clearTimeout(s),w(p)})}r.default=O},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(41)),m=i.__importStar(o(1)),v=m.getGlobalObject();typeof Window=="undefined"&&typeof WorkerGlobalScope=="undefined"&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function S(){var O=v.location;return!v.WebSocket||!O||!O.origin||O.origin.indexOf("http")>-1}var T=v.navigator&&v.navigator.userAgent.toString(),R=v.location&&v.location.href,C={agent:"browser",logTimestamps:!0,userAgent:T,currentUrl:R,noUpgrade:T&&!!T.match(/MSIE\s8\.0/),binaryType:"arraybuffer",WebSocket:v.WebSocket,fetchSupported:!!v.fetch,xhrSupported:v.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,jsonpSupported:typeof document!="undefined",allowComet:S(),streamingSupported:!0,useProtocolHeartbeats:!0,createHmac:null,msgpack:a.default,supportsBinary:!!v.TextDecoder,preferBinary:!1,ArrayBuffer:v.ArrayBuffer,atob:v.atob,nextTick:typeof v.setImmediate!="undefined"?v.setImmediate.bind(v):function(O){setTimeout(O,0)},addEventListener:v.addEventListener,inspect:JSON.stringify,stringByteSize:function(O){return v.TextDecoder&&new v.TextEncoder().encode(O).length||O.length},TextEncoder:v.TextEncoder,TextDecoder:v.TextDecoder,Promise:v.Promise,getRandomValues:function(O){if(O!==void 0)return function(f,E){O.getRandomValues(f),E&&E(null)}}(v.crypto||msCrypto)};r.default=C},function(n,r,o){(function(i){Object.defineProperty(r,"__esModule",{value:!0});var a=o(0),m=a.__importStar(o(1)),v="ablyjs-storage-test",S=function(){function T(){try{i.sessionStorage.setItem(v,v),i.sessionStorage.removeItem(v),this.sessionSupported=!0}catch(R){this.sessionSupported=!1}try{i.localStorage.setItem(v,v),i.localStorage.removeItem(v),this.localSupported=!0}catch(R){this.localSupported=!1}}return T.prototype.get=function(R){return this._get(R,!1)},T.prototype.getSession=function(R){return this._get(R,!0)},T.prototype.remove=function(R){return this._remove(R,!1)},T.prototype.removeSession=function(R){return this._remove(R,!0)},T.prototype.set=function(R,C,O){return this._set(R,C,O,!1)},T.prototype.setSession=function(R,C,O){return this._set(R,C,O,!0)},T.prototype._set=function(R,C,O,f){var E={value:C};return O&&(E.expires=m.now()+O),this.storageInterface(f).setItem(R,JSON.stringify(E))},T.prototype._get=function(R,C){if(C&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!C&&!this.localSupported)throw new Error("Local Storage not supported");var O=this.storageInterface(C).getItem(R);if(!O)return null;var f=JSON.parse(O);return f.expires&&f.expires<m.now()?(this.storageInterface(C).removeItem(R),null):f.value},T.prototype._remove=function(R,C){return this.storageInterface(C).removeItem(R)},T.prototype.storageInterface=function(R){return R?i.sessionStorage:i.localStorage},T}();r.default=new S}).call(this,o(13))},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i=o(0),a=i.__importDefault(o(67)),m={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",jsonpInternetUpUrl:"https://internet-up.ably-realtime.com/is-the-internet-up-0-9.js",defaultTransports:[a.default.XhrPolling,a.default.XhrStreaming,a.default.JsonP,a.default.WebSocket],baseTransportOrder:[a.default.XhrPolling,a.default.XhrStreaming,a.default.JsonP,a.default.WebSocket],transportPreferenceOrder:[a.default.JsonP,a.default.XhrPolling,a.default.XhrStreaming,a.default.WebSocket],upgradeTransports:[a.default.XhrStreaming,a.default.WebSocket]};r.default=m},function(n,r,o){Object.defineProperty(r,"__esModule",{value:!0});var i;(function(a){a.WebSocket="web_socket",a.Comet="comet",a.XhrStreaming="xhr_streaming",a.XhrPolling="xhr_polling",a.JsonP="jsonp"})(i||(i={})),r.default=i},function(n,r,o){o.r(r);var i=o(29),a=o.n(i),m=o(1),v=o(3),S=o.n(v),T=o(12),R=o.n(T),C=o(17),O=o.n(C),f=function(d){var h="xhr_polling";function w(c,u,l){l.stream=!1,R.a.call(this,c,u,l),this.shortName=h}return m.inherits(w,R.a),w.isAvailable=function(){return S.a.Config.xhrSupported&&S.a.Config.allowComet},w.prototype.toString=function(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected},w.prototype.createRequest=function(c,u,l,s,g){return O.a.createRequest(c,u,l,s,g,this.timeouts)},typeof d!="undefined"&&w.isAvailable()&&(d.supportedTransports[h]=w),w},E=f,P=function(d){var h="xhr_streaming";function w(c,u,l){R.a.call(this,c,u,l),this.shortName=h}return m.inherits(w,R.a),w.isAvailable=function(){return S.a.Config.xhrSupported&&S.a.Config.streamingSupported&&S.a.Config.allowComet},w.prototype.toString=function(){return"XHRStreamingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected},w.prototype.createRequest=function(c,u,l,s,g){return O.a.createRequest(c,u,l,s,g,this.timeouts)},typeof d!="undefined"&&w.isAvailable()&&(d.supportedTransports[h]=w),w},y=P;r.default=[a.a,E,y]}]).default})})(Zc);var Qh=Zc.exports;const Jh=Oe(Qh),ys=(e,t,n,r,o)=>dt(this,null,function*(){try{const i=new Jh.Realtime({token:e.token,clientId:e.clientId});i.connection.on("connected",()=>{o==null||o("connected")}),i.connection.on("failed",v=>{console.error("[❌ ABLY CONNECTION FAILED]",v),o==null||o("failed")}),i.connection.on("disconnected",()=>{o==null||o("disconnected")});const a=`room:${t}:${n}`,m=i.channels.get(a);return m.subscribe("messages",v=>{var S;try{const T=(S=v.data)==null?void 0:S.message;if(T&&T.role==="employee"){const R={id:T.id||Xt(),text:T.content||"",sender:"bot",timestamp:T.createdAt?new Date(T.createdAt):new Date};r(R)}}catch(T){console.error("[❌ MESSAGE PARSING ERROR]",T)}}),{client:i,channel:m}}catch(i){throw console.error("[❌ ABLY INITIALIZATION ERROR]",i),i}}),Yh=(e,t)=>dt(this,null,function*(){try{const n=Xc(),r=yield fetch(`${n}?conversationId=${e}&chatbotUid=${t}`);return r.ok?yield r.json():(console.error("Failed to fetch conversation data:",r.statusText),null)}catch(n){return console.error("[❌ ABLY TOKEN FETCH ERROR]",n),null}}),Xh=e=>{e&&e.close()},qc=()=>({id:Xt(),text:"Lo siento, hubo un problema con la conexión. Esta es una respuesta de demostración.",sender:"bot",timestamp:new Date().toISOString()}),Zh=(e,t,n,r)=>{const o=Kh(t,e),i={id:e,senderId:r||"unknown",createdAt:new Date().toISOString(),chatbotActivated:!0,updatedAt:new Date().toISOString(),source:"IFRAME",website:typeof window!="undefined"?window.location.origin:"",messages:o};return{conversationId:e,conversation:i,chatbotUid:n.apiKey}},qh=e=>dt(this,null,function*(){try{const t=Wh(),n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return n.ok?yield n.json():(console.error("WebChat: API request failed:",n.status,n.statusText),null)}catch(t){return console.error("WebChat: Error sending message to API:",t),null}}),ep=e=>{if(e&&e.content){let t;return e.createdAt?t=e.createdAt.endsWith("Z")?e.createdAt:`${e.createdAt}Z`:t=new Date().toISOString(),{id:e.id||Xt(),text:e.content,sender:"bot",timestamp:t}}return null},tp=e=>`¡Hola! Soy ${e||"tu asistente"}, ¿En qué te puedo ayudar?
91
91
 
92
92
  Aunque no lo creas, soy una inteligencia artificial! Puedo resolver todas tus dudas 😊
93
93
 
94
- También puedes pedir hablar con nuestro equipo de los sueños!`,np=e=>({id:Xt(),text:tp(e),sender:"bot",timestamp:new Date}),ef=()=>typeof window!="undefined"&&window.innerWidth<640,rp=({config:e})=>{e.apiKey||console.warn("WebChat: apiKey is required but not provided in config");const[t,n]=oe.useState(()=>Zo(e)),[r,o]=oe.useState(!1),[i,a]=oe.useState(()=>ef()),[m,v]=oe.useState(""),[S,T]=oe.useState(!1),[R,C]=oe.useState(!1),[O,f]=oe.useState(!1),[E,P]=oe.useState(""),[,y]=oe.useState(null),d=oe.useRef(null),[h,w]=oe.useState(!1),[c,u]=oe.useState(!1),[l,s]=oe.useState(""),[g,p]=oe.useState([e.initialMessage?{id:Xt(),text:e.initialMessage,sender:"bot",timestamp:new Date}:np(e.title)]),x=oe.useCallback((U,z="bot")=>{p(V=>[...V,U]),!r&&(U.sender==="bot"||z==="bot")&&U.id!==l&&w(!0)},[r,l]);oe.useEffect(()=>{const U=()=>{const z=ef();a(z)};return window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[]),oe.useEffect(()=>zh(()=>{n(Zo(e))}),[e]),oe.useEffect(()=>{n(Zo(e))},[e]),oe.useEffect(()=>{dt(this,null,function*(){const z=Qc();v(z);const V=yield Fh();P(V)})},[]),oe.useEffect(()=>{if(g.length>0){const U=g[g.length-1];U.sender==="bot"&&s(U.id)}},[]);const D=oe.useCallback(U=>{x(U,"ably")},[x]),N=oe.useCallback(U=>dt(this,null,function*(){if(!(c||d.current))try{if(U.tokenDetails){const z=yield ys(U.tokenDetails,e.apiKey||"",m,D);y(z),d.current=z.client,u(!0)}}catch(z){console.error("[❌ ABLY SETUP ERROR from history]",z)}}),[c,m,D]),k=oe.useCallback(()=>dt(this,null,function*(){if(!(c||d.current))try{const U=yield Yh(m,e.apiKey||"");if(U!=null&&U.tokenDetails){const z=yield ys(U.tokenDetails,e.apiKey||"",m,D);y(z),d.current=z.client,u(!0)}}catch(U){console.error("[❌ ABLY SETUP ERROR from endpoint]",U)}}),[c,m,e.apiKey,D]),I=oe.useCallback(()=>dt(this,null,function*(){var z,V;const U=r;if(o(G=>!G),!U){w(!1);const G=g.filter(F=>F.sender==="bot").slice(-1)[0];G&&s(G.id)}if(!U&&!S&&m&&Jc()&&!c){C(!0);const G=yield Vh(m,e.apiKey||"");if(((V=(z=G==null?void 0:G.conversation)==null?void 0:z.messages)==null?void 0:V.length)>0){const F=$h(G.conversation.messages);p(F);const b=F.filter(L=>L.sender==="bot").slice(-1)[0];b&&s(b.id),yield N(G)}else console.warn("WebChat: No conversation history found, showing initial message");C(!1),T(!0)}else!U&&Jc()&&!c?yield k():U||console.warn("WebChat: Chat opened - no existing conversation to fetch")}),[r,m,S,c,e.apiKey,N,k,g]),M=oe.useCallback(()=>{o(!1)},[]),A=oe.useCallback(U=>dt(this,null,function*(){const z={id:Xt(),text:U,sender:"user",timestamp:new Date};p(G=>[...G,z]),f(!0);const V=[...g,z];try{const G=Zh(m,V,{apiKey:e.apiKey||""},E),F=yield qh(G);if(F){if(F.response.tokenDetails&&!d.current){const L=yield ys(F.response.tokenDetails,e.apiKey||"",m,D);y(L),d.current=L.client,u(!0)}const b=ep(F.response.message);b&&x(b,"bot")}else{setTimeout(()=>{const b=qc();x(b,"bot"),f(!1)},1e3);return}}catch(G){console.error("WebChat: Error in message handling:",G),setTimeout(()=>{const F=qc();x(F,"bot"),f(!1)},1e3);return}f(!1),Bh(!0)}),[m,g,e.apiKey,E,D,x]),j=Hh(e);return oe.useEffect(()=>()=>{Xh(d.current),d.current=null},[]),J.jsxs("div",{className:"nbc-font-sans",style:{zIndex:2147483647},children:[J.jsx(bh,{isOpen:r,onClick:I,primaryColor:t.primaryColor,position:j.position,marginBottom:j.marginBottom,marginSide:j.marginSide,hasNewMessages:h,isMobile:i}),J.jsx(Lh,{isOpen:r,onClose:M,config:t,messages:g,onSendMessage:A,isLoading:R,isAiTyping:O,position:j.position,marginBottom:j.marginBottom,marginSide:j.marginSide,isMobile:i,apiKeyMissing:!e.apiKey})]})},op='*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.nbc-fixed{position:fixed}.nbc-absolute{position:absolute}.nbc-relative{position:relative}.nbc-inset-0{inset:0}.nbc-inset-auto{inset:auto}.nbc-right-0{right:0}.nbc-right-2{right:.5rem}.nbc-top-0{top:0}.nbc-top-1\\/2{top:50%}.nbc-m-0{margin:0}.nbc-mb-1{margin-bottom:.25rem}.nbc-mb-4{margin-bottom:1rem}.nbc-ml-2{margin-left:.5rem}.nbc-mt-1{margin-top:.25rem}.nbc-flex{display:flex}.nbc-hidden{display:none}.nbc-h-10{height:2.5rem}.nbc-h-16{height:4rem}.nbc-h-2{height:.5rem}.nbc-h-3{height:.75rem}.nbc-h-4{height:1rem}.nbc-h-5{height:1.25rem}.nbc-h-7{height:1.75rem}.nbc-h-8{height:2rem}.nbc-h-auto{height:auto}.nbc-h-full{height:100%}.nbc-min-h-\\[220px\\]{min-height:220px}.nbc-w-10{width:2.5rem}.nbc-w-16{width:4rem}.nbc-w-2{width:.5rem}.nbc-w-3{width:.75rem}.nbc-w-4{width:1rem}.nbc-w-5{width:1.25rem}.nbc-w-7{width:1.75rem}.nbc-w-8{width:2rem}.nbc-w-auto{width:auto}.nbc-w-full{width:100%}.nbc-max-w-xs{max-width:20rem}.nbc-flex-1{flex:1 1 0%}.nbc-flex-shrink-0{flex-shrink:0}.nbc--translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-translate-y-0{--tw-translate-y: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-translate-y-2{--tw-translate-y: .5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-scale-95{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes nbc-bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.nbc-animate-bounce{animation:nbc-bounce 1s infinite}@keyframes nbc-ping{75%,to{transform:scale(2);opacity:0}}.nbc-animate-ping{animation:nbc-ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes nbc-pulse{50%{opacity:.5}}.nbc-animate-pulse{animation:nbc-pulse 2s cubic-bezier(.4,0,.6,1) infinite}.nbc-cursor-pointer{cursor:pointer}.nbc-flex-col{flex-direction:column}.nbc-items-start{align-items:flex-start}.nbc-items-end{align-items:flex-end}.nbc-items-center{align-items:center}.nbc-justify-start{justify-content:flex-start}.nbc-justify-end{justify-content:flex-end}.nbc-justify-center{justify-content:center}.nbc-justify-between{justify-content:space-between}.nbc-gap-2{gap:.5rem}.nbc-space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.nbc-space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.nbc-space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.nbc-space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.nbc-overflow-hidden{overflow:hidden}.nbc-overflow-y-auto{overflow-y:auto}.nbc-whitespace-nowrap{white-space:nowrap}.nbc-whitespace-pre-wrap{white-space:pre-wrap}.nbc-break-words{overflow-wrap:break-word}.nbc-rounded{border-radius:.25rem}.nbc-rounded-2xl{border-radius:1rem}.nbc-rounded-full{border-radius:9999px}.nbc-rounded-lg{border-radius:.5rem}.nbc-rounded-none{border-radius:0}.nbc-rounded-bl-md{border-bottom-left-radius:.375rem}.nbc-rounded-br-md{border-bottom-right-radius:.375rem}.nbc-border-0{border-width:0px}.nbc-border-2{border-width:2px}.nbc-border-t{border-top-width:1px}.nbc-border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.nbc-border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.nbc-bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.nbc-bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.nbc-bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.nbc-bg-transparent{background-color:transparent}.nbc-bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.nbc-bg-none{background-image:none}.nbc-object-cover{-o-object-fit:cover;object-fit:cover}.nbc-p-0{padding:0}.nbc-p-1{padding:.25rem}.nbc-p-2{padding:.5rem}.nbc-p-4{padding:1rem}.nbc-px-2{padding-left:.5rem;padding-right:.5rem}.nbc-px-4{padding-left:1rem;padding-right:1rem}.nbc-py-3{padding-top:.75rem;padding-bottom:.75rem}.nbc-pr-12{padding-right:3rem}.nbc-pt-4{padding-top:1rem}.nbc-text-center{text-align:center}.nbc-text-right{text-align:right}.nbc-font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.nbc-text-\\[15px\\]{font-size:15px}.nbc-text-base{font-size:1rem;line-height:1.5rem}.nbc-text-lg{font-size:1.125rem;line-height:1.75rem}.nbc-text-sm{font-size:.875rem;line-height:1.25rem}.nbc-text-xs{font-size:.75rem;line-height:1rem}.nbc-font-bold{font-weight:700}.nbc-font-medium{font-weight:500}.nbc-leading-none{line-height:1}.nbc-leading-relaxed{line-height:1.625}.nbc-text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.nbc-text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.nbc-text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.nbc-text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.nbc-text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.nbc-opacity-0{opacity:0}.nbc-opacity-100{opacity:1}.nbc-opacity-50{opacity:.5}.nbc-opacity-70{opacity:.7}.nbc-opacity-75{opacity:.75}.nbc-shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-outline-none{outline:2px solid transparent;outline-offset:2px}.nbc-transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.nbc-transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.nbc-duration-200{transition-duration:.2s}.nbc-duration-300{transition-duration:.3s}.nbc-ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.hover\\:nbc-scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\\:nbc-bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\\:nbc-bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\\:nbc-bg-opacity-20:hover{--tw-bg-opacity: .2}.hover\\:nbc-text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.disabled\\:nbc-cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:nbc-opacity-50:disabled{opacity:.5}',ip={apiKey:"",primaryColor:"#111111",avatar:"",title:"ChatBot - NotChatBot",placeholder:"Escribe tu mensaje...",initialMessage:"¡Hola! ¿En qué puedo ayudarte?",position:"bottom-right",marginBottom:20,marginSide:20,mobile:{position:"bottom-right",marginBottom:15,marginSide:15},desktop:{position:"bottom-right",marginBottom:25,marginSide:25},closeButtonIcon:"default",closeButtonText:"Cerrar",closeButtonCustomIcon:""},ap=()=>{if(typeof document!="undefined"&&!document.getElementById("webchat-styles")){const t=document.createElement("style");t.id="webchat-styles",t.textContent=op,document.head.appendChild(t)}},tf=e=>{try{const t=yt(yt({elementId:"webchat-notchatbot"},ip),e);ap();const n=document.getElementById(t.elementId);if(!n)return console.error(`WebChat: Element with id "${t.elementId}" not found`),null;const r=Bc(n);return r.render(mf.createElement(rp,{config:t})),console.log("WebChat: Successfully initialized"),{root:r,destroy:()=>{r.unmount(),console.log("WebChat: Destroyed")},getConversationId:()=>Qc()}}catch(t){return console.error("WebChat: Failed to initialize",t),null}},nf={initialize:tf};if(typeof window!="undefined"){const e=()=>{let t=document.getElementById("webchat-notchatbot");t||(t=document.createElement("div"),t.id="webchat-notchatbot",document.body.appendChild(t)),tf()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}return typeof window!="undefined"&&(window.WebChat=nf),nf});
94
+ También puedes pedir hablar con nuestro equipo de los sueños!`,np=e=>({id:Xt(),text:tp(e),sender:"bot",timestamp:new Date().toISOString()}),ef=()=>typeof window!="undefined"&&window.innerWidth<640,rp=({config:e})=>{e.apiKey||console.warn("WebChat: apiKey is required but not provided in config");const[t,n]=oe.useState(()=>Zo(e)),[r,o]=oe.useState(!1),[i,a]=oe.useState(()=>ef()),[m,v]=oe.useState(""),[S,T]=oe.useState(!1),[R,C]=oe.useState(!1),[O,f]=oe.useState(!1),[E,P]=oe.useState(""),[,y]=oe.useState(null),d=oe.useRef(null),[h,w]=oe.useState(!1),[c,u]=oe.useState(!1),[l,s]=oe.useState(""),[g,p]=oe.useState([e.initialMessage?{id:Xt(),text:e.initialMessage,sender:"bot",timestamp:new Date().toISOString()}:np(e.title)]),x=oe.useCallback((U,z="bot")=>{p(W=>[...W,U]),!r&&(U.sender==="bot"||z==="bot")&&U.id!==l&&w(!0)},[r,l]);oe.useEffect(()=>{const U=()=>{const z=ef();a(z)};return window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[]),oe.useEffect(()=>zh(()=>{n(Zo(e))}),[e]),oe.useEffect(()=>{n(Zo(e))},[e]),oe.useEffect(()=>{dt(this,null,function*(){const z=Qc();v(z);const W=yield Fh();P(W)})},[]),oe.useEffect(()=>{if(g.length>0){const U=g[g.length-1];U.sender==="bot"&&s(U.id)}},[]);const D=oe.useCallback(U=>{x(U,"ably")},[x]),N=oe.useCallback(U=>dt(this,null,function*(){if(!(c||d.current))try{if(U.tokenDetails){const z=yield ys(U.tokenDetails,e.apiKey||"",m,D);y(z),d.current=z.client,u(!0)}}catch(z){console.error("[❌ ABLY SETUP ERROR from history]",z)}}),[c,m,D]),k=oe.useCallback(()=>dt(this,null,function*(){if(!(c||d.current))try{const U=yield Yh(m,e.apiKey||"");if(U!=null&&U.tokenDetails){const z=yield ys(U.tokenDetails,e.apiKey||"",m,D);y(z),d.current=z.client,u(!0)}}catch(U){console.error("[❌ ABLY SETUP ERROR from endpoint]",U)}}),[c,m,e.apiKey,D]),I=oe.useCallback(()=>dt(this,null,function*(){var z,W;const U=r;if(o(G=>!G),!U){w(!1);const G=g.filter(F=>F.sender==="bot").slice(-1)[0];G&&s(G.id)}if(!U&&!S&&m&&Jc()&&!c){C(!0);const G=yield Vh(m,e.apiKey||"");if(((W=(z=G==null?void 0:G.conversation)==null?void 0:z.messages)==null?void 0:W.length)>0){const F=$h(G.conversation.messages);p(F);const b=F.filter(L=>L.sender==="bot").slice(-1)[0];b&&s(b.id),yield N(G)}else console.warn("WebChat: No conversation history found, showing initial message");C(!1),T(!0)}else!U&&Jc()&&!c?yield k():U||console.warn("WebChat: Chat opened - no existing conversation to fetch")}),[r,m,S,c,e.apiKey,N,k,g]),M=oe.useCallback(()=>{o(!1)},[]),A=oe.useCallback(U=>dt(this,null,function*(){const z=new Date().toISOString(),W={id:Xt(),text:U,sender:"user",timestamp:z};p(F=>[...F,W]),f(!0);const G=[...g,W];try{const F=Zh(m,G,{apiKey:e.apiKey||""},E),b=yield qh(F);if(b){if(b.response.tokenDetails&&!d.current){const B=yield ys(b.response.tokenDetails,e.apiKey||"",m,D);y(B),d.current=B.client,u(!0)}const L=ep(b.response.message);L&&x(L,"bot")}else{setTimeout(()=>{const L=qc();x(L,"bot"),f(!1)},1e3);return}}catch(F){console.error("WebChat: Error in message handling:",F),setTimeout(()=>{const b=qc();x(b,"bot"),f(!1)},1e3);return}f(!1),Bh(!0)}),[m,g,e.apiKey,E,D,x]),j=Hh(e);return oe.useEffect(()=>()=>{Xh(d.current),d.current=null},[]),J.jsxs("div",{className:"nbc-font-sans",style:{zIndex:2147483647},children:[J.jsx(bh,{isOpen:r,onClick:I,primaryColor:t.primaryColor,position:j.position,marginBottom:j.marginBottom,marginSide:j.marginSide,hasNewMessages:h,isMobile:i}),J.jsx(Lh,{isOpen:r,onClose:M,config:t,messages:g,onSendMessage:A,isLoading:R,isAiTyping:O,position:j.position,marginBottom:j.marginBottom,marginSide:j.marginSide,isMobile:i,apiKeyMissing:!e.apiKey})]})},op='*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.nbc-fixed{position:fixed}.nbc-absolute{position:absolute}.nbc-relative{position:relative}.nbc-inset-0{inset:0}.nbc-inset-auto{inset:auto}.nbc-right-0{right:0}.nbc-right-2{right:.5rem}.nbc-top-0{top:0}.nbc-top-1\\/2{top:50%}.nbc-m-0{margin:0}.nbc-mb-1{margin-bottom:.25rem}.nbc-mb-4{margin-bottom:1rem}.nbc-ml-2{margin-left:.5rem}.nbc-mt-1{margin-top:.25rem}.nbc-flex{display:flex}.nbc-hidden{display:none}.nbc-h-10{height:2.5rem}.nbc-h-16{height:4rem}.nbc-h-2{height:.5rem}.nbc-h-3{height:.75rem}.nbc-h-4{height:1rem}.nbc-h-5{height:1.25rem}.nbc-h-7{height:1.75rem}.nbc-h-8{height:2rem}.nbc-h-auto{height:auto}.nbc-h-full{height:100%}.nbc-min-h-\\[220px\\]{min-height:220px}.nbc-w-10{width:2.5rem}.nbc-w-16{width:4rem}.nbc-w-2{width:.5rem}.nbc-w-3{width:.75rem}.nbc-w-4{width:1rem}.nbc-w-5{width:1.25rem}.nbc-w-7{width:1.75rem}.nbc-w-8{width:2rem}.nbc-w-auto{width:auto}.nbc-w-full{width:100%}.nbc-max-w-xs{max-width:20rem}.nbc-flex-1{flex:1 1 0%}.nbc-flex-shrink-0{flex-shrink:0}.nbc--translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-translate-y-0{--tw-translate-y: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-translate-y-2{--tw-translate-y: .5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-scale-95{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.nbc-transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes nbc-bounce{0%,to{transform:translateY(-25%);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:none;animation-timing-function:cubic-bezier(0,0,.2,1)}}.nbc-animate-bounce{animation:nbc-bounce 1s infinite}@keyframes nbc-ping{75%,to{transform:scale(2);opacity:0}}.nbc-animate-ping{animation:nbc-ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes nbc-pulse{50%{opacity:.5}}.nbc-animate-pulse{animation:nbc-pulse 2s cubic-bezier(.4,0,.6,1) infinite}.nbc-cursor-pointer{cursor:pointer}.nbc-flex-col{flex-direction:column}.nbc-items-start{align-items:flex-start}.nbc-items-end{align-items:flex-end}.nbc-items-center{align-items:center}.nbc-justify-start{justify-content:flex-start}.nbc-justify-end{justify-content:flex-end}.nbc-justify-center{justify-content:center}.nbc-justify-between{justify-content:space-between}.nbc-gap-2{gap:.5rem}.nbc-space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.nbc-space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.nbc-space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.nbc-space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.nbc-overflow-hidden{overflow:hidden}.nbc-overflow-y-auto{overflow-y:auto}.nbc-whitespace-nowrap{white-space:nowrap}.nbc-whitespace-pre-wrap{white-space:pre-wrap}.nbc-break-words{overflow-wrap:break-word}.nbc-rounded{border-radius:.25rem}.nbc-rounded-2xl{border-radius:1rem}.nbc-rounded-full{border-radius:9999px}.nbc-rounded-lg{border-radius:.5rem}.nbc-rounded-none{border-radius:0}.nbc-rounded-bl-md{border-bottom-left-radius:.375rem}.nbc-rounded-br-md{border-bottom-right-radius:.375rem}.nbc-border-0{border-width:0px}.nbc-border-2{border-width:2px}.nbc-border-t{border-top-width:1px}.nbc-border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.nbc-border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.nbc-bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.nbc-bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.nbc-bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.nbc-bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.nbc-bg-transparent{background-color:transparent}.nbc-bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.nbc-bg-none{background-image:none}.nbc-object-cover{-o-object-fit:cover;object-fit:cover}.nbc-p-0{padding:0}.nbc-p-1{padding:.25rem}.nbc-p-2{padding:.5rem}.nbc-p-4{padding:1rem}.nbc-px-2{padding-left:.5rem;padding-right:.5rem}.nbc-px-4{padding-left:1rem;padding-right:1rem}.nbc-py-3{padding-top:.75rem;padding-bottom:.75rem}.nbc-pr-12{padding-right:3rem}.nbc-pt-4{padding-top:1rem}.nbc-text-center{text-align:center}.nbc-text-right{text-align:right}.nbc-font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.nbc-text-\\[15px\\]{font-size:15px}.nbc-text-base{font-size:1rem;line-height:1.5rem}.nbc-text-lg{font-size:1.125rem;line-height:1.75rem}.nbc-text-sm{font-size:.875rem;line-height:1.25rem}.nbc-text-xs{font-size:.75rem;line-height:1rem}.nbc-font-bold{font-weight:700}.nbc-font-medium{font-weight:500}.nbc-leading-none{line-height:1}.nbc-leading-relaxed{line-height:1.625}.nbc-text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.nbc-text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.nbc-text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.nbc-text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.nbc-text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.nbc-opacity-0{opacity:0}.nbc-opacity-100{opacity:1}.nbc-opacity-50{opacity:.5}.nbc-opacity-70{opacity:.7}.nbc-opacity-75{opacity:.75}.nbc-shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.nbc-outline-none{outline:2px solid transparent;outline-offset:2px}.nbc-transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.nbc-transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.nbc-duration-200{transition-duration:.2s}.nbc-duration-300{transition-duration:.3s}.nbc-ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.hover\\:nbc-scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\\:nbc-bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\\:nbc-bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\\:nbc-bg-opacity-20:hover{--tw-bg-opacity: .2}.hover\\:nbc-text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.disabled\\:nbc-cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:nbc-opacity-50:disabled{opacity:.5}',ip={apiKey:"",primaryColor:"#111111",avatar:"",title:"ChatBot - NotChatBot",placeholder:"Escribe tu mensaje...",initialMessage:"¡Hola! ¿En qué puedo ayudarte?",position:"bottom-right",marginBottom:20,marginSide:20,mobile:{position:"bottom-right",marginBottom:15,marginSide:15},desktop:{position:"bottom-right",marginBottom:25,marginSide:25},closeButtonIcon:"default",closeButtonText:"Cerrar",closeButtonCustomIcon:""},ap=()=>{if(typeof document!="undefined"&&!document.getElementById("webchat-styles")){const t=document.createElement("style");t.id="webchat-styles",t.textContent=op,document.head.appendChild(t)}},tf=e=>{try{const t=yt(yt({elementId:"webchat-notchatbot"},ip),e);ap();const n=document.getElementById(t.elementId);if(!n)return console.error(`WebChat: Element with id "${t.elementId}" not found`),null;const r=Bc(n);return r.render(mf.createElement(rp,{config:t})),console.log("WebChat: Successfully initialized"),{root:r,destroy:()=>{r.unmount(),console.log("WebChat: Destroyed")},getConversationId:()=>Qc()}}catch(t){return console.error("WebChat: Failed to initialize",t),null}},nf={initialize:tf};if(typeof window!="undefined"){const e=()=>{let t=document.getElementById("webchat-notchatbot");t||(t=document.createElement("div"),t.id="webchat-notchatbot",document.body.appendChild(t)),tf()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}return typeof window!="undefined"&&(window.WebChat=nf),nf});