@squidcloud/backend 1.0.6 → 1.0.8

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -9,4 +9,4 @@
9
9
  ${e.query}
10
10
  `,variables:e.variables})).data}))}mutate(e){return lp(this,void 0,void 0,(function*(){return(yield this.client.mutate({mutation:sp`
11
11
  ${e.query}
12
- `})).data}))}}class hp{constructor(e){this.rpcManager=e,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new fp(this.rpcManager,e),this.clientsMap.set(e,t),t)}}var mp;class vp{constructor(e,t,r,n){this.clientId=e,this.rpcManager=t,this.lockManager=r,this.querySubscriptionManager=n}sendMutations(e,t){return r=this,n=void 0,a=function*(){const r=We(e),n=r.map((e=>`sendMutation_${Pe(e.squidDocIdObj)}`));yield this.lockManager.lock(...n),yield this.querySubscriptionManager.waitForAllQueriesToFinish();try{const e={clientId:this.clientId,mutations:r,integrationId:t};return yield this.rpcManager.post("mutation/mutate",e)}finally{this.lockManager.release(...n)}},new((i=void 0)||(i=Promise))((function(e,t){function o(e){try{p(a.next(e))}catch(e){t(e)}}function s(e){try{p(a.throw(e))}catch(e){t(e)}}function p(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,s)}p((a=a.apply(r,n||[])).next())}));var r,n,i,a}}class yp{constructor(e,t,r){this.clientId=e,this.rpcManager=t,this.socketManager=r,this.ongoingNamedQueryExecutions={},r.observeNotifications().pipe((0,je.filter)((e=>"namedQuery"===e.type)),(0,Rt.UI)((e=>e))).subscribe((e=>{this.handleNamedQueryResponse(e.clientRequestId,e.payload)}))}executeNamedQueryAndSubscribe(e,t,r){const n=ft(),i=new je.Subject;this.ongoingNamedQueryExecutions[n]=i;const a={integrationId:e,queryName:t,paramsRecordStr:Ee(r),clientId:this.clientId,clientRequestId:n};return this.rpcManager.post("named-query/execute",a).catch((r=>{console.error("Got error while executing named query",t,"for integration",e,r),i.error(r),i.complete()})),i.pipe((0,je.finalize)((()=>{delete this.ongoingNamedQueryExecutions[n]})),(0,je.share)())}handleNamedQueryResponse(e,t){const r=this.ongoingNamedQueryExecutions[e];if(!r)return;const n=Oe(t);n.success?r.next(n.result):(r.error(new Error(n.result)),r.complete())}}function bp(e){return[mp.SET_PATH,mp.DELETE_PATH].includes(e.type)}function gp(e){return e.type===mp.BATCH_ACTION}function _p(e){const t=[];if(bp(e))t.push(e);else if(gp(e))for(const r of e.payload)t.push(..._p(r));return t}function wp(e,t){return Ep(e,t)}function Sp(e){return"object"==typeof e}function Ep(e,t){let r=e;if(bp(t))r=function(e,t,r=[]){switch(t.type){case mp.DELETE_PATH:return Op(e,t.path);case mp.SET_PATH:const n=t;return function(e,t,r,n){return Np(e,t,r,n)}(e,t.path,r,n.payload);case mp.BATCH_ACTION:throw new Error("Unsupported")}}(e,t,[]);else{if(!gp(t))throw new Error(`Invalid action type: ${t.type}`);r=t.payload.reduce(((e,t)=>Ep(e,t)),e)}return r}function Op(e,t){if(!t.length)throw new Error("can not delete an empty path");const r=t[0];if(1===t.length)return function(e,t){if(e instanceof Array)throw new Error("Cannot remove an item from an array");const r=Object.assign({},e);return delete r[t],r}(e,r);const n=t.slice(1),i=xp(e,r);if(!i)return e;if(!Sp(i))throw new Error("Cannot delete from a non object state.");const a=Op(i,n);return a===i?e:Tp(e,r,a)}function Np(e,t,r,n){if(!t.length){if(Sp(n))return n;throw new Error("Relative path cannot be of length 0 when the new value is not an object.")}const i=t[0],a=[...r,i];if(1===t.length)return Tp(e,i,n);const o=t.slice(1),s=xp(e,i);return void 0!==s&&Sp(s)?Tp(e,i,Np(s,o,a,n)):Np(e=Tp(e,i,{}),t,r,n)}function Tp(e,t,r){return(e=Object.assign({},e))[t]=r,e}function xp(e,t){return e instanceof Array?e[function(e){const t=Number(e);if(isNaN(t))throw new Error(`The value is not a number: Actual: ${e}`);return Math.floor(t)}(t)]:e[t]}!function(e){e.DELETE_PATH="DELETE_PATH",e.SET_PATH="SET_PATH",e.BATCH_ACTION="BATCH_ACTION"}(mp||(mp={}));class Pp{constructor(){this.root=new kp}getOrCreatePathTrieNode(e,t){let r=this.root;for(const t of e)r.children.get(t)||r.children.set(t,new kp),r=r.children.get(t);return void 0!==t&&(r.nodeData=t),r}getPathTrieNode(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}return t}getPathTrie(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}if(t){const e=new Pp;return e.root=t,e}}iterateBfs(e){this.iterateInternal(this.root,e,[])}removeNode(e){e.length||(this.root=new kp);const t=[this.root];for(const r of e){const e=t[t.length-1].children.get(r);if(!e)throw new Error("Node does not exist");t.push(e)}for(let r=t.length-1;r>0;r--){const n=t[r],i=e[r-1];if((n.nodeData||n.children.size)&&r!==t.length-1)break;t[r-1].children.delete(i)}}clearNodeData(e){const t=this.getPathTrieNode(e);t&&(t.nodeData=void 0,t.children.size||this.removeNode(e))}getNodeList(e){const t=[];let r=this.root;for(const n of e){if(!r)return t;t.push(r),r=r.children.get(n)}return t}iterateInternal(e,t,r){if(!1!==t(e.nodeData,r))for(const[n,i]of e.children)this.iterateInternal(i,t,r.concat(n))}}class kp{constructor(){this.children=new Map([])}}class Dp{constructor(){this.subscriptionsTree=new Pp,this.state={},this.batchCount=0,this.batchedActions=[]}dispatch(e){this.batchCount>0&&this.batchedActions.push(e),this.state=wp(this.state,e),0===this.batchCount&&this.dispatchSubscriptions(e)}runInBatch(e){this.batchCount++;try{e()}finally{if(this.batchCount--,0===this.batchCount&&this.batchedActions.length){const e={type:mp.BATCH_ACTION,payload:[...this.batchedActions]};this.batchedActions.splice(0),this.dispatch(e)}}}observePath(e,t){return new je.Observable((r=>{const n=this.getOrCreateSubjectForPath(e);r.next(this.getStateInPath(e));const i=n.pipe((0,Rt.hX)((e=>{if(!t)return!0;const r=new Pp,n=t();for(const e of n)r.getOrCreatePathTrieNode(e,!0);const i=_p(e.action).map((e=>e.path));let a=!1;for(const e of i)if(0===r.getNodeList(e).length){a=!0;break}return a})),(0,Rt.UI)((e=>e.data))).subscribe(r);return()=>{i.unsubscribe(),n.observed||(n.complete(),this.subscriptionsTree.clearNodeData(e))}}))}setKeyInPath(e,t,r,n=!1){this.setInPath([...e,t],r,n)}setPartial(e,t,r=!1){let n=this.getStateInPath(e);n||(n={}),this.setInPath(e,Object.assign(Object.assign({},n),t),r)}setInPath(e,t,r=!1){if(r&&this.getStateInPath(e)===t)return;const n={type:mp.SET_PATH,path:e,payload:t};this.dispatch(n)}pushToArray(e,t){let r=this.getStateInPath(e);r=r?[...r]:[],r.push(t),this.setInPath(e,r)}deletePath(e){const t={type:mp.DELETE_PATH,path:e};this.dispatch(t)}getState(){return this.state}getStateInPath(e){return Ap(this.state,e)}destroy(){this.subscriptionsTree.iterateBfs((e=>{e&&e.subject&&e.subject.complete()}))}getOrCreateSubjectForPath(e){const t=this.subscriptionsTree.getOrCreatePathTrieNode(e);t.nodeData||(t.nodeData=new Ip);const r=t.nodeData;return r.subject||(r.subject=new je.Subject),r.subject}dispatchSubscriptions(e){const t=function(e,t){const r=new Pp;for(const n of _p(e)){let e=r.getOrCreatePathTrieNode(n.path);if(!t||e.nodeData)continue;let i=t.getPathTrieNode(n.path);if(i){const t=[[e,i]];for(;t.length;){const r=t.shift();if(e=r[0],i=r[1],!e.nodeData){for(const[r,n]of i.children)e.children.get(r)||e.children.set(r,new kp),t.push([e.children.get(r),n]);e.nodeData=!0}}}}return r}(e,this.subscriptionsTree);t.iterateBfs(((t,r)=>{const n=this.subscriptionsTree.getPathTrieNode(r);n&&n.nodeData&&n.nodeData.subject.next({action:e,data:Ap(this.getState(),r)})}))}}function Ap(e,t){let r=e;for(const e of t){if(null==r)return;if(!Sp(r))throw new Error("result must be a state object");r=r[e]}return r}class Ip{}var jp=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};const Cp="client";class Rp{constructor(e,t,r,n,i){this.rpcManager=e,this.clientId=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.safeToSendQueriesToServer=new je.BehaviorSubject(!0),this.onOrphanDocuments=new je.Subject,this.ongoingQueries=new Map,this.inflightQueriesCount=new je.BehaviorSubject(0),this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Mp,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.destructManager.onPreDestruct((()=>{this.predestruct()}))}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return $e(this.ongoingQueries.get(e)).query}setGotResponseFromServer(e){$e(this.ongoingQueries.get(e)).gotResponseFromServer=!0}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=xe(t),i=this.queryMappingManager.getMapping(Cp,r,n);return i?et(i,e):[]}setClientRequestIdsForLocalDoc(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set,n=new Set(t?this.findQueriesForDocument(t,e).map((e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId)):[]),i=new Set([...r,...n]);for(const t of[...r]){if(n.has(t))continue;r.delete(t);const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),r.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let r=this.localDocumentToClientRequestIds.get(e);r||(r=new Set,this.localDocumentToClientRequestIds.set(e,r)),r.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...i]}errorOutAllQueries(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of r){const r=this.ongoingQueries.get(e);r&&r.subject.error(t)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotResponseFromServer||!e.activated)continue;const n=this.clientRequestIdToLocalDocuments.get(r),i=this.documentStore.sortAndLimitDocs(n,e.query);let a=!1;for(const t of e.supportedQueries)a=a||this.updateOngoingQueryWithNewDataFromSupportingQuery(i,t);let o=e;for(;!o.allObservables;)o=$e(null==o?void 0:o.supportingOngoingQuery);a&&t.add(o),e.subject.next(i)}for(const e of t){const t=this.collectAllObservables(e);$e(e.allObservables).next(t)}}processQuery(e,t,r,n,i){const a=this.createOngoingQueryGraph(e,t,r,n,i,!0);this.sendQueryToServer(a),a.allObservables=new je.ReplaySubject(1);const o=a.allObservables.pipe((0,je.switchMap)((e=>(0,je.combineLatest)(e).pipe((0,Rt.UI)((e=>this.joinResults(e,n,a)))))),(0,Rt.hX)((()=>this.allOngoingQueriesGotServerResult(a))),(0,je.startWith)(void 0),(0,je.pairwise)(),(0,Rt.hX)((([e,t])=>!Ae.isEqual(e,t))),(0,Rt.UI)((([e,t])=>t)),i?(0,je.tap)():(0,je.take)(1),(0,je.finalize)((()=>{var e;a.subject.complete(),this.completeAllSupportedQueries(a),null===(e=a.allObservables)||void 0===e||e.complete()}))),s=this.collectAllObservables(a);return a.allObservables.next(s),o}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestId(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=$e(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r),this.ongoingQueries.delete(e)}waitForAllQueriesToFinish(){return jp(this,void 0,void 0,(function*(){return(0,je.firstValueFrom)(this.inflightQueriesCount.pipe((0,Rt.hX)((e=>0===e)))).then((()=>{}))}))}registerQueryFinalizer(e){const t=e.clientRequestId,r=rt(this.clientId,t);e.subject.pipe((0,je.finalize)((()=>{if(this.queryMappingManager.removeQuery(t,r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientId:this.clientId,clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch((t=>{console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestId(t)}))).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,a,o={}){if(o[t])return o[t];const s=ft(),p=[],d={clientRequestId:s,activated:a,alias:t,query:e,subscribe:i,subject:new je.ReplaySubject(1),supportedQueries:p,supportingOngoingQuery:void 0,joinCondition:void 0,gotResponseFromServer:!1,isEmptyForJoin:!1};this.registerQueryFinalizer(d),this.ongoingQueries.set(s,d),o[t]=d;for(const[e,a]of Object.entries(n)){const s=a.leftAlias;if(s!==t&&e!==t)continue;const u=s===t?e:s;if(s===t){const e=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,o);e.joinCondition=a,p.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,o)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.subject.pipe((0,Rt.UI)((e=>({docs:e,alias:r})))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=[],i=e.reduce(((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e)),{});i[r.alias].forEach((e=>{n.push({[r.alias]:e})}));const a=this.getOngoingQueriesBfs(r),o=new Set;for(let e=1;e<a.length;e++){const r=a[e].alias;o.has(r)||(o.add(r),this.join(n,r,i[r],t))}return n}join(e,t,r,n){var i;if(!e.length)return;const a=Object.keys(e[0]),o=n[t];if(!o||!a.includes(o.leftAlias))return;const s=new Map;(r||[]).forEach((e=>{const t=e[o.rightFieldName];s.has(t)||s.set(t,[]),$e(s.get(t)).push(e)}));for(const r of[...e]){const n=s.get(null===(i=r[o.leftAlias])||void 0===i?void 0:i[o.leftFieldName])||[];if(n.length)for(const i of n)r[t]?e.push(Object.assign(Object.assign({},r),{[t]:i})):r[t]=i;else r[t]||(r[t]=void 0)}}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=$e(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=$e(t.joinCondition),i=t.query;if(t.activated){const a=$e(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),o=new Set(e.map((e=>{var t;return null!==(t=e[n.leftFieldName])&&void 0!==t?t:null})));for(const e of a)e.query.conditions.filter((e=>e.fieldName===n.rightFieldName)).forEach((e=>{o.delete(e.value)}));if(0===o.size)return!1;const s=Ae.cloneDeep(i);s.conditions=s.conditions.filter((e=>e.fieldName!==n.rightFieldName)),[...o].forEach((e=>{s.conditions.push({fieldName:n.rightFieldName,operator:"==",value:e})}));const p=Object.assign(Object.assign({},t),{query:s,activated:!0,gotResponseFromServer:!1,subject:new je.ReplaySubject(1),clientRequestId:ft(),isEmptyForJoin:!1});return this.registerQueryFinalizer(p),this.ongoingQueries.set(p.clientRequestId,p),$e(t.supportingOngoingQuery).supportedQueries.push(p),this.sendQueryToServer(p),!0}{const r=e.map((e=>{var t;return{fieldName:n.rightFieldName,operator:"==",value:null!==(t=e[n.leftFieldName])&&void 0!==t?t:null}}));return t.activated=!0,r.length?(i.conditions.push(...r),this.sendQueryToServer(t)):t.isEmptyForJoin=!0,!0}}allOngoingQueriesGotServerResult(e){return!!e.isEmptyForJoin||!!e.gotResponseFromServer&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotServerResult(e))))}completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=$e(t.shift());t.push(...e.supportedQueries||[]),e.subject.complete()}}predestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete(),this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.subject.complete(),null===(e=r.allObservables)||void 0===e||e.complete()}hasSubscription(e){var t;return!!(null===(t=this.ongoingQueries.get(e))||void 0===t?void 0:t.subscribe)}sendQueryToServer(e){const t=e.query,r=e.clientRequestId,n={query:t,clientRequestId:r,subscribe:e.subscribe,clientId:this.clientId},i=rt(this.clientId,r);this.queryMappingManager.addQuery(Cp,t,i).then(),this.ongoingQueries.set(r,e),this.safeToSendQueriesToServer.pipe((0,Rt.hX)(Boolean),(0,je.take)(1)).subscribe((()=>{e.subject.closed||(this.inflightQueriesCount.next(this.inflightQueriesCount.value+1),this.rpcManager.post("query/query",n).catch((t=>{e.subject.error(t)})).finally((()=>{this.inflightQueriesCount.next(this.inflightQueriesCount.value-1)})))}))}migrateDocIds(e){const t=Object.keys(e);for(const r of this.clientRequestIdToLocalDocuments.values())t.forEach((t=>{r.has(t)&&(r.delete(t),r.add(e[t]))}));t.forEach((t=>{Ue(this.localDocumentToClientRequestIds,t,e[t])}))}}class Mp extends Xe{constructor(){super(...arguments),this.stateService=new Dp,this.querySubscriptionIdToQuery={}}addQuery(e,t,r){return jp(this,void 0,void 0,(function*(){this.stateService.runInBatch((()=>{let e=0;const n=new Set;for(const i of t.conditions){const a=this.getConditionStatePath(t,i),o=[...this.stateService.getStateInPath(a)||[]];if(dt(o,r),["==","!="].includes(i.operator)){const t=Ne(i.fieldName);n.has(t)||(e++,n.add(t))}else e++;this.stateService.setInPath(a,o)}if(!t.conditions.length){const e=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(e)||[]];dt(n,r),this.stateService.setInPath(e,n)}this.stateService.setInPath([...this.getQueryMetadataStatePath(t,r),"condCount"],e)})),this.querySubscriptionIdToQuery[r]=t}))}removeQuery(e,t){return jp(this,void 0,void 0,(function*(){const e=this.querySubscriptionIdToQuery[t];if(e)return this.stateService.runInBatch((()=>{for(const r of e.conditions){const n=this.getConditionStatePath(e,r),i=[...this.stateService.getStateInPath(n)||[]];ut(i,t),i.length?this.stateService.setInPath(n,i):this.stateService.deletePath(n)}if(!e.conditions.length){const r=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(r)||[]];ut(n,t),this.stateService.setInPath(r,n)}this.stateService.deletePath(this.getQueryMetadataStatePath(e,t))})),e}))}getMapping(e,t,r){return this.stateService.getStateInPath(["queryMapping",t,r,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){const r=Ne(t.fieldName),n=Ne(t.value);return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",`${r}`,`${t.operator}`,`${n}`]}}var Fp=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};class $p{constructor(e,t,r,n){this.rpcEndpoint=e,this.socketManager=t,this.staticHeaders={},this.onGoingRpcsCounter=new je.BehaviorSubject(0),Fe(e,"Http endpoint must be provided."),n&&this.setStaticHeader("Authorization",`ApiKey ${n}`),this.rpcEndpoint.endsWith("/")||(this.rpcEndpoint+="/"),r.onDestruct((()=>Fp(this,void 0,void 0,(function*(){yield this.awaitAllSettled()}))))}awaitAllSettled(){return Fp(this,void 0,void 0,(function*(){yield(0,je.firstValueFrom)(this.onGoingRpcsCounter.pipe((0,je.filter)((e=>0===e))))}))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getEndpoint(){return this.rpcEndpoint}getStaticHeaders(){return this.staticHeaders}post(e,t){return Fp(this,void 0,void 0,(function*(){yield(0,je.firstValueFrom)(this.socketManager.observeConnectionReady().pipe((0,je.filter)(Boolean)));let r={"Content-Type":"application/json"};Object.keys(this.staticHeaders)&&(r=Object.assign(Object.assign({},r),this.staticHeaders)),this.onGoingRpcsCounter.next(this.onGoingRpcsCounter.value+1);try{const n=yield cp()(`${this.rpcEndpoint}${e}`,{method:"POST",body:Ee(t),headers:r});let i;try{i=yield n.text()}catch(e){i="Cannot read body"}if(!n.ok)throw new Vp(n.status,n.statusText,n.headers,n.url,i);try{return JSON.parse(i)}catch(e){return i}}finally{this.onGoingRpcsCounter.next(this.onGoingRpcsCounter.value-1)}}))}}class Vp extends Error{constructor(e,t,r,n,i){super(`RPC error ${e} ${t} calling ${n}: ${i}`),this.statusCode=e,this.statusText=t,this.headers=r,this.url=n,this.body=i}}const Lp=Object.create(null);Lp.open="0",Lp.close="1",Lp.ping="2",Lp.pong="3",Lp.message="4",Lp.upgrade="5",Lp.noop="6";const Bp=Object.create(null);Object.keys(Lp).forEach((e=>{Bp[Lp[e]]=e}));const qp={type:"error",data:"parser error"},Up=({type:e,data:t},r,n)=>{if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=(e=>Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength))(t);return n(((e,t)=>t?e:"b"+e.toString("base64"))(e,r))}return n(Lp[e]+(t||""))},zp=(e,t)=>{const r=Buffer.isBuffer(e);return"arraybuffer"===t&&r?Qp(e):e},Qp=e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e[t];return t},Wp=(e,t)=>{if("string"!=typeof e)return{type:"message",data:zp(e,t)};const r=e.charAt(0);if("b"===r){const r=Buffer.from(e.substring(1),"base64");return{type:"message",data:zp(r,t)}}return Bp[r]?e.length>1?{type:Bp[r],data:e.substring(1)}:{type:Bp[r]}:qp},Yp=String.fromCharCode(30);function Hp(e){if(e)return function(e){for(var t in Hp.prototype)e[t]=Hp.prototype[t];return e}(e)}Hp.prototype.on=Hp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Hp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Hp.prototype.off=Hp.prototype.removeListener=Hp.prototype.removeAllListeners=Hp.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},Hp.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},Hp.prototype.emitReserved=Hp.prototype.emit,Hp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Hp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Gp=global;function Kp(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Jp=Gp.setTimeout,Zp=Gp.clearTimeout;function Xp(e,t){t.useNativeTimers?(e.setTimeoutFn=Jp.bind(Gp),e.clearTimeoutFn=Zp.bind(Gp)):(e.setTimeoutFn=Gp.setTimeout.bind(Gp),e.clearTimeoutFn=Gp.clearTimeout.bind(Gp))}var ed=i(1314);const td=ed("engine.io-client:transport");class rd extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class nd extends Hp{constructor(e){super(),this.writable=!1,Xp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new rd(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState?this.write(e):td("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Wp(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}}const id="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ad={};let od,sd=0,pd=0;function dd(e){let t="";do{t=id[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function ud(){const e=dd(+new Date);return e!==od?(sd=0,od=e):e+"."+dd(sd++)}for(;pd<64;pd++)ad[id[pd]]=pd;function cd(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}var ld=i(4934);const fd=ld||i.t(ld,2),hd=ed("engine.io-client:polling");function md(){}const vd=null!=new fd({xdomain:!1}).responseType;class yd extends Hp{constructor(e,t){super(),Xp(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=Kp(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new fd(e);try{hd("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},hd("xhr data %s",this.data),t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=yd.requestsCount++,yd.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=md,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete yd.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function bd(){for(let e in yd.requests)yd.requests.hasOwnProperty(e)&&yd.requests[e].abort()}yd.requestsCount=0,yd.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",bd):"function"==typeof addEventListener&&addEventListener("onpagehide"in Gp?"pagehide":"unload",bd,!1)),i(4291),i(1938),i(7204);var gd=i(4965);i(6574);const _d=gd,wd=process.nextTick,Sd=ed("engine.io-client:websocket"),Ed="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),Od={websocket:class extends nd{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=Ed?{}:Kp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=new _d(e,t,r)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType||"nodebuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;Up(r,this.supportsBinary,(e=>{const t={};r.options&&(t.compress=r.options.compress),this.opts.perMessageDeflate&&("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1);try{this.ws.send(e,t)}catch(e){Sd("websocket closed before onclose event")}n&&wd((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let r="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=ud()),this.supportsBinary||(e.b64=1);const n=cd(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}check(){return!!_d}},polling:class extends nd{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=vd&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{hd("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(hd("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){hd("pre-pause polling complete"),--e||t()}))),this.writable||(hd("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){hd("pre-pause writing complete"),--e||t()})))}else t()}poll(){hd("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){hd("polling got data %s",e),((e,t)=>{const r=e.split(Yp),n=[];for(let e=0;e<r.length;e++){const i=Wp(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState?this.poll():hd('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{hd("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(hd("transport open - closing"),e()):(hd("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach(((e,a)=>{Up(e,!1,(e=>{n[a]=e,++i===r&&t(n.join(Yp))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let r="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=ud()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port);const n=cd(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new yd(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){hd("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Nd=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Td=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function xd(e){const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Nd.exec(e||""),a={},o=14;for(;o--;)a[Td[o]]=i[o]||"";return-1!=r&&-1!=n&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const r=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1),"/"==t.slice(-1)&&r.splice(r.length-1,1),r}(0,a.path),a.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,a.query),a}const Pd=ed("engine.io-client:socket");class kd extends Hp{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=xd(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=xd(t.host).host),Xp(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){Pd('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return Pd("options: %j",r),new Od[e](r)}open(){let e;if(this.opts.rememberUpgrade&&kd.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return Pd("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){Pd("setting transport %s",e.name),this.transport&&(Pd("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){Pd('probing transport "%s"',e);let t=this.createTransport(e),r=!1;kd.priorWebsocketSuccess=!1;const n=()=>{r||(Pd('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(n=>{if(!r)if("pong"===n.type&&"probe"===n.data){if(Pd('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;kd.priorWebsocketSuccess="websocket"===t.name,Pd('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{r||"closed"!==this.readyState&&(Pd("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{Pd('probe transport "%s" failed',e);const r=new Error("probe error");r.transport=t.name,this.emitReserved("upgradeError",r)}})))};function i(){r||(r=!0,d(),t.close(),t=null)}const a=r=>{const n=new Error("probe error: "+r);n.transport=t.name,i(),Pd('probe transport "%s" failed because of error: %s',e,r),this.emitReserved("upgradeError",n)};function o(){a("transport closed")}function s(){a("socket closed")}function p(e){t&&e.name!==t.name&&(Pd('"%s" works - aborting "%s"',e.name,t.name),i())}const d=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",o),this.off("close",s),this.off("upgrading",p)};t.once("open",n),t.once("error",a),t.once("close",o),this.once("close",s),this.once("upgrading",p),t.open()}onOpen(){if(Pd("socket open"),this.readyState="open",kd.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){Pd("starting upgrade probes");let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(Pd('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}else Pd('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();Pd("flushing %d packets in socket",e.length),this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return Pd("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);e+=2}var t;return Pd("payload size is %d (max: %d)",e,this.maxPayload),this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),Pd("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Pd("socket error %j",e),kd.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(Pd('socket close with reason: "%s"',e),this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}kd.protocol=4,kd.protocol;const Dd=ed("socket.io-client:url"),Ad="function"==typeof ArrayBuffer,Id=Object.prototype.toString,jd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Id.call(Blob),Cd="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Id.call(File);function Rd(e){return Ad&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||jd&&e instanceof Blob||Cd&&e instanceof File}function Md(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Md(e[t]))return!0;return!1}if(Rd(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Md(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Md(e[t]))return!0;return!1}function Fd(e){const t=[],r=e.data,n=e;return n.data=$d(r,t),n.attachments=t.length,{packet:n,buffers:t}}function $d(e,t){if(!e)return e;if(Rd(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=$d(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=$d(e[n],t));return r}return e}function Vd(e,t){return e.data=Ld(e.data,t),delete e.attachments,e}function Ld(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Ld(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Ld(e[r],t));return e}const Bd=ed("socket.io-parser"),qd=5;var Ud;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Ud||(Ud={}));class zd{constructor(e){this.replacer=e}encode(e){return Bd("encoding packet %j",e),e.type!==Ud.EVENT&&e.type!==Ud.ACK||!Md(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ud.EVENT?Ud.BINARY_EVENT:Ud.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ud.BINARY_EVENT&&e.type!==Ud.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),Bd("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=Fd(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}class Qd extends Hp{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Ud.BINARY_EVENT;r||t.type===Ud.BINARY_ACK?(t.type=r?Ud.EVENT:Ud.ACK,this.reconstructor=new Wd(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Rd(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Ud[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Ud.BINARY_EVENT||r.type===Ud.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Qd.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return Bd("decoded %s as %j",e,r),r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Ud.CONNECT:return"object"==typeof t;case Ud.DISCONNECT:return void 0===t;case Ud.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Ud.EVENT:case Ud.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Ud.ACK:case Ud.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Wd{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Vd(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Yd(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Hd=ed("socket.io-client:socket"),Gd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Kd extends Hp{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Yd(e,"open",this.onopen.bind(this)),Yd(e,"packet",this.onpacket.bind(this)),Yd(e,"error",this.onerror.bind(this)),Yd(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Gd.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Ud.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;Hd("emitting packet with ack id %d",e);const n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return!this.flags.volatile||n&&this.connected?this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r):Hd("discard packet as the transport is not currently writable"),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&(Hd("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));Hd("event with ack id %d has timed out after %d ms",e,n),t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(r===this._queue[0])return null!==e?r.tryCount>this._opts.retries&&(Hd("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(e)):(Hd("packet [%d] was successfully sent",r.id),this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(Hd("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,Hd("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):Hd("packet [%d] has already been sent and is waiting for an ack",t.id)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Hd("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ud.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Hd("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ud.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ud.EVENT:case Ud.BINARY_EVENT:this.onevent(e);break;case Ud.ACK:case Ud.BINARY_ACK:this.onack(e);break;case Ud.DISCONNECT:this.ondisconnect();break;case Ud.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];Hd("emitting event %j",t),null!=e.id&&(Hd("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,Hd("sending ack %j",n),t.packet({type:Ud.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(Hd("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):Hd("bad ack %s",e.id)}onconnect(e,t){Hd("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){Hd("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Hd("performing disconnect (%s)",this.nsp),this.packet({type:Ud.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function Jd(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Jd.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},Jd.prototype.reset=function(){this.attempts=0},Jd.prototype.setMin=function(e){this.ms=e},Jd.prototype.setMax=function(e){this.max=e},Jd.prototype.setJitter=function(e){this.jitter=e};const Zd=ed("socket.io-client:manager");class Xd extends Hp{constructor(e,r){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(r=e,e=void 0),(r=r||{}).path=r.path||"/socket.io",this.opts=r,Xp(this,r),this.reconnection(!1!==r.reconnection),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=r.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Jd({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==r.timeout?2e4:r.timeout),this._readyState="closed",this.uri=e;const i=r.parser||t;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==r.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(Zd("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Zd("opening %s",this.uri),this.engine=new kd(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=Yd(t,"open",(function(){r.onopen(),e&&e()})),i=Yd(t,"error",(t=>{Zd("error"),r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;Zd("connect attempt will timeout after %d",e),0===e&&n();const r=this.setTimeoutFn((()=>{Zd("connect attempt timed out after %d",e),n(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}return this.subs.push(n),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){Zd("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Yd(e,"ping",this.onping.bind(this)),Yd(e,"data",this.ondata.bind(this)),Yd(e,"error",this.onerror.bind(this)),Yd(e,"close",this.onclose.bind(this)),Yd(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){wd((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){Zd("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new Kd(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return void Zd("socket %s is still active, skipping close",e);this._close()}_packet(e){Zd("writing packet %j",e);const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){Zd("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){Zd("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){Zd("closed due to %s",e),this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Zd("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Zd("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(Zd("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(Zd("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(Zd("reconnect success"),e.onreconnect())})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const eu=ed("socket.io-client"),tu={};function ru(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(Dd("protocol-less url %s",e),e=void 0!==r?r.protocol+"//"+e:"https://"+e),Dd("parse %s",e),n=xd(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,a=r.path,o=tu[i]&&a in tu[i].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?(eu("ignoring socket cache for %s",n),s=new Xd(n,t)):(tu[i]||(eu("new io instance for %s",n),tu[i]=new Xd(n,t)),s=tu[i]),r.query&&!t.query&&(t.query=r.queryKey),s.socket(r.path,t)}Object.assign(ru,{Manager:Xd,Socket:Kd,io:ru,connect:ru});const nu=e=>e();var iu=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};class au{constructor(e,t,r=nu,n){this.clientId=e,this.socketIoEndpoint=t,this.messageNotificationWrapper=r,this.destructManager=n,this.webSocketObserver=new je.Subject,this.allMessagesObserver=new je.Subject,this.connectionReady=new je.BehaviorSubject(!1),this.seenMessageIds=new Set,this.firstConnection=!0,this.destructManager.onDestruct((()=>iu(this,void 0,void 0,(function*(){yield this.destruct()})))),this.setupMessageAcknowledgments(),this.connect()}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,je.distinctUntilChanged)())}sendMessage(e){(0,je.firstValueFrom)(this.connectionReady.pipe((0,je.filter)(Boolean))).then((()=>{$e(this.socket).emit("message",e)}))}connect(){this.socket=ru(this.socketIoEndpoint,{query:{clientId:this.clientId},reconnectionDelay:5e3,transports:["websocket"]}),this.socket.on("connect",(()=>{})),this.socket.on("disconnect",((e,t)=>{this.connectionReady.next(!1)})),this.socket.on("connectionReady",(()=>{this.connectionReady.next(!0),this.firstConnection||this.sendMessage({type:"catchup"}),this.firstConnection=!1})),this.socket.on("connect_error",(e=>{console.error("An error occurred while connecting to the socket",e)})),this.socket.on("message",(e=>{const t=Oe(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}))}setupMessageAcknowledgments(){const e=new je.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,je.tap)((e=>t.push(e))),(0,je.debounceTime)(100)).subscribe((()=>iu(this,void 0,void 0,(function*(){const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))))}destruct(){var e;return iu(this,void 0,void 0,(function*(){this.sendMessage({type:"kill"}),this.connectionReady.next(!1),yield(0,je.firstValueFrom)((0,je.timer)(0)),null===(e=this.socket)||void 0===e||e.disconnect(),this.webSocketObserver.complete(),this.allMessagesObserver.complete()}))}}var ou=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};class su{constructor(e){this.destructManager=new Yt,Fe(e.appId,"APP_ID_MUST_BE_PROVIDED");const t=function(e,t){const r=new URL("https://squid.cloud");r.host=`${t}.${e}.${r.host}`,"local"===e&&(r.protocol="http",r.port="8000");const n=r.toString();return n.endsWith("/")?n:n+"/"}(e.region,e.appId);this.clientId=ft(),this.socketManager=new au(this.clientId,t,e.messageNotificationWrapper,this.destructManager),this.rpcManager=new $p(t,this.socketManager,this.destructManager,e.apiKey),this.documentStore=new Kt,this.lockManager=new ht,this.documentIdentityService=new Ht(this.documentStore,this.destructManager),this.documentReferenceFactory=new Gt,this.querySubscriptionManager=new Rp(this.rpcManager,this.clientId,this.documentStore,this.destructManager,this.documentIdentityService);const r=new vp(this.clientId,this.rpcManager,this.lockManager,this.querySubscriptionManager);this.queryBuilderFactory=new $t(this.querySubscriptionManager,this.documentReferenceFactory,this.documentIdentityService),this.joinQueryBuilderFactory=new Mt(this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory),this.collectionReferenceFactory=new qt(this.documentReferenceFactory,this.queryBuilderFactory,this.joinQueryBuilderFactory,this.documentIdentityService),this.dataManager=new Wt(this.documentStore,r,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new Bt(this.clientId,this.rpcManager,this.socketManager),this.namedQueryManager=new yp(this.clientId,this.rpcManager,this.socketManager),this.apiManager=new Lt(this.clientId,this.rpcManager,this.socketManager,e.apiServerUrlOverrideMapping),this.graphqlClientFactory=new hp(this.rpcManager)}static getInstance(e){const t=Se(e);let r=su.squidInstancesMap.get(t);return r||(r=new su(e),su.squidInstancesMap.set(t,r),r)}static getInstances(){return Array.from(su.squidInstancesMap.values())}setAuthIdToken(e){e?this.rpcManager.setStaticHeader("Authorization",`Bearer ${e}`):this.rpcManager.deleteStaticHeader("Authorization")}collection(e,t="internal"){return this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this.dataManager.runInTransaction(e)}executeFunction(e,...t){return(0,je.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))}executeNamedQuery(e,t,r){return(0,je.firstValueFrom)(this.namedQueryManager.executeNamedQueryAndSubscribe(e,t,r))}callApi(e,t,r={}){return(0,je.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,t,r))}graphql(e){return this.graphqlClientFactory.get(e)}destruct(){return ou(this,void 0,void 0,(function*(){return this.destructManager.destruct()}))}unsubscribe(){return ou(this,void 0,void 0,(function*(){this.querySubscriptionManager.unsubscribe(),yield this.rpcManager.awaitAllSettled()}))}}su.squidInstancesMap=new Map;class pu{metadata(){return yt.data}cleanup(){return e=this,t=void 0,n=function*(){for(const e of su.getInstances())yield e.destruct()},new((r=void 0)||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}));var e,t,r,n}}const du=require("path");var uu=i(7147);class cu{constructor(e){this.region=process.env.SQUID_REGION||"local",this.secrets=e.secrets,this.backendApiKey=e.backendApiKey,this.logger=e.logger,this.context=e.context,this.codeDir=e.codeDir,this.auth=e.auth}get squid(){return su.getInstance({appId:this.context.appId,apiKey:this.backendApiKey,region:this.region})}get assetsDirectory(){const e=du.resolve(this.codeDir||"","public");if(uu.existsSync(e))return e;const t=du.resolve(process.cwd(),"src/public");return uu.existsSync(t)?t:e}getUserAuth(){var e;if("Bearer"===(null===(e=this.auth)||void 0===e?void 0:e.type))return this.auth}getApiKeyAuth(){var e;if("ApiKey"===(null===(e=this.auth)||void 0===e?void 0:e.type))return this.auth}isAuthenticated(){return!!this.auth}createWebhookResponse(e,t,r){return{body:e||"",statusCode:t||(e?200:204),headers:r||{},__isWebhookResponse__:!0}}}})();var o=exports;for(var s in a)o[s]=a[s];a.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
12
+ `})).data}))}}class hp{constructor(e){this.rpcManager=e,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new fp(this.rpcManager,e),this.clientsMap.set(e,t),t)}}var mp;class vp{constructor(e,t,r,n){this.clientId=e,this.rpcManager=t,this.lockManager=r,this.querySubscriptionManager=n}sendMutations(e,t){return r=this,n=void 0,a=function*(){const r=We(e),n=r.map((e=>`sendMutation_${Pe(e.squidDocIdObj)}`));yield this.lockManager.lock(...n),yield this.querySubscriptionManager.waitForAllQueriesToFinish();try{const e={clientId:this.clientId,mutations:r,integrationId:t};return yield this.rpcManager.post("mutation/mutate",e)}finally{this.lockManager.release(...n)}},new((i=void 0)||(i=Promise))((function(e,t){function o(e){try{p(a.next(e))}catch(e){t(e)}}function s(e){try{p(a.throw(e))}catch(e){t(e)}}function p(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,s)}p((a=a.apply(r,n||[])).next())}));var r,n,i,a}}class yp{constructor(e,t,r){this.clientId=e,this.rpcManager=t,this.socketManager=r,this.ongoingNamedQueryExecutions={},r.observeNotifications().pipe((0,je.filter)((e=>"namedQuery"===e.type)),(0,Rt.UI)((e=>e))).subscribe((e=>{this.handleNamedQueryResponse(e.clientRequestId,e.payload)}))}executeNamedQueryAndSubscribe(e,t,r){const n=ft(),i=new je.Subject;this.ongoingNamedQueryExecutions[n]=i;const a={integrationId:e,queryName:t,paramsRecordStr:Ee(r),clientId:this.clientId,clientRequestId:n};return this.rpcManager.post("named-query/execute",a).catch((r=>{console.error("Got error while executing named query",t,"for integration",e,r),i.error(r),i.complete()})),i.pipe((0,je.finalize)((()=>{delete this.ongoingNamedQueryExecutions[n]})),(0,je.share)())}handleNamedQueryResponse(e,t){const r=this.ongoingNamedQueryExecutions[e];if(!r)return;const n=Oe(t);n.success?r.next(n.result):(r.error(new Error(n.result)),r.complete())}}function bp(e){return[mp.SET_PATH,mp.DELETE_PATH].includes(e.type)}function gp(e){return e.type===mp.BATCH_ACTION}function _p(e){const t=[];if(bp(e))t.push(e);else if(gp(e))for(const r of e.payload)t.push(..._p(r));return t}function wp(e,t){return Ep(e,t)}function Sp(e){return"object"==typeof e}function Ep(e,t){let r=e;if(bp(t))r=function(e,t,r=[]){switch(t.type){case mp.DELETE_PATH:return Op(e,t.path);case mp.SET_PATH:const n=t;return function(e,t,r,n){return Np(e,t,r,n)}(e,t.path,r,n.payload);case mp.BATCH_ACTION:throw new Error("Unsupported")}}(e,t,[]);else{if(!gp(t))throw new Error(`Invalid action type: ${t.type}`);r=t.payload.reduce(((e,t)=>Ep(e,t)),e)}return r}function Op(e,t){if(!t.length)throw new Error("can not delete an empty path");const r=t[0];if(1===t.length)return function(e,t){if(e instanceof Array)throw new Error("Cannot remove an item from an array");const r=Object.assign({},e);return delete r[t],r}(e,r);const n=t.slice(1),i=xp(e,r);if(!i)return e;if(!Sp(i))throw new Error("Cannot delete from a non object state.");const a=Op(i,n);return a===i?e:Tp(e,r,a)}function Np(e,t,r,n){if(!t.length){if(Sp(n))return n;throw new Error("Relative path cannot be of length 0 when the new value is not an object.")}const i=t[0],a=[...r,i];if(1===t.length)return Tp(e,i,n);const o=t.slice(1),s=xp(e,i);return void 0!==s&&Sp(s)?Tp(e,i,Np(s,o,a,n)):Np(e=Tp(e,i,{}),t,r,n)}function Tp(e,t,r){return(e=Object.assign({},e))[t]=r,e}function xp(e,t){return e instanceof Array?e[function(e){const t=Number(e);if(isNaN(t))throw new Error(`The value is not a number: Actual: ${e}`);return Math.floor(t)}(t)]:e[t]}!function(e){e.DELETE_PATH="DELETE_PATH",e.SET_PATH="SET_PATH",e.BATCH_ACTION="BATCH_ACTION"}(mp||(mp={}));class Pp{constructor(){this.root=new kp}getOrCreatePathTrieNode(e,t){let r=this.root;for(const t of e)r.children.get(t)||r.children.set(t,new kp),r=r.children.get(t);return void 0!==t&&(r.nodeData=t),r}getPathTrieNode(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}return t}getPathTrie(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}if(t){const e=new Pp;return e.root=t,e}}iterateBfs(e){this.iterateInternal(this.root,e,[])}removeNode(e){e.length||(this.root=new kp);const t=[this.root];for(const r of e){const e=t[t.length-1].children.get(r);if(!e)throw new Error("Node does not exist");t.push(e)}for(let r=t.length-1;r>0;r--){const n=t[r],i=e[r-1];if((n.nodeData||n.children.size)&&r!==t.length-1)break;t[r-1].children.delete(i)}}clearNodeData(e){const t=this.getPathTrieNode(e);t&&(t.nodeData=void 0,t.children.size||this.removeNode(e))}getNodeList(e){const t=[];let r=this.root;for(const n of e){if(!r)return t;t.push(r),r=r.children.get(n)}return t}iterateInternal(e,t,r){if(!1!==t(e.nodeData,r))for(const[n,i]of e.children)this.iterateInternal(i,t,r.concat(n))}}class kp{constructor(){this.children=new Map([])}}class Dp{constructor(){this.subscriptionsTree=new Pp,this.state={},this.batchCount=0,this.batchedActions=[]}dispatch(e){this.batchCount>0&&this.batchedActions.push(e),this.state=wp(this.state,e),0===this.batchCount&&this.dispatchSubscriptions(e)}runInBatch(e){this.batchCount++;try{e()}finally{if(this.batchCount--,0===this.batchCount&&this.batchedActions.length){const e={type:mp.BATCH_ACTION,payload:[...this.batchedActions]};this.batchedActions.splice(0),this.dispatch(e)}}}observePath(e,t){return new je.Observable((r=>{const n=this.getOrCreateSubjectForPath(e);r.next(this.getStateInPath(e));const i=n.pipe((0,Rt.hX)((e=>{if(!t)return!0;const r=new Pp,n=t();for(const e of n)r.getOrCreatePathTrieNode(e,!0);const i=_p(e.action).map((e=>e.path));let a=!1;for(const e of i)if(0===r.getNodeList(e).length){a=!0;break}return a})),(0,Rt.UI)((e=>e.data))).subscribe(r);return()=>{i.unsubscribe(),n.observed||(n.complete(),this.subscriptionsTree.clearNodeData(e))}}))}setKeyInPath(e,t,r,n=!1){this.setInPath([...e,t],r,n)}setPartial(e,t,r=!1){let n=this.getStateInPath(e);n||(n={}),this.setInPath(e,Object.assign(Object.assign({},n),t),r)}setInPath(e,t,r=!1){if(r&&this.getStateInPath(e)===t)return;const n={type:mp.SET_PATH,path:e,payload:t};this.dispatch(n)}pushToArray(e,t){let r=this.getStateInPath(e);r=r?[...r]:[],r.push(t),this.setInPath(e,r)}deletePath(e){const t={type:mp.DELETE_PATH,path:e};this.dispatch(t)}getState(){return this.state}getStateInPath(e){return Ap(this.state,e)}destroy(){this.subscriptionsTree.iterateBfs((e=>{e&&e.subject&&e.subject.complete()}))}getOrCreateSubjectForPath(e){const t=this.subscriptionsTree.getOrCreatePathTrieNode(e);t.nodeData||(t.nodeData=new Ip);const r=t.nodeData;return r.subject||(r.subject=new je.Subject),r.subject}dispatchSubscriptions(e){const t=function(e,t){const r=new Pp;for(const n of _p(e)){let e=r.getOrCreatePathTrieNode(n.path);if(!t||e.nodeData)continue;let i=t.getPathTrieNode(n.path);if(i){const t=[[e,i]];for(;t.length;){const r=t.shift();if(e=r[0],i=r[1],!e.nodeData){for(const[r,n]of i.children)e.children.get(r)||e.children.set(r,new kp),t.push([e.children.get(r),n]);e.nodeData=!0}}}}return r}(e,this.subscriptionsTree);t.iterateBfs(((t,r)=>{const n=this.subscriptionsTree.getPathTrieNode(r);n&&n.nodeData&&n.nodeData.subject.next({action:e,data:Ap(this.getState(),r)})}))}}function Ap(e,t){let r=e;for(const e of t){if(null==r)return;if(!Sp(r))throw new Error("result must be a state object");r=r[e]}return r}class Ip{}var jp=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};const Cp="client";class Rp{constructor(e,t,r,n,i){this.rpcManager=e,this.clientId=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.safeToSendQueriesToServer=new je.BehaviorSubject(!0),this.onOrphanDocuments=new je.Subject,this.ongoingQueries=new Map,this.inflightQueriesCount=new je.BehaviorSubject(0),this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Mp,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.destructManager.onPreDestruct((()=>{this.predestruct()}))}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return $e(this.ongoingQueries.get(e)).query}setGotResponseFromServer(e){$e(this.ongoingQueries.get(e)).gotResponseFromServer=!0}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=xe(t),i=this.queryMappingManager.getMapping(Cp,r,n);return i?et(i,e):[]}setClientRequestIdsForLocalDoc(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set,n=new Set(t?this.findQueriesForDocument(t,e).map((e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId)):[]),i=new Set([...r,...n]);for(const t of[...r]){if(n.has(t))continue;r.delete(t);const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),r.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let r=this.localDocumentToClientRequestIds.get(e);r||(r=new Set,this.localDocumentToClientRequestIds.set(e,r)),r.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...i]}errorOutAllQueries(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of r){const r=this.ongoingQueries.get(e);r&&r.subject.error(t)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotResponseFromServer||!e.activated)continue;const n=this.clientRequestIdToLocalDocuments.get(r),i=this.documentStore.sortAndLimitDocs(n,e.query);let a=!1;for(const t of e.supportedQueries)a=a||this.updateOngoingQueryWithNewDataFromSupportingQuery(i,t);let o=e;for(;!o.allObservables;)o=$e(null==o?void 0:o.supportingOngoingQuery);a&&t.add(o),e.subject.next(i)}for(const e of t){const t=this.collectAllObservables(e);$e(e.allObservables).next(t)}}processQuery(e,t,r,n,i){const a=this.createOngoingQueryGraph(e,t,r,n,i,!0);this.sendQueryToServer(a),a.allObservables=new je.ReplaySubject(1);const o=a.allObservables.pipe((0,je.switchMap)((e=>(0,je.combineLatest)(e).pipe((0,Rt.UI)((e=>this.joinResults(e,n,a)))))),(0,Rt.hX)((()=>this.allOngoingQueriesGotServerResult(a))),(0,je.startWith)(void 0),(0,je.pairwise)(),(0,Rt.hX)((([e,t])=>!Ae.isEqual(e,t))),(0,Rt.UI)((([e,t])=>t)),i?(0,je.tap)():(0,je.take)(1),(0,je.finalize)((()=>{var e;a.subject.complete(),this.completeAllSupportedQueries(a),null===(e=a.allObservables)||void 0===e||e.complete()}))),s=this.collectAllObservables(a);return a.allObservables.next(s),o}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestId(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=$e(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r),this.ongoingQueries.delete(e)}waitForAllQueriesToFinish(){return jp(this,void 0,void 0,(function*(){return(0,je.firstValueFrom)(this.inflightQueriesCount.pipe((0,Rt.hX)((e=>0===e)))).then((()=>{}))}))}registerQueryFinalizer(e){const t=e.clientRequestId,r=rt(this.clientId,t);e.subject.pipe((0,je.finalize)((()=>{if(this.queryMappingManager.removeQuery(t,r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientId:this.clientId,clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch((t=>{console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestId(t)}))).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,a,o={}){if(o[t])return o[t];const s=ft(),p=[],d={clientRequestId:s,activated:a,alias:t,query:e,subscribe:i,subject:new je.ReplaySubject(1),supportedQueries:p,supportingOngoingQuery:void 0,joinCondition:void 0,gotResponseFromServer:!1,isEmptyForJoin:!1};this.registerQueryFinalizer(d),this.ongoingQueries.set(s,d),o[t]=d;for(const[e,a]of Object.entries(n)){const s=a.leftAlias;if(s!==t&&e!==t)continue;const u=s===t?e:s;if(s===t){const e=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,o);e.joinCondition=a,p.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,o)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.subject.pipe((0,Rt.UI)((e=>({docs:e,alias:r})))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=[],i=e.reduce(((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e)),{});i[r.alias].forEach((e=>{n.push({[r.alias]:e})}));const a=this.getOngoingQueriesBfs(r),o=new Set;for(let e=1;e<a.length;e++){const r=a[e].alias;o.has(r)||(o.add(r),this.join(n,r,i[r],t))}return n}join(e,t,r,n){var i;if(!e.length)return;const a=Object.keys(e[0]),o=n[t];if(!o||!a.includes(o.leftAlias))return;const s=new Map;(r||[]).forEach((e=>{const t=e[o.rightFieldName];s.has(t)||s.set(t,[]),$e(s.get(t)).push(e)}));for(const r of[...e]){const n=s.get(null===(i=r[o.leftAlias])||void 0===i?void 0:i[o.leftFieldName])||[];if(n.length)for(const i of n)r[t]?e.push(Object.assign(Object.assign({},r),{[t]:i})):r[t]=i;else r[t]||(r[t]=void 0)}}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=$e(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=$e(t.joinCondition),i=t.query;if(t.activated){const a=$e(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),o=new Set(e.map((e=>{var t;return null!==(t=e[n.leftFieldName])&&void 0!==t?t:null})));for(const e of a)e.query.conditions.filter((e=>e.fieldName===n.rightFieldName)).forEach((e=>{o.delete(e.value)}));if(0===o.size)return!1;const s=Ae.cloneDeep(i);s.conditions=s.conditions.filter((e=>e.fieldName!==n.rightFieldName)),[...o].forEach((e=>{s.conditions.push({fieldName:n.rightFieldName,operator:"==",value:e})}));const p=Object.assign(Object.assign({},t),{query:s,activated:!0,gotResponseFromServer:!1,subject:new je.ReplaySubject(1),clientRequestId:ft(),isEmptyForJoin:!1});return this.registerQueryFinalizer(p),this.ongoingQueries.set(p.clientRequestId,p),$e(t.supportingOngoingQuery).supportedQueries.push(p),this.sendQueryToServer(p),!0}{const r=e.map((e=>{var t;return{fieldName:n.rightFieldName,operator:"==",value:null!==(t=e[n.leftFieldName])&&void 0!==t?t:null}}));return t.activated=!0,r.length?(i.conditions.push(...r),this.sendQueryToServer(t)):t.isEmptyForJoin=!0,!0}}allOngoingQueriesGotServerResult(e){return!!e.isEmptyForJoin||!!e.gotResponseFromServer&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotServerResult(e))))}completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=$e(t.shift());t.push(...e.supportedQueries||[]),e.subject.complete()}}predestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete(),this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.subject.complete(),null===(e=r.allObservables)||void 0===e||e.complete()}hasSubscription(e){var t;return!!(null===(t=this.ongoingQueries.get(e))||void 0===t?void 0:t.subscribe)}sendQueryToServer(e){const t=e.query,r=e.clientRequestId,n={query:t,clientRequestId:r,subscribe:e.subscribe,clientId:this.clientId},i=rt(this.clientId,r);this.queryMappingManager.addQuery(Cp,t,i).then(),this.ongoingQueries.set(r,e),this.safeToSendQueriesToServer.pipe((0,Rt.hX)(Boolean),(0,je.take)(1)).subscribe((()=>{e.subject.closed||(this.inflightQueriesCount.next(this.inflightQueriesCount.value+1),this.rpcManager.post("query/query",n).catch((t=>{e.subject.error(t)})).finally((()=>{this.inflightQueriesCount.next(this.inflightQueriesCount.value-1)})))}))}migrateDocIds(e){const t=Object.keys(e);for(const r of this.clientRequestIdToLocalDocuments.values())t.forEach((t=>{r.has(t)&&(r.delete(t),r.add(e[t]))}));t.forEach((t=>{Ue(this.localDocumentToClientRequestIds,t,e[t])}))}}class Mp extends Xe{constructor(){super(...arguments),this.stateService=new Dp,this.querySubscriptionIdToQuery={}}addQuery(e,t,r){return jp(this,void 0,void 0,(function*(){this.stateService.runInBatch((()=>{let e=0;const n=new Set;for(const i of t.conditions){const a=this.getConditionStatePath(t,i),o=[...this.stateService.getStateInPath(a)||[]];if(dt(o,r),["==","!="].includes(i.operator)){const t=Ne(i.fieldName);n.has(t)||(e++,n.add(t))}else e++;this.stateService.setInPath(a,o)}if(!t.conditions.length){const e=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(e)||[]];dt(n,r),this.stateService.setInPath(e,n)}this.stateService.setInPath([...this.getQueryMetadataStatePath(t,r),"condCount"],e)})),this.querySubscriptionIdToQuery[r]=t}))}removeQuery(e,t){return jp(this,void 0,void 0,(function*(){const e=this.querySubscriptionIdToQuery[t];if(e)return this.stateService.runInBatch((()=>{for(const r of e.conditions){const n=this.getConditionStatePath(e,r),i=[...this.stateService.getStateInPath(n)||[]];ut(i,t),i.length?this.stateService.setInPath(n,i):this.stateService.deletePath(n)}if(!e.conditions.length){const r=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(r)||[]];ut(n,t),this.stateService.setInPath(r,n)}this.stateService.deletePath(this.getQueryMetadataStatePath(e,t))})),e}))}getMapping(e,t,r){return this.stateService.getStateInPath(["queryMapping",t,r,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){const r=Ne(t.fieldName),n=Ne(t.value);return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",`${r}`,`${t.operator}`,`${n}`]}}var Fp=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};class $p{constructor(e,t,r,n){this.rpcEndpoint=e,this.socketManager=t,this.staticHeaders={},this.onGoingRpcsCounter=new je.BehaviorSubject(0),Fe(e,"Http endpoint must be provided."),n&&this.setStaticHeader("Authorization",`ApiKey ${n}`),this.rpcEndpoint.endsWith("/")||(this.rpcEndpoint+="/"),r.onDestruct((()=>Fp(this,void 0,void 0,(function*(){yield this.awaitAllSettled()}))))}awaitAllSettled(){return Fp(this,void 0,void 0,(function*(){yield(0,je.firstValueFrom)(this.onGoingRpcsCounter.pipe((0,je.filter)((e=>0===e))))}))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getEndpoint(){return this.rpcEndpoint}getStaticHeaders(){return this.staticHeaders}post(e,t){return Fp(this,void 0,void 0,(function*(){yield(0,je.firstValueFrom)(this.socketManager.observeConnectionReady().pipe((0,je.filter)(Boolean)));let r={"Content-Type":"application/json"};Object.keys(this.staticHeaders)&&(r=Object.assign(Object.assign({},r),this.staticHeaders)),this.onGoingRpcsCounter.next(this.onGoingRpcsCounter.value+1);try{const n=yield cp()(`${this.rpcEndpoint}${e}`,{method:"POST",body:Ee(t),headers:r});let i;try{i=yield n.text()}catch(e){i="Cannot read body"}if(!n.ok)throw new Vp(n.status,n.statusText,n.headers,n.url,i);try{return JSON.parse(i)}catch(e){return i}}finally{this.onGoingRpcsCounter.next(this.onGoingRpcsCounter.value-1)}}))}}class Vp extends Error{constructor(e,t,r,n,i){super(`RPC error ${e} ${t} calling ${n}: ${i}`),this.statusCode=e,this.statusText=t,this.headers=r,this.url=n,this.body=i}}const Lp=Object.create(null);Lp.open="0",Lp.close="1",Lp.ping="2",Lp.pong="3",Lp.message="4",Lp.upgrade="5",Lp.noop="6";const Bp=Object.create(null);Object.keys(Lp).forEach((e=>{Bp[Lp[e]]=e}));const qp={type:"error",data:"parser error"},Up=({type:e,data:t},r,n)=>{if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=(e=>Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength))(t);return n(((e,t)=>t?e:"b"+e.toString("base64"))(e,r))}return n(Lp[e]+(t||""))},zp=(e,t)=>{const r=Buffer.isBuffer(e);return"arraybuffer"===t&&r?Qp(e):e},Qp=e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e[t];return t},Wp=(e,t)=>{if("string"!=typeof e)return{type:"message",data:zp(e,t)};const r=e.charAt(0);if("b"===r){const r=Buffer.from(e.substring(1),"base64");return{type:"message",data:zp(r,t)}}return Bp[r]?e.length>1?{type:Bp[r],data:e.substring(1)}:{type:Bp[r]}:qp},Yp=String.fromCharCode(30);function Hp(e){if(e)return function(e){for(var t in Hp.prototype)e[t]=Hp.prototype[t];return e}(e)}Hp.prototype.on=Hp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Hp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Hp.prototype.off=Hp.prototype.removeListener=Hp.prototype.removeAllListeners=Hp.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},Hp.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},Hp.prototype.emitReserved=Hp.prototype.emit,Hp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Hp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Gp=global;function Kp(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Jp=Gp.setTimeout,Zp=Gp.clearTimeout;function Xp(e,t){t.useNativeTimers?(e.setTimeoutFn=Jp.bind(Gp),e.clearTimeoutFn=Zp.bind(Gp)):(e.setTimeoutFn=Gp.setTimeout.bind(Gp),e.clearTimeoutFn=Gp.clearTimeout.bind(Gp))}var ed=i(1314);const td=ed("engine.io-client:transport");class rd extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class nd extends Hp{constructor(e){super(),this.writable=!1,Xp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new rd(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState?this.write(e):td("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Wp(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}}const id="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ad={};let od,sd=0,pd=0;function dd(e){let t="";do{t=id[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function ud(){const e=dd(+new Date);return e!==od?(sd=0,od=e):e+"."+dd(sd++)}for(;pd<64;pd++)ad[id[pd]]=pd;function cd(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}var ld=i(4934);const fd=ld||i.t(ld,2),hd=ed("engine.io-client:polling");function md(){}const vd=null!=new fd({xdomain:!1}).responseType;class yd extends Hp{constructor(e,t){super(),Xp(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=Kp(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new fd(e);try{hd("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},hd("xhr data %s",this.data),t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=yd.requestsCount++,yd.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=md,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete yd.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function bd(){for(let e in yd.requests)yd.requests.hasOwnProperty(e)&&yd.requests[e].abort()}yd.requestsCount=0,yd.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",bd):"function"==typeof addEventListener&&addEventListener("onpagehide"in Gp?"pagehide":"unload",bd,!1)),i(4291),i(1938),i(7204);var gd=i(4965);i(6574);const _d=gd,wd=process.nextTick,Sd=ed("engine.io-client:websocket"),Ed="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),Od={websocket:class extends nd{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=Ed?{}:Kp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=new _d(e,t,r)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType||"nodebuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;Up(r,this.supportsBinary,(e=>{const t={};r.options&&(t.compress=r.options.compress),this.opts.perMessageDeflate&&("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1);try{this.ws.send(e,t)}catch(e){Sd("websocket closed before onclose event")}n&&wd((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let r="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=ud()),this.supportsBinary||(e.b64=1);const n=cd(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}check(){return!!_d}},polling:class extends nd{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=vd&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{hd("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(hd("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){hd("pre-pause polling complete"),--e||t()}))),this.writable||(hd("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){hd("pre-pause writing complete"),--e||t()})))}else t()}poll(){hd("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){hd("polling got data %s",e),((e,t)=>{const r=e.split(Yp),n=[];for(let e=0;e<r.length;e++){const i=Wp(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState?this.poll():hd('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{hd("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(hd("transport open - closing"),e()):(hd("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach(((e,a)=>{Up(e,!1,(e=>{n[a]=e,++i===r&&t(n.join(Yp))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let r="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=ud()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port);const n=cd(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new yd(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){hd("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Nd=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Td=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function xd(e){const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Nd.exec(e||""),a={},o=14;for(;o--;)a[Td[o]]=i[o]||"";return-1!=r&&-1!=n&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const r=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1),"/"==t.slice(-1)&&r.splice(r.length-1,1),r}(0,a.path),a.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,a.query),a}const Pd=ed("engine.io-client:socket");class kd extends Hp{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=xd(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=xd(t.host).host),Xp(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){Pd('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return Pd("options: %j",r),new Od[e](r)}open(){let e;if(this.opts.rememberUpgrade&&kd.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return Pd("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){Pd("setting transport %s",e.name),this.transport&&(Pd("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){Pd('probing transport "%s"',e);let t=this.createTransport(e),r=!1;kd.priorWebsocketSuccess=!1;const n=()=>{r||(Pd('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(n=>{if(!r)if("pong"===n.type&&"probe"===n.data){if(Pd('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;kd.priorWebsocketSuccess="websocket"===t.name,Pd('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{r||"closed"!==this.readyState&&(Pd("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{Pd('probe transport "%s" failed',e);const r=new Error("probe error");r.transport=t.name,this.emitReserved("upgradeError",r)}})))};function i(){r||(r=!0,d(),t.close(),t=null)}const a=r=>{const n=new Error("probe error: "+r);n.transport=t.name,i(),Pd('probe transport "%s" failed because of error: %s',e,r),this.emitReserved("upgradeError",n)};function o(){a("transport closed")}function s(){a("socket closed")}function p(e){t&&e.name!==t.name&&(Pd('"%s" works - aborting "%s"',e.name,t.name),i())}const d=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",o),this.off("close",s),this.off("upgrading",p)};t.once("open",n),t.once("error",a),t.once("close",o),this.once("close",s),this.once("upgrading",p),t.open()}onOpen(){if(Pd("socket open"),this.readyState="open",kd.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){Pd("starting upgrade probes");let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(Pd('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}else Pd('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();Pd("flushing %d packets in socket",e.length),this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return Pd("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);e+=2}var t;return Pd("payload size is %d (max: %d)",e,this.maxPayload),this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),Pd("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Pd("socket error %j",e),kd.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(Pd('socket close with reason: "%s"',e),this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}kd.protocol=4,kd.protocol;const Dd=ed("socket.io-client:url"),Ad="function"==typeof ArrayBuffer,Id=Object.prototype.toString,jd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Id.call(Blob),Cd="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Id.call(File);function Rd(e){return Ad&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||jd&&e instanceof Blob||Cd&&e instanceof File}function Md(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Md(e[t]))return!0;return!1}if(Rd(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Md(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Md(e[t]))return!0;return!1}function Fd(e){const t=[],r=e.data,n=e;return n.data=$d(r,t),n.attachments=t.length,{packet:n,buffers:t}}function $d(e,t){if(!e)return e;if(Rd(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=$d(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=$d(e[n],t));return r}return e}function Vd(e,t){return e.data=Ld(e.data,t),delete e.attachments,e}function Ld(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Ld(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Ld(e[r],t));return e}const Bd=ed("socket.io-parser"),qd=5;var Ud;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Ud||(Ud={}));class zd{constructor(e){this.replacer=e}encode(e){return Bd("encoding packet %j",e),e.type!==Ud.EVENT&&e.type!==Ud.ACK||!Md(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ud.EVENT?Ud.BINARY_EVENT:Ud.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ud.BINARY_EVENT&&e.type!==Ud.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),Bd("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=Fd(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}class Qd extends Hp{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Ud.BINARY_EVENT;r||t.type===Ud.BINARY_ACK?(t.type=r?Ud.EVENT:Ud.ACK,this.reconstructor=new Wd(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Rd(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Ud[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Ud.BINARY_EVENT||r.type===Ud.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Qd.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return Bd("decoded %s as %j",e,r),r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Ud.CONNECT:return"object"==typeof t;case Ud.DISCONNECT:return void 0===t;case Ud.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Ud.EVENT:case Ud.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Ud.ACK:case Ud.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Wd{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Vd(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Yd(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Hd=ed("socket.io-client:socket"),Gd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Kd extends Hp{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Yd(e,"open",this.onopen.bind(this)),Yd(e,"packet",this.onpacket.bind(this)),Yd(e,"error",this.onerror.bind(this)),Yd(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Gd.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Ud.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;Hd("emitting packet with ack id %d",e);const n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return!this.flags.volatile||n&&this.connected?this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r):Hd("discard packet as the transport is not currently writable"),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&(Hd("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));Hd("event with ack id %d has timed out after %d ms",e,n),t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(r===this._queue[0])return null!==e?r.tryCount>this._opts.retries&&(Hd("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(e)):(Hd("packet [%d] was successfully sent",r.id),this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(Hd("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,Hd("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):Hd("packet [%d] has already been sent and is waiting for an ack",t.id)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Hd("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ud.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Hd("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ud.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ud.EVENT:case Ud.BINARY_EVENT:this.onevent(e);break;case Ud.ACK:case Ud.BINARY_ACK:this.onack(e);break;case Ud.DISCONNECT:this.ondisconnect();break;case Ud.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];Hd("emitting event %j",t),null!=e.id&&(Hd("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,Hd("sending ack %j",n),t.packet({type:Ud.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(Hd("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):Hd("bad ack %s",e.id)}onconnect(e,t){Hd("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){Hd("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Hd("performing disconnect (%s)",this.nsp),this.packet({type:Ud.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function Jd(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Jd.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},Jd.prototype.reset=function(){this.attempts=0},Jd.prototype.setMin=function(e){this.ms=e},Jd.prototype.setMax=function(e){this.max=e},Jd.prototype.setJitter=function(e){this.jitter=e};const Zd=ed("socket.io-client:manager");class Xd extends Hp{constructor(e,r){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(r=e,e=void 0),(r=r||{}).path=r.path||"/socket.io",this.opts=r,Xp(this,r),this.reconnection(!1!==r.reconnection),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=r.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Jd({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==r.timeout?2e4:r.timeout),this._readyState="closed",this.uri=e;const i=r.parser||t;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==r.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(Zd("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Zd("opening %s",this.uri),this.engine=new kd(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=Yd(t,"open",(function(){r.onopen(),e&&e()})),i=Yd(t,"error",(t=>{Zd("error"),r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;Zd("connect attempt will timeout after %d",e),0===e&&n();const r=this.setTimeoutFn((()=>{Zd("connect attempt timed out after %d",e),n(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}return this.subs.push(n),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){Zd("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Yd(e,"ping",this.onping.bind(this)),Yd(e,"data",this.ondata.bind(this)),Yd(e,"error",this.onerror.bind(this)),Yd(e,"close",this.onclose.bind(this)),Yd(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){wd((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){Zd("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new Kd(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return void Zd("socket %s is still active, skipping close",e);this._close()}_packet(e){Zd("writing packet %j",e);const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){Zd("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){Zd("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){Zd("closed due to %s",e),this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)Zd("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Zd("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(Zd("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(Zd("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(Zd("reconnect success"),e.onreconnect())})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const eu=ed("socket.io-client"),tu={};function ru(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(Dd("protocol-less url %s",e),e=void 0!==r?r.protocol+"//"+e:"https://"+e),Dd("parse %s",e),n=xd(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,a=r.path,o=tu[i]&&a in tu[i].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?(eu("ignoring socket cache for %s",n),s=new Xd(n,t)):(tu[i]||(eu("new io instance for %s",n),tu[i]=new Xd(n,t)),s=tu[i]),r.query&&!t.query&&(t.query=r.queryKey),s.socket(r.path,t)}Object.assign(ru,{Manager:Xd,Socket:Kd,io:ru,connect:ru});const nu=e=>e();var iu=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};class au{constructor(e,t,r=nu,n){this.clientId=e,this.socketIoEndpoint=t,this.messageNotificationWrapper=r,this.destructManager=n,this.webSocketObserver=new je.Subject,this.allMessagesObserver=new je.Subject,this.connectionReady=new je.BehaviorSubject(!1),this.seenMessageIds=new Set,this.firstConnection=!0,this.destructManager.onDestruct((()=>iu(this,void 0,void 0,(function*(){yield this.destruct()})))),this.setupMessageAcknowledgments(),this.connect()}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,je.distinctUntilChanged)())}sendMessage(e){(0,je.firstValueFrom)(this.connectionReady.pipe((0,je.filter)(Boolean))).then((()=>{$e(this.socket).emit("message",e)}))}connect(){this.socket=ru(this.socketIoEndpoint,{query:{clientId:this.clientId},reconnectionDelay:5e3,transports:["websocket"]}),this.socket.on("connect",(()=>{})),this.socket.on("disconnect",((e,t)=>{this.connectionReady.next(!1)})),this.socket.on("connectionReady",(()=>{this.connectionReady.next(!0),this.firstConnection||this.sendMessage({type:"catchup"}),this.firstConnection=!1})),this.socket.on("connect_error",(e=>{console.error("An error occurred while connecting to the socket with url: ",this.socketIoEndpoint,e)})),this.socket.on("message",(e=>{const t=Oe(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}))}setupMessageAcknowledgments(){const e=new je.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,je.tap)((e=>t.push(e))),(0,je.debounceTime)(100)).subscribe((()=>iu(this,void 0,void 0,(function*(){const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))))}destruct(){var e;return iu(this,void 0,void 0,(function*(){this.sendMessage({type:"kill"}),this.connectionReady.next(!1),yield(0,je.firstValueFrom)((0,je.timer)(0)),null===(e=this.socket)||void 0===e||e.disconnect(),this.webSocketObserver.complete(),this.allMessagesObserver.complete()}))}}var ou=function(e,t,r,n){return new(r||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}))};class su{constructor(e){this.destructManager=new Yt,Fe(e.appId,"APP_ID_MUST_BE_PROVIDED");const t=function(e,t){const r=new URL("https://squid.cloud");r.host=`${t}.${e}.${r.host}`,"local"===e&&(r.protocol="http",r.port="8000");const n=r.toString();return n.endsWith("/")?n:n+"/"}(e.region,e.appId);this.clientId=ft(),this.socketManager=new au(this.clientId,t,e.messageNotificationWrapper,this.destructManager),this.rpcManager=new $p(t,this.socketManager,this.destructManager,e.apiKey),this.documentStore=new Kt,this.lockManager=new ht,this.documentIdentityService=new Ht(this.documentStore,this.destructManager),this.documentReferenceFactory=new Gt,this.querySubscriptionManager=new Rp(this.rpcManager,this.clientId,this.documentStore,this.destructManager,this.documentIdentityService);const r=new vp(this.clientId,this.rpcManager,this.lockManager,this.querySubscriptionManager);this.queryBuilderFactory=new $t(this.querySubscriptionManager,this.documentReferenceFactory,this.documentIdentityService),this.joinQueryBuilderFactory=new Mt(this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory),this.collectionReferenceFactory=new qt(this.documentReferenceFactory,this.queryBuilderFactory,this.joinQueryBuilderFactory,this.documentIdentityService),this.dataManager=new Wt(this.documentStore,r,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new Bt(this.clientId,this.rpcManager,this.socketManager),this.namedQueryManager=new yp(this.clientId,this.rpcManager,this.socketManager),this.apiManager=new Lt(this.clientId,this.rpcManager,this.socketManager,e.apiServerUrlOverrideMapping),this.graphqlClientFactory=new hp(this.rpcManager)}static getInstance(e){const t=Se(e);let r=su.squidInstancesMap.get(t);return r||(r=new su(e),su.squidInstancesMap.set(t,r),r)}static getInstances(){return Array.from(su.squidInstancesMap.values())}setAuthIdToken(e){e?this.rpcManager.setStaticHeader("Authorization",`Bearer ${e}`):this.rpcManager.deleteStaticHeader("Authorization")}collection(e,t="internal"){return this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this.dataManager.runInTransaction(e)}executeFunction(e,...t){return(0,je.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))}executeNamedQuery(e,t,r){return(0,je.firstValueFrom)(this.namedQueryManager.executeNamedQueryAndSubscribe(e,t,r))}callApi(e,t,r={}){return(0,je.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,t,r))}graphql(e){return this.graphqlClientFactory.get(e)}destruct(){return ou(this,void 0,void 0,(function*(){return this.destructManager.destruct()}))}unsubscribe(){return ou(this,void 0,void 0,(function*(){this.querySubscriptionManager.unsubscribe(),yield this.rpcManager.awaitAllSettled()}))}}su.squidInstancesMap=new Map;class pu{metadata(){return yt.data}cleanup(){return e=this,t=void 0,n=function*(){for(const e of su.getInstances())yield e.destruct()},new((r=void 0)||(r=Promise))((function(i,a){function o(e){try{p(n.next(e))}catch(e){a(e)}}function s(e){try{p(n.throw(e))}catch(e){a(e)}}function p(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}p((n=n.apply(e,t||[])).next())}));var e,t,r,n}}const du=require("path");var uu=i(7147);class cu{constructor(e){this.region=process.env.SQUID_REGION||"local",this.secrets=e.secrets,this.backendApiKey=e.backendApiKey,this.logger=e.logger,this.context=e.context,this.codeDir=e.codeDir,this.auth=e.auth}get squid(){return su.getInstance({appId:this.context.appId,apiKey:this.backendApiKey,region:this.region})}get assetsDirectory(){const e=du.resolve(this.codeDir||"","public");if(uu.existsSync(e))return e;const t=du.resolve(process.cwd(),"src/public");return uu.existsSync(t)?t:e}getUserAuth(){var e;if("Bearer"===(null===(e=this.auth)||void 0===e?void 0:e.type))return this.auth}getApiKeyAuth(){var e;if("ApiKey"===(null===(e=this.auth)||void 0===e?void 0:e.type))return this.auth}isAuthenticated(){return!!this.auth}createWebhookResponse(e,t,r){return{body:e||"",statusCode:t||(e?200:204),headers:r||{},__isWebhookResponse__:!0}}}})();var o=exports;for(var s in a)o[s]=a[s];a.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squidcloud/backend",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Squid Cloud's backend SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/backend/src/index.d.ts",