@forgebuild/hotal-ui 0.23.156 → 0.23.202
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/ai-chat-widget.js +75 -0
- package/dist/components/availability-calendar.js +7 -0
- package/dist/components/booking-card.js +30 -0
- package/dist/components/booking-checkout.js +40 -0
- package/dist/components/booking-confirmed.js +1 -0
- package/dist/components/booking-flow.js +26 -0
- package/dist/components/booking-progress-bar.js +1 -0
- package/dist/components/booking-summary.js +14 -0
- package/dist/components/chunks/ably-5cVT4knS.js +9 -0
- package/dist/components/chunks/calendar-B8eNjUm2.js +1 -0
- package/dist/components/chunks/client-BDk8LqGN.js +3 -0
- package/dist/components/chunks/floating-ui.dom-DY3dGoEq.js +1 -0
- package/dist/components/chunks/gsap-DWxn8li7.js +1 -0
- package/dist/components/chunks/lib-Bd4dedte.js +1 -0
- package/dist/components/chunks/min-DdO-yBwh.js +17 -0
- package/dist/components/chunks/preload-helper-Czpn1I53.js +1 -0
- package/dist/components/chunks/rolldown-runtime-CbXtAM7H.js +1 -0
- package/dist/components/confirmation-card.js +3 -0
- package/dist/components/dining-teaser.js +19 -0
- package/dist/components/event-contact-form.js +33 -0
- package/dist/components/event-inquiries-feed.js +29 -0
- package/dist/components/extras-catalogue.js +25 -0
- package/dist/components/floor-plan-hero.js +2 -0
- package/dist/components/google-reviews.js +31 -0
- package/dist/components/instagram-feed.js +16 -0
- package/dist/components/island-map.js +1 -0
- package/dist/components/live-dining-orders-feed.js +37 -0
- package/dist/components/live-golf-bookings-feed.js +18 -0
- package/dist/components/live-reservations-feed.js +18 -0
- package/dist/components/live-room-bookings-feed.js +18 -0
- package/dist/components/live-shop-orders-feed.js +37 -0
- package/dist/components/live-spa-bookings-feed.js +55 -0
- package/dist/components/menu-section.js +90 -0
- package/dist/components/proshop-catalogue.js +20 -0
- package/dist/components/reservation-bar.js +5 -0
- package/dist/components/reservation-cancel.js +4 -0
- package/dist/components/restaurant-order-form.js +9 -0
- package/dist/components/room-grid.js +26 -0
- package/dist/components/searchable-select.js +20 -0
- package/dist/components/service-booking-bar.js +14 -0
- package/dist/components/spa-booking-widget.js +198 -0
- package/dist/components/stay-search.js +31 -0
- package/dist/components/tripadvisor-reviews.js +38 -0
- package/dist/components/venue-carousel.js +18 -0
- package/dist/hotal-ui.js +5004 -4714
- package/dist/index.d.ts +35 -3
- package/package.json +6 -2
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-CbXtAM7H.js";var t=e(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.Ably=r():n.Ably=r()})(e,()=>{var e={},t={exports:e},n=Object.defineProperty,r=Object.defineProperties,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyDescriptors,o=Object.getOwnPropertyNames,s=Object.getOwnPropertySymbols,c=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable,u=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,d=(e,t)=>{for(var n in t||={})c.call(t,n)&&u(e,n,t[n]);if(s)for(var n of s(t))l.call(t,n)&&u(e,n,t[n]);return e},f=(e,t)=>r(e,a(t)),p=(e,t)=>{var n={};for(var r in e)c.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&s)for(var r of s(e))t.indexOf(r)<0&&l.call(e,r)&&(n[r]=e[r]);return n},ee=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},m=(e,t,r,a)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==r&&n(e,s,{get:()=>t[s],enumerable:!(a=i(t,s))||a.enumerable});return e},te=e=>m(n({},`__esModule`,{value:!0}),e),ne=function(e,t){this[0]=e,this[1]=t},re=(e,t,n)=>{var r=(e,t,i,a)=>{try{var o=n[e](t),s=(t=o.value)instanceof ne,c=o.done;Promise.resolve(s?t[0]:t).then(n=>s?r(e===`return`?e:`next`,t[1]?{done:n.done,value:n.value}:n,i,a):i({value:n,done:c})).catch(e=>r(`throw`,e,i,a))}catch(e){a(e)}},i=e=>a[e]=t=>new Promise((n,i)=>r(e,t,n,i)),a={};return n=n.apply(e,t),a[Symbol.asyncIterator]=()=>a,i(`next`),i(`throw`),i(`return`),a},ie={};ee(ie,{ErrorInfo:()=>v,Realtime:()=>ci,Rest:()=>Ar,default:()=>Sa,makeProtocolMessageFromDeserialized:()=>br,msgpack:()=>ha}),t.exports=te(ie);var h=class{},ae=typeof global<`u`?global:typeof window<`u`?window:self;function oe(e,t){return`${e}`.padStart(t?3:2,`0`)}function se(e){return h.Config.logTimestamps?function(t){let n=new Date(h.Config.now());e(oe(n.getHours())+`:`+oe(n.getMinutes())+`:`+oe(n.getSeconds())+`.`+oe(n.getMilliseconds(),1)+` `+t)}:function(t){e(t)}}var ce=()=>{let e,t;return typeof ae?.console?.log==`function`?(e=function(...e){console.log.apply(console,e)},t=console.warn?function(...e){console.warn.apply(console,e)}:e):e=t=function(){},[e,t].map(se)},g=class e{constructor(){this.deprecated=(e,t)=>{this.deprecationWarning(`${e} is deprecated and will be removed in a future version. ${t}`)},this.shouldLog=e=>e<=this.logLevel,this.setLog=(e,t)=>{e!==void 0&&(this.logLevel=e),t!==void 0&&(this.logHandler=this.logErrorHandler=t)},this.logLevel=e.defaultLogLevel,this.logHandler=e.defaultLogHandler,this.logErrorHandler=e.defaultLogErrorHandler}static initLogHandlers(){let[t,n]=ce();this.defaultLogHandler=t,this.defaultLogErrorHandler=n,this.defaultLogger=new e}static logActionNoStrip(e,t,n,r){e.logAction(t,n,r)}static silentFailureLogSuffix(){return` This call currently fails silently because clientOptions.strictMode is not enabled. A future major version will make this call fail with an error. Set clientOptions.strictMode: true to make this call reject with an error now.`}logAction(e,t,n){this.shouldLog(e)&&(e===1?this.logErrorHandler:this.logHandler)(`Ably: `+t+`: `+n,e)}renamedClientOption(e,t){this.deprecationWarning(`The \`${e}\` client option has been renamed to \`${t}\`. Please update your code to use \`${t}\` instead. \`${e}\` will be removed in a future version.`)}renamedMethod(e,t,n){this.deprecationWarning(`\`${e}\`\u2019s \`${t}\` method has been renamed to \`${n}\`. Please update your code to use \`${n}\` instead. \`${t}\` will be removed in a future version.`)}deprecationWarning(e){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${e}`,1)}};g.defaultLogLevel=1,g.LOG_NONE=0,g.LOG_ERROR=1,g.LOG_MAJOR=2,g.LOG_MINOR=3,g.LOG_MICRO=4,g.logAction=(e,t,n,r)=>{g.logActionNoStrip(e,t,n,r)};var _=g,le={};ee(le,{Format:()=>ke,allSame:()=>Oe,allToLowerCase:()=>Be,allToUpperCase:()=>Ve,arrChooseN:()=>ze,arrDeleteValue:()=>Ce,arrEquals:()=>Ye,arrIntersect:()=>xe,arrIntersectOb:()=>Se,arrPopRandomElement:()=>Ae,arrWithoutValue:()=>we,cheapRandStr:()=>Le,containsValue:()=>ye,copy:()=>fe,createMissingPluginError:()=>Xe,dataSizeBytes:()=>Ie,decodeBody:()=>T,detectV1Callback:()=>S,encodeBody:()=>E,ensureArray:()=>pe,forInOwnNonNullProperties:()=>De,getBackoffCoefficient:()=>He,getGlobalObject:()=>Ge,getJitterCoefficient:()=>Ue,getRetryTime:()=>We,inherits:()=>ve,inspectBody:()=>Fe,inspectError:()=>C,intersect:()=>be,isEmpty:()=>he,isErrorInfoOrPartialErrorInfo:()=>Pe,isNil:()=>x,isObject:()=>me,keysArray:()=>Te,listenerToAsyncIterator:()=>Qe,matchDerivedChannel:()=>qe,mixin:()=>b,parseQueryString:()=>Ne,prototypicalClone:()=>_e,randomString:()=>Re,shallowClone:()=>ge,shallowEquals:()=>Ke,stringifyValues:()=>Me,throwMissingPluginError:()=>D,toBase64:()=>Je,toQueryString:()=>je,valuesArray:()=>Ee,whenPromiseSettles:()=>w,withTimeoutAsync:()=>Ze});function ue(e){let t=`[`+e.constructor.name;return e.message&&(t+=`: `+e.message),e.statusCode&&(t+=`; statusCode=`+e.statusCode),e.code&&(t+=`; code=`+e.code),e.cause&&(t+=`; cause=`+C(e.cause)),e.remediation&&(t+=`; remediation=`+e.remediation),e.detail&&Object.keys(e.detail).length>0&&(t+=`; detail=`+JSON.stringify(e.detail)),e.href&&!(e.message&&e.message.indexOf(`help.ably.io`)>-1)&&(t+=`; see `+e.href+` `),t+=`]`,t}var v=class e extends Error{constructor(t,n,r,i,a){var o=(...e)=>{super(...e)};if(typeof t==`object`){let n=t;if(typeof n.message!=`string`||typeof n.code!=`number`||typeof n.statusCode!=`number`||!x(n.detail)&&(typeof n.detail!=`object`||Array.isArray(n.detail)))throw Error(`ErrorInfo: invalid values: `+h.Config.inspect(n));o(n.message),Object.setPrototypeOf!==void 0&&Object.setPrototypeOf(this,e.prototype),this.code=n.code,this.statusCode=n.statusCode,this.detail=n.detail,Object.assign(this,n)}else o(t),Object.setPrototypeOf!==void 0&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=r,this.cause=i,this.detail=a}toString(){return ue(this)}static fromValues(t){let n=new e(t);return n.code&&!n.href&&(n.href=`https://help.ably.io/error/`+n.code),n}},y=class e extends Error{constructor(t,n,r,i,a){var o=(...e)=>{super(...e)};if(typeof t==`object`){let n=t;if(typeof n.message!=`string`||!x(n.code)&&typeof n.code!=`number`||!x(n.statusCode)&&typeof n.statusCode!=`number`||!x(n.detail)&&(typeof n.detail!=`object`||Array.isArray(n.detail)))throw Error(`PartialErrorInfo: invalid values: `+h.Config.inspect(n));o(n.message),Object.setPrototypeOf!==void 0&&Object.setPrototypeOf(this,e.prototype),this.code=n.code,this.statusCode=n.statusCode,this.detail=n.detail,Object.assign(this,n)}else o(t),Object.setPrototypeOf!==void 0&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=r,this.cause=i,this.detail=a}toString(){return ue(this)}static fromValues(t){let n=new e(t);return n.code&&!n.href&&(n.href=`https://help.ably.io/error/`+n.code),n}};function de(e){return Math.floor(Math.random()*e.length)}function b(e,...t){for(let n=0;n<t.length;n++){let r=t[n];if(!r)break;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=r[t])}return e}function fe(e){return b({},e)}function pe(e){return x(e)?[]:Array.isArray(e)?e:[e]}function me(e){return Object.prototype.toString.call(e)==`[object Object]`}function he(e){for(let t in e)return!1;return!0}function x(e){return e==null}function ge(e){let t={};for(let n in e)t[n]=e[n];return t}function _e(e,t){class n{}n.prototype=e;let r=new n;return t&&b(r,t),r}var ve=function(e,t){if(h.Config.inherits){h.Config.inherits(e,t);return}e.super_=t,e.prototype=_e(t.prototype,{constructor:e})};function ye(e,t){for(let n in e)if(e[n]==t)return!0;return!1}function be(e,t){return Array.isArray(t)?xe(e,t):Se(e,t)}function xe(e,t){let n=[];for(let r=0;r<e.length;r++){let i=e[r];t.indexOf(i)!=-1&&n.push(i)}return n}function Se(e,t){let n=[];for(let r=0;r<e.length;r++){let i=e[r];i in t&&n.push(i)}return n}function Ce(e,t){let n=e.indexOf(t),r=n!=-1;return r&&e.splice(n,1),r}function we(e,t){let n=e.slice();return Ce(n,t),n}function Te(e,t){let n=[];for(let r in e)t&&!Object.prototype.hasOwnProperty.call(e,r)||n.push(r);return n}function Ee(e,t){let n=[];for(let r in e)t&&!Object.prototype.hasOwnProperty.call(e,r)||n.push(e[r]);return n}function De(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function Oe(e,t){if(e.length===0)return!0;let n=e[0][t];return e.every(function(e){return e[t]===n})}var ke=(e=>(e.msgpack=`msgpack`,e.json=`json`,e))(ke||{});function Ae(e){return e.splice(de(e),1)[0]}function je(e){let t=[];if(e)for(let n in e)t.push(encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t.length?`?`+t.join(`&`):``}function Me(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function Ne(e){let t,n=/([^?&=]+)=?([^&]*)/g,r={};for(;t=n.exec(e);)r[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return r}function Pe(e){return typeof e==`object`&&!!e&&(e instanceof v||e instanceof y)}function S(e,t){let n=e.length;if(typeof e[n-1]==`function`&&!(n<=t&&typeof e[n-2]!=`function`))throw new v({message:`v1 callback signature is no longer supported: v2 methods return a promise.`,code:40025,statusCode:400,remediation:"Drop the trailing callback and `await` the returned promise. See https://github.com/ably/ably-js/blob/main/docs/migration-guides/v2/lib.md."})}function C(e){return e instanceof Error||e?.constructor?.name===`ErrorInfo`||e?.constructor?.name===`PartialErrorInfo`?e.toString():h.Config.inspect(e)}function Fe(e){return h.BufferUtils.isBuffer(e)?e.toString():typeof e==`string`?e:h.Config.inspect(e)}function Ie(e){if(h.BufferUtils.isBuffer(e))return h.BufferUtils.byteLength(e);if(typeof e==`string`)return h.Config.stringByteSize(e);if(typeof e==`number`)return 8;if(typeof e==`boolean`)return 1;throw Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof e}`)}function Le(){return String(Math.random()).substr(2)}var Re=async e=>{let t=await h.Config.getRandomArrayBuffer(e);return h.BufferUtils.base64Encode(t)};function ze(e,t){let n=Math.min(t,e.length),r=e.slice(),i=[];for(let e=0;e<n;e++)i.push(Ae(r));return i}function w(e,t){e.then(e=>{t?.(null,e)}).catch(e=>{t?.(e)})}function T(e,t,n){return n==`msgpack`?(t||D(`MsgPack`),t.decode(e)):JSON.parse(String(e))}function E(e,t,n){return n==`msgpack`?(t||D(`MsgPack`),t.encode(e,!0)):JSON.stringify(e)}function Be(e){return e.map(function(e){return e&&e.toLowerCase()})}function Ve(e){return e.map(function(e){return e&&e.toUpperCase()})}function He(e){return Math.min((e+2)/3,2)}function Ue(){return 1-Math.random()*.2}function We(e,t){return e*He(t)*Ue()}function Ge(){return typeof global<`u`?global:typeof window<`u`?window:self}function Ke(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function qe(e){let t=e.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!t||!t.length||t.length<5)throw new v({message:`Channel name is empty or could not be parsed`,code:40010,statusCode:400,remediation:`Pass a non-empty channel name to channels.getDerived(name, { filter: ... }) and put the filter expression in the filter option, not in the name. A channel-params prefix such as "[?rewind=1]foo" is allowed. See https://ably.com/docs/channels#derived.`});if(t[2])throw new v({message:`cannot use a derived option with a ${t[2]} channel`,code:40010,statusCode:400,remediation:`Use a base channel name instead, without the "${t[2]}" qualifier.`});return{qualifierParam:t[3]||``,channelName:t[4]}}function Je(e){let t=h.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function Ye(e,t){return e.length===t.length&&e.every(function(e,n){return e===t[n]})}function Xe(e){let t;switch(e){case`Push`:t=`Import Push from "ably/push" and pass it in ClientOptions.plugins: { Push }.`;break;case`LiveObjects`:t=`Import { LiveObjects } from "ably/liveobjects" and pass it in ClientOptions.plugins: { LiveObjects }.`;break;default:t=`Import ${e} from "ably/modular" and pass it in ClientOptions.plugins: { ${e} }. See the modular variant reference at https://sdk.ably.com/builds/ably/ably-js/main/typedoc/modules/modular.html.`}return new v({message:`${e} plugin not provided`,code:40019,statusCode:400,remediation:t})}function D(e){throw Xe(e)}async function Ze(e,t=5e3,n=`Timeout expired`){let r=new v(n,5e4,500);return Promise.race([e,new Promise((e,n)=>h.Config.setTimeout(()=>n(r),t))])}function Qe(e){return re(this,null,function*(){let t=[],n=null,r=e(e=>{if(n){let t=n;n=null,t(e)}else t.push(e)});try{for(;;)if(t.length>0)yield t.shift();else{if(n)throw new v({message:`Concurrent next() calls are not supported`,code:4e4,statusCode:400,remediation:`Drive the async iterator from a single for-await-of loop.`});yield yield new ne(new Promise(e=>{n=e}))}}finally{r()}})}var $e=`2.27.0`,O={ENDPOINT:`main`,ENVIRONMENT:``,REST_HOST:`rest.ably.io`,REALTIME_HOST:`realtime.ably.io`,FALLBACK_HOSTS:[`main.a.fallback.ably-realtime.com`,`main.b.fallback.ably-realtime.com`,`main.c.fallback.ably-realtime.com`,`main.d.fallback.ably-realtime.com`,`main.e.fallback.ably-realtime.com`],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:$e,protocolVersion:6,agent:`ably-js/`+$e,getPort:et,getHttpScheme:tt,getPrimaryDomainFromEndpoint:rt,getEndpointFallbackHosts:it,getFallbackHosts:ot,getHosts:st,checkHost:ct,objectifyOptions:dt,normaliseOptions:pt,defaultGetHeaders:_t,defaultPostHeaders:vt};function et(e,t){return t||e.tls?e.tlsPort:e.port}function tt(e){return e.tls?`https://`:`http://`}function nt(e){return e.includes(`.`)||e.includes(`::`)||e===`localhost`}function rt(e){return nt(e)?e:e.startsWith(`nonprod:`)?`${e.replace(`nonprod:`,``)}.realtime.ably-nonprod.net`:`${e}.realtime.ably.net`}function it(e){return nt(e)?[]:e.startsWith(`nonprod:`)?at(e.replace(`nonprod:`,``),`ably-realtime-nonprod.com`):at(e,`ably-realtime.com`)}function at(e,t){return[`a`,`b`,`c`,`d`,`e`].map(n=>`${e}.${n}.fallback.${t}`)}function ot(e){let t=e.fallbackHosts,n=e.httpMaxRetryCount===void 0?O.httpMaxRetryCount:e.httpMaxRetryCount;return t?ze(t,n):[]}function st(e){return[e.primaryDomain].concat(ot(e))}function ct(e){if(typeof e!=`string`)throw new v({message:`host must be a string: was of type `+typeof e,code:4e4,statusCode:400,remediation:"Make every entry of `fallbackHosts` a string. If you set `restHost` or `realtimeHost`, pass each as a single string, not an array or object."});if(!e.length)throw new v({message:"host must not be zero-length: an entry of `fallbackHosts` is an empty string",code:4e4,statusCode:400,remediation:"Remove any empty-string entry from the `fallbackHosts` array."})}function lt(e){let t={};for(let n in O.TIMEOUTS)t[n]=e[n]||O.TIMEOUTS[n];return t}function ut(e){let t=O.agent;if(e.agents)for(var n in e.agents)t+=` `+n+`/`+e.agents[n];return t}function dt(e,t,n,r,i){if(e===void 0){let e=t?`${n} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${n} must be initialized with a client options object`;throw _.logAction(r,_.LOG_ERROR,`${n}()`,e),Error(e)}let a;if(typeof e==`string`){if(e.indexOf(`:`)==-1){if(!t){let e=`${n} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw _.logAction(r,_.LOG_ERROR,`${n}()`,e),Error(e)}a={token:e}}else{if(!t){let e=`${n} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw _.logAction(r,_.LOG_ERROR,`${n}()`,e),Error(e)}a={key:e}}}else a=e;return i&&(a=f(d({},a),{plugins:d(d({},i),a.plugins)})),a}function ft(e){if(e.endpoint&&(e.environment||e.restHost||e.realtimeHost))throw new v({message:"The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",code:40106,statusCode:400,remediation:"Remove `environment`, `restHost`, and `realtimeHost` from `ClientOptions` and use only `endpoint`, which replaces them."});if(e.environment&&(e.restHost||e.realtimeHost))throw new v({message:"The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",code:40106,statusCode:400,remediation:"Remove `environment`, `restHost`, and `realtimeHost` from `ClientOptions` and use only `endpoint`, which replaces them."})}function pt(e,t,n){let r=n??_.defaultLogger;e.environment&&r.deprecated("The `environment` client option","Use the `endpoint` client option instead."),e.restHost&&r.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),e.realtimeHost&&r.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),ft(e),typeof e.recover==`function`&&e.closeOnUnload===!0&&(_.logAction(r,_.LOG_ERROR,`Defaults.normaliseOptions`,`closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter`),e.recover=void 0),`closeOnUnload`in e||(e.closeOnUnload=!e.recover),`queueMessages`in e||(e.queueMessages=!0);let i=e.endpoint||O.ENDPOINT;!e.fallbackHosts&&!e.restHost&&!e.realtimeHost&&!e.port&&!e.tlsPort&&(e.fallbackHosts=it(e.environment||i));let a=e.environment&&`${e.environment}.realtime.ably.net`,o=e.restHost||e.realtimeHost||a||rt(i);(e.fallbackHosts||[]).concat(o).forEach(ct),e.port=e.port||O.PORT,e.tlsPort=e.tlsPort||O.TLS_PORT,`tls`in e||(e.tls=!0);let s=lt(e);e.useBinaryProtocol=t?`useBinaryProtocol`in e?h.Config.supportsBinary&&e.useBinaryProtocol:h.Config.preferBinary:!1;let c={};e.clientId&&(c[`X-Ably-ClientId`]=h.BufferUtils.base64Encode(h.BufferUtils.utf8Encode(e.clientId))),`idempotentRestPublishing`in e||(e.idempotentRestPublishing=!0);let l=null,u=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[t,n]=e.connectivityCheckUrl.split(`?`);l=n?Ne(n):{},t.indexOf(`://`)===-1&&(t=`https://`+t),u=t}let p=e.wsConnectivityCheckUrl;return p&&p.indexOf(`://`)===-1&&(p=`wss://`+p),f(d({},e),{primaryDomain:o,maxMessageSize:e.maxMessageSize||O.maxMessageSize,timeouts:s,connectivityCheckParams:l,connectivityCheckUrl:u,wsConnectivityCheckUrl:p,headers:c})}function mt(e,t,n){let r=n||{};if(r.cipher){e||D(`Crypto`);let n=e.getCipher(r.cipher,t);r.cipher=n.cipherParams,r.channelCipher=n.cipher}else`cipher`in r&&(r.cipher=void 0,r.channelCipher=null);return r}var ht={json:`application/json`,xml:`application/xml`,html:`text/html`,msgpack:`application/x-msgpack`,text:`text/plain`},gt={format:`json`,protocolVersion:O.protocolVersion};function _t(e,{format:t,protocolVersion:n=gt.protocolVersion}={}){return{accept:ht[t??(e.useBinaryProtocol?`msgpack`:`json`)],"X-Ably-Version":n.toString(),"Ably-Agent":ut(e)}}function vt(e,{format:t,protocolVersion:n=gt.protocolVersion}={}){let r=ht[t??(e.useBinaryProtocol?`msgpack`:`json`)];return{accept:r,"content-type":r,"X-Ably-Version":n.toString(),"Ably-Agent":ut(e)}}var k=O;function yt(e){return Object.assign(O,e)}var bt=class e{constructor(e,t){this.logger=e,this.members=t||[]}call(e,t){for(let n of this.members)if(n)try{n(e,t)}catch(e){_.logAction(this.logger,_.LOG_ERROR,`Multicaster multiple callback handler`,`Unexpected exception: `+e+`; stack = `+e.stack)}}push(...e){this.members.push(...e)}createPromise(){return new Promise((e,t)=>{this.push((n,r)=>{n?t(n):e(r)})})}resolveAll(e){this.call(null,e)}rejectAll(e){this.call(e)}static create(t,n){let r=new e(t,n);return Object.assign((e,t)=>r.call(e,t),{push:e=>r.push(e),createPromise:()=>r.createPromise(),resolveAll:e=>r.resolveAll(e),rejectAll:e=>r.rejectAll(e)})}},xt=(e=>(e.Get=`get`,e.Delete=`delete`,e.Post=`post`,e.Put=`put`,e.Patch=`patch`,e))(xt||{}),A=xt,St=(e=>(e[e.Success=200]=`Success`,e[e.NoContent=204]=`NoContent`,e[e.BadRequest=400]=`BadRequest`,e[e.Unauthorized=401]=`Unauthorized`,e[e.Forbidden=403]=`Forbidden`,e[e.RequestTimeout=408]=`RequestTimeout`,e[e.InternalServerError=500]=`InternalServerError`,e))(St||{});function Ct(e){return e>=200&&e<400}var wt=St,Tt=2**17;function Et(){return(`000000`+Math.floor(Math.random()*0x2386f26fc10000)).slice(-16)}function Dt(e){return!!e.connection}function Ot(e){return Pe(e)?(e.code||(e.statusCode===403?e.code=40300:(e.code=40170,e.statusCode=401)),e):new v(C(e),e.code||40170,e.statusCode||401)}var kt=(e,t)=>{let n=h.BufferUtils,r=n.utf8Encode(e),i=n.utf8Encode(t),a=n.hmacSha256(r,i);return n.base64Encode(a)};function At(e){if(!e)return``;typeof e==`string`&&(e=JSON.parse(e));let t=Object.create(null),n=Te(e,!0);if(!n)return``;n.sort();for(let r=0;r<n.length;r++)t[n[r]]=e[n[r]].sort();return JSON.stringify(t)}function jt(e,t){if(e.authCallback)_.logAction(t,_.LOG_MINOR,`Auth()`,`using token auth with authCallback`);else if(e.authUrl)_.logAction(t,_.LOG_MINOR,`Auth()`,`using token auth with authUrl`);else if(e.key)_.logAction(t,_.LOG_MINOR,`Auth()`,`using token auth with client-side signing`);else if(e.tokenDetails)_.logAction(t,_.LOG_MINOR,`Auth()`,`using token auth with supplied token only`);else{let e=`authOptions must include valid authentication parameters`;throw _.logAction(t,_.LOG_ERROR,`Auth()`,e),new v(e,40106,401)}}function Mt(e){return`useTokenAuth`in e&&!e.useTokenAuth}function Nt(e){return e.useTokenAuth||!Mt(e)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}function Pt(e){return!e.key&&!e.authCallback&&!e.authUrl}var Ft=0;function It(){return Ft++}var j=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,Nt(t))Pt(t)&&_.logAction(this.logger,_.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(t.defaultTokenParams,t),jt(this.authOptions,this.logger);else{if(!t.key){let e=`No authentication options provided`;throw _.logAction(this.logger,_.LOG_ERROR,`Auth()`,e),new v({message:e,code:40106,statusCode:401,remediation:`Set one of the following in ClientOptions: key, authUrl, authCallback, token, or tokenDetails. For production use, prefer authUrl or authCallback for client-side (browser, mobile apps), or key for server-side.`})}_.logAction(this.logger,_.LOG_MINOR,`Auth()`,`anonymous, using basic auth`),this._saveBasicOptions(t)}}get logger(){return this.client.logger}authorize(...e){return S(e,0),this._authorizeImpl(e[0],e[1])}async _authorizeImpl(e,t){if(t&&t.key&&this.authOptions.key!==t.key)throw new v({message:`authorize called with a key that does not match the existing key being used by the client`,code:40102,statusCode:401,remediation:`To use a different key, construct a new Ably client with the key as a client option.`});try{let n=await this._forceNewToken(e??null,t??null);return Dt(this.client)?new Promise((e,t)=>{this.client.connection.connectionManager.onAuthUpdated(n,(n,r)=>n?t(n):e(r))}):n}catch(e){throw this.client.connection&&e.statusCode===wt.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(e),e}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),jt(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}requestToken(...e){return S(e,0),this._requestTokenImpl(e[0],e[1])}async _requestTokenImpl(e,t){let n=t||this.authOptions,r=e||fe(this.tokenParams),i,a=this.client;if(n.authCallback)_.logAction(this.logger,_.LOG_MINOR,`Auth.requestToken()`,`using token auth with authCallback`),i=n.authCallback;else if(n.authUrl)_.logAction(this.logger,_.LOG_MINOR,`Auth.requestToken()`,`using token auth with authUrl`),i=(e,t)=>{let r=b({accept:`application/json, text/plain`},n.authHeaders),i=n.authMethod&&n.authMethod.toLowerCase()===`post`,a,o=n.authUrl.indexOf(`?`);o>-1&&(a=Ne(n.authUrl.slice(o)),n.authUrl=n.authUrl.slice(0,o),i||(n.authParams=b(a,n.authParams)));let s=b({},n.authParams||{},e),c=e=>{let n=e.body??null,r=null;if(e.error)_.logAction(this.logger,_.LOG_MICRO,`Auth.requestToken().tokenRequestCallback`,`Received Error: `+C(e.error));else{let t=e.headers[`content-type`]??null;r=Array.isArray(t)?t.join(`, `):t,_.logAction(this.logger,_.LOG_MICRO,`Auth.requestToken().tokenRequestCallback`,`Received; content-type: `+r+`; body: `+Fe(n))}if(e.error){t(e.error,null);return}if(e.unpacked){t(null,n);return}if(h.BufferUtils.isBuffer(n)&&(n=n.toString()),!r){t(new v({message:`authUrl response is missing a Content-Type header`,code:40170,statusCode:401,remediation:`Set a Content-Type response header on your authUrl endpoint: application/json for a TokenDetails/TokenRequest object, text/plain for a token string, or application/jwt for a JWT.`}),null);return}let i=r.indexOf(`application/json`)>-1,a=r.indexOf(`text/plain`)>-1||r.indexOf(`application/jwt`)>-1;if(!i&&!a){t(new v({message:`authUrl responded with unacceptable Content-Type `+r+`. Expected one of: text/plain, application/jwt or application/json`,code:40170,statusCode:401,remediation:`Change your authUrl endpoint to respond with a Content-Type the SDK can parse: application/json (TokenDetails/TokenRequest), text/plain (token string), or application/jwt (JWT).`}),null);return}if(i){if(n.length>Tt){t(new v({message:`authUrl JSON response exceeded the maximum permitted length of 128 KB`,code:40170,statusCode:401,remediation:`Two things commonly cause this. If your authUrl wraps the Ably token in an envelope with extra fields, return only the token payload (a token string, or a TokenRequest/TokenDetails object). If the token carries a very large capability, narrow it: grant a wildcard resource such as "*" or "namespace:*" instead of listing every channel.`}),null);return}try{n=JSON.parse(n)}catch(e){t(new v(`Unexpected error processing authURL response; err = `+e.message,40170,401),null);return}}t(null,n,r)};if(_.logAction(this.logger,_.LOG_MICRO,`Auth.requestToken().tokenRequestCallback`,`Requesting token from `+n.authUrl+`; Params: `+JSON.stringify(s)+`; method: `+(i?`POST`:`GET`)),i){let e=r||{};e[`content-type`]=`application/x-www-form-urlencoded`;let t=je(s).slice(1);w(this.client.http.doUri(A.Post,n.authUrl,e,t,a),(e,t)=>c(e||t))}else w(this.client.http.doUri(A.Get,n.authUrl,r||{},null,s),(e,t)=>c(e||t))};else if(n.key)_.logAction(this.logger,_.LOG_MINOR,`Auth.requestToken()`,`using token auth with client-side signing`),i=(e,t)=>{w(this.createTokenRequest(e,n),(e,n)=>t(e,n??null))};else throw _.logAction(this.logger,_.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`),new v({message:`Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)`,code:40171,statusCode:403,remediation:`Initialise the client with one of ClientOptions.{ key, authUrl, authCallback } so the SDK can refresh tokens.`});`capability`in r&&(r.capability=At(r.capability));let o=(e,t)=>{let r=`/keys/`+e.keyName+`/requestToken`,i=function(e){return a.baseUri(e)+r},o=k.defaultPostHeaders(this.client.options,{format:`json`});n.requestHeaders&&b(o,n.requestHeaders),_.logAction(this.logger,_.LOG_MICRO,`Auth.requestToken().requestToken`,`Sending POST to `+r+`; Token params: `+JSON.stringify(e)),w(this.client.http.do(A.Post,i,o,JSON.stringify(e),null),(e,n)=>e?t(e):t(n.error,n.body,n.unpacked))};return new Promise((e,t)=>{let a=!1,s=this.client.options.timeouts.realtimeRequestTimeout,c=h.Config.setTimeout(()=>{a=!0;let e=`Token request via authCallback/authUrl did not complete within the configured timeout (`+s/1e3+` seconds)`;_.logAction(this.logger,_.LOG_ERROR,`Auth.requestToken()`,e),t(new v({message:e,code:40170,statusCode:401,remediation:`Add logging to your authCallback/authUrl to find where it stalls, and make sure it always resolves and that authUrl is reachable. If the work legitimately takes longer, raise ClientOptions.realtimeRequestTimeout.`}))},s);i(r,(r,i,s)=>{if(a)return;if(h.Config.clearTimeout(c),r){_.logAction(this.logger,_.LOG_ERROR,`Auth.requestToken()`,`token request signing call returned error; err = `+C(r)),t(Ot(r));return}if(typeof i==`string`){i.length===0?t(new v({message:`Token string is empty`,code:40170,statusCode:401,remediation:`Return a non-empty value from your authCallback/authUrl: a token string, a TokenRequest, or a TokenDetails object.`})):i.length>Tt?t(new v({message:`Token string exceeded max permitted length (was `+i.length+` bytes)`,code:40170,statusCode:401,remediation:`Return only the bare signed token string from your authCallback/authUrl, not an envelope, debug output, or a stringified TokenDetails wrapping it, since a token must serialise to under 128 KB. If the token carries a very large capability, narrow it: grant a wildcard resource such as "*" or "namespace:*" instead of listing every channel.`})):i===`undefined`||i===`null`?t(new v({message:`Token string was literal null/undefined`,code:40170,statusCode:401,remediation:`Return the token itself, not "undefined"/"null". Callbacks that have no value to return should pass an error instead.`})):i[0]===`{`&&!(s&&s.indexOf(`application/jwt`)>-1)?t(new v({message:`Token was double-encoded`,code:40170,statusCode:401,remediation:`Return TokenDetails/TokenRequest as a parsed object, or set Content-Type: application/jwt for JWT tokens.`})):e({token:i});return}if(typeof i!=`object`||!i){let e=`Expected token request callback to call back with a token string or token request/details object, but got a `+typeof i;_.logAction(this.logger,_.LOG_ERROR,`Auth.requestToken()`,e),t(new v({message:e,code:40170,statusCode:401,remediation:`If authenticating with an authCallback, update it to callback with (err, tokenStringOrTokenDetailsOrTokenRequest). If authenticating with an authUrl, update the server to respond with a token string or TokenDetails/TokenRequest JSON.`}));return}let l=JSON.stringify(i).length;if(l>Tt&&!n.suppressMaxLengthCheck){t(new v({message:`Token request/details object exceeded max permitted stringified size (was `+l+` bytes)`,code:40170,statusCode:401,remediation:`The TokenRequest/TokenDetails object must serialise to under 128 KB. Trim any unused fields, and if it carries a very large capability, narrow it: grant a wildcard resource such as "*" or "namespace:*" instead of listing every channel.`}));return}if(`issued`in i){e(i);return}if(!(`keyName`in i)){let e=`Expected token request callback to call back with a token string, token request object, or token details object. The returned object has neither a keyName nor an issued field.`;_.logAction(this.logger,_.LOG_ERROR,`Auth.requestToken()`,e),t(new v({message:e,code:40170,statusCode:401,remediation:"Return a token string, a TokenRequest (an object with a `keyName` field), or a TokenDetails (an object with an `issued` field) from your authCallback/authUrl."}));return}o(i,(n,r,i)=>{if(n){_.logAction(this.logger,_.LOG_ERROR,`Auth.requestToken()`,`token request API call returned error; err = `+C(n)),t(Ot(n));return}i||(r=JSON.parse(r)),_.logAction(this.logger,_.LOG_MINOR,`Auth.getToken()`,`token received`),e(r)})})})}createTokenRequest(...e){return S(e,0),this._createTokenRequestImpl(e[0],e[1])}async _createTokenRequestImpl(e,t){t||=this.authOptions,e||=fe(this.tokenParams);let n=t.key;if(!n)throw new v({message:`No key specified`,code:40101,statusCode:403,remediation:`Pass { key } in the authOptions argument, or set ClientOptions.key and omit the authOptions argument. A passed authOptions replaces the stored options rather than merging.`});let r=n.split(`:`),i=r[0],a=r[1];if(!a)throw new v({message:`Invalid key specified: the key has no colon-separated secret`,code:40101,statusCode:403,remediation:'Copy the full "appId.keyId:secret" key including the colon and secret from the Ably dashboard. If you have the Ably CLI installed, `ably auth keys list` shows the keys configured on the current app.'});if(e.clientId===``)throw new v({message:`clientId can’t be an empty string`,code:40012,statusCode:400,remediation:`Pass a non-empty clientId, or omit the field entirely for an anonymous token.`});`capability`in e&&(e.capability=At(e.capability));let o=b({keyName:i},e),s=e.clientId||``,c=e.ttl||``,l=e.capability||``;o.timestamp||=await this._getTimestamp(t&&t.queryTime);let u=o.nonce||=Et(),d=o.timestamp,f=o.keyName+`
|
|
2
|
+
`+c+`
|
|
3
|
+
`+l+`
|
|
4
|
+
`+s+`
|
|
5
|
+
`+d+`
|
|
6
|
+
`+u+`
|
|
7
|
+
`;return o.mac=o.mac||kt(f,a),_.logAction(this.logger,_.LOG_MINOR,`Auth.getTokenRequest()`,`generated signed request`),o}async getAuthParams(){if(this.method==`basic`)return{key:this.key};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw Error(`Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails`);return{access_token:e.token}}}async getAuthHeaders(){if(this.method==`basic`)return{authorization:`Basic `+this.basicKey};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw Error(`Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails`);return{authorization:`Bearer `+Je(e.token)}}}_saveBasicOptions(e){this.method=`basic`,this.key=e.key,this.basicKey=Je(e.key),this.authOptions=e||{},`clientId`in e&&this._userSetClientId(e.clientId)}_saveTokenOptions(e,t){this.method=`token`,e&&(this.tokenParams=e),t&&(t.token&&(t.tokenDetails=typeof t.token==`string`?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),`clientId`in t&&this._userSetClientId(t.clientId),this.authOptions=t)}async _ensureValidAuthCredentials(e){let t=this.tokenDetails;if(t){if(this._tokenClientIdMismatch(t.clientId))throw new v({message:`Mismatch between clientId in token (`+t.clientId+`) and current clientId (`+this.clientId+`)`,code:40102,statusCode:403,remediation:`Issue the token with the same clientId as ClientOptions.clientId, or omit ClientOptions.clientId and let the token define it.`});if(!this.client.isTimeOffsetSet()||!t.expires||t.expires>=this.client.getTimestampUsingOffset())return _.logAction(this.logger,_.LOG_MINOR,`Auth.getToken()`,`using cached token; expires = `+t.expires),t;_.logAction(this.logger,_.LOG_MINOR,`Auth.getToken()`,`deleting expired token`),this.tokenDetails=null}let n=(this.waitingForTokenRequest||=bt.create(this.logger)).createPromise();if(this.currentTokenRequestId!==null&&!e)return n;let r=this.currentTokenRequestId=It(),i,a=null;try{i=await this.requestToken(this.tokenParams,this.authOptions)}catch(e){a=e}if(this.currentTokenRequestId>r)return _.logAction(this.logger,_.LOG_MINOR,`Auth._ensureValidAuthCredentials()`,`Discarding token request response; overtaken by newer one`),n;this.currentTokenRequestId=null;let o=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,a?(o?.rejectAll(a),n):(o?.resolveAll(this.tokenDetails=i),n)}_userSetClientId(e){if(typeof e!=`string`&&e!==null)throw new v({message:`clientId must be either a string or null`,code:40012,statusCode:400,remediation:`Pass a stable string such as a user id to identify the client, or null (or omit it) for an anonymous client. Values like numbers or objects are not accepted.`});if(e===`*`)throw new v({message:`Can’t use "*" as a clientId as that string is reserved. clientId sets a single fixed identity for the client`,code:40012,statusCode:400,remediation:`Omit clientId and specify the identity per operation instead, for example with presence.enterClient(otherId, data) or by setting clientId on each message you publish. This requires the library to be instantiated with an API key or a token bound to a wildcard clientId. To request a wildcard token, set defaultTokenParams: { clientId: "*" } in ClientOptions. A wildcard token lets the client claim any clientId per operation but does not give it an identity of its own.`});{let t=this._uncheckedSetClientId(e);if(t)throw t}}_uncheckedSetClientId(e){if(this._tokenClientIdMismatch(e)){let t=`Unexpected clientId mismatch: client has `+this.clientId+`, requested `+e,n=new v({message:t,code:40102,statusCode:401,remediation:`Issue the token with the matching clientId, or omit ClientOptions.clientId and let the token define it.`});return _.logAction(this.logger,_.LOG_ERROR,`Auth._uncheckedSetClientId()`,t),n}return this.clientId=this.tokenParams.clientId=e,null}_tokenClientIdMismatch(e){return!!(this.clientId&&this.clientId!==`*`&&e&&e!==`*`&&this.clientId!==e)}static isTokenErr(e){return e.code&&e.code>=40140&&e.code<40150}revokeTokens(e,t){return this.client.rest.revokeTokens(e,t)}async _getTimestamp(e){return this.client.getTimestamp(e||!!this.authOptions.queryTime)}};function Lt(e){let t=[];if(e)for(let n in e)t.push(n+`=`+e[n]);return t.join(`&`)}function M(e,t){return e+(t?`?`:``)+Lt(t)}function Rt(e,t,n,r,i){e.error?_.logActionNoStrip(i,_.LOG_MICRO,`Http.`+t+`()`,`Received Error; `+M(n,r)+`; Error: `+C(e.error)):_.logActionNoStrip(i,_.LOG_MICRO,`Http.`+t+`()`,`Received; `+M(n,r)+`; Headers: `+Lt(e.headers)+`; StatusCode: `+e.statusCode+`; Body`+(h.BufferUtils.isBuffer(e.body)?` (Base64): `+h.BufferUtils.base64Encode(e.body):`: `+e.body))}function zt(e,t,n,r,i){i.shouldLog(_.LOG_MICRO)&&_.logActionNoStrip(i,_.LOG_MICRO,`Http.`+e+`()`,`Sending; `+M(t,r)+`; Body`+(h.BufferUtils.isBuffer(n)?` (Base64): `+h.BufferUtils.base64Encode(n):`: `+n))}var Bt=class{constructor(e){this.client=e,this.platformHttp=new h.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){return this.client?.logger??_.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){let t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(k.getFallbackHosts(e.options)):k.getHosts(e.options)}async do(e,t,n,r,i){try{let a=this.client;if(!a)return{error:new v(`http.do called without client`,5e4,500)};let o=typeof t==`function`?t:function(e){return a.baseUri(e)+t},s=a._currentFallback;if(s){if(s.validUntil>h.Config.now()){let c=await this.doUri(e,o(s.host),n,r,i);return c.error&&this.platformHttp.shouldFallback(c.error)?(a._currentFallback=null,this.do(e,t,n,r,i)):c}a._currentFallback=null}let c=this._getHosts(a);if(c.length===1)return this.doUri(e,o(c[0]),n,r,i);let l=null,u=async(t,s)=>{let c=t.shift();l??=h.Config.now();let d=await this.doUri(e,o(c),n,r,i);return d.error&&this.platformHttp.shouldFallback(d.error)&&t.length?h.Config.now()-l>a.options.timeouts.httpMaxRetryDuration?{error:new v(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${a.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:u(t,!0):(s&&(a._currentFallback={host:c,validUntil:h.Config.now()+a.options.timeouts.fallbackRetryTimeout}),d)};return u(c)}catch(e){return{error:new v(`Unexpected error in Http.do: ${C(e)}`,500,5e4)}}}async doUri(e,t,n,r,i){try{zt(e,t,r,i,this.logger);let a=await this.platformHttp.doUri(e,t,n,r,i);return this.logger.shouldLog(_.LOG_MICRO)&&Rt(a,e,t,i,this.logger),a}catch(e){return{error:new v(`Unexpected error in Http.doUri: ${C(e)}`,500,5e4)}}}};function Vt(e,t,n,r){try{n.apply(t,r)}catch(t){_.logAction(e,_.LOG_ERROR,`EventEmitter.emit()`,`Unexpected listener exception: `+t+`; stack = `+(t&&t.stack))}}function Ht(e,t,n){let r,i,a;for(let o=0;o<e.length;o++)if(r=e[o],n&&(r=r[n]),Array.isArray(r)){for(;(i=r.indexOf(t))!==-1;)r.splice(i,1);n&&r.length===0&&delete e[o][n]}else if(me(r))for(a in r)Object.prototype.hasOwnProperty.call(r,a)&&Array.isArray(r[a])&&Ht([r],t,a)}var N=class{constructor(e){this.logger=e,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...e){if(e.length===1){let t=e[0];if(typeof t==`function`)this.any.push(t);else throw Error(`EventListener.on(): Invalid arguments: `+h.Config.inspect(e))}if(e.length===2){let[t,n]=e;if(typeof n!=`function`)throw Error(`EventListener.on(): Invalid arguments: `+h.Config.inspect(e));if(x(t))this.any.push(n);else if(Array.isArray(t))t.forEach(e=>{this.on(e,n)});else{if(typeof t!=`string`)throw Error(`EventListener.on(): Invalid arguments: `+h.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(e.length==0||x(e[0])&&x(e[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[t,n]=e,r=null,i=null;if(e.length===1||!n)typeof t==`function`?r=t:i=t;else{if(typeof n!=`function`)throw Error(`EventEmitter.off(): invalid arguments:`+h.Config.inspect(e));[i,r]=[t,n]}if(r&&x(i)){Ht([this.any,this.events,this.anyOnce,this.eventsOnce],r);return}if(Array.isArray(i)){i.forEach(e=>{this.off(e,r)});return}if(typeof i!=`string`)throw Error(`EventEmitter.off(): invalid arguments:`+h.Config.inspect(e));r?Ht([this.events,this.eventsOnce],r,i):(delete this.events[i],delete this.eventsOnce[i])}listeners(e){if(e){let t=this.events[e]||[];return this.eventsOnce[e]&&Array.prototype.push.apply(t,this.eventsOnce[e]),t.length?t:null}return this.any.length?this.any:null}emit(e,...t){let n={event:e},r=[];this.anyOnce.length&&(Array.prototype.push.apply(r,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(r,this.any);let i=this.eventsOnce[e];i&&(Array.prototype.push.apply(r,i),delete this.eventsOnce[e]);let a=this.events[e];a&&Array.prototype.push.apply(r,a),r.forEach(e=>{Vt(this.logger,n,e,t)})}once(...e){let t=e.length;if(t===0||t===1&&typeof e[0]!=`function`){let t=e[0];return new Promise(e=>{this.once(t,e)})}let[n,r]=e;if(e.length===1&&typeof n==`function`)this.anyOnce.push(n);else if(x(n)){if(typeof r!=`function`)throw Error(`EventEmitter.once(): Invalid arguments:`+h.Config.inspect(e));this.anyOnce.push(r)}else if(Array.isArray(n)){let t=this,i=function(){let a=Array.prototype.slice.call(arguments);if(n.forEach(function(e){t.off(e,i)}),typeof r!=`function`)throw Error(`EventEmitter.once(): Invalid arguments:`+h.Config.inspect(e));r.apply(this,a)};n.forEach(function(e){t.on(e,i)})}else{if(typeof n!=`string`)throw Error(`EventEmitter.once(): Invalid arguments:`+h.Config.inspect(e));let t=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(r){if(typeof r!=`function`)throw Error(`EventEmitter.once(): Invalid arguments:`+h.Config.inspect(e));t.push(r)}}}async whenState(e,t){if(typeof e!=`string`||typeof t!=`string`)throw Error(`whenState requires a valid state String argument`);return e===t?null:this.once(e)}},P={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,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},Ut=[];Object.keys(P).forEach(function(e){Ut[P[e]]=e});var F={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},Wt=Object.keys(F);F.MODE_ALL=F.PRESENCE|F.PUBLISH|F.SUBSCRIBE|F.PRESENCE_SUBSCRIBE|F.ANNOTATION_PUBLISH|F.ANNOTATION_SUBSCRIBE|F.OBJECT_SUBSCRIBE|F.OBJECT_PUBLISH;var Gt=[`PRESENCE`,`PUBLISH`,`SUBSCRIBE`,`PRESENCE_SUBSCRIBE`,`ANNOTATION_PUBLISH`,`ANNOTATION_SUBSCRIBE`,`OBJECT_SUBSCRIBE`,`OBJECT_PUBLISH`];function Kt(e){return!e||!e.channelOptions?{channelOptions:e,plugins:{},baseEncodedPreviousPayload:void 0}:e}function qt(e,t,n){if(n&&n.cipher){e||D(`Crypto`);let r=e.getCipher(n.cipher,t);return{cipher:r.cipherParams,channelCipher:r.cipher}}return n??{}}async function Jt(e,t){let{data:n,encoding:r}=await Yt(e.data,e.encoding,t);return e.data=n,e.encoding=r,e}async function Yt(e,t,n){let r=n.channelCipher,i=e,a=t?t+`/`:``;h.BufferUtils.isBuffer(i)||(i=h.BufferUtils.utf8Encode(String(i)),a+=`utf-8/`);let o=await r.encrypt(i);return a=a+`cipher+`+r.algorithm,{data:o,encoding:a}}async function Xt(e,t){let{data:n,encoding:r}=Zt(e.data,e.encoding);return e.data=n,e.encoding=r,t!=null&&t.cipher?Jt(e,t):e}function Zt(e,t){if(typeof e==`string`||h.BufferUtils.isBuffer(e)||e==null)return{data:e,encoding:t};if(me(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+`/json`:`json`};throw new v({message:`Data type is unsupported`,code:40013,statusCode:400,remediation:`Message data must be a string, Buffer/ArrayBuffer/TypedArray, plain object, or array. Convert other types (e.g. Date, Map, Set) to one of these before publishing.`})}async function Qt(e,t){let{data:n,encoding:r,error:i}=await $t(e.data,e.encoding,t);if(e.data=n,e.encoding=r,i)throw i}async function $t(e,t,n){let r=Kt(n),i=e,a=e,o=t,s;if(t){let e=t.split(`/`),n,c=e.length,l=``;try{for(;(n=c)>0;){let t=e[--c].match(/([-\w]+)(\+([\w-]+))?/);if(!t)break;switch(l=t[1],l){case`base64`:a=h.BufferUtils.base64Decode(String(a)),n==e.length&&(i=a);continue;case`utf-8`:a=h.BufferUtils.utf8Decode(a);continue;case`json`:a=JSON.parse(a);continue;case`cipher`:if(r.channelOptions!=null&&r.channelOptions.cipher&&r.channelOptions.channelCipher){let e=t[3],n=r.channelOptions.channelCipher;if(e!=n.algorithm)throw Error(`Unable to decrypt message with given cipher; incompatible cipher params`);a=await n.decrypt(a);continue}throw Error(`Unable to decrypt message; not an encrypted channel`);case`vcdiff`:if(!r.plugins||!r.plugins.vcdiff)throw new v({message:`Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)`,code:40019,statusCode:400,remediation:`Install @ably/vcdiff-decoder and pass it in ClientOptions.plugins.vcdiff.`});if(typeof Uint8Array>`u`)throw new v({message:`Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)`,code:40020,statusCode:400,remediation:`Disable channel deltas (do not set delta in channel params) on environments without typed-array support, or upgrade the JavaScript runtime.`});try{let e=r.baseEncodedPreviousPayload;typeof e==`string`&&(e=h.BufferUtils.utf8Encode(e));let t=h.BufferUtils.toBuffer(e);a=h.BufferUtils.toBuffer(a),a=h.BufferUtils.arrayBufferViewToBuffer(r.plugins.vcdiff.decode(a,t)),i=a}catch(e){throw new v({message:`Vcdiff delta decode failed with `+e,code:40018,statusCode:400,remediation:`The SDK recovers automatically by re-attaching from the last successfully processed message, and the server re-sends the affected message in full before deltas resume. If this recurs, disable deltas for this channel by removing delta from the channel params.`})}continue;default:throw Error(`Unknown encoding`)}}}catch(e){let t=e;s=new v({message:`Error processing the ${l} encoding, decoder returned \u2018${t.message}\u2019`,code:t.code||40013,statusCode:400,remediation:t.remediation})}finally{o=n<=0?null:e.slice(0,n).join(`/`)}}return s?{error:s,data:a,encoding:o}:(r.baseEncodedPreviousPayload=i,{data:a,encoding:o})}function en(...e){let t=e.length>0?`json`:`msgpack`,{data:n,encoding:r}=tn(this.data,this.encoding,t);return Object.assign({},this,{encoding:r,data:n})}function tn(e,t,n){return!e||!h.BufferUtils.isBuffer(e)?{data:e,encoding:t}:n===`msgpack`?{data:h.BufferUtils.toBuffer(e),encoding:t}:{data:h.BufferUtils.base64Encode(e),encoding:t?t+`/base64`:`base64`}}var nn={encryptData:Yt,encodeData:Zt,encodeDataForWire:tn,decodeData:$t};function rn(e){let{id:t,connectionId:n,timestamp:r}=e,i;switch(e.action){case P.MESSAGE:i=e.messages;break;case P.PRESENCE:case P.SYNC:i=e.presence;break;case P.ANNOTATION:i=e.annotations;break;case P.OBJECT:case P.OBJECT_SYNC:i=e.state;break;default:throw new v(`Unexpected action `+e.action,4e4,400)}for(let e=0;e<i.length;e++){let a=i[e];a.connectionId||=n,a.timestamp||=r,t&&!a.id&&(a.id=t+`:`+e)}}function I(e,t){let n=`[`+t;for(let t in e)t===`data`?typeof e.data==`string`?n+=`; data=`+e.data:h.BufferUtils.isBuffer(e.data)?n+=`; data (buffer)=`+h.BufferUtils.base64Encode(e.data):e.data!==void 0&&(n+=`; data (json)=`+JSON.stringify(e.data)):t&&(t===`extras`||t===`operation`)?n+=`; `+t+`=`+JSON.stringify(e[t]):t===`version`?n+=`; version=`+JSON.stringify(e[t]):t===`annotations`?n+=`; annotations=`+JSON.stringify(e[t]):e[t]!==void 0&&(n+=`; `+t+`=`+e[t]);return n+=`]`,n}var L=class{},an=class{constructor(e){this.Platform=h,this.ErrorInfo=v,this.Logger=_,this.Defaults=k,this.Utils=le,this.EventEmitter=N,this.MessageEncoding=nn,this._additionalHTTPRequestImplementations=e.plugins??null,this.logger=new _,this.logger.setLog(e.logLevel,e.logHandler),_.logAction(this.logger,_.LOG_MICRO,`BaseClient()`,`initialized with clientOptions `+h.Config.inspect(e)),this._MsgPack=e.plugins?.MsgPack??null;let t=this.options=k.normaliseOptions(e,this._MsgPack,this.logger);if(t.key){let e=t.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!e){let e=`invalid key parameter`;throw _.logAction(this.logger,_.LOG_ERROR,`BaseClient()`,e),new v({message:e,code:40400,statusCode:404,remediation:'ClientOptions.key must be the full "appId.keyId:secret" string copied from the Ably dashboard. If you have the Ably CLI installed, `ably auth keys list` shows the keys configured on the current app.'})}t.keyName=e[1],t.keySecret=e[2]}if(`clientId`in t){if(typeof t.clientId!=`string`&&t.clientId!==null)throw new v({message:`clientId must be either a string or null`,code:40012,statusCode:400,remediation:`Pass a stable string such as a user id to identify the client, or null (or omit it) for an anonymous client. Values like numbers or objects are not accepted.`});if(t.clientId===`*`)throw new v({message:`Can’t use "*" as a clientId as that string is reserved`,code:40012,statusCode:400,remediation:`ClientOptions.clientId sets one fixed identity and cannot be "*". To let this client act as any clientId, request a wildcard token instead: set defaultTokenParams: { clientId: "*" } on the client. The "*" belongs in the token request, not in ClientOptions.clientId.`})}_.logAction(this.logger,_.LOG_MINOR,`BaseClient()`,`started; version = `+k.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new Bt(this),this.auth=new j(this,t),this._rest=e.plugins?.Rest?new e.plugins.Rest(this):null,this._Crypto=e.plugins?.Crypto??null,this.__FilteredSubscriptions=e.plugins?.MessageInteractions??null,this._Annotations=e.plugins?.Annotations??null,this._liveObjectsPlugin=e.plugins?.LiveObjects??null}get rest(){return this._rest||D(`Rest`),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||D(`MessageInteractions`),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}get pushConfig(){return this.options.plugins?.Push?.pushConfig??h.Config.push}device(){if((!this.options.plugins?.Push||!this.push.LocalDevice)&&D(`Push`),!this._device){if(this.pushConfig?.storageIsAsync)throw new v({message:`client.device() cannot load the local device synchronously: push storage on this platform is asynchronous`,code:4e4,statusCode:400,remediation:`Use await client.getDevice() instead. device() is deprecated and will become asynchronous in the next major release.`});this._device=this.push.LocalDevice.load(this)}return this._device}async getDevice(){if((!this.options.plugins?.Push||!this.push.LocalDevice)&&D(`Push`),!this._device){let e=this._devicePromise??=this.push.LocalDevice.loadAsync(this);try{this._device=await e}catch(t){throw this._devicePromise===e&&(this._devicePromise=void 0),t}}return this._device}baseUri(e){return k.getHttpScheme(this.options)+e+`:`+k.getPort(this.options,!1)}async stats(e){return this.rest.stats(e)}async time(e){return this.rest.time(e)}async request(e,t,n,r,i,a){return this.rest.request(e,t,n,r,i,a)}batchPublish(e){return this.rest.batchPublish(e)}batchPresence(e){return this.rest.batchPresence(e)}setLog(e){this.logger.setLog(e.level,e.handler)}async getTimestamp(e){return!this.isTimeOffsetSet()&&e?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return h.Config.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};an.Platform=h;var on=an,R=class e{toJSON(){return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:this.push?.recipient,state:this.push?.state,error:this.push?.error}}}toString(){let e=`[DeviceDetails`;return this.id&&(e+=`; id=`+this.id),this.platform&&(e+=`; platform=`+this.platform),this.formFactor&&(e+=`; formFactor=`+this.formFactor),this.clientId&&(e+=`; clientId=`+this.clientId),this.metadata&&(e+=`; metadata=`+this.metadata),this.deviceIdentityToken&&(e+=`; deviceIdentityToken=`+JSON.stringify(this.deviceIdentityToken)),this.push?.recipient&&(e+=`; push.recipient=`+JSON.stringify(this.push.recipient)),this.push?.state&&(e+=`; push.state=`+this.push.state),this.push?.error&&(e+=`; push.error=`+JSON.stringify(this.push.error)),this.push?.metadata&&(e+=`; push.metadata=`+this.push.metadata),e+=`]`,e}static toRequestBody(e,t,n){return E(e,t,n)}static fromResponseBody(t,n,r){return r&&(t=T(t,n,r)),Array.isArray(t)?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return t.error=t.error&&v.fromValues(t.error),Object.assign(new e,t)}static fromLocalDevice(t){return Object.assign(new e,t)}static fromValuesArray(t){let n=t.length,r=Array(n);for(let i=0;i<n;i++)r[i]=e.fromValues(t[i]);return r}};async function sn(e,t,n,r){return e.http.supportsAuthHeaders?r(b(await e.auth.getAuthHeaders(),t),n):r(t,b(await e.auth.getAuthParams(),n))}function cn(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===wt.NoContent)return f(d({},e),{body:[],unpacked:!0});let r=e.body;if(!e.unpacked)try{r=T(r,t,n)}catch(e){return Pe(e)?{err:e}:{err:new y(C(e),null)}}if(!r)return{err:new y(`unenvelope(): Response body is missing`,null)};let{statusCode:i,response:a,headers:o}=r;if(i===void 0)return f(d({},e),{body:r,unpacked:!0});if(i<200||i>=300){let t=a&&a.error||e.err;return t||(t=Error(`Error in unenveloping `+r),t.statusCode=i),{err:t,body:a,headers:o,unpacked:!0,statusCode:i}}return{err:e.err,body:a,headers:o,unpacked:!0,statusCode:i}}function ln(e,t,n,r,i){e.err?_.logAction(i,_.LOG_MICRO,`Resource.`+t+`()`,`Received Error; `+M(n,r)+`; Error: `+C(e.err)):_.logAction(i,_.LOG_MICRO,`Resource.`+t+`()`,`Received; `+M(n,r)+`; Headers: `+Lt(e.headers)+`; StatusCode: `+e.statusCode+`; Body: `+(h.BufferUtils.isBuffer(e.body)?` (Base64): `+h.BufferUtils.base64Encode(e.body):`: `+h.Config.inspect(e.body)))}var z=class e{static async get(t,n,r,i,a,o){return e.do(A.Get,t,n,null,r,i,a,o??!1)}static async delete(t,n,r,i,a,o){return e.do(A.Delete,t,n,null,r,i,a,o)}static async post(t,n,r,i,a,o,s){return e.do(A.Post,t,n,r,i,a,o,s)}static async patch(t,n,r,i,a,o,s){return e.do(A.Patch,t,n,r,i,a,o,s)}static async put(t,n,r,i,a,o,s){return e.do(A.Put,t,n,r,i,a,o,s)}static async do(e,t,n,r,i,a,o,s){o&&((a||={}).envelope=o);let c=t.logger;async function l(i,a){if(c.shouldLog(_.LOG_MICRO)){let o=r;if(i[`content-type`]?.indexOf(`msgpack`)>0)try{t._MsgPack||D(`MsgPack`),o=t._MsgPack.decode(r)}catch(t){_.logAction(c,_.LOG_MICRO,`Resource.`+e+`()`,`Sending MsgPack Decoding Error: `+C(t))}_.logAction(c,_.LOG_MICRO,`Resource.`+e+`()`,`Sending; `+M(n,a)+`; Body: `+o)}let o=await t.http.do(e,n,i,r,a);return o.error&&j.isTokenErr(o.error)?(await t.auth.authorize(null,null),sn(t,i,a,l)):{err:o.error,body:o.body,headers:o.headers,unpacked:o.unpacked,statusCode:o.statusCode}}let u=await sn(t,i,a,l);if(o&&(u=cn(u,t._MsgPack,o)),c.shouldLog(_.LOG_MICRO)&&ln(u,e,n,a,c),s){if(u.err)throw u.err;{let e=d({},u);return delete e.err,e}}return u}};function un(e){let t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&Ne(t[2])}function dn(e){typeof e==`string`&&(e=e.split(`,`));let t={};for(let n=0;n<e.length;n++){let r=e[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(r){let e=un(r[1]);e&&(t[r[2]]=e)}}return t}function fn(e,t,n){return!(n&&(t||typeof e.code==`number`))}var pn=class{constructor(e,t,n,r,i,a){this.client=e,this.path=t,this.headers=n,this.envelope=r??null,this.bodyHandler=i,this.useHttpPaginatedResponse=a||!1}get logger(){return this.client.logger}async get(e){let t=await z.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){let t=await z.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){let n=await z.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){let n=await z.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){let n=await z.patch(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async handlePage(e){if(e.err&&fn(e.err,e.body,this.useHttpPaginatedResponse))throw _.logAction(this.logger,_.LOG_ERROR,`PaginatedResource.handlePage()`,`Unexpected error getting resource: err = `+C(e.err)),e.err;let t,n,r;try{t=e.statusCode==wt.NoContent?[]:await this.bodyHandler(e.body,e.headers||{},e.unpacked)}catch(t){throw e.err||t}return e.headers&&(n=e.headers.Link||e.headers.link)&&(r=dn(n)),this.useHttpPaginatedResponse?new hn(this,t,e.headers||{},e.statusCode,r,e.err):new mn(this,t,r)}},mn=class{constructor(e,t,n){this.resource=e,this.items=t,this._relParams=n}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new v({message:`No link to the first page of results`,code:40400,statusCode:404,remediation:`first() is only available on results from a paginated REST query (such as channel history, presence, or stats), whose response includes a link to the first page. This result has no such link, so there is no first page to return.`})}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new v({message:`No link to the current page of results`,code:40400,statusCode:404,remediation:`current() reloads the current page and is only available on results from a paginated REST query (such as channel history, presence, or stats). This result has no such link. To page through results, use next() with hasNext() or isLast() instead.`})}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&`first`in this._relParams}hasCurrent(){return this._relParams!=null&&`current`in this._relParams}hasNext(){return this._relParams!=null&&`next`in this._relParams}isLast(){return!this.hasNext()}async get(e){let t=this.resource,n=await z.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},hn=class extends mn{constructor(e,t,n,r,i,a){super(e,t,i),this.statusCode=r,this.success=r<300&&r>=200,this.headers=n,this.errorCode=a&&a.code,this.errorMessage=a&&a.message,this.errorDetail=a?.detail}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage,errorDetail:this.errorDetail}}},B=pn,gn=class e{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let e=`[PushChannelSubscription`;return this.channel&&(e+=`; channel=`+this.channel),this.deviceId&&(e+=`; deviceId=`+this.deviceId),this.clientId&&(e+=`; clientId=`+this.clientId),e+=`]`,e}static fromResponseBody(t,n,r){return r&&(t=T(t,n,r)),Array.isArray(t)?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){let n=t.length,r=Array(n);for(let i=0;i<n;i++)r[i]=e.fromValues(t[i]);return r}};gn.toRequestBody=E;var _n=gn,vn=`Run push.activate() in a browser environment with service worker support, or in React Native using the ably/react-native-push plugin. From a server, use client.push.admin instead. Call client.push.admin.publish(recipient, payload) to send to a device or clientId. Call client.push.admin.deviceRegistrations.save(device) to register a device record.`,yn=`Run push.deactivate() in a browser environment with service worker support, or in React Native using the ably/react-native-push plugin. From a server, call client.push.admin.deviceRegistrations.remove(deviceId) to remove a device registration.`,bn=`Call push.updateToken() in React Native with the ably/react-native-push plugin configured, passing plugins: { Push: ReactNativePush.create({ storage, requestToken }) } in the client options. From a server, use client.push.admin.deviceRegistrations.save(device) to modify a device registration instead.`,xn=class{constructor(e){this.client=e,this.admin=new Sn(e);let t=e.options.plugins?.Push;e.pushConfig&&t&&(this.stateMachine=new t.ActivationStateMachine(e),this.LocalDevice=t.localDeviceFactory(R))}async activate(e,t){let n=this.client.options.plugins?.Push;if(!n)throw Xe(`Push`);let r=this.stateMachine;if(!r)throw new v({message:`This platform is not supported as a target of push notifications: push activation requires a browser environment with service worker support, or a React Native environment with the ably/react-native-push plugin`,code:4e4,statusCode:400,remediation:vn});if(r.activatedCallback)throw new v({message:`Activation already in progress`,code:4e4,statusCode:400,remediation:`Await the in-flight push.activate() before calling it again.`});let i=new Promise((e,n)=>{r.activatedCallback=t=>{if(t){n(t);return}e()},r.updateFailedCallback=t});try{await this.client.getDevice(),await r.ensureInitialized()}catch(e){throw delete r.activatedCallback,delete r.updateFailedCallback,e}r.handleEvent(new n.CalledActivate(r,e)),await i}async deactivate(e){let t=this.client.options.plugins?.Push;if(!t)throw Xe(`Push`);let n=this.stateMachine;if(!n)throw new v({message:`This platform is not supported as a target of push notifications: push activation requires a browser environment with service worker support, or a React Native environment with the ably/react-native-push plugin`,code:4e4,statusCode:400,remediation:yn});if(n.deactivatedCallback)throw new v({message:`Deactivation already in progress`,code:4e4,statusCode:400,remediation:`Await the in-flight push.deactivate() before calling it again.`});let r=new Promise((e,t)=>{n.deactivatedCallback=n=>{if(n){t(n);return}e()}});try{await this.client.getDevice(),await n.ensureInitialized()}catch(e){throw delete n.deactivatedCallback,e}n.handleEvent(new t.CalledDeactivate(n,e)),await r}async updateToken(e){if(!this.client.options.plugins?.Push)throw Xe(`Push`);let t=this.stateMachine;if(!t)throw new v({message:`This platform is not supported as a target of push notifications: push token updates require a React Native environment with the ably/react-native-push plugin`,code:4e4,statusCode:400,remediation:bn});if(!e||e.transportType!==`fcm`&&e.transportType!==`apns`||typeof e.token!=`string`||e.token.length===0)throw new v({message:`push.updateToken() requires a { transportType, token } object with transportType 'fcm' or 'apns' and a non-empty token string`,code:4e4,statusCode:400,remediation:`Pass the refreshed token in the shape your requestToken callback returns, for example { transportType: 'fcm', token } with the token value delivered by messaging().onTokenRefresh.`});let n=await this.client.getDevice();if(await t.ensureInitialized(),!n.deviceIdentityToken)throw new v({message:`Push token cannot be updated because the device is not activated for push notifications`,code:4e4,statusCode:400,remediation:`Call client.push.activate() and await its completion before calling push.updateToken(). Wire updateToken() to your platform token refresh listener only after activation has completed.`});n.push.recipient=e.transportType===`apns`?{transportType:`apns`,deviceToken:e.token}:{transportType:`fcm`,registrationToken:e.token},await n.persist(),t.handleEvent(new t.GotPushDeviceDetails)}},Sn=class{constructor(e){this.client=e,this.deviceRegistrations=new wn(e),this.channelSubscriptions=new Tn(e),this.liveActivity=new Cn(e)}async publish(e,t){let n=this.client,r=n.options.useBinaryProtocol?`msgpack`:`json`,i=k.defaultPostHeaders(n.options),a={},o=b({recipient:e},t);b(i,n.options.headers),n.options.pushFullWait&&b(a,{fullWait:`true`});let s=E(o,n._MsgPack,r);await z.post(n,`/push/publish`,s,i,a,null,!0)}async createApnsBroadcast(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=k.defaultPostHeaders(t.options),i={};b(r,t.options.headers);let a=E({messageStoragePolicy:e.messageStoragePolicy},t._MsgPack,n),o=await z.post(t,`/push/apnsBroadcastChannels`,a,r,i,null,!0);return o.unpacked?o.body:T(o.body,t._MsgPack,n)}},Cn=class{constructor(e){this.client=e}async start(e){let{recipient:t,apnsBroadcast:n,apns:r,headers:i}=e,a=Array.isArray(t.channels)&&t.channels.length>0,o=!!t.deviceId;if(a===o)throw new v(`LiveActivity.start() requires exactly one of recipient.channels or recipient.deviceId`,4e4,400);let s={apns:r};a&&(s.channels=t.channels),o&&(s.deviceId=t.deviceId),i&&(s.headers=i),await this._post(n,`start`,s)}async update(e){let{apnsBroadcast:t,apns:n,headers:r}=e,i={apns:n};r&&(i.headers=r),await this._post(t,`broadcast`,i)}async end(e){let{apnsBroadcast:t,apns:n,headers:r}=e,i={apns:n};r&&(i.headers=r),await this._post(t,`end`,i)}async _post(e,t,n){let r=this.client,i=r.options.useBinaryProtocol?`msgpack`:`json`,a=k.defaultPostHeaders(r.options),o={};b(a,r.options.headers);let s=E(n,r._MsgPack,i);await z.post(r,`/push/apnsBroadcastChannels/`+encodeURIComponent(e)+`/`+t,s,a,o,null,!0)}},wn=class{constructor(e){this.client=e}async save(e){let t=this.client,n=R.fromValues(e),r=t.options.useBinaryProtocol?`msgpack`:`json`,i=k.defaultPostHeaders(t.options),a={};b(i,t.options.headers),t.options.pushFullWait&&b(a,{fullWait:`true`});let o=E(n,t._MsgPack,r),s=await z.put(t,`/push/deviceRegistrations/`+encodeURIComponent(e.id),o,i,a,null,!0);return R.fromResponseBody(s.body,t._MsgPack,s.unpacked?void 0:r)}async get(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=k.defaultGetHeaders(t.options),i=e.id||e;if(typeof i!=`string`||!i.length)throw new v({message:`First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails`,code:4e4,statusCode:400,remediation:`Pass either the device id string or a DeviceDetails object with a non-empty .id field. The local device id is available from client.device().id after push.activate() completes. Alternatively pass the .id of a DeviceDetails returned by push.admin.deviceRegistrations.save().`});b(r,t.options.headers);let a=await z.get(t,`/push/deviceRegistrations/`+encodeURIComponent(i),r,{},null,!0);return R.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:n)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=this.client.http.supportsLinkHeaders?void 0:n,i=k.defaultGetHeaders(t.options);return b(i,t.options.headers),new B(t,`/push/deviceRegistrations`,i,r,async function(e,r,i){return R.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async remove(e){let t=this.client,n=k.defaultGetHeaders(t.options),r={},i=e.id||e;if(typeof i!=`string`||!i.length)throw new v({message:`First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails`,code:4e4,statusCode:400,remediation:`Pass either the device id string or the DeviceDetails object (with a non-empty .id field). To deactivate the local device, call client.push.deactivate() instead.`});b(n,t.options.headers),t.options.pushFullWait&&b(r,{fullWait:`true`}),await z.delete(t,`/push/deviceRegistrations/`+encodeURIComponent(i),n,r,null,!0)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=k.defaultGetHeaders(t.options,{format:n});b(r,t.options.headers),t.options.pushFullWait&&b(e,{fullWait:`true`}),await z.delete(t,`/push/deviceRegistrations`,r,e,null,!0)}},Tn=class e{constructor(t){this.remove=e.prototype.removeWhere,this.client=t}async save(e){let t=this.client,n=_n.fromValues(e),r=t.options.useBinaryProtocol?`msgpack`:`json`,i=k.defaultPostHeaders(t.options),a={};b(i,t.options.headers),t.options.pushFullWait&&b(a,{fullWait:`true`});let o=E(n,t._MsgPack,r),s=await z.post(t,`/push/channelSubscriptions`,o,i,a,null,!0);return _n.fromResponseBody(s.body,t._MsgPack,s.unpacked?void 0:r)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=this.client.http.supportsLinkHeaders?void 0:n,i=k.defaultGetHeaders(t.options);return b(i,t.options.headers),new B(t,`/push/channelSubscriptions`,i,r,async function(e,r,i){return _n.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=k.defaultGetHeaders(t.options,{format:n});b(r,t.options.headers),t.options.pushFullWait&&b(e,{fullWait:`true`}),await z.delete(t,`/push/channelSubscriptions`,r,e,null,!0)}async listChannels(e){let t=this.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=this.client.http.supportsLinkHeaders?void 0:n,i=k.defaultGetHeaders(t.options);return b(i,t.options.headers),t.options.pushFullWait&&b(e,{fullWait:`true`}),new B(t,`/push/channels`,i,r,async function(e,r,i){let a=!i&&n?T(e,t._MsgPack,n):e;for(let e=0;e<a.length;e++)a[e]=String(a[e]);return a}).get(e)}},En=xn,Dn=[`absent`,`present`,`enter`,`leave`,`update`];async function On(e,t,n,r){let i=qt(t,e,r??null);return Nn.fromValues(n).decode(i,e)}async function kn(e,t,n,r){return Promise.all(n.map(function(n){return On(e,t,n,r)}))}async function An(e,t){return Nn.fromValues(e).decode(t.channelOptions,t.logger)}async function jn(e,t){return Promise.all(e.map(function(e){return An(e,t)}))}var Mn=class e extends L{isSynthesized(){return!this.id||!this.connectionId||this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw Error(`parseId(): Presence message does not contain an id`);let e=this.id.split(`:`);return{connectionId:e[0],msgSerial:parseInt(e[1],10),index:parseInt(e[2],10)}}async encode(e){return Xt(Object.assign(new Nn,this,{action:Dn.indexOf(this.action||`present`)}),e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}static fromData(t){return t instanceof e?t:e.fromValues({data:t})}toString(){return I(this,`PresenceMessage`)}},Nn=class e extends L{toJSON(...e){return en.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decode(e,t){let n=Object.assign(new Mn,f(d({},this),{action:Dn[this.action]}));try{await Qt(n,e)}catch(e){_.logAction(t,_.LOG_ERROR,`WirePresenceMessage.decode()`,C(e))}return n}toString(){return I(this,`WirePresenceMessage`)}},V=Mn,Pn=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){_.logAction(this.logger,_.LOG_MICRO,`RestPresence.get()`,`channel = `+this.channel.name);let t=this.channel.client,n=t.options.useBinaryProtocol?`msgpack`:`json`,r=this.channel.client.http.supportsLinkHeaders?void 0:n,i=k.defaultGetHeaders(t.options);return b(i,t.options.headers),new B(t,this.channel.client.rest.presenceMixin.basePath(this),i,r,async(e,r,i)=>jn(i?e:T(e,t._MsgPack,n),this.channel)).get(e)}async history(e){return _.logAction(this.logger,_.LOG_MICRO,`RestPresence.history()`,`channel = `+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},Fn=[`message.create`,`message.update`,`message.delete`,`meta`,`message.summary`,`message.append`];function In(e){return Fn[e||0]||`unknown`}function Ln(e){let t=0;return e.name&&(t+=e.name.length),e.clientId&&(t+=e.clientId.length),e.extras&&(t+=JSON.stringify(e.extras).length),e.data&&(t+=Ie(e.data)),t}async function Rn(e,t,n,r){let i=qt(t,e,r??null);return Kn.fromValues(n).decode(i,e)}async function zn(e,t,n,r){return Promise.all(n.map(function(n){return Rn(e,t,n,r)}))}async function Bn(e,t){return Kn.fromValues(e).decode(t.channelOptions,t.logger)}async function Vn(e,t){return Promise.all(e.map(function(e){return Bn(e,t)}))}async function Hn(e,t){return Promise.all(e.map(e=>e.encode(t)))}var Un=E;function Wn(e){let t,n=0;for(let r=0;r<e.length;r++)t=e[r],n+=t.size||(t.size=Ln(t));return n}var Gn=class e extends L{expandFields(){if(this.version||={},!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(let[e,t]of Object.entries(this.annotations.summary))if(e.endsWith(`:distinct.v1`)||e.endsWith(`:unique.v1`)||e.endsWith(`:multiple.v1`))for(let[,e]of Object.entries(t))e.clipped||=!1;else e.endsWith(`:flag.v1`)&&(t.clipped||=!1)}async encode(e){return Xt(Object.assign(new Kn,this,{action:Fn.indexOf(this.action||`message.create`)}),e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return I(this,`Message`)}},Kn=class e extends L{toJSON(...e){return en.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decodeWithErr(e,t){let n=Object.assign(new Gn,f(d({},this),{action:In(this.action)})),r;try{await Qt(n,e)}catch(e){_.logAction(t,_.LOG_ERROR,`WireMessage.decode()`,C(e)),r=e}return n.expandFields(),{decoded:n,err:r}}async decode(e,t){let{decoded:n}=await this.decodeWithErr(e,t);return n}toString(){return I(this,`WireMessage`)}},H=Gn,qn=9;function Jn(e){return e.every(function(e){return!e.id})}var Yn=class{constructor(e,t,n){this._annotations=null,_.logAction(e.logger,_.LOG_MINOR,`RestChannel()`,`started; name = `+t),this.name=t,this.client=e,this.presence=new Pn(this),this.channelOptions=mt(e._Crypto??null,this.logger,n),e.options.plugins?.Push&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._Annotations&&(this._annotations=new e._Annotations.RestAnnotations(this)),e._liveObjectsPlugin&&(this._object=new e._liveObjectsPlugin.RestObject(this))}get annotations(){return this._annotations||D(`Annotations`),this._annotations}get push(){return this._push||D(`Push`),this._push}get object(){return this._object||D(`LiveObjects`),this._object}get logger(){return this.client.logger}setOptions(e){this.channelOptions=mt(this.client._Crypto??null,this.logger,e)}async history(e){return _.logAction(this.logger,_.LOG_MICRO,`RestChannel.history()`,`channel = `+this.name),this.client.rest.channelMixin.history(this,e??null)}async publish(...e){let t=e[0],n=e[1],r,i;if(typeof t==`string`||t===null)r=[H.fromValues({name:t,data:n})],i=e[2];else if(me(t))r=[H.fromValues(t)],i=e[1];else if(Array.isArray(t))r=H.fromValuesArray(t),i=e[1];else throw new v({message:`publish() expects an event name (string or null), a message object, or an array of message objects as its first argument`,code:40013,statusCode:400,remediation:`Call publish(name, data) for a single event, or publish(message | message[]) with a Message-shaped object.`});i||={};let a=this.client,o=a.options,s=o.useBinaryProtocol?`msgpack`:`json`,c=a.options.idempotentRestPublishing,l=k.defaultPostHeaders(a.options);if(b(l,o.headers),c&&Jn(r)){let e=await Re(qn);r.forEach(function(t,n){t.id=e+`:`+n.toString()})}let u=await Hn(r,this.channelOptions),d=Wn(u),f=o.maxMessageSize;if(d>f)throw new v({message:`Maximum size of messages that can be published at once exceeded (was ${d} bytes, against a limit of ${f} bytes)`,code:40009,statusCode:400,remediation:`Split the publish into multiple calls so each batch is under the limit. If you set ClientOptions.maxMessageSize yourself, raise it. It can only restrict below your account limit, not above it. To lift the account limit, contact Ably support.`});return this._publish(Un(u,a._MsgPack,s),l,i)}async _publish(e,t,n){let r=this.client,i=r.options.useBinaryProtocol?`msgpack`:`json`,{body:a,unpacked:o}=await z.post(r,r.rest.channelMixin.basePath(this)+`/messages`,e,t,n,null,!0),s=(o?a:T(a,r._MsgPack,i))||{};return delete s.channel,delete s.messageId,s}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(e){return _.logAction(this.logger,_.LOG_MICRO,`RestChannel.getMessage()`,`channel = `+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,`RestChannel.updateMessage()`,`channel = `+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,`message.update`,e,t,n)}async deleteMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,`RestChannel.deleteMessage()`,`channel = `+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,`message.delete`,e,t,n)}async appendMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,`RestChannel.appendMessage()`,`channel = `+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,`message.append`,e,t,n)}async getMessageVersions(e,t){return _.logAction(this.logger,_.LOG_MICRO,`RestChannel.getMessageVersions()`,`channel = `+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}},Xn=class e{constructor(e){this.entries=e&&e.entries||void 0,this.schema=e&&e.schema||void 0,this.appId=e&&e.appId||void 0,this.inProgress=e&&e.inProgress||void 0,this.unit=e&&e.unit||void 0,this.intervalId=e&&e.intervalId||void 0}static fromValues(t){return new e(t)}},Zn=class{static basePath(e){return`/channels/`+encodeURIComponent(e.name)}static history(e,t){let n=e.client,r=n.options.useBinaryProtocol?`msgpack`:`json`,i=e.client.http.supportsLinkHeaders?void 0:r,a=k.defaultGetHeaders(n.options);return b(a,n.options.headers),new B(n,this.basePath(e)+`/messages`,a,i,async function(t,i,a){return Vn(a?t:T(t,n._MsgPack,r),e)}).get(t)}static async status(e){let t=e.client.options.useBinaryProtocol?`msgpack`:`json`,n=k.defaultPostHeaders(e.client.options);return(await z.get(e.client,this.basePath(e),n,{},t,!0)).body}static async getMessage(e,t){let n=typeof t==`string`?t:t.serial;if(!n)throw new v({message:`This message lacks a serial`,code:40003,statusCode:400,remediation:`Pass the Message received from a subscribe callback (which carries .serial), or its serial string. Newly constructed Message objects do not have a serial.`});let r=e.client,i=r.options.useBinaryProtocol?`msgpack`:`json`,a=k.defaultGetHeaders(r.options);b(a,r.options.headers);let{body:o,unpacked:s}=await z.get(r,this.basePath(e)+`/messages/`+encodeURIComponent(n),a,{},null,!0);return Bn(s?o:T(o,r._MsgPack,i),e)}static async updateDeleteMessage(e,t,n,r,i){if(!n.serial)throw new v({message:`This message lacks a serial`,code:40003,statusCode:400,remediation:`Pass the Message received from a subscribe callback (which carries .serial), not a freshly constructed object.`});let a=e.client,o=a.options.useBinaryProtocol?`msgpack`:`json`,s=k.defaultPostHeaders(a.options);b(s,a.options.headers);let c=H.fromValues(n);c.action=t,c.version=r;let l=Un(await c.encode(e.channelOptions),a._MsgPack,o),u=z.patch,{body:d,unpacked:f}=await u(a,this.basePath(e)+`/messages/`+encodeURIComponent(n.serial),l,s,i||{},null,!0);return(f?d:T(d,a._MsgPack,o))||{versionSerial:null}}static getMessageVersions(e,t,n){let r=typeof t==`string`?t:t.serial;if(!r)throw new v({message:`This message lacks a serial`,code:40003,statusCode:400,remediation:`Pass the Message received from a subscribe callback (which carries .serial), or its serial string. Newly constructed Message objects do not have a serial.`});let i=e.client,a=i.options.useBinaryProtocol?`msgpack`:`json`,o=e.client.http.supportsLinkHeaders?void 0:a,s=k.defaultGetHeaders(i.options);return b(s,i.options.headers),new B(i,this.basePath(e)+`/messages/`+encodeURIComponent(r)+`/versions`,s,o,async(t,n,r)=>Vn(r?t:T(t,i._MsgPack,a),e)).get(n||{})}},Qn=class{static basePath(e){return Zn.basePath(e.channel)+`/presence`}static async history(e,t){let n=e.channel.client,r=n.options.useBinaryProtocol?`msgpack`:`json`,i=e.channel.client.http.supportsLinkHeaders?void 0:r,a=k.defaultGetHeaders(n.options);return b(a,n.options.headers),new B(n,this.basePath(e)+`/history`,a,i,async(t,i,a)=>jn(a?t:T(t,n._MsgPack,r),e.channel)).get(t)}},$n=class{constructor(e){this.channelMixin=Zn,this.presenceMixin=Qn,this.Resource=z,this.PaginatedResource=B,this.DeviceDetails=R,this.PushChannelSubscription=_n,this.client=e,this.channels=new er(this.client),this.push=new En(this.client)}async stats(e){let t=k.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?`msgpack`:`json`,r=this.client.http.supportsLinkHeaders?void 0:n;return b(t,this.client.options.headers),new B(this.client,`/stats`,t,r,async(e,t,r)=>{let i=r?e:T(e,this.client._MsgPack,n);for(let e=0;e<i.length;e++)i[e]=Xn.fromValues(i[e]);return i}).get(e)}async time(e){let t=k.defaultGetHeaders(this.client.options,{format:`json`});this.client.options.headers&&b(t,this.client.options.headers);let{error:n,body:r,unpacked:i}=await this.client.http.do(A.Get,e=>this.client.baseUri(e)+`/time`,t,null,e);if(n)throw n;i||(r=JSON.parse(r));let a=r[0];if(!a)throw new v(`Internal error (unexpected result type from GET /time)`,5e4,500);return this.client.serverTimeOffset=a-h.Config.now(),a}async request(e,t,n,r,i,a){let[o,s,c]=this.client.options.useBinaryProtocol?(this.client._MsgPack||D(`MsgPack`),[this.client._MsgPack.encode,this.client._MsgPack.decode,`msgpack`]):[JSON.stringify,JSON.parse,`json`],l=this.client.http.supportsLinkHeaders?void 0:c;r||={};let u=e.toLowerCase(),d=u==`get`?k.defaultGetHeaders(this.client.options,{format:c,protocolVersion:n}):k.defaultPostHeaders(this.client.options,{format:c,protocolVersion:n});typeof i!=`string`&&(i=o(i)??null),b(d,this.client.options.headers),a&&b(d,a);let f=new B(this.client,t,d,l,async function(e,t,n){return pe(n?e:s(e))},!0);if(!h.Http.methods.includes(u))throw new v({message:`Unsupported method `+u,code:40500,statusCode:405,remediation:`Use one of: ${h.Http.methods.join(`, `)}.`});return h.Http.methodsWithBody.includes(u)?f[u](r,i):f[u](r)}async batchPublish(e){let t,n;Array.isArray(e)?(t=e,n=!1):(t=[e],n=!0);let r=this.client.options.useBinaryProtocol?`msgpack`:`json`,i=k.defaultPostHeaders(this.client.options);this.client.options.headers&&b(i,this.client.options.headers);let a=E(t,this.client._MsgPack,r),o=await z.post(this.client,`/messages`,a,i,{},null,!0),s=o.unpacked?o.body:T(o.body,this.client._MsgPack,r);return n?s[0]:s}async batchPresence(e){let t=this.client.options.useBinaryProtocol?`msgpack`:`json`,n=k.defaultGetHeaders(this.client.options);this.client.options.headers&&b(n,this.client.options.headers);let r=e.join(`,`),i=await z.get(this.client,`/presence`,n,{channels:r},null,!0);return i.unpacked?i.body:T(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(Nt(this.client.options))throw new v({message:`Cannot revoke tokens when using token auth`,code:40162,statusCode:401,remediation:`Token revocation must use basic auth, so construct a separate Ably.Rest client with ClientOptions.key (the API key that issued the tokens) just for this call. Revocable tokens must have been enabled on the key in the Ably dashboard before the tokens were issued, otherwise there is nothing to revoke.`});let n=this.client.options.keyName,r=t??{},i=d({targets:e.map(e=>`${e.type}:${e.value}`)},r),a=this.client.options.useBinaryProtocol?`msgpack`:`json`,o=k.defaultPostHeaders(this.client.options);this.client.options.headers&&b(o,this.client.options.headers);let s=E(i,this.client._MsgPack,a),c=await z.post(this.client,`/keys/${n}/revokeTokens`,s,o,{},null,!0);return c.unpacked?c.body:T(c.body,this.client._MsgPack,a)}},er=class{constructor(e){this.client=e,this.all=Object.create(null)}get(e,t){e=String(e);let n=this.all[e];return n?t&&n.setOptions(t):this.all[e]=n=new Yn(this.client,e,t),n}release(e){delete this.all[String(e)]}},tr=class extends on{constructor(e){super(k.objectifyOptions(e,!1,`BaseRest`,_.defaultLogger,{Rest:$n}))}},nr={Rest:$n},rr=class extends H{static async fromEncoded(e,t){return Rn(_.defaultLogger,h.Crypto,e,t)}static async fromEncodedArray(e,t){return zn(_.defaultLogger,h.Crypto,e,t)}static fromValues(e){return H.fromValues(e)}},ir=class extends V{static async fromEncoded(e,t){return On(_.defaultLogger,h.Crypto,e,t)}static async fromEncodedArray(e,t){return kn(_.defaultLogger,h.Crypto,e,t)}static fromValues(e){return V.fromValues(e)}},ar=[`annotation.create`,`annotation.delete`];async function or(e,t,n){return U.fromValues(t).decode(n||{},e)}async function sr(e,t,n){return Promise.all(t.map(function(t){return or(e,t,n)}))}async function cr(e,t){return U.fromValues(e).decode(t.channelOptions,t.logger)}async function lr(e,t){return Promise.all(e.map(function(e){return cr(e,t)}))}var ur=class e extends L{async encode(){return Xt(Object.assign(new U,this,{action:ar.indexOf(this.action||`annotation.create`)}),{})}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return I(this,`Annotation`)}},U=class e extends L{toJSON(...e){return en.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decode(e,t){let n=Object.assign(new ur,f(d({},this),{action:ar[this.action]}));try{await Qt(n,e)}catch(e){_.logAction(t,_.LOG_ERROR,`WireAnnotation.decode()`,C(e))}return n}toString(){return I(this,`WireAnnotation`)}},W=ur,dr=class extends W{static async fromEncoded(e,t){return or(_.defaultLogger,e,t)}static async fromEncodedArray(e,t){return sr(_.defaultLogger,e,t)}static fromValues(e){return W.fromValues(e)}};function fr(e,t){let n;switch(typeof e){case`string`:n=e;break;case`object`:n=e.serial}if(!n||typeof n!=`string`)throw new v({message:`The message argument of annotations.`+t+"() must be either a Message or other object carrying a non-empty string `serial` property, or a message serial as a non-empty string",code:40003,statusCode:400,remediation:`Pass the Message received from a subscribe callback (which carries .serial), or its serial string. Newly constructed Message objects do not have a serial.`});return n}function pr(e,t,n){let r=fr(e,n);if(!t||typeof t!=`object`)throw new v({message:`Second argument of annotations.`+n+`() must be an object (the intended annotation to publish)`,code:40003,statusCode:400,remediation:`Pass an Annotation-shaped object as the second argument, e.g. { type: "reaction:unique.v1", name: "👍" }.`});let i=W.fromValues(t);return i.messageSerial=r,i.action||=`annotation.create`,i}function mr(e,t){return e.client.rest.channelMixin.basePath(e)+`/messages/`+encodeURIComponent(t)+`/annotations`}var hr=class{constructor(e){this.channel=e}async publish(e,t){return this._publish(e,t,`publish`)}async _publish(e,t,n){let r=pr(e,t,n),i=await r.encode(),a=this.channel.client,o=a.options.useBinaryProtocol?`msgpack`:`json`,s=k.defaultPostHeaders(a.options),c={};b(s,a.options.headers);let l=E([i],a._MsgPack,o);await z.post(a,mr(this.channel,r.messageSerial),l,s,c,null,!0)}async delete(e,t){return t.action=`annotation.delete`,this._publish(e,t,`delete`)}async get(e,t){let n=this.channel.client,r=fr(e,`get`),i=n.options.useBinaryProtocol?`msgpack`:`json`,a=n.http.supportsLinkHeaders?void 0:i,o=k.defaultGetHeaders(n.options);return b(o,n.options.headers),new B(n,mr(this.channel,r),o,a,async(e,t,r)=>lr(r?e:T(e,n._MsgPack,i),this.channel)).get(t)}},gr=E;function _r(e){let t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return`[ `+t.join(`, `)+` ]`}function vr(e,t,n,r,i,a){return yr(T(e,t,a),n,r,i)}function yr(e,t,n,r){let i;e.error&&(i=v.fromValues(e.error));let a;e.messages&&(a=Kn.fromValuesArray(e.messages));let o;t&&e.presence&&(o=t.WirePresenceMessage.fromValuesArray(e.presence));let s;n&&e.annotations&&(s=n.WireAnnotation.fromValuesArray(e.annotations));let c;return r&&e.state&&(c=r.WireObjectMessage.fromValuesArray(e.state,le,nn)),Object.assign(new Sr,f(d({},e),{presence:o,messages:a,annotations:s,state:c,error:i}))}function br(e){return t=>yr(t,{PresenceMessage:V,WirePresenceMessage:Nn},{Annotation:W,WireAnnotation:U,RealtimeAnnotations:kr,RestAnnotations:hr},e?.LiveObjectsPlugin??null)}function G(e){return Object.assign(new Sr,e)}function xr(e,t,n,r){let i=`[ProtocolMessage`;e.action!==void 0&&(i+=`; action=`+Ut[e.action]||e.action);let a=[`id`,`channel`,`channelSerial`,`connectionId`,`count`,`msgSerial`,`timestamp`],o;for(let t=0;t<a.length;t++)o=a[t],e[o]!==void 0&&(i+=`; `+o+`=`+e[o]);if(e.messages&&(i+=`; messages=`+_r(Kn.fromValuesArray(e.messages))),e.presence&&t&&(i+=`; presence=`+_r(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(i+=`; annotations=`+_r(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&r&&(i+=`; state=`+_r(r.WireObjectMessage.fromValuesArray(e.state,le,nn))),e.error&&(i+=`; error=`+v.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(i+=`; token=`+e.auth.accessToken),e.flags&&(i+=`; flags=`+Wt.filter(e.hasFlag).join(`,`)),e.params){let t=``;De(e.params,function(n){t.length>0&&(t+=`; `),t+=n+`=`+e.params[n]}),t.length>0&&(i+=`; params=[`+t+`]`)}return i+=`]`,i}var Sr=class{constructor(){this.hasFlag=e=>(this.flags&F[e])>0}setFlag(e){return this.flags|=F[e]}getMode(){return(this.flags||0)&F.MODE_ALL}encodeModesToFlags(e){e.forEach(e=>this.setFlag(e))}decodeModesFromFlags(){let e=[];return Gt.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},Cr=Sr,wr=class{constructor(e,t,n,r,i){this.previous=e,this.current=t,t===`attached`&&(this.resumed=n,this.hasBacklog=r),i&&(this.reason=i)}};function Tr(e){if(e&&`params`in e&&!me(e.params))return new v({message:`options.params must be an object`,code:4e4,statusCode:400,remediation:`Pass an object map of channel params (e.g. { rewind: "1" }), not a string or array.`});if(e&&`modes`in e){if(!Array.isArray(e.modes))return new v({message:`options.modes must be an array`,code:4e4,statusCode:400,remediation:`Pass an array of ChannelMode strings, e.g. { modes: ["publish", "subscribe"] }.`});for(let t=0;t<e.modes.length;t++){let n=e.modes[t];if(!n||typeof n!=`string`||!Gt.includes(String.prototype.toUpperCase.call(n)))return new v({message:`Invalid channel mode: `+n,code:4e4,statusCode:400,remediation:`Valid ChannelMode values are: ${Gt.join(`, `).toLowerCase()}. The server grants only the modes the key or token capability permits and silently drops the rest on attach. After attach, channel.modes shows what was granted. If you have the Ably CLI installed, \`ably auth keys list\` shows your key's capabilities.`})}}}var Er=class e extends N{constructor(e,t,n){super(e.logger),this._annotations=null,this._mode=0,this._silentSubscribeWarned=!1,this.retryCount=0,this.history=function(...e){return S(e,0),this._historyImpl(e[0])},this._historyImpl=async function(e){_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.history()`,`channel = `+this.name);let t=this.client.rest.channelMixin;if(e&&e.untilAttach){if(this.state!==`attached`)throw new v({message:`option untilAttach requires the channel to be attached, was: `+this.state,code:4e4,statusCode:400,remediation:`Await channel.attach() before calling history({ untilAttach: true }).`});if(!this.properties.attachSerial)throw new v({message:`untilAttach was specified and channel is attached, but attachSerial is not defined`,code:4e4,statusCode:400,remediation:`Detach the channel (await channel.detach()) and re-attach (await channel.attach()) so the SDK records the attachSerial from the new attach, then retry history({ untilAttach: true }).`});delete e.untilAttach,e.from_serial=this.properties.attachSerial}return t.history(this,e)},this.whenState=e=>N.prototype.whenState.call(this,e,this.state),_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel()`,`started; name = `+t),this.name=t,this.channelOptions=mt(e._Crypto??null,this.logger,n),this.client=e,this._presence=e._RealtimePresence?new e._RealtimePresence.RealtimePresence(this):null,e._Annotations&&(this._annotations=new e._Annotations.RealtimeAnnotations(this)),this.connectionManager=e.connection.connectionManager,this.state=`initialized`,this.subscriptions=new N(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this._decodingContext={channelOptions:this.channelOptions,plugins:e.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._attachedReceived=new N(this.logger),this.internalStateChanges=new N(this.logger),e.options.plugins?.Push&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._liveObjectsPlugin&&(this._object=new e._liveObjectsPlugin.RealtimeObject(this))}get presence(){return this._presence||D(`RealtimePresence`),this._presence}get annotations(){return this._annotations||D(`Annotations`),this._annotations}get push(){return this._push||D(`Push`),this._push}get object(){return this._object||D(`LiveObjects`),this._object}emit(e,...t){super.emit(e,...t),this.internalStateChanges.emit(e,...t)}invalidStateError(){return new v({message:`Channel operation failed as channel state is `+this.state,code:90001,statusCode:400,cause:this.errorReason||void 0,remediation:`Inspect channel.errorReason for the underlying cause. It may be null after a clean detach. From "failed" or "detached", call channel.attach() to recover. From "suspended" the SDK re-attaches automatically, or call channel.attach() to retry now.`})}static processListenerArgs(e){return e=Array.prototype.slice.call(e),typeof e[0]==`function`&&e.unshift(null),e}async setOptions(e){let t=this.channelOptions,n=Tr(e);if(n)throw n;if(this.channelOptions=mt(this.client._Crypto??null,this.logger,e),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(e,t))return this.attachImpl(),new Promise((e,t)=>{let n=()=>{this._attachedReceived.off(r),this.internalStateChanges.off(i)},r=()=>{n(),e()},i=e=>{n(),t(e.reason)};this._attachedReceived.once(`attached`,r),this.internalStateChanges.once([`detached`,`failed`],i)})}_shouldReattachToSetOptions(e,t){if(this.state!==`attached`&&this.state!==`attaching`)return!1;if(e?.params){let n=Dr(e.params),r=Dr(t.params);if(Object.keys(n).length!==Object.keys(r).length||!Ke(r,n))return!0}return!!(e?.modes&&(!t.modes||!Ye(e.modes,t.modes)))}publish(...e){return S(e,0),this._publishImpl(e)}async _publishImpl(e){let t=e[0],n=e[1],r,i;if(typeof t==`string`||t==null)r=[H.fromValues({name:t,data:n})],i=e[2];else if(me(t))r=[H.fromValues(t)],i=e[1];else if(Array.isArray(t))r=H.fromValuesArray(t),i=e[1];else throw new v({message:`The single-argument form of publish() expects a message object or an array of message objects`,code:40013,statusCode:400,remediation:`Call publish(name, data) for a single event, or publish(message | message[]) with a Message-shaped object.`});let a=this.client.options.maxMessageSize,o=await Hn(r,this.channelOptions),s=Wn(o);if(s>a)throw new v({message:`Maximum size of messages that can be published at once exceeded (was ${s} bytes, against a limit of ${a} bytes)`,code:40009,statusCode:400,remediation:`Split the publish into multiple calls so each batch is under the limit. If a single message exceeds the limit, reduce its payload size. To lift the account limit, contact Ably support.`});this.throwIfUnpublishableState(),_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.publish()`,`sending message; channel state is `+this.state+`, message count = `+o.length);let c=G({action:P.MESSAGE,channel:this.name,messages:o,params:i?Me(i):void 0});return this.sendAndAwaitAck(c)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state===`failed`||this.state===`suspended`)throw this.invalidStateError()}onEvent(e){_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.onEvent()`,`received message`);let t=this.subscriptions;for(let n=0;n<e.length;n++){let r=e[n];t.emit(r.name,r)}}async attach(){return this.state===`attached`?null:new Promise((e,t)=>{this._attach(!1,null,(n,r)=>n?t(n):e(r))})}_attach(e,t,n){n||=e=>{e&&_.logAction(this.logger,_.LOG_ERROR,`RealtimeChannel._attach()`,`Channel attach failed: `+e.toString())};let r=this.connectionManager;if(!r.activeState()){n(r.getError());return}(this.state!==`attaching`||e)&&this.requestState(`attaching`,t),this.internalStateChanges.once(function(e){switch(this.event){case`attached`:n?.(null,e);break;case`detached`:case`suspended`:case`failed`:n?.(e.reason||r.getError()||new v(`Unable to attach; reason unknown; state = `+this.event,9e4,500));break;case`detaching`:n?.(new v(`Attach request superseded by a subsequent detach request`,9e4,409))}})}attachImpl(){_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.attachImpl()`,`sending ATTACH message`);let e=G({action:P.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&e.encodeModesToFlags(Ve(this.channelOptions.modes)),this._lastPayload.decodeFailureRecoveryInProgress&&(e.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.send(e)}async detach(){let e=this.connectionManager;switch(this.state){case`suspended`:this.notifyState(`detached`);return;case`detached`:return;case`failed`:throw new v({message:`Unable to detach as channel state is failed`,code:90001,statusCode:400,remediation:`A failed channel is not attached, so there is nothing to detach. Inspect channel.errorReason for the cause. Call channel.attach() to recover the channel, or channels.release(name) to discard it.`});default:if(e.state.state!==`connected`){this.notifyState(`detached`);return}this.requestState(`detaching`);case`detaching`:return new Promise((t,n)=>{this.internalStateChanges.once(function(r){switch(this.event){case`detached`:t();break;case`attached`:case`suspended`:case`failed`:n(r.reason||e.getError()||new v(`Unable to detach; reason unknown; state = `+this.event,9e4,500));break;case`attaching`:n(new v(`Detach request superseded by a subsequent attach request`,9e4,409))}})})}}detachImpl(){_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.detach()`,`sending DETACH message`);let e=G({action:P.DETACH,channel:this.name});this.send(e)}subscribe(...e){return S(e,2),this._subscribeImpl(e)}async _subscribeImpl(t){let[n,r]=e.processListenerArgs(t);if(this.state===`failed`)throw v.fromValues(this.invalidStateError());n&&typeof n==`object`&&!Array.isArray(n)?this.client._FilteredSubscriptions.subscribeFilter(this,n,r):this.subscriptions.on(n,r);let i=null;if(this.channelOptions.attachOnSubscribe!==!1&&(i=await this.attach()),this.state===`attached`&&(this._mode&F.SUBSCRIBE)===0){let e=new v({message:`The channel was attached without the subscribe mode, so the server will not deliver messages to this listener.`,code:90009,statusCode:400,remediation:'Include "subscribe" in the channel modes: realtime.channels.get(name, { modes: ["subscribe", ...] }), or call channel.setOptions({ modes: [...] }) on an existing channel to trigger a reattach. Alternatively, omit modes entirely and ensure your token/API-key capability permits subscribe on this channel. If you have the Ably CLI installed, `ably auth keys list` shows your key\'s capabilities.'});if(this.client.options.strictMode===!0)throw e;this._silentSubscribeWarned||=(_.logActionNoStrip(this.logger,_.LOG_ERROR,`RealtimeChannel.subscribe()`,e.message+`; remediation=`+e.remediation+_.silentFailureLogSuffix()),!0)}return i}unsubscribe(...t){let[n,r]=e.processListenerArgs(t);if(typeof n==`object`&&!r||this.filteredSubscriptions?.has(r)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,n,r).forEach(e=>this.subscriptions.off(e));return}this.subscriptions.off(n,r)}sync(){switch(this.state){case`initialized`:case`detaching`:case`detached`:throw new y({message:`Unable to sync to channel; not attached`,code:4e4})}let e=this.connectionManager;if(!e.activeState())throw e.getError();let t=G({action:P.SYNC,channel:this.name});this.syncChannelSerial&&(t.channelSerial=this.syncChannelSerial),e.send(t)}send(e){this.connectionManager.send(e)}async sendAndAwaitAck(e){return new Promise((t,n)=>{this.connectionManager.send(e,this.client.options.queueMessages,(e,r)=>{e?n(e):t(r)})})}async sendPresence(e){let t=G({action:P.PRESENCE,channel:this.name,presence:e});await this.sendAndAwaitAck(t)}requeuePresenceFromConnectionQueue(e){if(this._presence&&(this.state===`attached`||this.state===`attaching`||this.state===`suspended`)){let t=e.callback;return this._presence.requeuePresenceMessages(e.message.presence??[],e=>t?.(e)),!0}return!1}async sendState(e){let t=G({action:P.OBJECT,channel:this.name,state:e});return this.sendAndAwaitAck(t)}async processMessage(e){(e.action===P.ATTACHED||e.action===P.MESSAGE||e.action===P.PRESENCE||e.action===P.OBJECT||e.action===P.ANNOTATION)&&this.setChannelSerial(e.channelSerial);let t,n=!1;switch(e.action){case P.ATTACHED:{let t=e.hasFlag(`RESUMED`);t||(this.properties.attachSerial=e.channelSerial),this._mode=e.getMode(),this._silentSubscribeWarned=!1,this.params=e.params||{};let n=e.decodeModesFromFlags();this.modes=n&&Be(n)||void 0;let r=e.hasFlag(`HAS_PRESENCE`),i=e.hasFlag(`HAS_BACKLOG`),a=e.hasFlag(`HAS_OBJECTS`);if(this._attachedReceived.emit(`attached`),this.state===`attached`){t||this._presence&&this._presence.onAttached(r),this._object&&this._object.onAttached(a);let n=new wr(this.state,this.state,t,i,e.error);(!t||this.channelOptions.updateOnAttached)&&this.emit(`update`,n)}else this.state===`detaching`?this.checkPendingState():this.notifyState(`attached`,e.error,t,r,i,a);break}case P.DETACHED:{let t=e.error?v.fromValues(e.error):new v(`Channel detached`,90001,404);this.state===`detaching`?this.notifyState(`detached`,t):this.state===`attaching`?this.notifyState(`suspended`,t):(this.state===`attached`||this.state===`suspended`)&&this.requestState(`attaching`,t);break}case P.SYNC:if(n=!0,t=this.syncChannelSerial=e.channelSerial,!e.presence)break;case P.PRESENCE:{if(!e.presence)break;rn(e);let r=this.channelOptions;if(this._presence){let i=await Promise.all(e.presence.map(e=>e.decode(r,this.logger)));this._presence.setPresence(i,n,t)}break}case P.OBJECT:case P.OBJECT_SYNC:{if(!this._object||!e.state)return;rn(e);let t=this.client.connection.connectionManager.getActiveTransportFormat(),n=e.state.map(e=>e.decode(this.client,t));e.action===P.OBJECT?this._object.handleObjectMessages(n):this._object.handleObjectSyncMessages(n,e.channelSerial);break}case P.MESSAGE:{if(this.state!==`attached`){_.logAction(this.logger,_.LOG_MAJOR,`RealtimeChannel.processMessage()`,`Message "`+e.id+`" skipped as this channel "`+this.name+`" state is not "attached" (state is "`+this.state+`").`);return}rn(e);let t=e.messages,n=t[0],r=t[t.length-1];if(n.extras&&n.extras.delta&&n.extras.delta.from!==this._lastPayload.messageId){let t=`Delta message decode failure - previous message not available for message "`+e.id+`" on this channel "`+this.name+`".`;_.logAction(this.logger,_.LOG_ERROR,`RealtimeChannel.processMessage()`,t),this._startDecodeFailureRecovery(new v(t,40018,400));break}let i=[];for(let e=0;e<t.length;e++){let{decoded:n,err:r}=await t[e].decodeWithErr(this._decodingContext,this.logger);if(i[e]=n,r)switch(r.code){case 40018:this._startDecodeFailureRecovery(r);return;case 40019:case 40021:this.notifyState(`failed`,r);return}}this._lastPayload.messageId=r.id,this._lastPayload.protocolMessageChannelSerial=e.channelSerial,this.onEvent(i);break}case P.ANNOTATION:{rn(e);let t=this.channelOptions;if(this._annotations){let n=await Promise.all((e.annotations||[]).map(e=>e.decode(t,this.logger)));this._annotations._processIncoming(n)}break}case P.ERROR:{let t=e.error;t&&t.code==80016?this.checkPendingState():this.notifyState(`failed`,v.fromValues(t));break}default:_.logAction(this.logger,_.LOG_MAJOR,`RealtimeChannel.processMessage()`,`Protocol error: unrecognised message action (`+e.action+`)`)}}_startDecodeFailureRecovery(e){this._lastPayload.decodeFailureRecoveryInProgress||(_.logAction(this.logger,_.LOG_MAJOR,`RealtimeChannel.processMessage()`,`Starting decode failure recovery process.`),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,e,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel.onAttached`,`activating channel; name = `+this.name)}notifyState(e,t,n,r,i,a){if(_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.notifyState`,`name = `+this.name+`, current state = `+this.state+`, notifying state `+e),this.clearStateTimer(),[`detached`,`failed`].includes(e)&&(this.properties.channelSerial=null),e===this.state)return;this._presence&&this._presence.actOnChannelState(e,r,t),this._object&&this._object.actOnChannelState(e,a),e===`suspended`&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),t&&(this.errorReason=t);let o=new wr(this.state,e,n,i,t),s=`Channel state for channel "`+this.name+`"`,c=e+(t?`; reason: `+t:``);e===`failed`?_.logAction(this.logger,_.LOG_ERROR,s,c):_.logAction(this.logger,_.LOG_MAJOR,s,c),e!==`attaching`&&e!==`suspended`&&(this.retryCount=0),e===`attached`&&this.onAttached(),this.state=e,this.emit(e,o)}requestState(e,t){_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel.requestState`,`name = `+this.name+`, state = `+e),this.notifyState(e,t),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel.checkPendingState`,`sendEvents is false; state is `+this.connectionManager.state.state);return}switch(_.logAction(this.logger,_.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()}}timeoutPendingState(){switch(this.state){case`attaching`:{let e=new v({message:`Channel attach timed out`,code:90007,statusCode:408,remediation:`The channel is now suspended. The SDK retries the attach automatically while the connection is connected, and you can call channel.attach() to retry immediately. Inspect channel.errorReason if it keeps timing out.`});this.notifyState(`suspended`,e);break}case`detaching`:{let e=new v({message:`Channel detach timed out`,code:90007,statusCode:408,remediation:`The detach timed out and the channel is back in the attached state. Call channel.detach() again to retry. Inspect channel.errorReason if it keeps timing out.`});this.notifyState(`attached`,e);break}default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||=h.Config.setTimeout(()=>{_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel.startStateTimerIfNotRunning`,`timer expired`),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout)}clearStateTimer(){let e=this.stateTimer;e&&(h.Config.clearTimeout(e),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let e=We(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=h.Config.setTimeout(()=>{this.state===`suspended`&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel retry timer expired`,`attempting a new attach`),this.requestState(`attaching`))},e)}cancelRetryTimer(){this.retryTimer&&=(h.Config.clearTimeout(this.retryTimer),null)}getReleaseErr(){let e=this.state;return e===`initialized`||e===`detached`||e===`failed`?null:new v({message:`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). The current state is `+e,code:90001,statusCode:400,remediation:`Call channel.detach() and wait for the channel to reach "detached" before calling channels.release(name).`})}setChannelSerial(e){_.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.setChannelSerial()`,`Updating channel serial; serial = `+e+`; previous = `+this.properties.channelSerial),e&&(this.properties.channelSerial=e)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(e){return _.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.getMessage()`,`channel = `+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.updateMessage()`,`channel = `+this.name),this.sendUpdate(e,`message.update`,t,n)}async deleteMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.deleteMessage()`,`channel = `+this.name),this.sendUpdate(e,`message.delete`,t,n)}async appendMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.appendMessage()`,`channel = `+this.name),this.sendUpdate(e,`message.append`,t,n)}async sendUpdate(e,t,n,r){if(!e.serial)throw new v({message:`This message lacks a serial`,code:40003,statusCode:400,remediation:`Pass the Message received from a subscribe callback (which carries .serial), not a freshly constructed object.`});this.throwIfUnpublishableState();let i=await H.fromValues(f(d({},e),{action:t,version:n})).encode(this.channelOptions),a=G({action:P.MESSAGE,channel:this.name,messages:[i],params:r?Me(r):void 0});return{versionSerial:(await this.sendAndAwaitAck(a)).serials[0]??null}}async getMessageVersions(e,t){return _.logAction(this.logger,_.LOG_MICRO,`RealtimeChannel.getMessageVersions()`,`channel = `+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}async ensureAttached(){switch(this.state){case`attached`:case`suspended`:break;case`initialized`:case`detached`:case`detaching`:case`attaching`:await this.attach();break;default:throw v.fromValues(this.invalidStateError())}}};function Dr(e){let t=e||{},{agent:n}=t;return p(t,[`agent`])}var Or=Er,kr=class{constructor(e){this.channel=e,this.logger=e.logger,this.subscriptions=new N(this.logger)}async publish(e,t){let n=this.channel.name,r=pr(e,t,`publish`),i=await r.encode();this.channel.throwIfUnpublishableState(),_.logAction(this.logger,_.LOG_MICRO,`RealtimeAnnotations.publish()`,`channelName = `+n+`, sending annotation with messageSerial = `+r.messageSerial+`, type = `+r.type);let a=G({action:P.ANNOTATION,channel:n,annotations:[i]});await this.channel.sendAndAwaitAck(a)}async delete(e,t){t.action=`annotation.delete`,await this.publish(e,t)}async subscribe(...e){let t=Or.processListenerArgs(e),n=t[0],r=t[1],i=this.channel;if(i.state===`failed`)throw v.fromValues(i.invalidStateError());if(this.subscriptions.on(n,r),this.channel.channelOptions.attachOnSubscribe!==!1&&await i.attach(),this.channel.state===`attached`&&(this.channel._mode&F.ANNOTATION_SUBSCRIBE)===0){let e=new v({message:`You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)`,code:93001,statusCode:400,remediation:'Include "annotation_subscribe" in the channel modes: realtime.channels.get(name, { modes: ["annotation_subscribe", ...] }), or call channel.setOptions({ modes: [...] }) on an existing channel to trigger a reattach. Calling channels.get(name, { modes }) on an existing channel throws. The server only grants the mode if your key or token has the annotation-subscribe capability. Without it the attach succeeds but the server silently drops the mode and annotations are never delivered. `ably auth keys list` shows your key\'s capabilities.'});throw _.logActionNoStrip(this.logger,_.LOG_MAJOR,`RealtimeAnnotations.subscribe()`,e.message+`; remediation=`+e.remediation),e}}unsubscribe(...e){let t=Or.processListenerArgs(e),n=t[0],r=t[1];this.subscriptions.off(n,r)}_processIncoming(e){for(let t of e)this.subscriptions.emit(t.type||``,t)}async get(e,t){return hr.prototype.get.call(this,e,t)}},K=class e extends tr{constructor(t){if(!e._MsgPack)throw Error(`Expected DefaultRest._MsgPack to have been set`);super(k.objectifyOptions(t,!0,`Rest`,_.defaultLogger,f(d({},nr),{Crypto:e.Crypto??void 0,MsgPack:e._MsgPack??void 0,Annotations:{Annotation:W,WireAnnotation:U,RealtimeAnnotations:kr,RestAnnotations:hr}})))}static get Crypto(){if(this._Crypto===null)throw Error(`Encryption not enabled; use ably.encryption.js instead`);return this._Crypto}static set Crypto(e){this._Crypto=e}};K._Crypto=null,K.Message=rr,K.PresenceMessage=ir,K.Annotation=dr,K._MsgPack=null,K._Http=Bt;var Ar=K,jr=class extends N{constructor(e){super(e),this.messages=[]}count(){return this.messages.length}push(e){this.messages.push(e)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(e){this.messages.push.apply(this.messages,e)}prepend(e){this.messages.unshift.apply(this.messages,e)}completeMessages(e,t,n){_.logAction(this.logger,_.LOG_MICRO,`MessageQueue.completeMessages()`,e==`all`?`(all)`:`serial = `+e.serial+`; count = `+e.count),t||=null;let r=this.messages;if(r.length===0)throw Error(`MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue`);let i=[];if(e===`all`)i=r.splice(0);else{let t=r[0];if(t){let n=t.message.msgSerial,a=e.serial+e.count;a>n&&(i=r.splice(0,a-n))}}for(let e=0;e<i.length;e++){let r=i[e],a=n?.[e];r.callback(t,a)}r.length==0&&this.emit(`idle`)}completeAllMessages(e){this.completeMessages(`all`,e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){_.logAction(this.logger,_.LOG_MICRO,`MessageQueue.clear()`,`clearing `+this.messages.length+` messages`),this.messages=[],this.emit(`idle`)}},Mr=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;let n=e.action;this.sendAttempted=!1,this.ackRequired=typeof n==`number`&&[P.MESSAGE,P.PRESENCE,P.ANNOTATION,P.OBJECT].includes(n)}},Nr=class extends N{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new jr(this.logger),e.on(`ack`,(e,t,n)=>{this.onAck(e,t,n)}),e.on(`nack`,(e,t,n)=>{this.onNack(e,t,n)})}onAck(e,t,n){_.logAction(this.logger,_.LOG_MICRO,`Protocol.onAck()`,`serial = `+e+`; count = `+t),this.messageQueue.completeMessages({serial:e,count:t},null,n)}onNack(e,t,n){_.logAction(this.logger,_.LOG_ERROR,`Protocol.onNack()`,`serial = `+e+`; count = `+t+`; err = `+C(n)),n||=new v(`Unable to send message; channel not responding`,50001,500),this.messageQueue.completeMessages({serial:e,count:t},n)}onceIdle(e){let t=this.messageQueue;if(t.count()===0){e();return}t.once(`idle`,e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(_.LOG_MICRO)&&_.logActionNoStrip(this.logger,_.LOG_MICRO,`Protocol.send()`,`sending msg; `+xr(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let e=this.transport;this.onceIdle(function(){e.disconnect()})}},Pr=class{constructor(e,t,n,r){this.previous=e,this.current=t,n&&(this.retryIn=n),r&&(this.reason=r)}},q={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Fr={disconnected:()=>v.fromValues({statusCode:400,code:q.DISCONNECTED,message:`Connection to server temporarily unavailable`}),suspended:()=>v.fromValues({statusCode:400,code:q.SUSPENDED,message:`Connection to server unavailable`}),failed:()=>v.fromValues({statusCode:400,code:q.FAILED,message:`Connection failed or disconnected by server`}),closing:()=>v.fromValues({statusCode:400,code:q.CLOSING,message:`Connection closing`}),closed:()=>v.fromValues({statusCode:400,code:q.CLOSED,message:`Connection closed`}),unknownConnectionErr:()=>v.fromValues({statusCode:500,code:q.UNKNOWN_CONNECTION_ERR,message:`Internal connection error`}),unknownChannelErr:()=>v.fromValues({statusCode:500,code:q.UNKNOWN_CONNECTION_ERR,message:`Internal channel error`})};function Ir(e){return!e.statusCode||!e.code||e.statusCode>=500||Object.values(q).includes(e.code)}var J=Fr,Lr=G({action:P.CLOSE}),Rr=G({action:P.DISCONNECT}),zr=class extends N{constructor(e,t,n,r){super(e.logger),r&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=e,this.auth=t,this.params=n,this.timeouts=n.options.timeouts,this.format=n.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish(`closed`,J.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish(`disconnected`,e||J.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish(`failed`,e||J.failed())}finish(e,t){this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,h.Config.clearTimeout(this.idleTimer??void 0),this.idleTimer=null,this.emit(e,t),this.dispose())}onProtocolMessage(e){switch(this.logger.shouldLog(_.LOG_MICRO)&&_.logActionNoStrip(this.logger,_.LOG_MICRO,`Transport.onProtocolMessage()`,`received on `+this.shortName+`: `+xr(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+`; connectionId = `+this.connectionManager.connectionId),this.onActivity(),e.action){case P.HEARTBEAT:_.logActionNoStrip(this.logger,_.LOG_MICRO,`Transport.onProtocolMessage()`,this.shortName+` heartbeat; connectionId = `+this.connectionManager.connectionId),this.emit(`heartbeat`,e.id);break;case P.CONNECTED:this.onConnect(e),this.emit(`connected`,e.error,e.connectionId,e.connectionDetails,e);break;case P.CLOSED:this.onClose(e);break;case P.DISCONNECTED:this.onDisconnect(e);break;case P.ACK:this.emit(`ack`,e.msgSerial,e.count,e.res);break;case P.NACK:this.emit(`nack`,e.msgSerial,e.count,e.error);break;case P.SYNC:this.connectionManager.onChannelMessage(e,this);break;case P.ACTIVATE:break;case P.AUTH:w(this.auth.authorize(),e=>{e&&_.logAction(this.logger,_.LOG_ERROR,`Transport.onProtocolMessage()`,`Ably requested re-authentication, but unable to obtain a new token: `+C(e))});break;case P.ERROR:if(_.logAction(this.logger,_.LOG_MINOR,`Transport.onProtocolMessage()`,`received error action; connectionId = `+this.connectionManager.connectionId+`; err = `+h.Config.inspect(e.error)+(e.channel?`, channel: `+e.channel:``)),e.channel===void 0){this.onFatalError(e);break}this.connectionManager.onChannelMessage(e,this);break;default:this.connectionManager.onChannelMessage(e,this)}}onConnect(e){if(this.isConnected=!0,!e.connectionDetails)throw Error(`Transport.onConnect(): Connect message recieved without connectionDetails`);let t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){let t=e&&e.error;_.logAction(this.logger,_.LOG_MINOR,`Transport.onDisconnect()`,`err = `+C(t)),this.finish(`disconnected`,t)}onFatalError(e){let t=e&&e.error;_.logAction(this.logger,_.LOG_MINOR,`Transport.onFatalError()`,`err = `+C(t)),this.finish(`failed`,t)}onClose(e){let t=e&&e.error;_.logAction(this.logger,_.LOG_MINOR,`Transport.onClose()`,`err = `+C(t)),this.finish(`closed`,t)}requestClose(){_.logAction(this.logger,_.LOG_MINOR,`Transport.requestClose()`,``),this.send(Lr)}requestDisconnect(){_.logAction(this.logger,_.LOG_MINOR,`Transport.requestDisconnect()`,``),this.send(Rr)}ping(e){let t={action:P.HEARTBEAT};e&&(t.id=e),this.send(G(t))}dispose(){_.logAction(this.logger,_.LOG_MINOR,`Transport.dispose()`,``),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=h.Config.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(e){this.idleTimer||=h.Config.setTimeout(()=>{this.onIdleTimerExpire()},e)}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw Error(`Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set`);this.idleTimer=null;let e=h.Config.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){let t=`No activity seen from realtime in `+e+`ms; assuming connection has dropped`;_.logAction(this.logger,_.LOG_ERROR,`Transport.onIdleTimerExpire()`,t),this.disconnect(new v(t,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,r,i){let a=new e(t,n,r),o,s=function(e){h.Config.clearTimeout(o),i({event:this.event,error:e})},c=t.options.timeouts.realtimeRequestTimeout;return o=h.Config.setTimeout(()=>{a.off([`preconnect`,`disconnected`,`failed`]),a.dispose(),s.call({event:`disconnected`},new v(`Timeout waiting for transport to indicate itself viable`,5e4,500))},c),a.on([`failed`,`disconnected`],s),a.on(`preconnect`,function(){_.logAction(t.logger,_.LOG_MINOR,`Transport.tryConnect()`,`viable transport `+a),h.Config.clearTimeout(o),a.off([`failed`,`disconnected`],s),i(null,a)}),a.connect(),a}static isAvailable(){throw new v(`isAvailable not implemented for transport`,5e4,500)}},Y;(e=>{e.WebSocket=`web_socket`,e.Comet=`comet`,e.XhrPolling=`xhr_polling`})(Y||={});var Br=typeof global<`u`?global:typeof window<`u`?window:self,Vr=()=>h.WebStorage!==void 0&&h.WebStorage?.localSupported,Hr=()=>h.WebStorage!==void 0&&h.WebStorage?.sessionSupported,Ur=function(){},Wr=`ably-transport-preference`;function Gr(e){try{return JSON.parse(e)}catch{return null}}var Kr=class{constructor(e,t,n,r){this.options=e,this.host=t,this.mode=n,this.connectionKey=r,this.format=e.useBinaryProtocol?`msgpack`:`json`}getConnectParams(e){let t=e?fe(e):{},n=this.options;switch(this.mode){case`resume`:t.resume=this.connectionKey;break;case`recover`:{let e=Gr(n.recover);e&&(t.recover=e.connectionKey);break}}return n.clientId!==void 0&&(t.clientId=n.clientId),n.echoMessages===!1&&(t.echo=`false`),this.format!==void 0&&(t.format=this.format),this.stream!==void 0&&(t.stream=this.stream),this.heartbeats!==void 0&&(t.heartbeats=this.heartbeats),t.v=k.protocolVersion,t.agent=ut(this.options),n.transportParams!==void 0&&b(t,n.transportParams),t}toString(){let e=`[mode=`+this.mode;return this.host&&(e+=`,host=`+this.host),this.connectionKey&&(e+=`,connectionKey=`+this.connectionKey),this.format&&(e+=`,format=`+this.format),e+=`]`,e}},qr=class e extends N{constructor(e,t){super(e.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=e,this.initTransports(),this.options=t;let n=t.timeouts,r=n.webSocketConnectTimeout+n.realtimeRequestTimeout;if(this.states={initialized:{state:`initialized`,terminal:!1,queueEvents:!0,sendEvents:!1,failState:`disconnected`},connecting:{state:`connecting`,terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:r,failState:`disconnected`},connected:{state:`connected`,terminal:!1,queueEvents:!1,sendEvents:!0,failState:`disconnected`},disconnected:{state:`disconnected`,terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:n.disconnectedRetryTimeout,failState:`disconnected`},suspended:{state:`suspended`,terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.suspendedRetryTimeout,failState:`suspended`},closing:{state:`closing`,terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.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`}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new jr(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=n.connectionStateTtl,this.maxIdleInterval=null,this.transports=be(t.transports||k.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(Y.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(Y.XhrPolling)?this.baseTransport=Y.XhrPolling:this.transports.includes(Y.Comet)&&(this.baseTransport=Y.Comet),this.domains=k.getHosts(t),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.wsCheckPromise=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,_.logAction(this.logger,_.LOG_MINOR,`Realtime.ConnectionManager()`,`started`),_.logAction(this.logger,_.LOG_MICRO,`Realtime.ConnectionManager()`,`requested transports = [`+(t.transports||k.defaultTransports)+`]`),_.logAction(this.logger,_.LOG_MICRO,`Realtime.ConnectionManager()`,`available transports = [`+this.transports+`]`),_.logAction(this.logger,_.LOG_MICRO,`Realtime.ConnectionManager()`,`http domains = [`+this.domains+`]`),!this.transports.length){let e=`no requested transports available`;throw _.logAction(this.logger,_.LOG_ERROR,`realtime.ConnectionManager()`,e),Error(e)}let i=h.Config.addEventListener;i&&(Hr()&&typeof t.recover==`function`&&i(`beforeunload`,this.persistConnection.bind(this)),t.closeOnUnload===!0&&i(`beforeunload`,()=>{_.logAction(this.logger,_.LOG_MAJOR,`Realtime.ConnectionManager()`,`beforeunload event has triggered the connection to close as closeOnUnload is true`),this.requestState({state:`closing`})}),i(`online`,()=>{var e;this.state==this.states.disconnected||this.state==this.states.suspended?(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager caught browser ‘online’ event`,`reattempting connection`),this.requestState({state:`connecting`})):this.state==this.states.connecting&&((e=this.pendingTransport)==null||e.off(),this.disconnectAllTransports(),this.startConnect())}),i(`offline`,()=>{this.state==this.states.connected&&(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager caught browser ‘offline’ event`,`disconnecting active transport`),this.disconnectAllTransports())}))}static supportedTransports(e){let t={supportedTransports:{}};return this.initTransports(e,t),t.supportedTransports}static initTransports(e,t){let n=d(d({},h.Transports.bundledImplementations),e);[Y.WebSocket,...h.Transports.order].forEach(e=>{let r=n[e];r&&r.isAvailable()&&(t.supportedTransports[e]=r)})}initTransports(){e.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(e,t){return new Kr(this.options,e,t,this.connectionKey)}getTransportParams(e){(e=>{if(this.connectionKey){e(`resume`);return}if(typeof this.options.recover==`string`){e(`recover`);return}let t=this.options.recover,n=this.getSessionRecoverData(),r=this.sessionRecoveryName();if(n&&typeof t==`function`){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.getTransportParams()`,`Calling clientOptions-provided recover function with last session data (recovery scope: `+r+`)`),t(n,t=>{t?(this.options.recover=n.recoveryKey,e(`recover`)):e(`clean`)});return}e(`clean`)})(t=>{let n=this.createTransportParams(null,t);if(t===`recover`){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.getTransportParams()`,`Transport recovery mode = recover; recoveryKey = `+this.options.recover);let e=Gr(this.options.recover);e&&(this.msgSerial=e.msgSerial)}else _.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.getTransportParams()`,`Transport params = `+n.toString());e(n)})}tryATransport(e,t,n){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.tryATransport()`,`trying `+t),this.proposedTransport=zr.tryConnect(this.supportedTransports[t],this,this.realtime.auth,e,(r,i)=>{let a=this.state;if(a==this.states.closing||a==this.states.closed||a==this.states.failed){i&&(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.tryATransport()`,`connection `+a.state+` while we were attempting the transport; closing `+i),i.close()),n(!0);return}if(r){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.tryATransport()`,`transport `+t+` `+r.event+`, err: `+r.error.toString()),j.isTokenErr(r.error)&&!(this.errorReason&&j.isTokenErr(this.errorReason))?(this.errorReason=r.error,w(this.realtime.auth._forceNewToken(null,null),r=>{if(r){this.actOnErrorFromAuthorize(r);return}this.tryATransport(e,t,n)})):r.event===`failed`?(this.notifyState({state:`failed`,error:r.error}),n(!0)):r.event===`disconnected`&&(Ir(r.error)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:r.error}),n(!0)));return}_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.tryATransport()`,`viable transport `+t+`; setting pending`),this.setTransportPending(i,e),n(null,i)})}setTransportPending(e,t){let n=t.mode;_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.setTransportPending()`,`transport = `+e+`; mode = `+n),this.pendingTransport=e,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),e.once(`connected`,(t,r,i)=>{this.activateTransport(t,e,r,i),n===`recover`&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let r=this;e.on([`disconnected`,`closed`,`failed`],function(t){r.deactivateTransport(e,this.event,t)}),this.emit(`transport.pending`,e)}activateTransport(e,t,n,r){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.activateTransport()`,`transport = `+t),e&&_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.activateTransport()`,`error = `+e),n&&_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.activateTransport()`,`connectionId = `+n),r&&_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.activateTransport()`,`connectionDetails = `+JSON.stringify(r)),this.persistTransportPreference(t);let i=this.state,a=this.states.connected.state;if(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.activateTransport()`,`current state = `+i.state),i.state==this.states.closing.state||i.state==this.states.closed.state||i.state==this.states.failed.state)return _.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.activateTransport()`,`Disconnecting transport and abandoning`),t.disconnect(),!1;if(delete this.pendingTransport,!t.isConnected)return _.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.activateTransport()`,`Declining to activate transport `+t+` since it appears to no longer be connected`),!1;let o=this.activeProtocol;this.activeProtocol=new Nr(t),this.host=t.params.host;let s=r.connectionKey;if(s&&this.connectionKey!=s&&this.setConnection(n,r,!!e),this.onConnectionDetailsUpdate(r,t),h.Config.nextTick(()=>{t.on(`connected`,(e,n,r)=>{this.onConnectionDetailsUpdate(r,t),this.emit(`update`,new Pr(a,a,null,e))})}),i.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit(`update`,new Pr(a,a,null,e))):(this.notifyState({state:`connected`,error:e}),this.errorReason=this.realtime.connection.errorReason=e||null),this.emit(`transport.active`,t),o){if(o.messageQueue.count()>0&&_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.activateTransport()`,`Previous active protocol (for transport `+o.transport.shortName+`, new one is `+t.shortName+`) finishing with `+o.messageQueue.count()+` messages still pending`),o.transport===t){let e=`Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = `+t.shortName+`; stack = `+Error().stack;_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.activateTransport()`,e)}else o.finish()}return!0}deactivateTransport(e,t,n){let r=this.activeProtocol,i=r&&r.getTransport()===e,a=e===this.pendingTransport,o=this.noTransportsScheduledForActivation();if(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.deactivateTransport()`,`transport = `+e),_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.deactivateTransport()`,`state = `+t+(i?`; was active`:a?`; was pending`:``)+(o?``:`; another transport is scheduled for activation`)),n&&n.message&&_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.deactivateTransport()`,`reason = `+n.message),i&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.deactivateTransport()`,`Getting, clearing, and requeuing `+this.activeProtocol.messageQueue.count()+` pending messages`),this.queuePendingMessages(r.getPendingMessages()),r.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit(`transport.inactive`,e),i&&o||i&&t===`failed`||t===`closed`||r===null&&a){if(t===`disconnected`&&n&&n.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:t,error:n,retryImmediately:!0});return}let e=t===`failed`&&j.isTokenErr(n)?`disconnected`:t;this.notifyState({state:e,error:n});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(e,t,n){let r=this.connectionId;(r&&r!==e||!r&&n)&&(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.setConnection()`,`Resetting msgSerial`),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==e&&_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.setConnection()`,`New connectionId; reattaching any attached channels`),this.realtime.connection.id=this.connectionId=e,this.realtime.connection.key=this.connectionKey=t.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.queuedMessages.resetSendAttempted(),this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}persistConnection(){if(Hr()){let e=this.createRecoveryKey();e&&this.setSessionRecoverData({recoveryKey:e,disconnectedAt:h.Config.now(),location:Br.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){return this.activeProtocol?.getTransport().format}getError(){if(this.errorReason){let e=y.fromValues(this.errorReason);return e.cause=this.errorReason,e}return this.getStateError()}getStateError(){var e;return(e=J)[this.state.state]?.call(e)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(e){let t=`Connection state`,n=e.current+(e.reason?`; reason: `+e.reason:``);e.current===`failed`?_.logAction(this.logger,_.LOG_ERROR,t,n):_.logAction(this.logger,_.LOG_MAJOR,t,n),_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.enactStateChange`,`setting new state: `+e.current+`; reason = `+(e.reason&&e.reason.message));let r=this.state=this.states[e.current];e.reason&&(this.errorReason=e.reason,this.realtime.connection.errorReason=e.reason),r.terminal&&this.clearConnection(),this.emit(`connectionstate`,e)}startTransitionTimer(e){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.startTransitionTimer()`,`transitionState: `+e.state),this.transitionTimer&&(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.startTransitionTimer()`,`clearing already-running timer`),h.Config.clearTimeout(this.transitionTimer)),this.transitionTimer=h.Config.setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager `+e.state+` timer expired`,`requesting new state: `+e.failState),this.notifyState({state:e.failState}))},e.retryDelay)}cancelTransitionTimer(){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.cancelTransitionTimer()`,``),this.transitionTimer&&=(h.Config.clearTimeout(this.transitionTimer),null)}startSuspendTimer(){this.suspendTimer||=h.Config.setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager suspend timer expired`,`requesting new state: suspended`),this.states.connecting.failState=`suspended`,this.notifyState({state:`suspended`}))},this.connectionStateTtl)}checkSuspendTimer(e){e!==`disconnected`&&e!==`suspended`&&e!==`connecting`&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState=`disconnected`,this.suspendTimer&&=(h.Config.clearTimeout(this.suspendTimer),null)}startRetryTimer(e){this.retryTimer=h.Config.setTimeout(()=>{_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager retry timer expired`,`retrying`),this.retryTimer=null,this.requestState({state:`connecting`})},e)}cancelRetryTimer(){this.retryTimer&&=(h.Config.clearTimeout(this.retryTimer),null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=h.Config.setTimeout(()=>{_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager WebSocket slow timer`,`checking connectivity`),this.checkWsConnectivityOnce().then(e=>{e?_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager WebSocket slow timer`,`ws connectivity check succeeded`):_.logAction(this.logger,_.LOG_MAJOR,`ConnectionManager WebSocket slow timer`,`ws connectivity check failed`)}),this.realtime.http.checkConnectivity&&w(this.realtime.http.checkConnectivity(),(e,t)=>{e||!t?(_.logAction(this.logger,_.LOG_MAJOR,`ConnectionManager WebSocket slow timer`,`http connectivity check failed`),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:`disconnected`,error:new v(`Unable to connect (network unreachable)`,80003,404)})):_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager WebSocket slow timer`,`http connectivity check succeeded`)})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&=(h.Config.clearTimeout(this.webSocketSlowTimer),null)}startWebSocketGiveUpTimer(e){this.webSocketGiveUpTimer=h.Config.setTimeout(()=>{this.wsCheckResult||(this.baseTransport?(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager WebSocket give up timer`,`websocket connection took more than `+this.options.timeouts.webSocketConnectTimeout+`ms`),this.abandonWebSocketForBaseTransport(e)):_.logAction(this.logger,_.LOG_MAJOR,`ConnectionManager WebSocket give up timer`,`websocket connectivity appears to be unavailable but no other transports to try`))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&=(h.Config.clearTimeout(this.webSocketGiveUpTimer),null)}notifyState(e){var t;let n=e.state,r=n===`disconnected`&&(this.state===this.states.connected||e.retryImmediately||this.state===this.states.connecting&&e.error&&j.isTokenErr(e.error)&&!(this.errorReason&&j.isTokenErr(this.errorReason)));if(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.notifyState()`,`new state: `+n+(r?`; will retry connection immediately`:``)),n==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(e.state),(n===`suspended`||n===`connected`)&&(this.disconnectedRetryCount=0),this.state.terminal))return;let i=this.states[e.state],a=i.retryDelay;i.state===`disconnected`&&(this.disconnectedRetryCount++,a=We(i.retryDelay,this.disconnectedRetryCount));let o=new Pr(this.state.state,i.state,a,e.error||(t=J)[i.state]?.call(t));if(r){let e=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=h.Config.now(),this.requestState({state:`connecting`}))},t=this.lastAutoReconnectAttempt&&h.Config.now()-this.lastAutoReconnectAttempt+1;t&&t<1e3?(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.notifyState()`,`Last reconnect attempt was only `+t+`ms ago, waiting another `+(1e3-t)+`ms before trying again`),h.Config.setTimeout(e,1e3-t)):h.Config.nextTick(e)}else(n===`disconnected`||n===`suspended`)&&this.startRetryTimer(a);(n===`disconnected`&&!r||n===`suspended`||i.terminal)&&h.Config.nextTick(()=>{this.disconnectAllTransports()}),n==`connected`&&!this.activeProtocol&&_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.notifyState()`,`Broken invariant: attempted to go into connected state, but there is no active protocol`),this.enactStateChange(o),this.state.sendEvents?(this.queuedPresenceToChannelQueues(),this.sendQueuedMessages()):this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(n,o.reason),this.failQueuedMessages(o.reason))}requestState(e){var t;let n=e.state;if(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.requestState()`,`requested state: `+n+`; current state: `+this.state.state),n==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(n),n==`connecting`&&this.state.state==`connected`)||n==`closing`&&this.state.state==`closed`)return;let r=this.states[n],i=new Pr(this.state.state,r.state,null,e.error||(t=J)[r.state]?.call(t));this.enactStateChange(i),n==`connecting`&&h.Config.nextTick(()=>{this.startConnect()}),n==`closing`&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.startConnect()`,`Must be in connecting state to connect, but was `+this.state.state);return}let e=this.realtime.auth,t=++this.connectCounter,n=()=>{this.getTransportParams(e=>{if(e.mode===`recover`&&e.options.recover){let t=Gr(e.options.recover);t&&this.realtime.channels.recoverChannels(t.channelSerials)}t===this.connectCounter&&this.connectImpl(e,t)})};if(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.startConnect()`,`starting connection`),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),e.method===`basic`)n();else{let r=e=>{t===this.connectCounter&&(e?this.actOnErrorFromAuthorize(e):n())};this.errorReason&&j.isTokenErr(this.errorReason)?w(e._forceNewToken(null,null),r):w(e._ensureValidAuthCredentials(!1),r)}}connectImpl(e,t){let n=this.state.state;if(n!==this.states.connecting.state){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.connectImpl()`,`Must be in connecting state to connect, but was `+n);return}let r=this.getTransportPreference();r&&r===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.connectImpl():`,`web socket connectivity available, cancelling connection attempt with `+this.baseTransport),this.disconnectAllTransports(),this.connectWs(e,++this.connectCounter))}).catch(Ur),r&&r===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(e,t):this.connectWs(e,t)}connectWs(e,t){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.connectWs()`),this.wsCheckResult=null,this.wsCheckPromise=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(e),this.tryTransportWithFallbacks(`web_socket`,e,!0,t,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(e,t){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.connectBase()`),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,e,!1,t,()=>!0):this.notifyState({state:`disconnected`,error:new v(`No transports left to try`,8e4,404)})}abandonWebSocketForBaseTransport(e){var t,n;_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.abandonWebSocketForBaseTransport()`,`websocket connectivity appears to be unavailable; trying base transport`),this.abandonedWebSocket=!0,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),(t=this.proposedTransport)==null||t.dispose(),(n=this.pendingTransport)==null||n.dispose(),this.connectBase(e,++this.connectCounter)}checkWsAvailabilityBeforeGivingUp(e,t,n){return!this.baseTransport||this.abandonedWebSocket||this.wsCheckResult?!1:(this.checkWsConnectivityOnce().then(r=>{t!==this.connectCounter||this.abandonedWebSocket||this.state!==this.states.connecting||(r?n(new v(`Unable to connect (and no more fallback hosts to try)`,80003,404)):this.abandonWebSocketForBaseTransport(e))}),!0)}checkWsConnectivityOnce(){return this.wsCheckPromise||=this.checkWsConnectivity().then(()=>(this.wsCheckResult=!0,!0),()=>(this.wsCheckResult=!1,!1)),this.wsCheckPromise}tryTransportWithFallbacks(e,t,n,r,i){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.tryTransportWithFallbacks()`,e);let a=e=>{this.notifyState({state:this.states.connecting.failState,error:e})},o=this.domains.slice(),s=(e,t)=>{if(r===this.connectCounter){if(!i()){t&&t.dispose();return}!t&&!e&&l()}},c=o.shift();if(!c){a(new v(`Unable to connect (no available host)`,80003,404));return}t.host=c;let l=()=>{if(!o.length){if(n&&this.checkWsAvailabilityBeforeGivingUp(t,r,a))return;a(new v(`Unable to connect (and no more fallback hosts to try)`,80003,404));return}if(!this.realtime.http.checkConnectivity){a(new y(`Internal error: Http.checkConnectivity not set`,null,500));return}w(this.realtime.http.checkConnectivity(),(n,c)=>{if(r===this.connectCounter&&i()){if(n){a(n);return}if(!c){a(new v(`Unable to connect (network unreachable)`,80003,404));return}t.host=Ae(o),this.tryATransport(t,e,s)}})};if(this.forceFallbackHost&&o.length){this.forceFallbackHost=!1,l();return}this.tryATransport(t,e,s)}closeImpl(){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.closeImpl()`,`closing connection`),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.closeImpl()`,`Closing pending transport: `+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.closeImpl()`,`Closing active transport: `+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:`closed`})}onAuthUpdated(e,t){switch(this.state.state){case`connected`:{_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.onAuthUpdated()`,`Sending AUTH message on active transport`);let n=this.activeProtocol?.getTransport();n&&n.onAuthUpdated&&n.onAuthUpdated(e);let r=G({action:P.AUTH,auth:{accessToken:e.token}});this.send(r);let i=()=>{this.off(a),t(null,e)},a=e=>{e.current===`failed`&&(this.off(i),this.off(a),t(e.reason||this.getStateError()))};this.once(`connectiondetails`,i),this.on(`connectionstate`,a);break}case`connecting`:_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.onAuthUpdated()`,`Aborting current connection attempts in order to start again with the new auth details`),this.disconnectAllTransports();default:{_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.onAuthUpdated()`,`Connection state is `+this.state.state+`; waiting until either connected or failed`);let n=r=>{switch(r.current){case`connected`:this.off(n),t(null,e);break;case`failed`:case`closed`:case`suspended`:this.off(n),t(r.reason||this.getStateError())}};this.on(`connectionstate`,n),this.state.state===`connecting`?this.startConnect():this.requestState({state:`connecting`})}}}disconnectAllTransports(){_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.disconnectAllTransports()`,`Disconnecting all transports`),this.connectCounter++,this.pendingTransport&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.disconnectAllTransports()`,`Disconnecting pending transport: `+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.disconnectAllTransports()`,`Disconnecting proposed transport: `+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.disconnectAllTransports()`,`Disconnecting active transport: `+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(e,t,n){n||=Ur;let r=this.state;if(r.sendEvents){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.send()`,`sending event`),this.sendImpl(new Mr(e,n));return}if(!(t&&r.queueEvents)){let e=`rejecting event, queueEvent was `+t+`, state was `+r.state;_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.send()`,e),n(this.errorReason||new v(e,9e4,400));return}this.logger.shouldLog(_.LOG_MICRO)&&_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.send()`,`queueing msg; `+xr(e,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(e,n)}sendImpl(e){let t=e.message;e.ackRequired&&!e.sendAttempted&&(t.msgSerial=this.msgSerial++);try{this.activeProtocol.send(e)}catch(e){_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.sendImpl()`,`Unexpected exception in transport.send(): `+e.stack)}}queue(e,t){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.queue()`,`queueing event`),this.queuedMessages.push(new Mr(e,t))}queuedPresenceToChannelQueues(){this.queuedMessages.messages=this.queuedMessages.messages.filter(e=>{if(e.message.action!==P.PRESENCE)return!0;let t=e.message.channel,n=t?this.realtime.channels.all[t]:void 0;return!(n&&n.requeuePresenceFromConnectionQueue(e))})}sendQueuedMessages(){_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.sendQueuedMessages()`,`sending `+this.queuedMessages.count()+` queued messages`);let e;for(;e=this.queuedMessages.shift();)this.sendImpl(e)}queuePendingMessages(e){e&&e.length&&(_.logAction(this.logger,_.LOG_MICRO,`ConnectionManager.queuePendingMessages()`,`queueing `+e.length+` pending messages`),this.queuedMessages.prepend(e))}failQueuedMessages(e){let t=this.queuedMessages.count();t>0&&(_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.failQueuedMessages()`,`failing `+t+` queued messages, err = `+C(e)),this.queuedMessages.completeAllMessages(e))}onChannelMessage(e,t){this.pendingChannelMessagesState.queue.push({message:e,transport:t}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let e=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(e.message).catch(e=>{_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.processNextPendingChannelMessage() received error `,e)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(e){await this.realtime.channels.processChannelMessage(e)}async ping(){if(this.state.state!==`connected`)throw new v({message:`Unable to ping service: not connected`,code:4e4,statusCode:400,remediation:`Wait for connection.state to be "connected" before calling ping(). Use await connection.whenState("connected") or connection.once("connected", …). From the "closed" or "failed" state, or "initialized" with autoConnect disabled, the SDK does not connect automatically, so call connection.connect() first.`});let e=this.activeProtocol?.getTransport();if(!e)throw this.getStateError();_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.ping()`,`transport = `+e);let t=h.Config.now(),n=Le();return Ze(new Promise(r=>{let i=a=>{a===n&&(e.off(`heartbeat`,i),r(h.Config.now()-t))};e.on(`heartbeat`,i),e.ping(n)}),this.options.timeouts.realtimeRequestTimeout,`Timeout waiting for heartbeat response`)}abort(e){this.activeProtocol.getTransport().fail(e)}getTransportPreference(){var e;return this.transportPreference||Vr()&&((e=h.WebStorage)?.get)?.call(e,Wr)}persistTransportPreference(e){var t,n;this.transportPreference=e.shortName,Vr()&&((n=(t=h.WebStorage)?.set)==null||n.call(t,Wr,e.shortName))}unpersistTransportPreference(){var e,t;this.transportPreference=null,Vr()&&((t=(e=h.WebStorage)?.remove)==null||t.call(e,Wr))}actOnErrorFromAuthorize(e){if(e.code===40171)this.notifyState({state:`failed`,error:e});else if(e.code===40102)this.notifyState({state:`failed`,error:e});else if(e.statusCode===wt.Forbidden){let t=`Client configured authentication provider returned 403, failing the connection`;_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.actOnErrorFromAuthorize()`,t);let n=new v({message:t,code:80019,statusCode:403,cause:e,remediation:`Inspect cause for the underlying error, then fix your authUrl/authCallback so it does not respond 403 for a valid client.`});this.notifyState({state:`failed`,error:n})}else{let t=`Client configured authentication provider request failed`;_.logAction(this.logger,_.LOG_MINOR,`ConnectionManager.actOnErrorFromAuthorize`,t);let n=new v({message:t,code:80019,statusCode:401,cause:e,remediation:`Check network connectivity to your authUrl/authCallback endpoint and that it returns a valid token shape. Inspect cause for the underlying error.`});this.notifyState({state:this.state.failState,error:n})}}onConnectionDetailsUpdate(e,t){if(!e)return;this.connectionDetails=e,e.maxMessageSize&&(this.options.maxMessageSize=e.maxMessageSize);let n=e.clientId;if(n){let e=this.realtime.auth._uncheckedSetClientId(n);if(e){_.logAction(this.logger,_.LOG_ERROR,`ConnectionManager.onConnectionDetailsUpdate()`,e.message),t.fail(e);return}}let r=e.connectionStateTtl;r&&(this.connectionStateTtl=r),this.maxIdleInterval=e.maxIdleInterval,this.emit(`connectiondetails`,e)}checkWsConnectivity(){let e=this.options.wsConnectivityCheckUrl||k.wsConnectivityCheckUrl,t=new h.Config.WebSocket(e);return new Promise((e,n)=>{let r=!1;t.onopen=()=>{r||(r=!0,e(),t.close())},t.onclose=t.onerror=()=>{r||(r=!0,n())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||`ably-connection-recovery`}getSessionRecoverData(){var e;return Hr()&&((e=h.WebStorage)?.getSession)?.call(e,this.sessionRecoveryName())}setSessionRecoverData(e){var t;return Hr()&&((t=h.WebStorage)?.setSession)?.call(t,this.sessionRecoveryName(),e)}clearSessionRecoverData(){var e;return Hr()&&((e=h.WebStorage)?.removeSession)?.call(e,this.sessionRecoveryName())}},Jr=class extends N{constructor(e,t){super(e.logger),this.whenState=e=>N.prototype.whenState.call(this,e,this.state),this.ably=e,this.connectionManager=new qr(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on(`connectionstate`,e=>{let t=this.state=e.current;h.Config.nextTick(()=>{this.emit(t,e)})}),this.connectionManager.on(`update`,e=>{h.Config.nextTick(()=>{this.emit(`update`,e)})})}connect(){_.logAction(this.logger,_.LOG_MINOR,`Connection.connect()`,``),this.connectionManager.requestState({state:`connecting`})}ping(...e){return S(e,0),this._pingImpl()}async _pingImpl(){return _.logAction(this.logger,_.LOG_MINOR,`Connection.ping()`,``),this.connectionManager.ping()}close(){_.logAction(this.logger,_.LOG_MINOR,`Connection.close()`,`connectionKey = `+this.key),this.connectionManager.requestState({state:`closing`})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},Yr=class e extends on{constructor(t){if(super(k.objectifyOptions(t,!1,`BaseRealtime`,_.defaultLogger)),_.logAction(this.logger,_.LOG_MINOR,`Realtime()`,``),typeof EdgeRuntime==`string`)throw new v(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=e.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=this.options.plugins?.RealtimePresence??null,this.connection=new Jr(this,this.options),this._channels=new Zr(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(e){let t={};return e?.WebSocketTransport&&(t[Y.WebSocket]=e.WebSocketTransport),e?.XHRPolling&&(t[Y.XhrPolling]=e.XHRPolling),t}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){_.logAction(this.logger,_.LOG_MINOR,`Realtime.connect()`,``),this.connection.connect()}close(){_.logAction(this.logger,_.LOG_MINOR,`Realtime.close()`,``),this.connection.close()}};Yr.EventEmitter=N;var Xr=Yr,Zr=class extends N{constructor(e){super(e.logger),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on(`transport.active`,()=>{this.onTransportActive()})}channelSerials(){let e={};for(let t of Te(this.all,!0)){let n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(let t of Te(e,!0)){let n=this.get(t);n.properties.channelSerial=e[t]}}async processChannelMessage(e){let t=e.channel;if(t===void 0){_.logAction(this.logger,_.LOG_ERROR,`Channels.processChannelMessage()`,`received event unspecified channel, action = `+e.action);return}let n=this.all[t];if(!n){_.logAction(this.logger,_.LOG_ERROR,`Channels.processChannelMessage()`,`received event for non-existent channel: `+t);return}await n.processMessage(e)}onTransportActive(){for(let e in this.all){let t=this.all[e];t.state===`attaching`||t.state===`detaching`?t.checkPendingState():t.state===`suspended`?t._attach(!1,null):t.state===`attached`&&t.requestState(`attaching`)}}propogateConnectionInterruption(e,t){let n={closing:`detached`,closed:`detached`,failed:`failed`,suspended:`suspended`},r=[`attaching`,`attached`,`detaching`,`suspended`],i=n[e];for(let e in this.all){let n=this.all[e];r.includes(n.state)&&n.notifyState(i,t)}}get(e,t){e=String(e);let n=this.all[e];if(!n)n=this.all[e]=new Or(this.realtime,e,t);else if(t){if(n._shouldReattachToSetOptions(t,n.channelOptions))throw new v({message:`Channels.get() cannot be used to set channel options that would cause the channel to reattach: channels.get() returns the existing channel instance.`,code:4e4,statusCode:400,remediation:`To change params or modes on an existing channel, call channel.setOptions(opts) on the channel returned by channels.get(name). setOptions() re-attaches the channel to apply the new options.`});n.setOptions(t)}return n}getDerived(e,t,n){if(t.filter){let n=Je(t.filter),r=qe(e);e=`[filter=${n}${r.qualifierParam}]${r.channelName}`}return this.get(e,n)}release(e){e=String(e),_.logAction(this.logger,_.LOG_MAJOR,`Channels.release()`,`Releasing references to channel `+e);let t=this.all[e];if(!t)return;let n=t.state;if(n===`initialized`||n===`detached`||n===`failed`){delete this.all[e];return}t.detach().catch(t=>{_.logAction(this.logger,_.LOG_ERROR,`Channels.release()`,`Error detaching channel `+e+` prior to release: `+C(t))}).then(()=>{delete this.all[e]})}},Qr=Xr;function $r(e,t){if(e.isSynthesized()||t.isSynthesized())return e.timestamp>=t.timestamp;let n=e.parseId(),r=t.parseId();return n.msgSerial===r.msgSerial?n.index>r.index:n.msgSerial>r.msgSerial}var ei=class extends N{constructor(e,t,n=$r){super(e.logger),this.presence=e,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=t,this.newerThan=n}get(e){return this.map[e]}getClient(e){let t=this.map,n=[];for(let r in t){let i=t[r];i.clientId==e&&i.action!=`absent`&&n.push(i)}return n}list(e){let t=this.map,n=e&&e.clientId,r=e&&e.connectionId,i=[];for(let e in t){let a=t[e];a.action!==`absent`&&(n&&n!=a.clientId||r&&r!=a.connectionId||i.push(a))}return i}put(e){(e.action===`enter`||e.action===`update`)&&(e=V.fromValues(e),e.action=`present`);let t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];let r=t[n];return r&&!this.newerThan(e,r)?!1:(t[n]=e,!0)}values(){let e=this.map,t=[];for(let n in e){let r=e[n];r.action!=`absent`&&t.push(r)}return t}remove(e){let t=this.map,n=this.memberKey(e),r=t[n];return r&&!this.newerThan(e,r)?!1:(this.syncInProgress?(e=V.fromValues(e),e.action=`absent`,t[n]=e):delete t[n],!!r)}startSync(){let e=this.map,t=this.syncInProgress;_.logAction(this.logger,_.LOG_MINOR,`PresenceMap.startSync()`,`channel = `+this.presence.channel.name+`; syncInProgress = `+t),this.residualMembers=Object.create(null);for(let t in e)e[t].action!==`absent`&&(this.residualMembers[t]=e[t]);this.setInProgress(!0)}endSync(){let e=this.map,t=this.syncInProgress;if(_.logAction(this.logger,_.LOG_MINOR,`PresenceMap.endSync()`,`channel = `+this.presence.channel.name+`; syncInProgress = `+t),t){for(let t in e)e[t].action===`absent`&&delete e[t];this.presence._synthesizeLeaves(Ee(this.residualMembers));for(let t in this.residualMembers)delete e[t];this.residualMembers=null,this.setInProgress(!1)}this.emit(`sync`)}async waitSync(){let e=this.syncInProgress;_.logAction(this.logger,_.LOG_MINOR,`PresenceMap.waitSync()`,`channel = `+this.presence.channel.name+`; syncInProgress = `+e),e&&await this.once(`sync`)}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){_.logAction(this.logger,_.LOG_MICRO,`PresenceMap.setInProgress()`,`inProgress = `+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function ti(e){return e.channel.client.auth.clientId}function ni(e){let t=e.channel.client,n=t.auth.clientId;return(!n||n===`*`)&&t.connection.state===`connected`}var ri=class extends N{constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new ei(this,e=>e.clientId+`:`+e.connectionId),this._myMembers=new ei(this,e=>e.clientId),this.subscriptions=new N(this.logger),this.pendingPresence=[]}enter(...e){return S(e,0),this._enterImpl(e[0])}async _enterImpl(e){if(ni(this))throw new v({message:`clientId must be specified to enter a presence channel`,code:40012,statusCode:400,remediation:`Set ClientOptions.clientId (or include clientId in the token) before calling presence.enter() again. To enter on behalf of another identity, use presence.enterClient(otherId, data), which requires the library to be instantiated with an API key or a token bound to a wildcard clientId.`});return this._enterOrUpdateClient(void 0,void 0,e,`enter`)}update(...e){return S(e,0),this._updateImpl(e[0])}async _updateImpl(e){if(ni(this))throw new v({message:`clientId must be specified to update presence data`,code:40012,statusCode:400,remediation:`Set ClientOptions.clientId (or include clientId in the token) before calling presence.update() again. To update on behalf of another identity, use presence.updateClient(otherId, data), which requires the library to be instantiated with an API key or a token bound to a wildcard clientId.`});return this._enterOrUpdateClient(void 0,void 0,e,`update`)}async enterClient(e,t){return this._enterOrUpdateClient(void 0,e,t,`enter`)}async updateClient(e,t){return this._enterOrUpdateClient(void 0,e,t,`update`)}async _enterOrUpdateClient(e,t,n,r){let i=this.channel;if(!i.connectionManager.activeState())throw i.connectionManager.getError();_.logAction(this.logger,_.LOG_MICRO,`RealtimePresence.`+r+`Client()`,`channel = `+i.name+`, id = `+e+`, client = `+(t||`(implicit) `+ti(this)));let a=V.fromData(n);a.action=r,e&&(a.id=e),t&&(a.clientId=t);let o=await a.encode(i.channelOptions);switch(i.state){case`attached`:return i.sendPresence([o]);case`initialized`:case`detached`:i.attach();case`attaching`:if(i.client.options.queueMessages)return new Promise((e,t)=>{this.pendingPresence.push({presence:o,callback:n=>n?t(n):e()})});default:{let e=new y(`Unable to `+r+` presence channel while in `+i.state+` state`,90001);throw e.code=90001,e}}}leave(...e){return S(e,0),this._leaveImpl(e[0])}async _leaveImpl(e){if(ni(this))throw new v({message:`clientId must have been specified to enter or leave a presence channel`,code:40012,statusCode:400,remediation:`To leave a member entered on behalf of another identity, call presence.leaveClient(otherId). A client that never had a clientId has no self-entered member to leave. leaveClient requires the library to be instantiated with an API key or a token bound to a wildcard clientId.`});return this.leaveClient(void 0,e)}async leaveClient(e,t){let n=this.channel;if(!n.connectionManager.activeState())throw n.connectionManager.getError();_.logAction(this.logger,_.LOG_MICRO,`RealtimePresence.leaveClient()`,`leaving; channel = `+this.channel.name+`, client = `+e);let r=V.fromData(t);r.action=`leave`,e&&(r.clientId=e);let i=await r.encode(n.channelOptions);switch(n.state){case`attached`:return n.sendPresence([i]);case`attaching`:if(n.client.options.queueMessages)return new Promise((e,t)=>{this.pendingPresence.push({presence:i,callback:n=>n?t(n):e()})});default:throw new y({message:`Unable to leave presence channel while in `+n.state+` state`,code:90001,remediation:`presence.leave() only works while the channel is attached. From "suspended" or "attaching", await channel.attach() and retry, since your presence membership is restored when the channel re-attaches. From "initialized", "detached", or "failed" there is nothing to leave: either no member was entered, or the SDK already cleared your membership when the channel left the attached state.`})}}get(...e){return S(e,0),this._getImpl(e[0])}async _getImpl(e){let t=!e||(`waitForSync`in e?e.waitForSync:!0);function n(t){return e?t.list(e):t.values()}if(this.channel.state===`suspended`){if(t)throw v.fromValues({statusCode:400,code:91005,message:`Presence state is out of sync due to channel being in the SUSPENDED state`,remediation:`Wait for the channel to reach "attached" before calling presence.get(), or pass { waitForSync: false } to read the last known (stale) members.`});return n(this.members)}if(await this.channel.ensureAttached(),(this.channel._mode&F.PRESENCE_SUBSCRIBE)===0){let e=new v({message:`The channel was attached without the presence_subscribe mode, so the server has not delivered any members to this client.`,code:91008,statusCode:400,remediation:'Include "presence_subscribe" in the channel modes: realtime.channels.get(name, { modes: ["presence_subscribe", ...] }), or call channel.setOptions({ modes: [...] }) on an existing channel to trigger a reattach. Alternatively, omit modes entirely and ensure your token/API-key capability permits subscribe on this channel. If you have the Ably CLI installed, `ably auth keys list` shows your key\'s capabilities.'});if(this.channel.client.options.strictMode===!0)throw e;_.logActionNoStrip(this.logger,_.LOG_ERROR,`RealtimePresence.get()`,e.message+`; remediation=`+e.remediation+_.silentFailureLogSuffix())}let r=this.members;return t&&await r.waitSync(),n(this.members)}history(...e){return S(e,0),this._historyImpl(e[0])}async _historyImpl(e){_.logAction(this.logger,_.LOG_MICRO,`RealtimePresence.history()`,`channel = `+this.name);let t=this.channel.client.rest.presenceMixin;if(e&&e.untilAttach){if(this.channel.state===`attached`)delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new v({message:`option untilAttach requires the channel to be attached, was: `+this.channel.state,code:4e4,statusCode:400,remediation:`Await channel.attach() before calling presence.history({ untilAttach: true }).`})}return t.history(this,e)}setPresence(e,t,n){_.logAction(this.logger,_.LOG_MICRO,`RealtimePresence.setPresence()`,`received presence for `+e.length+` participants; syncChannelSerial = `+n);let r,i,a,o=this.members,s=this._myMembers,c=[],l=this.channel.connectionManager.connectionId;t&&(n&&(a=n.match(/^([\w-]+):(.*)$/))&&(r=a[1],i=a[2]),(!this.members.syncInProgress||this._syncId!==void 0&&r!==this._syncId)&&this.members.startSync(),r!==void 0&&(this._syncId=r));for(let t of e)switch(t.action){case`leave`:o.remove(t)&&c.push(t),t.connectionId===l&&!t.isSynthesized()&&s.remove(t);break;case`enter`:case`present`:case`update`:o.put(t)&&c.push(t),t.connectionId===l&&s.put(t)}t&&!i&&(o.endSync(),this._syncId=void 0,this.channel.syncChannelSerial=null);for(let e=0;e<c.length;e++){let t=c[e];this.subscriptions.emit(t.action,t)}}onAttached(e){_.logAction(this.logger,_.LOG_MINOR,`RealtimePresence.onAttached()`,`channel = `+this.channel.name+`, hasPresence = `+e),e?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let t=this.pendingPresence,n=t.length;if(n){this.pendingPresence=[];let e=[],r=bt.create(this.logger);_.logAction(this.logger,_.LOG_MICRO,`RealtimePresence.onAttached`,`sending `+n+` queued presence messages`);for(let i=0;i<n;i++){let n=t[i];e.push(n.presence),r.push(n.callback)}this.channel.sendPresence(e).then(()=>r()).catch(e=>r(e))}}actOnChannelState(e,t,n){switch(e){case`attached`:this.onAttached(t);break;case`detached`:case`failed`:this._clearMyMembers(),this.members.clear();case`suspended`:this.failPendingPresence(n)}}failPendingPresence(e){if(this.pendingPresence.length){_.logAction(this.logger,_.LOG_MINOR,`RealtimeChannel.failPendingPresence`,`channel; name = `+this.channel.name+`, err = `+C(e));for(let t=0;t<this.pendingPresence.length;t++)try{this.pendingPresence[t].callback(e)}catch{}this.pendingPresence=[]}}requeuePresenceMessages(e,t){for(let n of e)this.pendingPresence.push({presence:n,callback:t})}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let e=this._myMembers,t=this.channel.connectionManager.connectionId;for(let n in e.map){let r=e.map[n];_.logAction(this.logger,_.LOG_MICRO,`RealtimePresence._ensureMyMembersPresent()`,`Auto-reentering clientId "`+r.clientId+`" into the presence set`);let i=r.connectionId===t?r.id:void 0;this._enterOrUpdateClient(i,r.clientId,r.data,`enter`).catch(e=>{let t=new v({message:`Presence auto re-enter failed`,code:91004,statusCode:400,cause:e,remediation:`Listen for the channel "update" event and call presence.enter(...) again once the channel is attached. For a member entered on behalf of another clientId, call presence.enterClient(clientId, data) instead.`});_.logAction(this.logger,_.LOG_ERROR,`RealtimePresence._ensureMyMembersPresent()`,`Presence auto re-enter failed; reason = `+C(e));let n=new wr(this.channel.state,this.channel.state,!0,!1,t);this.channel.emit(`update`,n)})}}_synthesizeLeaves(e){let t=this.subscriptions;e.forEach(function(e){let n=V.fromValues({action:`leave`,connectionId:e.connectionId,clientId:e.clientId,data:e.data,encoding:e.encoding,timestamp:h.Config.now()});t.emit(`leave`,n)})}subscribe(...e){return S(e,2),this._subscribeImpl(e)}async _subscribeImpl(e){let t=Or.processListenerArgs(e),n=t[0],r=t[1],i=this.channel;if(i.state===`failed`)throw v.fromValues(i.invalidStateError());this.subscriptions.on(n,r),i.channelOptions.attachOnSubscribe!==!1&&await i.attach()}unsubscribe(...e){let t=Or.processListenerArgs(e),n=t[0],r=t[1];this.subscriptions.off(n,r)}},ii=Y.WebSocket;function ai(e){return!!e.on}var oi=class extends zr{constructor(e,t,n){super(e,t,n),this.shortName=ii,n.heartbeats=h.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!h.Config.WebSocket}createWebSocket(e,t){return this.uri=e+je(t),new h.Config.WebSocket(this.uri)}toString(){return`WebSocketTransport; uri=`+this.uri}connect(){_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.connect()`,`starting`),zr.prototype.connect.call(this);let e=this,t=this.params,n=t.options,r=(n.tls?`wss://`:`ws://`)+this.wsHost+`:`+k.getPort(n)+`/`;_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.connect()`,`uri: `+r),w(this.auth.getAuthParams(),function(n,i){if(e.isDisposed)return;let a=``;for(let e in i)a+=` `+e+`: `+i[e]+`;`;if(_.logAction(e.logger,_.LOG_MINOR,`WebSocketTransport.connect()`,`authParams:`+a+` err: `+n),n){e.disconnect(n);return}let o=t.getConnectParams(i);try{let t=e.wsConnection=e.createWebSocket(r,o);t.binaryType=h.Config.binaryType,t.onopen=function(){e.onWsOpen()},t.onclose=function(t){e.onWsClose(t)},t.onmessage=function(t){e.onWsData(t.data)},t.onerror=function(t){e.onWsError(t)},ai(t)&&t.on(`ping`,function(){e.onActivity()})}catch(t){_.logAction(e.logger,_.LOG_ERROR,`WebSocketTransport.connect()`,`Unexpected exception creating websocket: err = `+(t.stack||t.message)),e.disconnect(t)}})}send(e){let t=this.wsConnection;if(!t){_.logAction(this.logger,_.LOG_ERROR,`WebSocketTransport.send()`,`No socket connection`);return}try{t.send(gr(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(e){let t=`Exception from ws connection when trying to send: `+C(e);_.logAction(this.logger,_.LOG_ERROR,`WebSocketTransport.send()`,t),this.finish(`disconnected`,new v(t,5e4,500))}}onWsData(e){_.logAction(this.logger,_.LOG_MICRO,`WebSocketTransport.onWsData()`,`data received; length = `+e.length+`; type = `+typeof e);try{this.onProtocolMessage(vr(e,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(e){_.logAction(this.logger,_.LOG_ERROR,`WebSocketTransport.onWsData()`,`Unexpected exception handing channel message: `+e.stack)}}onWsOpen(){_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.onWsOpen()`,`opened WebSocket`),this.emit(`preconnect`)}onWsClose(e){let t,n;if(typeof e==`object`?(n=e.code,t=e.wasClean||n===1e3):(n=e,t=n==1e3),delete this.wsConnection,t){_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.onWsClose()`,`Cleanly closed WebSocket`);let e=new v(`Websocket closed`,80003,400);this.finish(`disconnected`,e)}else{let e=`Unclean disconnection of WebSocket ; code = `+n,t=new v(e,80003,400);_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.onWsClose()`,e),this.finish(`disconnected`,t)}this.emit(`disposed`)}onWsError(e){_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.onError()`,`Error from WebSocket: `+e.message),h.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){_.logAction(this.logger,_.LOG_MINOR,`WebSocketTransport.dispose()`,``),this.isDisposed=!0;let e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,h.Config.nextTick(()=>{if(_.logAction(this.logger,_.LOG_MICRO,`WebSocketTransport.dispose()`,`closing websocket`),!e)throw Error(`WebSocketTransport.dispose(): wsConnection is not defined`);e.close()}))}},si=class{static subscribeFilter(e,t,n){let r=e=>{let r={name:e.name,refTimeserial:e.extras?.ref?.timeserial,refType:e.extras?.ref?.type,isRef:!!e.extras?.ref?.timeserial,clientId:e.clientId};Object.entries(t).find(([e,t])=>t!==void 0&&r[e]!==t)||n(e)};this.addFilteredSubscription(e,t,n,r),e.subscriptions.on(r)}static addFilteredSubscription(e,t,n,r){if(e.filteredSubscriptions||=new Map,e.filteredSubscriptions.has(n)){let i=e.filteredSubscriptions.get(n);i.set(t,(i?.get(t))?.concat(r)||[r])}else e.filteredSubscriptions.set(n,new Map([[t,[r]]]))}static getAndDeleteFilteredSubscriptions(e,t,n){if(!e.filteredSubscriptions)return[];if(!n&&t)return Array.from(e.filteredSubscriptions.entries()).map(([n,r])=>{var i;let a=r.get(t);return r.delete(t),r.size===0&&((i=e.filteredSubscriptions)==null||i.delete(n)),a}).reduce((e,t)=>t?e.concat(...t):e,[]);if(!n||!e.filteredSubscriptions.has(n))return[];let r=e.filteredSubscriptions.get(n);if(!t){let t=Array.from(r.values()).reduce((e,t)=>e.concat(...t),[]);return e.filteredSubscriptions.delete(n),t}let i=r.get(t);return r.delete(t),i||[]}},X=class e extends Qr{constructor(t){let n=e._MsgPack;if(!n)throw Error(`Expected DefaultRealtime._MsgPack to have been set`);super(k.objectifyOptions(t,!0,`Realtime`,_.defaultLogger,f(d({},nr),{Crypto:e.Crypto??void 0,MsgPack:n,RealtimePresence:{RealtimePresence:ri,PresenceMessage:V,WirePresenceMessage:Nn},Annotations:{Annotation:W,WireAnnotation:U,RealtimeAnnotations:kr,RestAnnotations:hr},WebSocketTransport:oi,MessageInteractions:si})))}static get Crypto(){if(this._Crypto===null)throw Error(`Encryption not enabled; use ably.encryption.js instead`);return this._Crypto}static set Crypto(e){this._Crypto=e}};X.Utils=le,X.ConnectionManager=qr,X.ProtocolMessage=Cr,X._Crypto=null,X.Message=rr,X.PresenceMessage=ir,X.Annotation=dr,X._MsgPack=null,X._Http=Bt,X._PresenceMap=ei,X._MessageEncoding=nn;var ci=X,li=Uint8Array,ui=Uint32Array,di=Math.pow,fi=new ui(8),pi=[],mi=new ui(64);function hi(e){return(e-(e|0))*di(2,32)|0}for(var gi=2,_i=0;_i<64;){for(vi=!0,yi=2;yi<=gi/2;yi++)gi%yi===0&&(vi=!1);vi&&(_i<8&&(fi[_i]=hi(di(gi,1/2))),pi[_i]=hi(di(gi,1/3)),_i++),gi++}var vi,yi,bi=!!new li(new ui([1]).buffer)[0];function xi(e){return bi?e>>>24|(e>>>16&255)<<8|(e&65280)<<8|e<<24:e}function Z(e,t){return e>>>t|e<<32-t}function Si(e){var t=fi.slice(),n=e.length,r=n*8,i=512-(r+64)%512-1+r+65,a=new li(i/8),o=new ui(a.buffer);a.set(e,0),a[n]=128,o[o.length-1]=xi(r);for(var s,c=0;c<i/32;c+=16){var l=t.slice();for(s=0;s<64;s++){var u;if(s<16)u=xi(o[c+s]);else{var d=mi[s-15],f=mi[s-2];u=mi[s-7]+mi[s-16]+(Z(d,7)^Z(d,18)^d>>>3)+(Z(f,17)^Z(f,19)^f>>>10)}mi[s]=u|=0;for(var p=(Z(l[4],6)^Z(l[4],11)^Z(l[4],25))+(l[4]&l[5]^~l[4]&l[6])+l[7]+u+pi[s],ee=(Z(l[0],2)^Z(l[0],13)^Z(l[0],22))+(l[0]&l[1]^l[2]&(l[0]^l[1])),m=7;m>0;m--)l[m]=l[m-1];l[0]=p+ee|0,l[4]=l[4]+p|0}for(s=0;s<8;s++)t[s]=t[s]+l[s]|0}return new li(new ui(t.map(function(e){return xi(e)})).buffer)}function Ci(e,t){if(e.length>64&&(e=Si(e)),e.length<64){let t=new Uint8Array(64);t.set(e,0),e=t}for(var n=new Uint8Array(64),r=new Uint8Array(64),i=0;i<64;i++)n[i]=54^e[i],r[i]=92^e[i];var a=new Uint8Array(t.length+64);a.set(n,0),a.set(t,64);var o=new Uint8Array(96);return o.set(r,0),o.set(Si(a),64),Si(o)}var wi=new class{constructor(){this.base64CharSet=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,this.hexCharSet=`0123456789abcdef`}uint8ViewToBase64(e){let t=``,n=this.base64CharSet,r=e.byteLength,i=r%3,a=r-i,o,s,c,l,u;for(let r=0;r<a;r+=3)u=e[r]<<16|e[r+1]<<8|e[r+2],o=(u&16515072)>>18,s=(u&258048)>>12,c=(u&4032)>>6,l=u&63,t+=n[o]+n[s]+n[c]+n[l];return i==1?(u=e[a],o=(u&252)>>2,s=(u&3)<<4,t+=n[o]+n[s]+`==`):i==2&&(u=e[a]<<8|e[a+1],o=(u&64512)>>10,s=(u&1008)>>4,c=(u&15)<<2,t+=n[o]+n[s]+n[c]+`=`),t}base64ToArrayBuffer(e){let t=atob==null?void 0:atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++){let n=t.charCodeAt(e);r[e]=n}return this.toArrayBuffer(r)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw Error(`Can't convert to Buffer: browser does not support the necessary types`);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(this.toArrayBuffer(e));throw Error(`BufferUtils.toBuffer expected an ArrayBuffer or a view onto one`)}toArrayBuffer(e){if(!ArrayBuffer)throw Error(`Can't convert to ArrayBuffer: browser does not support the necessary types`);if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);throw Error(`BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one`)}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64UrlEncode(e){return this.base64Encode(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}base64Decode(e){if(ArrayBuffer&&h.Config.atob)return this.base64ToArrayBuffer(e);throw Error(`Expected ArrayBuffer to exist and Platform.Config.atob to be configured`)}hexEncode(e){return this.toBuffer(e).reduce((e,t)=>e+t.toString(16).padStart(2,`0`),``)}hexDecode(e){if(e.length%2!=0)throw Error(`Can't create a byte array from a hex string of odd length`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(t)}utf8Encode(e){if(h.Config.TextEncoder){let t=new h.Config.TextEncoder().encode(e);return this.toArrayBuffer(t)}throw Error(`Expected TextEncoder to be configured`)}utf8Decode(e){if(!this.isBuffer(e))throw Error(`Expected input of utf8decode to be an arraybuffer or typed array`);if(TextDecoder)return new TextDecoder().decode(e);throw Error(`Expected TextDecoder to be configured`)}areBuffersEqual(e,t){if(!e||!t)return!1;let n=this.toArrayBuffer(e),r=this.toArrayBuffer(t);if(n.byteLength!=r.byteLength)return!1;let i=new Uint8Array(n),a=new Uint8Array(r);for(var o=0;o<i.length;o++)if(i[o]!=a[o])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}concat(e){let t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e){let e=this.toBuffer(t);n.set(e,r),r+=e.byteLength}return n.buffer}sha256(e){let t=Si(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){let n=Ci(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},Ti=function(e,t){function n(e){if(e.algorithm===`aes`&&e.mode===`cbc`){if(e.keyLength===128||e.keyLength===256)return;throw Error(`Unsupported key length `+e.keyLength+` for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)`)}}function r(e){return e.replace(`_`,`/`).replace(`-`,`+`)}function i(e){return e instanceof a}class a{constructor(e,t,n,r){this.algorithm=e,this.keyLength=t,this.mode=n,this.key=r}}class o{static getDefaultParams(e){var i;if(!e.key)throw Error(`Crypto.getDefaultParams: a key is required`);i=typeof e.key==`string`?t.toArrayBuffer(t.base64Decode(r(e.key))):e.key instanceof ArrayBuffer?e.key:t.toArrayBuffer(e.key);var o=e.algorithm||`aes`,s=i.byteLength*8,c=e.mode||`cbc`,l=new a(o,s,c,i);if(e.keyLength&&e.keyLength!==l.keyLength)throw Error(`Crypto.getDefaultParams: a keyLength of `+e.keyLength+` was specified, but the key actually has length `+l.keyLength);return n(l),l}static async generateRandomKey(t){try{return e.getRandomArrayBuffer((t||256)/8)}catch(e){throw new v(`Failed to generate random key: `+e.message,400,5e4)}}static getCipher(e,t){var n=i(e)?e:this.getDefaultParams(e);return{cipherParams:n,cipher:new s(n,e.iv??null,t)}}}o.CipherParams=a;class s{constructor(e,n,r){if(this.logger=r,!crypto.subtle)throw Error(isSecureContext?`Crypto operations are not possible since the browser’s SubtleCrypto class is unavailable (reason unknown).`:`Crypto operations are is not possible since the current environment is a non-secure context and hence the browser’s SubtleCrypto class is not available.`);this.algorithm=e.algorithm+`-`+String(e.keyLength)+`-`+e.mode,this.webCryptoAlgorithm=e.algorithm+`-`+e.mode,this.key=t.toArrayBuffer(e.key),this.iv=n?t.toArrayBuffer(n):null}concat(e,n){let r=new ArrayBuffer(e.byteLength+n.byteLength),i=new DataView(r),a=new DataView(t.toArrayBuffer(e));for(let e=0;e<a.byteLength;e++)i.setInt8(e,a.getInt8(e));let o=new DataView(t.toArrayBuffer(n));for(let e=0;e<o.byteLength;e++)i.setInt8(a.byteLength+e,o.getInt8(e));return r}async encrypt(e){_.logAction(this.logger,_.LOG_MICRO,`CBCCipher.encrypt()`,``);let t=await this.getIv(),n=await crypto.subtle.importKey(`raw`,this.key,this.webCryptoAlgorithm,!1,[`encrypt`]),r=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:t},n,e);return this.concat(t,r)}async decrypt(e){_.logAction(this.logger,_.LOG_MICRO,`CBCCipher.decrypt()`,``);let n=t.toArrayBuffer(e),r=n.slice(0,16),i=n.slice(16),a=await crypto.subtle.importKey(`raw`,this.key,this.webCryptoAlgorithm,!1,[`decrypt`]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:r},a,i)}async getIv(){if(this.iv){var n=this.iv;return this.iv=null,n}let r=await e.getRandomArrayBuffer(16);return t.toArrayBuffer(r)}}return o},Ei=(e=>(e[e.REQ_SEND=0]=`REQ_SEND`,e[e.REQ_RECV=1]=`REQ_RECV`,e[e.REQ_RECV_POLL=2]=`REQ_RECV_POLL`,e[e.REQ_RECV_STREAM=3]=`REQ_RECV_STREAM`,e))(Ei||{}),Q=Ei;function Di(){return new v(`No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.`,400,4e4)}var Oi,ki=(Oi=class{constructor(e){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=e??null;let t=e?.options.connectivityCheckUrl||k.connectivityCheckUrl,n=e?.options.connectivityCheckParams??null,r=!e?.options.connectivityCheckUrl,i=d(d({},ki.bundledRequestImplementations),e?._additionalHTTPRequestImplementations),a=i.XHRRequest,o=i.FetchRequest,s=!!(a||o);if(!s)throw Di();h.Config.xhrSupported&&a?(this.supportsAuthHeaders=!0,this.Request=async function(t,n,r,i,o){return new Promise(s=>{let c=a.createRequest(n,r,i,o,Q.REQ_SEND,(e&&e.options.timeouts)??null,this.logger,t);c.once(`complete`,(e,t,n,r,i)=>s({error:e,body:t,headers:n,unpacked:r,statusCode:i})),c.exec()})},this.checkConnectivity=e?.options.disableConnectivityCheck?async function(){return!0}:async function(){_.logAction(this.logger,_.LOG_MICRO,`(XHRRequest)Http.checkConnectivity()`,`Sending; `+t);let e=await this.doUri(A.Get,t,null,null,n),i=!1;return i=r?!e.error&&e.body?.replace(/\n/,``)==`yes`:!e.error&&Ct(e.statusCode),_.logAction(this.logger,_.LOG_MICRO,`(XHRRequest)Http.checkConnectivity()`,`Result: `+i),i}):h.Config.fetchSupported&&o?(this.supportsAuthHeaders=!0,this.Request=async(t,n,r,i,a)=>o(t,e??null,n,r,i,a),this.checkConnectivity=e?.options.disableConnectivityCheck?async function(){return!0}:async function(){_.logAction(this.logger,_.LOG_MICRO,`(Fetch)Http.checkConnectivity()`,`Sending; `+t);let e=await this.doUri(A.Get,t,null,null,null),n=!e.error&&e.body?.replace(/\n/,``)==`yes`;return _.logAction(this.logger,_.LOG_MICRO,`(Fetch)Http.checkConnectivity()`,`Result: `+n),n}):this.Request=async()=>({error:s?new y(`no supported HTTP transports available`,null,400):Di()})}get logger(){return this.client?.logger??_.defaultLogger}async doUri(e,t,n,r,i){return this.Request?this.Request(e,t,n,i,r):{error:new y(`Request invoked before assigned to`,null,500)}}shouldFallback(e){let t=e.statusCode;return t===408&&!e.code||t===400&&!e.code||t>=500&&t<=504}},Oi.methods=[A.Get,A.Delete,A.Post,A.Put,A.Patch],Oi.methodsWithoutBody=[A.Get,A.Delete],Oi.methodsWithBody=[A.Post,A.Put,A.Patch],Oi),Ai=ki,ji=`ablyjs-storage-test`,Mi=typeof global<`u`?global:typeof window<`u`?window:self,Ni=new class{constructor(){try{Mi.sessionStorage.setItem(ji,ji),Mi.sessionStorage.removeItem(ji),this.sessionSupported=!0}catch{this.sessionSupported=!1}try{Mi.localStorage.setItem(ji,ji),Mi.localStorage.removeItem(ji),this.localSupported=!0}catch{this.localSupported=!1}}get(e){return this._get(e,!1)}getSession(e){return this._get(e,!0)}remove(e){return this._remove(e,!1)}removeSession(e){return this._remove(e,!0)}set(e,t,n){return this._set(e,t,n,!1)}setSession(e,t,n){return this._set(e,t,n,!0)}_set(e,t,n,r){let i={value:t};return n&&(i.expires=Date.now()+n),this.storageInterface(r).setItem(e,JSON.stringify(i))}_get(e,t){if(t&&!this.sessionSupported)throw Error(`Session Storage not supported`);if(!t&&!this.localSupported)throw Error(`Local Storage not supported`);let n=this.storageInterface(t).getItem(e);if(!n)return null;let r=JSON.parse(n);return r.expires&&r.expires<Date.now()?(this.storageInterface(t).removeItem(e),null):r.value}_remove(e,t){return this.storageInterface(t).removeItem(e)}storageInterface(e){return e?Mi.sessionStorage:Mi.localStorage}},$=Ge(),Pi=typeof EdgeRuntime==`string`;typeof Window>`u`&&typeof WorkerGlobalScope>`u`&&!Pi&&console.log(`Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm`);function Fi(){let e=$.location;return!$.WebSocket||!e||!e.origin||e.origin.indexOf(`http`)>-1}function Ii(){return typeof WorkerGlobalScope<`u`&&self instanceof WorkerGlobalScope}var Li={agent:`browser`,logTimestamps:!0,userAgent:$.navigator&&$.navigator.userAgent.toString(),currentUrl:$.location&&$.location.href,binaryType:`arraybuffer`,WebSocket:$.WebSocket,fetchSupported:!!$.fetch,xhrSupported:$.XMLHttpRequest&&`withCredentials`in new XMLHttpRequest,allowComet:Fi(),useProtocolHeartbeats:!0,supportsBinary:!!$.TextDecoder,preferBinary:!1,ArrayBuffer:$.ArrayBuffer,atob:$.atob,nextTick:typeof $.queueMicrotask==`function`?e=>$.queueMicrotask(e):e=>Promise.resolve().then(e),setTimeout:$.setTimeout.bind($),clearTimeout:$.clearTimeout.bind($),now:Date.now,addEventListener:$.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return $.TextDecoder&&new $.TextEncoder().encode(e).length||e.length},TextEncoder:$.TextEncoder,TextDecoder:$.TextDecoder,getRandomArrayBuffer:async function(e){let t=new Uint8Array(e);return $.crypto.getRandomValues(t),t.buffer},isWebworker:Ii(),push:{platform:`browser`,formFactor:`desktop`,storage:Ni}};function Ri(e){return e.code?j.isTokenErr(e)?!1:[80015,80017,80030].includes(e.code)?!0:e.code>=4e4&&e.code<5e4:!1}function zi(e){return Ri(e)?[G({action:P.ERROR,error:e})]:[G({action:P.DISCONNECTED,error:e})]}var Bi=class extends zr{constructor(e,t,n){super(e,t,n,!0),this.onAuthUpdated=e=>{this.authParams={access_token:e.token}},this.stream=`stream`in n?n.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){_.logAction(this.logger,_.LOG_MINOR,`CometTransport.connect()`,`starting`),zr.prototype.connect.call(this);let e=this.params,t=e.options,n=e.host||t.primaryDomain,r=k.getPort(t),i=t.tls?`https://`:`http://`;this.baseUri=i+n+`:`+r+`/comet/`;let a=this.baseUri+`connect`;_.logAction(this.logger,_.LOG_MINOR,`CometTransport.connect()`,`uri: `+a),w(this.auth.getAuthParams(),(e,t)=>{if(e){this.disconnect(e);return}if(this.isDisposed)return;this.authParams=t;let n=this.params.getConnectParams(t);`stream`in n&&(this.stream=n.stream),_.logAction(this.logger,_.LOG_MINOR,`CometTransport.connect()`,`connectParams:`+je(n));let r=!1,i=this.recvRequest=this.createRequest(a,null,n,null,this.stream?Q.REQ_RECV_STREAM:Q.REQ_RECV);i.on(`data`,e=>{this.recvRequest&&(r||(r=!0,this.emit(`preconnect`)),this.onData(e))}),i.on(`complete`,e=>{if(this.recvRequest||(e||=new v(`Request cancelled`,80003,400)),this.recvRequest=null,!r&&!e&&(r=!0,this.emit(`preconnect`)),this.onActivity(),e){e.code?this.onData(zi(e)):this.disconnect(e);return}h.Config.nextTick(()=>{this.recv()})}),i.exec()})}requestClose(){_.logAction(this.logger,_.LOG_MINOR,`CometTransport.requestClose()`),this._requestCloseOrDisconnect(!0)}requestDisconnect(){_.logAction(this.logger,_.LOG_MINOR,`CometTransport.requestDisconnect()`),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(e){let t=e?this.closeUri:this.disconnectUri;if(t){let n=this.createRequest(t,null,this.authParams,null,Q.REQ_SEND);n.on(`complete`,t=>{t&&(_.logAction(this.logger,_.LOG_ERROR,`CometTransport.request`+(e?`Close()`:`Disconnect()`),`request returned err = `+C(t)),this.finish(`disconnected`,t))}),n.exec()}}dispose(){_.logAction(this.logger,_.LOG_MINOR,`CometTransport.dispose()`,``),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&=(_.logAction(this.logger,_.LOG_MINOR,`CometTransport.dispose()`,`aborting recv request`),this.recvRequest.abort(),null),this.finish(`disconnected`,J.disconnected()),h.Config.nextTick(()=>{this.emit(`disposed`)}))}onConnect(e){if(this.isDisposed)return;let t=e.connectionDetails?.connectionKey;zr.prototype.onConnect.call(this,e);let n=this.baseUri+t;_.logAction(this.logger,_.LOG_MICRO,`CometTransport.onConnect()`,`baseUri = `+n),this.sendUri=n+`/send`,this.recvUri=n+`/recv`,this.closeUri=n+`/close`,this.disconnectUri=n+`/disconnect`}send(e){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(e);return}let t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)}sendAnyPending(){let e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))}sendItems(e){let t=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(e),Q.REQ_SEND);t.on(`complete`,(e,t)=>{if(e&&_.logAction(this.logger,_.LOG_ERROR,`CometTransport.sendItems()`,`on complete: err = `+C(e)),this.sendRequest=null,e){e.code?this.onData(zi(e)):this.disconnect(e);return}t&&this.onData(t),this.pendingItems&&h.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),t.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let e=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Q.REQ_RECV_STREAM:Q.REQ_RECV_POLL);e.on(`data`,e=>{this.onData(e)}),e.on(`complete`,e=>{if(this.recvRequest=null,this.onActivity(),e){e.code?this.onData(zi(e)):this.disconnect(e);return}h.Config.nextTick(()=>{this.recv()})}),e.exec()}onData(e){try{let t=this.decodeResponse(e);if(t&&t.length)for(let e=0;e<t.length;e++)this.onProtocolMessage(yr(t[e],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(e){_.logAction(this.logger,_.LOG_ERROR,`CometTransport.onData()`,`Unexpected exception handing channel event: `+e.stack)}}encodeRequest(e){return JSON.stringify(e)}decodeResponse(e){return typeof e==`string`?JSON.parse(e):e}};function Vi(e,t){return Be(Te(t)).includes(`x-ably-errorcode`)}function Hi(e,t){if(Vi(e,t))return e.error&&v.fromValues(e.error)}var Ui=function(){},Wi=0,Gi={};function Ki(e,t){return e.getResponseHeader&&e.getResponseHeader(t)}function qi(e){return e.getResponseHeader&&(e.getResponseHeader(`transfer-encoding`)||!e.getResponseHeader(`content-length`))}function Ji(e){let t=e.getAllResponseHeaders().trim().split(`\r
|
|
8
|
+
`),n={};for(let e=0;e<t.length;e++){let r=t[e].split(`:`).map(e=>e.trim());n[r[0].toLowerCase()]=r[1]}return n}var Yi=class e extends N{constructor(e,t,n,r,i,a,o,s){super(o),n||={},n.rnd=Le(),this.uri=e+je(n),this.headers=t||{},this.body=r,this.method=s?s.toUpperCase():x(r)?`GET`:`POST`,this.requestMode=i,this.timeouts=a,this.timedOut=!1,this.requestComplete=!1,this.id=String(++Wi),Gi[this.id]=this}static createRequest(t,n,r,i,a,o,s,c){let l=o||k.TIMEOUTS;return new e(t,n,fe(r),i,a,l,s,c)}complete(e,t,n,r,i){this.requestComplete||(this.requestComplete=!0,!e&&t&&this.emit(`data`,t),this.emit(`complete`,e,t,n,r,i),this.dispose())}abort(){this.dispose()}exec(){let e=this.headers,t=this.requestMode==Q.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,n=this.timer=setTimeout(()=>{this.timedOut=!0,i.abort()},t),r=this.method,i=this.xhr=new XMLHttpRequest,a=e.accept,o=this.body,s=`text`;a?a.indexOf(`application/x-msgpack`)===0&&(s=`arraybuffer`):e.accept=`application/json`,o&&(e[`content-type`]||(e[`content-type`]=`application/json`)).indexOf(`application/json`)>-1&&typeof o!=`string`&&(o=JSON.stringify(o)),i.open(r,this.uri,!0),i.responseType=s,`authorization`in e&&(i.withCredentials=!0);for(let t in e)i.setRequestHeader(t,e[t]);let c=(e,t,n,r)=>{let i=t+` (event type: `+e.type+`)`;(this==null?void 0:this.xhr)?.statusText&&(i+=`, current statusText is `+this.xhr.statusText),_.logAction(this.logger,_.LOG_ERROR,`Request.on`+e.type+`()`,i),this.complete(new y(i,n,r))};i.onerror=e=>{c(e,`XHR error occurred`,null,400)},i.onabort=e=>{this.timedOut?c(e,`Request aborted due to request timeout expiring`,null,408):c(e,`Request cancelled`,null,400)},i.ontimeout=e=>{c(e,`Request timed out`,null,408)};let l,u,d,f=0,p=!1,ee=()=>{if(clearTimeout(n),d=u<400,u==204){this.complete(null,null,null,null,u);return}l=this.requestMode==Q.REQ_RECV_STREAM&&d&&qi(i)},m=()=>{let t;try{let n=Ki(i,`content-type`);if(n?n.indexOf(`application/json`)>=0:i.responseType==`text`){let e=i.responseType===`arraybuffer`?h.BufferUtils.utf8Decode(i.response):String(i.responseText);t=e.length?JSON.parse(e):e,p=!0}else t=i.response;t.response===void 0?e=Ji(i):(u=t.statusCode,d=u<400,e=t.headers,t=t.response)}catch(e){this.complete(new y(`Malformed response body from server: `+e.message,null,400));return}if(d||Array.isArray(t)){this.complete(null,t,e,p,u);return}let n=Hi(t,e);n||=new y(`Error response received from server: `+u+` body was: `+h.Config.inspect(t),null,u),this.complete(n,t,e,p,u)};function te(){let e=i.responseText,t=e.length-1,n,r;for(;f<t&&(n=e.indexOf(`
|
|
9
|
+
`,f))>-1;)r=e.slice(f,n),f=n+1,ne(r)}let ne=e=>{try{e=JSON.parse(e)}catch(e){this.complete(new y(`Malformed response body from server: `+e.message,null,400));return}this.emit(`data`,e)},re=()=>{te(),this.streamComplete=!0,h.Config.nextTick(()=>{this.complete()})};i.onreadystatechange=()=>{let e=i.readyState;e<3||i.status!==0&&(u===void 0&&(u=i.status,ee()),e==3&&l?te():e==4&&(l?re():m()))},i.send(o)}dispose(){let e=this.xhr;if(e){e.onreadystatechange=e.onerror=e.onabort=e.ontimeout=Ui,this.xhr=null;let t=this.timer;t&&(clearTimeout(t),this.timer=null),this.requestComplete||e.abort()}delete Gi[this.id]}},Xi=Y.XhrPolling,Zi={order:[`xhr_polling`],bundledImplementations:{web_socket:oi,xhr_polling:class extends Bi{constructor(e,t,n){super(e,t,n),this.shortName=Xi,n.stream=!1,this.shortName=Xi}static isAvailable(){return!!(h.Config.xhrSupported&&h.Config.allowComet)}toString(){return`XHRPollingTransport; uri=`+this.baseUri+`; isConnected=`+this.isConnected}createRequest(e,t,n,r,i){return Yi.createRequest(e,t,n,r,i,this.timeouts,this.logger)}}}},Qi={connectivityCheckUrl:`https://internet-up.ably-realtime.com/is-the-internet-up.txt`,wsConnectivityCheckUrl:`wss://ws-up.ably-realtime.com`,defaultTransports:[Y.XhrPolling,Y.WebSocket]};function $i(e){if(e===void 0)return`undefined`;let t,n;if(e instanceof ArrayBuffer?(n=`ArrayBuffer`,t=new DataView(e)):e instanceof DataView&&(n=`DataView`,t=e),!t)return JSON.stringify(e);let r=[];for(let n=0;n<e.byteLength;n++){if(n>20){r.push(`...`);break}let e=t.getUint8(n).toString(16);e.length===1&&(e=`0`+e),r.push(e)}return`<`+n+` `+r.join(` `)+`>`}function ea(e,t,n){let r=new TextEncoder().encode(n);for(let n=0;n<r.length;n++)e.setUint8(t+n,r[n])}function ta(e,t,n){return new TextDecoder().decode(e.buffer.slice(t,t+n))}function na(e){return new TextEncoder().encode(e).length}function ra(e,t){let n=ma(e,t);if(n===0)return;let r=new ArrayBuffer(n);return pa(e,new DataView(r),0,t),r}var ia=4294967296,aa=1/ia;function oa(e,t){return t||=0,e.getInt32(t)*ia+e.getUint32(t+4)}function sa(e,t){return t||=0,e.getUint32(t)*ia+e.getUint32(t+4)}function ca(e,t,n){n<0x8000000000000000?(e.setInt32(t,Math.floor(n*aa)),e.setInt32(t+4,n&-1)):(e.setUint32(t,2147483647),e.setUint32(t+4,2147483647))}function la(e,t,n){n<0x10000000000000000?(e.setUint32(t,Math.floor(n*aa)),e.setInt32(t+4,n&-1)):(e.setUint32(t,4294967295),e.setUint32(t+4,4294967295))}var ua=class{constructor(e,t){this.map=e=>{let t={};for(let n=0;n<e;n++){let e=this.parse();t[e]=this.parse()}return t},this.bin=e=>{let t=new ArrayBuffer(e);return new Uint8Array(t).set(new Uint8Array(this.view.buffer,this.offset,e),0),this.offset+=e,t},this.buf=this.bin,this.str=e=>{let t=ta(this.view,this.offset,e);return this.offset+=e,t},this.array=e=>{let t=Array(e);for(let n=0;n<e;n++)t[n]=this.parse();return t},this.ext=e=>(this.offset+=e,{type:this.view.getInt8(this.offset),data:this.buf(e)}),this.parse=()=>{let e=this.view.getUint8(this.offset),t,n;if(!(e&128))return this.offset++,e;if((e&240)==128)return n=e&15,this.offset++,this.map(n);if((e&240)==144)return n=e&15,this.offset++,this.array(n);if((e&224)==160)return n=e&31,this.offset++,this.str(n);if((e&224)==224)return t=this.view.getInt8(this.offset),this.offset++,t;switch(e){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return n=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(n);case 197:return n=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(n);case 198:return n=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(n);case 199:return n=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(n);case 200:return n=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(n);case 201:return n=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(n);case 202:return t=this.view.getFloat32(this.offset+1),this.offset+=5,t;case 203:return t=this.view.getFloat64(this.offset+1),this.offset+=9,t;case 204:return t=this.view.getUint8(this.offset+1),this.offset+=2,t;case 205:return t=this.view.getUint16(this.offset+1),this.offset+=3,t;case 206:return t=this.view.getUint32(this.offset+1),this.offset+=5,t;case 207:return t=sa(this.view,this.offset+1),this.offset+=9,t;case 208:return t=this.view.getInt8(this.offset+1),this.offset+=2,t;case 209:return t=this.view.getInt16(this.offset+1),this.offset+=3,t;case 210:return t=this.view.getInt32(this.offset+1),this.offset+=5,t;case 211:return t=oa(this.view,this.offset+1),this.offset+=9,t;case 212:return n=1,this.offset++,this.ext(n);case 213:return n=2,this.offset++,this.ext(n);case 214:return n=4,this.offset++,this.ext(n);case 215:return n=8,this.offset++,this.ext(n);case 216:return n=16,this.offset++,this.ext(n);case 217:return n=this.view.getUint8(this.offset+1),this.offset+=2,this.str(n);case 218:return n=this.view.getUint16(this.offset+1),this.offset+=3,this.str(n);case 219:return n=this.view.getUint32(this.offset+1),this.offset+=5,this.str(n);case 220:return n=this.view.getUint16(this.offset+1),this.offset+=3,this.array(n);case 221:return n=this.view.getUint32(this.offset+1),this.offset+=5,this.array(n);case 222:return n=this.view.getUint16(this.offset+1),this.offset+=3,this.map(n);case 223:return n=this.view.getUint32(this.offset+1),this.offset+=5,this.map(n)}throw Error(`Unknown type 0x`+e.toString(16))},this.offset=t||0,this.view=e}};function da(e){let t=new ua(new DataView(e)),n=t.parse();if(t.offset!==e.byteLength)throw Error(e.byteLength-t.offset+` trailing bytes`);return n}function fa(e,t){return Object.keys(e).filter(function(n){let r=e[n];return(!t||r!=null)&&(typeof r!=`function`||!!r.toJSON)})}function pa(e,t,n,r){let i=typeof e;if(typeof e==`string`){let r=na(e);if(r<32)return t.setUint8(n,r|160),ea(t,n+1,e),1+r;if(r<256)return t.setUint8(n,217),t.setUint8(n+1,r),ea(t,n+2,e),2+r;if(r<65536)return t.setUint8(n,218),t.setUint16(n+1,r),ea(t,n+3,e),3+r;if(r<4294967296)return t.setUint8(n,219),t.setUint32(n+1,r),ea(t,n+5,e),5+r}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){let r=e.byteLength;if(r<256)return t.setUint8(n,196),t.setUint8(n+1,r),new Uint8Array(t.buffer).set(new Uint8Array(e),n+2),2+r;if(r<65536)return t.setUint8(n,197),t.setUint16(n+1,r),new Uint8Array(t.buffer).set(new Uint8Array(e),n+3),3+r;if(r<4294967296)return t.setUint8(n,198),t.setUint32(n+1,r),new Uint8Array(t.buffer).set(new Uint8Array(e),n+5),5+r}if(typeof e==`number`){if(Math.floor(e)!==e)return t.setUint8(n,203),t.setFloat64(n+1,e),9;if(e>=0){if(e<128)return t.setUint8(n,e),1;if(e<256)return t.setUint8(n,204),t.setUint8(n+1,e),2;if(e<65536)return t.setUint8(n,205),t.setUint16(n+1,e),3;if(e<4294967296)return t.setUint8(n,206),t.setUint32(n+1,e),5;if(e<0x10000000000000000)return t.setUint8(n,207),la(t,n+1,e),9;throw Error(`Number too big 0x`+e.toString(16))}if(e>=-32)return t.setInt8(n,e),1;if(e>=-128)return t.setUint8(n,208),t.setInt8(n+1,e),2;if(e>=-32768)return t.setUint8(n,209),t.setInt16(n+1,e),3;if(e>=-2147483648)return t.setUint8(n,210),t.setInt32(n+1,e),5;if(e>=-0x8000000000000000)return t.setUint8(n,211),ca(t,n+1,e),9;throw Error(`Number too small -0x`+(-e).toString(16).substr(1))}if(i===`undefined`)return r?0:(t.setUint8(n,212),t.setUint8(n+1,0),t.setUint8(n+2,0),3);if(e===null)return r?0:(t.setUint8(n,192),1);if(i===`boolean`)return t.setUint8(n,e?195:194),1;if(typeof e.toJSON==`function`)return pa(e.toJSON(),t,n,r);if(i===`object`){let i,a=0,o,s=Array.isArray(e);if(s?i=e.length:(o=fa(e,r),i=o.length),i<16?(t.setUint8(n,i|(s?144:128)),a=1):i<65536?(t.setUint8(n,s?220:222),t.setUint16(n+1,i),a=3):i<4294967296&&(t.setUint8(n,s?221:223),t.setUint32(n+1,i),a=5),s)for(let o=0;o<i;o++)a+=pa(e[o],t,n+a,r);else if(o)for(let s=0;s<i;s++){let i=o[s];a+=pa(i,t,n+a),a+=pa(e[i],t,n+a,r)}return a}if(i===`function`)return 0;throw Error(`Unknown type `+i)}function ma(e,t){let n=typeof e;if(n===`string`){let t=na(e);if(t<32)return 1+t;if(t<256)return 2+t;if(t<65536)return 3+t;if(t<4294967296)return 5+t}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){let t=e.byteLength;if(t<256)return 2+t;if(t<65536)return 3+t;if(t<4294967296)return 5+t}if(typeof e==`number`){if(Math.floor(e)!==e)return 9;if(e>=0){if(e<128)return 1;if(e<256)return 2;if(e<65536)return 3;if(e<4294967296)return 5;if(e<0x10000000000000000)return 9;throw Error(`Number too big 0x`+e.toString(16))}if(e>=-32)return 1;if(e>=-128)return 2;if(e>=-32768)return 3;if(e>=-2147483648)return 5;if(e>=-0x8000000000000000)return 9;throw Error(`Number too small -0x`+e.toString(16).substr(1))}if(n===`boolean`)return 1;if(e===null)return+!t;if(e===void 0)return t?0:3;if(typeof e.toJSON==`function`)return ma(e.toJSON(),t);if(n===`object`){let n,r=0;if(Array.isArray(e)){n=e.length;for(let i=0;i<n;i++)r+=ma(e[i],t)}else{let i=fa(e,t);n=i.length;for(let a=0;a<n;a++){let n=i[a];r+=ma(n)+ma(e[n],t)}}if(n<16)return 1+r;if(n<65536)return 3+r;if(n<4294967296)return 5+r;throw Error(`Array or object too long 0x`+n.toString(16))}if(n===`function`)return 0;throw Error(`Unknown type `+n)}var ha={encode:ra,decode:da,inspect:$i,utf8Write:ea,utf8Read:ta,utf8ByteCount:na};function ga(e,t){return!!t.get(`x-ably-errorcode`)}function _a(e,t){if(ga(e,t))return e.error&&v.fromValues(e.error)}function va(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}async function ya(e,t,n,r,i,a){let o=new Headers(r||{}),s=e?e.toUpperCase():x(a)?`GET`:`POST`,c=new AbortController,l,u=new Promise(e=>{l=setTimeout(()=>{c.abort(),e({error:new y(`Request timed out`,null,408)})},t?t.options.timeouts.httpRequestTimeout:k.TIMEOUTS.httpRequestTimeout)}),d={method:s,headers:o,body:a,signal:c.signal};h.Config.isWebworker||(d.credentials=o.has(`authorization`)?`include`:`same-origin`);let f=(async()=>{try{let e=new URLSearchParams(i||{});e.set(`rnd`,Le());let t=n+`?`+e,r=await Ge().fetch(t,d);if(clearTimeout(l),r.status==204)return{error:null,statusCode:r.status};let a=r.headers.get(`Content-Type`),o;o=a&&a.indexOf(`application/x-msgpack`)>-1?await r.arrayBuffer():a&&a.indexOf(`application/json`)>-1?await r.json():await r.text();let s=!!a&&a.indexOf(`application/x-msgpack`)===-1,c=va(r.headers);return r.ok?{error:null,body:o,headers:c,unpacked:s,statusCode:r.status}:{error:_a(o,r.headers)||new y(`Error response received from server: `+r.status+` body was: `+h.Config.inspect(o),null,r.status),body:o,headers:c,unpacked:s,statusCode:r.status}}catch(e){return clearTimeout(l),{error:e}}})();return Promise.race([u,f])}var ba={XHRRequest:Yi,FetchRequest:ya},xa=Ti(Li,wi);h.Crypto=xa,h.BufferUtils=wi,h.Http=Ai,h.Config=Li,h.Transports=Zi,h.WebStorage=Ni;for(let e of[Ar,ci])e.Crypto=xa,e._MsgPack=ha;Ai.bundledRequestImplementations=ba,_.initLogHandlers(),h.Defaults=yt(Qi),h.Config.agent&&(h.Defaults.agent+=` `+h.Config.agent);var Sa={ErrorInfo:v,Rest:Ar,Realtime:ci,msgpack:ha,makeProtocolMessageFromDeserialized:br};return typeof t.exports==`object`&&typeof e==`object`&&(t.exports=((e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of Object.getOwnPropertyNames(t))!Object.prototype.hasOwnProperty.call(e,i)&&i!==n&&Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(r=Object.getOwnPropertyDescriptor(t,i))||r.enumerable});return e})(t.exports,e)),t.exports})}));export default t();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return Array.from({length:12},(t,n)=>new Date(2e3,n,1).toLocaleDateString(e,{month:`long`}))}function t(e){return Array.from({length:7},(t,n)=>new Date(2e3,0,2+n).toLocaleDateString(e,{weekday:`short`}))}function n(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function r(e){let t=new Date(e);return t.setHours(0,0,0,0),t}function i(e,t){let n=e.toLocaleDateString(t,{weekday:`short`}),r=e.toLocaleDateString(t,{month:`short`});return`${n}, ${e.getDate()} ${r}`}function a(e,t,n){let i=r(e);if(n){let t=r(new Date(`${n}T00:00:00`));!isNaN(t.getTime())&&t>=r(e)&&(i=t)}let a=0;for(;t.includes(i.getDay())&&a<7;)i=new Date(i),i.setDate(i.getDate()+1),a++;return i}function o(e,t,i,a){let o=new Date(e,t,1).getDay(),s=new Date(e,t+1,0).getDate(),c=new Date(e,t,0).getDate(),l=[];for(let u=0;u<42;u++){let d=u-o+1,f,p=!0;d<1?(f=new Date(e,t-1,c+d),p=!1):d>s?(f=new Date(e,t+1,d-s),p=!1):f=new Date(e,t,d),f=r(f),l.push({date:f,iso:n(f),dayNumber:f.getDate(),inMonth:p,isPast:f<i,isClosedWeekday:a.includes(f.getDay())})}return l}export{a,t as i,i as n,r as o,e as r,n as s,o as t};
|