@squidcloud/backend 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,12 @@
1
1
  import { Squid } from '@squidcloud/client';
2
- import { AuthWithApiKey, AuthWithBearer, Logger, RunContext, SecretKey, SecretValue, ServiceConfig } from '@squidcloud/common';
3
- type Stage = 'local' | 'prod';
2
+ import { AuthWithApiKey, AuthWithBearer, Logger, RunContext, SecretKey, SecretValue, ServiceConfig, SquidRegion } from '@squidcloud/common';
4
3
  export declare class SquidService {
5
4
  readonly secrets: Record<SecretKey, SecretValue>;
6
5
  readonly logger: Logger;
7
6
  private readonly backendApiKey;
8
7
  readonly context: RunContext;
9
8
  readonly codeDir: string;
10
- readonly stage: Stage;
9
+ readonly region: SquidRegion;
11
10
  private readonly auth;
12
11
  constructor(config: ServiceConfig);
13
12
  get squid(): Squid;
@@ -16,4 +15,3 @@ export declare class SquidService {
16
15
  getApiKeyAuth(): AuthWithApiKey | undefined;
17
16
  isAuthenticated(): boolean;
18
17
  }
19
- export {};
package/dist/index.js CHANGED
@@ -9,4 +9,4 @@
9
9
  ${e.query}
10
10
  `,variables:e.variables})).data}))}mutate(e){return sp(this,void 0,void 0,(function*(){return(yield this.client.mutate({mutation:rp`
11
11
  ${e.query}
12
- `})).data}))}}class dp{constructor(e){this.rpcManager=e,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new pp(this.rpcManager,e),this.clientsMap.set(e,t),t)}}var up;class cp{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_${Te(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 lp{constructor(e,t,r){this.clientId=e,this.rpcManager=t,this.socketManager=r,this.ongoingNamedQueryExecutions={},r.observeNotifications().pipe((0,Ae.filter)((e=>"namedQuery"===e.type)),(0,Ct.UI)((e=>e))).subscribe((e=>{this.handleNamedQueryResponse(e.clientRequestId,e.payload)}))}executeNamedQueryAndSubscribe(e,t,r){const n=lt(),i=new Ae.Subject;this.ongoingNamedQueryExecutions[n]=i;const a={integrationId:e,queryName:t,paramsRecordStr:we(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,Ae.finalize)((()=>{delete this.ongoingNamedQueryExecutions[n]})),(0,Ae.share)())}handleNamedQueryResponse(e,t){const r=this.ongoingNamedQueryExecutions[e];if(!r)return;const n=Se(t);n.success?r.next(n.result):(r.error(new Error(n.result)),r.complete())}}class fp{constructor(e,t,r){this.querySubscriptionManager=e,this.documentReferenceFactory=t,this.documentIdentityService=r}getForDocument(e){const{collectionName:t,integrationId:r,docId:n}=Ne(e),i=Se(n),a=this.get(t,r);return Object.entries(i).forEach((([e,t])=>{a.where(e,"==",t)})),a}get(e,t){return new hp(e,t,this.querySubscriptionManager,this.documentReferenceFactory,e,!1,this,this.documentIdentityService)}getForJoin(e,t,r){return new hp(e,t,this.querySubscriptionManager,this.documentReferenceFactory,r,!0,this,this.documentIdentityService)}}class hp{constructor(e,t,r,n,i,a,o,s){this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=r,this.documentReferenceFactory=n,this.alias=i,this.supportsJoin=a,this.queryBuilderFactory=o,this.documentIdentityService=s,this.joins={},this.joinConditions={},this.simpleQueryBuilder=new Ke(e,t)}where(e,t,r){return this.simpleQueryBuilder.where(e,t,r),this}limit(e){return this.simpleQueryBuilder.limit(e),this}sortBy(e,t=!0){return this.simpleQueryBuilder.sortBy(e),this}join(e,t,r){$e(e.supportsJoin,'When joining, the join query has to use "joinQuery" in order to provide an alias.');const n={leftFieldName:t,rightFieldName:r,leftAlias:this.alias};this.joins[e.alias]=e.build(),Object.entries(e.joins).forEach((([e,t])=>{this.joins[e]=t}));for(const[t,r]of Object.entries(e.joinConditions))this.joinConditions[t]=r;return this.joinConditions[e.alias]=n,this}snapshot(){return(0,Ae.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.querySubscriptionManager.processQuery(this.build(),this.alias||this.collectionName,xe.cloneDeep(this.joins),xe.cloneDeep(this.joinConditions),e).pipe((0,Ct.UI)((e=>e.map((e=>{const t={};for(const[r,n]of Object.entries(e)){const e=r===this.alias?this.collectionName:this.joins[r].collectionName,i=r===this.alias?this.integrationId:this.joins[r].integrationId,a=n?Te(n.__docId__,e,i):void 0;t[r]=a?this.documentReferenceFactory.create(a,this.queryBuilderFactory):void 0}return t})))),(0,Ct.UI)((e=>this.supportsJoin?e:Object.values(e).map((e=>e[this.alias])))))}changes(){let e;$e(!this.supportsJoin,"Cannot listen on changes in join mode.");let t=new Set;return this.snapshots().pipe((0,Ae.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,Ae.switchMap)((t=>(Object.entries(t).forEach((([t,r])=>{!function(e,t,r){const n=e[t];void 0!==n&&(e[r]=n,delete e[t])}(e||{},t,r)})),Ae.NEVER))),(0,Ae.startWith)({}))),(0,Ct.UI)((([r,n])=>{const i={inserts:[],deletes:[],updates:[]};if(e){for(const n of r){const r=n.squidDocId,a=n.data();if(t.has(a))delete e[r],t.delete(a);else if(e[r]){i.updates.push(n);const a=e[r];delete e[r],t.delete(a)}else i.inserts.push(n)}for(const e of t)i.deletes.push(e)}else i.inserts=r;e={},t=new Set;for(const n of r){const r=n.data();e[n.squidDocId]=r,t.add(r)}return i})))}build(){return this.simpleQueryBuilder.build()}}function mp(e){return[up.SET_PATH,up.DELETE_PATH].includes(e.type)}function vp(e){return e.type===up.BATCH_ACTION}function yp(e){const t=[];if(mp(e))t.push(e);else if(vp(e))for(const r of e.payload)t.push(...yp(r));return t}function bp(e,t){return _p(e,t)}function gp(e){return"object"==typeof e}function _p(e,t){let r=e;if(mp(t))r=function(e,t,r=[]){switch(t.type){case up.DELETE_PATH:return wp(e,t.path);case up.SET_PATH:const n=t;return function(e,t,r,n){return Sp(e,t,r,n)}(e,t.path,r,n.payload);case up.BATCH_ACTION:throw new Error("Unsupported")}}(e,t,[]);else{if(!vp(t))throw new Error(`Invalid action type: ${t.type}`);r=t.payload.reduce(((e,t)=>_p(e,t)),e)}return r}function wp(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=Ep(e,r);if(!i)return e;if(!gp(i))throw new Error("Cannot delete from a non object state.");const a=wp(i,n);return a===i?e:Op(e,r,a)}function Sp(e,t,r,n){if(!t.length){if(gp(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 Op(e,i,n);const o=t.slice(1),s=Ep(e,i);return void 0!==s&&gp(s)?Op(e,i,Sp(s,o,a,n)):Sp(e=Op(e,i,{}),t,r,n)}function Op(e,t,r){return(e=Object.assign({},e))[t]=r,e}function Ep(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"}(up||(up={}));class Np{constructor(){this.root=new Tp}getOrCreatePathTrieNode(e,t){let r=this.root;for(const t of e)r.children.get(t)||r.children.set(t,new Tp),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 Np;return e.root=t,e}}iterateBfs(e){this.iterateInternal(this.root,e,[])}removeNode(e){e.length||(this.root=new Tp);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 Tp{constructor(){this.children=new Map([])}}class xp{constructor(){this.subscriptionsTree=new Np,this.state={},this.batchCount=0,this.batchedActions=[]}dispatch(e){this.batchCount>0&&this.batchedActions.push(e),this.state=bp(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:up.BATCH_ACTION,payload:[...this.batchedActions]};this.batchedActions.splice(0),this.dispatch(e)}}}observePath(e,t){return new Ae.Observable((r=>{const n=this.getOrCreateSubjectForPath(e);r.next(this.getStateInPath(e));const i=n.pipe((0,Ct.hX)((e=>{if(!t)return!0;const r=new Np,n=t();for(const e of n)r.getOrCreatePathTrieNode(e,!0);const i=yp(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,Ct.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:up.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:up.DELETE_PATH,path:e};this.dispatch(t)}getState(){return this.state}getStateInPath(e){return kp(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 Pp);const r=t.nodeData;return r.subject||(r.subject=new Ae.Subject),r.subject}dispatchSubscriptions(e){const t=function(e,t){const r=new Np;for(const n of yp(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 Tp),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:kp(this.getState(),r)})}))}}function kp(e,t){let r=e;for(const e of t){if(null==r)return;if(!gp(r))throw new Error("result must be a state object");r=r[e]}return r}class Pp{}var Dp=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 Ip="client";class jp{constructor(e,t,r,n,i){this.rpcManager=e,this.clientId=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.safeToSendQueriesToServer=new Ae.BehaviorSubject(!0),this.onOrphanDocuments=new Ae.Subject,this.ongoingQueries=new Map,this.inflightQueriesCount=new Ae.BehaviorSubject(0),this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Ap,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.destructManager.onPreDestruct((()=>{this.predestruct()}))}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return Fe(this.ongoingQueries.get(e)).query}setGotResponseFromServer(e){Fe(this.ongoingQueries.get(e)).gotResponseFromServer=!0}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=Ne(t),i=this.queryMappingManager.getMapping(Ip,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=Fe(null==o?void 0:o.supportingOngoingQuery);a&&t.add(o),e.subject.next(i)}for(const e of t){const t=this.collectAllObservables(e);Fe(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 Ae.ReplaySubject(1);const o=a.allObservables.pipe((0,Ae.switchMap)((e=>(0,Ae.combineLatest)(e).pipe((0,Ct.UI)((e=>this.joinResults(e,n,a)))))),(0,Ct.hX)((()=>this.allOngoingQueriesGotServerResult(a))),(0,Ae.startWith)(void 0),(0,Ae.pairwise)(),(0,Ct.hX)((([e,t])=>!xe.isEqual(e,t))),(0,Ct.UI)((([e,t])=>t)),i?(0,Ae.tap)():(0,Ae.take)(1),(0,Ae.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=Fe(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 Dp(this,void 0,void 0,(function*(){return(0,Ae.firstValueFrom)(this.inflightQueriesCount.pipe((0,Ct.hX)((e=>0===e)))).then((()=>{}))}))}registerQueryFinalizer(e){const t=e.clientRequestId,r=rt(this.clientId,t);e.subject.pipe((0,Ae.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=lt(),p=[],d={clientRequestId:s,activated:a,alias:t,query:e,subscribe:i,subject:new Ae.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,Ct.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,[]),Fe(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=Fe(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=Fe(t.joinCondition),i=t.query;if(t.activated){const a=Fe(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=xe.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 Ae.ReplaySubject(1),clientRequestId:lt(),isEmptyForJoin:!1});return this.registerQueryFinalizer(p),this.ongoingQueries.set(p.clientRequestId,p),Fe(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=Fe(t.shift());t.push(...e.supportedQueries||[]),e.subject.complete()}}predestruct(){var e;this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete();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(Ip,t,i).then(),this.ongoingQueries.set(r,e),this.safeToSendQueriesToServer.pipe((0,Ct.hX)(Boolean),(0,Ae.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 Ap extends Xe{constructor(){super(...arguments),this.stateService=new xp,this.querySubscriptionIdToQuery={}}addQuery(e,t,r){return Dp(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=Oe(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 Dp(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=Oe(t.fieldName),n=Oe(t.value);return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",`${r}`,`${t.operator}`,`${n}`]}}var Cp=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 Rp{constructor(e,t,r,n){this.rpcEndpoint=e,this.socketManager=t,this.staticHeaders={},this.onGoingRpcsCounter=new Ae.BehaviorSubject(0),$e(e,"Http endpoint must be provided."),n&&this.setStaticHeader("Authorization",`ApiKey ${n}`),this.rpcEndpoint.endsWith("/")||(this.rpcEndpoint+="/"),r.onDestruct((()=>Cp(this,void 0,void 0,(function*(){yield(0,Ae.firstValueFrom)(this.onGoingRpcsCounter.pipe((0,Ae.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 Cp(this,void 0,void 0,(function*(){yield(0,Ae.firstValueFrom)(this.socketManager.observeConnectionReady().pipe((0,Ae.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 fetch(`${this.rpcEndpoint}${e}`,{method:"POST",body:we(t),headers:r});let i;try{i=yield n.text()}catch(e){i="Cannot read body"}if(!n.ok)throw new Mp(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 Mp 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 $p=Object.create(null);$p.open="0",$p.close="1",$p.ping="2",$p.pong="3",$p.message="4",$p.upgrade="5",$p.noop="6";const Fp=Object.create(null);Object.keys($p).forEach((e=>{Fp[$p[e]]=e}));const Vp={type:"error",data:"parser error"},Lp=({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($p[e]+(t||""))},qp=(e,t)=>{const r=Buffer.isBuffer(e);return"arraybuffer"===t&&r?Bp(e):e},Bp=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},Up=(e,t)=>{if("string"!=typeof e)return{type:"message",data:qp(e,t)};const r=e.charAt(0);if("b"===r){const r=Buffer.from(e.substring(1),"base64");return{type:"message",data:qp(r,t)}}return Fp[r]?e.length>1?{type:Fp[r],data:e.substring(1)}:{type:Fp[r]}:Vp},zp=String.fromCharCode(30);function Qp(e){if(e)return function(e){for(var t in Qp.prototype)e[t]=Qp.prototype[t];return e}(e)}Qp.prototype.on=Qp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Qp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Qp.prototype.off=Qp.prototype.removeListener=Qp.prototype.removeAllListeners=Qp.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},Qp.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},Qp.prototype.emitReserved=Qp.prototype.emit,Qp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Qp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Wp=global;function Hp(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Gp=Wp.setTimeout,Kp=Wp.clearTimeout;function Jp(e,t){t.useNativeTimers?(e.setTimeoutFn=Gp.bind(Wp),e.clearTimeoutFn=Kp.bind(Wp)):(e.setTimeoutFn=Wp.setTimeout.bind(Wp),e.clearTimeoutFn=Wp.clearTimeout.bind(Wp))}var Yp=i(1314);const Zp=Yp("engine.io-client:transport");class Xp extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class ed extends Qp{constructor(e){super(),this.writable=!1,Jp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Xp(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):Zp("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Up(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 td="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),rd={};let nd,id=0,ad=0;function od(e){let t="";do{t=td[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function sd(){const e=od(+new Date);return e!==nd?(id=0,nd=e):e+"."+od(id++)}for(;ad<64;ad++)rd[td[ad]]=ad;function pd(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}var dd=i(4934);const ud=dd||i.t(dd,2),cd=Yp("engine.io-client:polling");function ld(){}const fd=null!=new ud({xdomain:!1}).responseType;class hd extends Qp{constructor(e,t){super(),Jp(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=Hp(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 ud(e);try{cd("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))},cd("xhr data %s",this.data),t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=hd.requestsCount++,hd.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=ld,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete hd.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 md(){for(let e in hd.requests)hd.requests.hasOwnProperty(e)&&hd.requests[e].abort()}hd.requestsCount=0,hd.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",md):"function"==typeof addEventListener&&addEventListener("onpagehide"in Wp?"pagehide":"unload",md,!1)),i(4291),i(1938),i(7204);var vd=i(4965);i(6574);const yd=vd,bd=process.nextTick,gd=Yp("engine.io-client:websocket"),_d="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),wd={websocket:class extends ed{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=_d?{}:Hp(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 yd(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;Lp(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){gd("websocket closed before onclose event")}n&&bd((()=>{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]=sd()),this.supportsBinary||(e.b64=1);const n=pd(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}check(){return!!yd}},polling:class extends ed{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=fd&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{cd("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(cd("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){cd("pre-pause polling complete"),--e||t()}))),this.writable||(cd("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){cd("pre-pause writing complete"),--e||t()})))}else t()}poll(){cd("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){cd("polling got data %s",e),((e,t)=>{const r=e.split(zp),n=[];for(let e=0;e<r.length;e++){const i=Up(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():cd('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{cd("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(cd("transport open - closing"),e()):(cd("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)=>{Lp(e,!1,(e=>{n[a]=e,++i===r&&t(n.join(zp))}))}))})(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]=sd()),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=pd(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 hd(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(){cd("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}}},Sd=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Od=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ed(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=Sd.exec(e||""),a={},o=14;for(;o--;)a[Od[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 Nd=Yp("engine.io-client:socket");class Td extends Qp{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Ed(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=Ed(t.host).host),Jp(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){Nd('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 Nd("options: %j",r),new wd[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Td.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 Nd("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){Nd("setting transport %s",e.name),this.transport&&(Nd("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){Nd('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Td.priorWebsocketSuccess=!1;const n=()=>{r||(Nd('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(Nd('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Td.priorWebsocketSuccess="websocket"===t.name,Nd('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{r||"closed"!==this.readyState&&(Nd("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{Nd('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(),Nd('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&&(Nd('"%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(Nd("socket open"),this.readyState="open",Td.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){Nd("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(Nd('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 Nd('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();Nd("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 Nd("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);e+=2}var t;return Nd("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"),Nd("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){Nd("socket error %j",e),Td.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(Nd('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}}Td.protocol=4,Td.protocol;const xd=Yp("socket.io-client:url"),kd="function"==typeof ArrayBuffer,Pd=Object.prototype.toString,Dd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Pd.call(Blob),Id="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Pd.call(File);function jd(e){return kd&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Dd&&e instanceof Blob||Id&&e instanceof File}function Ad(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ad(e[t]))return!0;return!1}if(jd(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ad(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ad(e[t]))return!0;return!1}function Cd(e){const t=[],r=e.data,n=e;return n.data=Rd(r,t),n.attachments=t.length,{packet:n,buffers:t}}function Rd(e,t){if(!e)return e;if(jd(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]=Rd(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]=Rd(e[n],t));return r}return e}function Md(e,t){return e.data=$d(e.data,t),delete e.attachments,e}function $d(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]=$d(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=$d(e[r],t));return e}const Fd=Yp("socket.io-parser"),Vd=5;var Ld;!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"}(Ld||(Ld={}));class qd{constructor(e){this.replacer=e}encode(e){return Fd("encoding packet %j",e),e.type!==Ld.EVENT&&e.type!==Ld.ACK||!Ad(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ld.EVENT?Ld.BINARY_EVENT:Ld.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ld.BINARY_EVENT&&e.type!==Ld.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)),Fd("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=Cd(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}class Bd extends Qp{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===Ld.BINARY_EVENT;r||t.type===Ld.BINARY_ACK?(t.type=r?Ld.EVENT:Ld.ACK,this.reconstructor=new Ud(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!jd(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===Ld[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Ld.BINARY_EVENT||r.type===Ld.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(!Bd.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return Fd("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 Ld.CONNECT:return"object"==typeof t;case Ld.DISCONNECT:return void 0===t;case Ld.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Ld.EVENT:case Ld.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Ld.ACK:case Ld.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ud{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=Md(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function zd(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Qd=Yp("socket.io-client:socket"),Wd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Hd extends Qp{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=[zd(e,"open",this.onopen.bind(this)),zd(e,"packet",this.onpacket.bind(this)),zd(e,"error",this.onerror.bind(this)),zd(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(Wd.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:Ld.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;Qd("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):Qd("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&&(Qd("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));Qd("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&&(Qd("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(e)):(Qd("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(Qd("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,Qd("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):Qd("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(){Qd("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ld.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){Qd("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 Ld.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 Ld.EVENT:case Ld.BINARY_EVENT:this.onevent(e);break;case Ld.ACK:case Ld.BINARY_ACK:this.onack(e);break;case Ld.DISCONNECT:this.ondisconnect();break;case Ld.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||[];Qd("emitting event %j",t),null!=e.id&&(Qd("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,Qd("sending ack %j",n),t.packet({type:Ld.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(Qd("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):Qd("bad ack %s",e.id)}onconnect(e,t){Qd("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(){Qd("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&&(Qd("performing disconnect (%s)",this.nsp),this.packet({type:Ld.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 Gd(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}Gd.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)},Gd.prototype.reset=function(){this.attempts=0},Gd.prototype.setMin=function(e){this.ms=e},Gd.prototype.setMax=function(e){this.max=e},Gd.prototype.setJitter=function(e){this.jitter=e};const Kd=Yp("socket.io-client:manager");class Jd extends Qp{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,Jp(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 Gd({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(Kd("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Kd("opening %s",this.uri),this.engine=new Td(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=zd(t,"open",(function(){r.onopen(),e&&e()})),i=zd(t,"error",(t=>{Kd("error"),r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;Kd("connect attempt will timeout after %d",e),0===e&&n();const r=this.setTimeoutFn((()=>{Kd("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(){Kd("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(zd(e,"ping",this.onping.bind(this)),zd(e,"data",this.ondata.bind(this)),zd(e,"error",this.onerror.bind(this)),zd(e,"close",this.onclose.bind(this)),zd(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){bd((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){Kd("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new Hd(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 Kd("socket %s is still active, skipping close",e);this._close()}_packet(e){Kd("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(){Kd("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){Kd("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){Kd("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)Kd("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Kd("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(Kd("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(Kd("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(Kd("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 Yd=Yp("socket.io-client"),Zd={};function Xd(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)||(xd("protocol-less url %s",e),e=void 0!==r?r.protocol+"//"+e:"https://"+e),xd("parse %s",e),n=Ed(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=Zd[i]&&a in Zd[i].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?(Yd("ignoring socket cache for %s",n),s=new Jd(n,t)):(Zd[i]||(Yd("new io instance for %s",n),Zd[i]=new Jd(n,t)),s=Zd[i]),r.query&&!t.query&&(t.query=r.queryKey),s.socket(r.path,t)}Object.assign(Xd,{Manager:Jd,Socket:Hd,io:Xd,connect:Xd});const eu=e=>e();var tu=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 ru{constructor(e,t,r=eu,n){this.clientId=e,this.socketIoEndpoint=t,this.messageNotificationWrapper=r,this.destructManager=n,this.webSocketObserver=new Ae.Subject,this.allMessagesObserver=new Ae.Subject,this.connectionReady=new Ae.BehaviorSubject(!1),this.seenMessageIds=new Set,this.firstConnection=!0,this.destructManager.onDestruct((()=>tu(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,Ae.distinctUntilChanged)())}sendMessage(e){(0,Ae.firstValueFrom)(this.connectionReady.pipe((0,Ae.filter)(Boolean))).then((()=>{Fe(this.socket).emit("message",e)}))}connect(){this.socket=Xd(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=Se(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 Ae.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,Ae.tap)((e=>t.push(e))),(0,Ae.debounceTime)(100)).subscribe((()=>tu(this,void 0,void 0,(function*(){const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))))}destruct(){var e;return tu(this,void 0,void 0,(function*(){this.sendMessage({type:"kill"}),this.connectionReady.next(!1),yield(0,Ae.firstValueFrom)((0,Ae.timer)(0)),null===(e=this.socket)||void 0===e||e.disconnect(),this.webSocketObserver.complete(),this.allMessagesObserver.complete()}))}}class nu{constructor(e){this.destructManager=new Bt,$e(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}`,e===Ye.LOCAL&&(r.protocol="http",r.port="8000");const n=r.toString();return n.endsWith("/")?n:n+"/"}(e.region,e.appId);this.clientId=lt(),this.socketManager=new ru(this.clientId,t,e.messageNotificationWrapper,this.destructManager),this.rpcManager=new Rp(t,this.socketManager,this.destructManager,e.apiKey),this.documentStore=new Qt,this.lockManager=new ft,this.documentIdentityService=new Ut(this.documentStore,this.destructManager),this.documentReferenceFactory=new zt,this.querySubscriptionManager=new jp(this.rpcManager,this.clientId,this.documentStore,this.destructManager,this.documentIdentityService);const r=new cp(this.clientId,this.rpcManager,this.lockManager,this.querySubscriptionManager);this.queryBuilderFactory=new fp(this.querySubscriptionManager,this.documentReferenceFactory,this.documentIdentityService),this.collectionReferenceFactory=new $t(this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService),this.dataManager=new qt(this.documentStore,r,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new Mt(this.clientId,this.rpcManager,this.socketManager),this.namedQueryManager=new lp(this.clientId,this.rpcManager,this.socketManager),this.apiManager=new Rt(this.clientId,this.rpcManager,this.socketManager,e.apiServerUrlOverrideMapping),this.graphqlClientFactory=new dp(this.rpcManager)}static getInstance(e){const t=_e(e);let r=nu.squidInstancesMap.get(t);return r||(r=new nu(e),nu.squidInstancesMap.set(t,r),r)}static getInstances(){return Array.from(nu.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,Ae.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))}executeNamedQuery(e,t,r){return(0,Ae.firstValueFrom)(this.namedQueryManager.executeNamedQueryAndSubscribe(e,t,r))}callApi(e,t,r={}){return(0,Ae.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,t,r))}graphql(e){return this.graphqlClientFactory.get(e)}destruct(){return e=this,t=void 0,n=function*(){return this.destructManager.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}}nu.squidInstancesMap=new Map;class iu{metadata(){return vt.data}cleanup(){return e=this,t=void 0,n=function*(){for(const e of nu.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 au=require("path");var ou=i(7147);class su{constructor(e){this.stage=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(){const e=process.env.SQUID_REGION;return nu.getInstance({appId:this.context.appId,apiKey:this.backendApiKey,region:e})}get assetsDirectory(){const e=au.resolve(this.codeDir||"","public");if(ou.existsSync(e))return e;const t=au.resolve(process.cwd(),"src/public");return ou.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}}})();var o=exports;for(var s in a)o[s]=a[s];a.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
12
+ `})).data}))}}class dp{constructor(e){this.rpcManager=e,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new pp(this.rpcManager,e),this.clientsMap.set(e,t),t)}}var up;class cp{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_${Te(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 lp{constructor(e,t,r){this.clientId=e,this.rpcManager=t,this.socketManager=r,this.ongoingNamedQueryExecutions={},r.observeNotifications().pipe((0,Ae.filter)((e=>"namedQuery"===e.type)),(0,Ct.UI)((e=>e))).subscribe((e=>{this.handleNamedQueryResponse(e.clientRequestId,e.payload)}))}executeNamedQueryAndSubscribe(e,t,r){const n=lt(),i=new Ae.Subject;this.ongoingNamedQueryExecutions[n]=i;const a={integrationId:e,queryName:t,paramsRecordStr:we(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,Ae.finalize)((()=>{delete this.ongoingNamedQueryExecutions[n]})),(0,Ae.share)())}handleNamedQueryResponse(e,t){const r=this.ongoingNamedQueryExecutions[e];if(!r)return;const n=Se(t);n.success?r.next(n.result):(r.error(new Error(n.result)),r.complete())}}class fp{constructor(e,t,r){this.querySubscriptionManager=e,this.documentReferenceFactory=t,this.documentIdentityService=r}getForDocument(e){const{collectionName:t,integrationId:r,docId:n}=Ne(e),i=Se(n),a=this.get(t,r);return Object.entries(i).forEach((([e,t])=>{a.where(e,"==",t)})),a}get(e,t){return new hp(e,t,this.querySubscriptionManager,this.documentReferenceFactory,e,!1,this,this.documentIdentityService)}getForJoin(e,t,r){return new hp(e,t,this.querySubscriptionManager,this.documentReferenceFactory,r,!0,this,this.documentIdentityService)}}class hp{constructor(e,t,r,n,i,a,o,s){this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=r,this.documentReferenceFactory=n,this.alias=i,this.supportsJoin=a,this.queryBuilderFactory=o,this.documentIdentityService=s,this.joins={},this.joinConditions={},this.simpleQueryBuilder=new Ke(e,t)}where(e,t,r){return this.simpleQueryBuilder.where(e,t,r),this}limit(e){return this.simpleQueryBuilder.limit(e),this}sortBy(e,t=!0){return this.simpleQueryBuilder.sortBy(e,t),this}join(e,t,r){$e(e.supportsJoin,'When joining, the join query has to use "joinQuery" in order to provide an alias.');const n={leftFieldName:t,rightFieldName:r,leftAlias:this.alias};this.joins[e.alias]=e.build(),Object.entries(e.joins).forEach((([e,t])=>{this.joins[e]=t}));for(const[t,r]of Object.entries(e.joinConditions))this.joinConditions[t]=r;return this.joinConditions[e.alias]=n,this}snapshot(){return(0,Ae.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.querySubscriptionManager.processQuery(this.build(),this.alias||this.collectionName,xe.cloneDeep(this.joins),xe.cloneDeep(this.joinConditions),e).pipe((0,Ct.UI)((e=>e.map((e=>{const t={};for(const[r,n]of Object.entries(e)){const e=r===this.alias?this.collectionName:this.joins[r].collectionName,i=r===this.alias?this.integrationId:this.joins[r].integrationId,a=n?Te(n.__docId__,e,i):void 0;t[r]=a?this.documentReferenceFactory.create(a,this.queryBuilderFactory):void 0}return t})))),(0,Ct.UI)((e=>this.supportsJoin?e:Object.values(e).map((e=>e[this.alias])))))}changes(){let e;$e(!this.supportsJoin,"Cannot listen on changes in join mode.");let t=new Set;return this.snapshots().pipe((0,Ae.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,Ae.switchMap)((t=>(Object.entries(t).forEach((([t,r])=>{!function(e,t,r){const n=e[t];void 0!==n&&(e[r]=n,delete e[t])}(e||{},t,r)})),Ae.NEVER))),(0,Ae.startWith)({}))),(0,Ct.UI)((([r,n])=>{const i={inserts:[],deletes:[],updates:[]};if(e){for(const n of r){const r=n.squidDocId,a=n.data();if(t.has(a))delete e[r],t.delete(a);else if(e[r]){i.updates.push(n);const a=e[r];delete e[r],t.delete(a)}else i.inserts.push(n)}for(const e of t)i.deletes.push(e)}else i.inserts=r;e={},t=new Set;for(const n of r){const r=n.data();e[n.squidDocId]=r,t.add(r)}return i})))}build(){return this.simpleQueryBuilder.build()}}function mp(e){return[up.SET_PATH,up.DELETE_PATH].includes(e.type)}function vp(e){return e.type===up.BATCH_ACTION}function yp(e){const t=[];if(mp(e))t.push(e);else if(vp(e))for(const r of e.payload)t.push(...yp(r));return t}function bp(e,t){return _p(e,t)}function gp(e){return"object"==typeof e}function _p(e,t){let r=e;if(mp(t))r=function(e,t,r=[]){switch(t.type){case up.DELETE_PATH:return wp(e,t.path);case up.SET_PATH:const n=t;return function(e,t,r,n){return Sp(e,t,r,n)}(e,t.path,r,n.payload);case up.BATCH_ACTION:throw new Error("Unsupported")}}(e,t,[]);else{if(!vp(t))throw new Error(`Invalid action type: ${t.type}`);r=t.payload.reduce(((e,t)=>_p(e,t)),e)}return r}function wp(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=Ep(e,r);if(!i)return e;if(!gp(i))throw new Error("Cannot delete from a non object state.");const a=wp(i,n);return a===i?e:Op(e,r,a)}function Sp(e,t,r,n){if(!t.length){if(gp(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 Op(e,i,n);const o=t.slice(1),s=Ep(e,i);return void 0!==s&&gp(s)?Op(e,i,Sp(s,o,a,n)):Sp(e=Op(e,i,{}),t,r,n)}function Op(e,t,r){return(e=Object.assign({},e))[t]=r,e}function Ep(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"}(up||(up={}));class Np{constructor(){this.root=new Tp}getOrCreatePathTrieNode(e,t){let r=this.root;for(const t of e)r.children.get(t)||r.children.set(t,new Tp),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 Np;return e.root=t,e}}iterateBfs(e){this.iterateInternal(this.root,e,[])}removeNode(e){e.length||(this.root=new Tp);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 Tp{constructor(){this.children=new Map([])}}class xp{constructor(){this.subscriptionsTree=new Np,this.state={},this.batchCount=0,this.batchedActions=[]}dispatch(e){this.batchCount>0&&this.batchedActions.push(e),this.state=bp(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:up.BATCH_ACTION,payload:[...this.batchedActions]};this.batchedActions.splice(0),this.dispatch(e)}}}observePath(e,t){return new Ae.Observable((r=>{const n=this.getOrCreateSubjectForPath(e);r.next(this.getStateInPath(e));const i=n.pipe((0,Ct.hX)((e=>{if(!t)return!0;const r=new Np,n=t();for(const e of n)r.getOrCreatePathTrieNode(e,!0);const i=yp(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,Ct.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:up.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:up.DELETE_PATH,path:e};this.dispatch(t)}getState(){return this.state}getStateInPath(e){return kp(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 Pp);const r=t.nodeData;return r.subject||(r.subject=new Ae.Subject),r.subject}dispatchSubscriptions(e){const t=function(e,t){const r=new Np;for(const n of yp(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 Tp),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:kp(this.getState(),r)})}))}}function kp(e,t){let r=e;for(const e of t){if(null==r)return;if(!gp(r))throw new Error("result must be a state object");r=r[e]}return r}class Pp{}var Dp=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 Ip="client";class jp{constructor(e,t,r,n,i){this.rpcManager=e,this.clientId=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.safeToSendQueriesToServer=new Ae.BehaviorSubject(!0),this.onOrphanDocuments=new Ae.Subject,this.ongoingQueries=new Map,this.inflightQueriesCount=new Ae.BehaviorSubject(0),this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Ap,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.destructManager.onPreDestruct((()=>{this.predestruct()}))}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return Fe(this.ongoingQueries.get(e)).query}setGotResponseFromServer(e){Fe(this.ongoingQueries.get(e)).gotResponseFromServer=!0}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=Ne(t),i=this.queryMappingManager.getMapping(Ip,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=Fe(null==o?void 0:o.supportingOngoingQuery);a&&t.add(o),e.subject.next(i)}for(const e of t){const t=this.collectAllObservables(e);Fe(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 Ae.ReplaySubject(1);const o=a.allObservables.pipe((0,Ae.switchMap)((e=>(0,Ae.combineLatest)(e).pipe((0,Ct.UI)((e=>this.joinResults(e,n,a)))))),(0,Ct.hX)((()=>this.allOngoingQueriesGotServerResult(a))),(0,Ae.startWith)(void 0),(0,Ae.pairwise)(),(0,Ct.hX)((([e,t])=>!xe.isEqual(e,t))),(0,Ct.UI)((([e,t])=>t)),i?(0,Ae.tap)():(0,Ae.take)(1),(0,Ae.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=Fe(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 Dp(this,void 0,void 0,(function*(){return(0,Ae.firstValueFrom)(this.inflightQueriesCount.pipe((0,Ct.hX)((e=>0===e)))).then((()=>{}))}))}registerQueryFinalizer(e){const t=e.clientRequestId,r=rt(this.clientId,t);e.subject.pipe((0,Ae.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=lt(),p=[],d={clientRequestId:s,activated:a,alias:t,query:e,subscribe:i,subject:new Ae.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,Ct.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,[]),Fe(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=Fe(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=Fe(t.joinCondition),i=t.query;if(t.activated){const a=Fe(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=xe.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 Ae.ReplaySubject(1),clientRequestId:lt(),isEmptyForJoin:!1});return this.registerQueryFinalizer(p),this.ongoingQueries.set(p.clientRequestId,p),Fe(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=Fe(t.shift());t.push(...e.supportedQueries||[]),e.subject.complete()}}predestruct(){var e;this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete();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(Ip,t,i).then(),this.ongoingQueries.set(r,e),this.safeToSendQueriesToServer.pipe((0,Ct.hX)(Boolean),(0,Ae.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 Ap extends Xe{constructor(){super(...arguments),this.stateService=new xp,this.querySubscriptionIdToQuery={}}addQuery(e,t,r){return Dp(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=Oe(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 Dp(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=Oe(t.fieldName),n=Oe(t.value);return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",`${r}`,`${t.operator}`,`${n}`]}}var Cp=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 Rp{constructor(e,t,r,n){this.rpcEndpoint=e,this.socketManager=t,this.staticHeaders={},this.onGoingRpcsCounter=new Ae.BehaviorSubject(0),$e(e,"Http endpoint must be provided."),n&&this.setStaticHeader("Authorization",`ApiKey ${n}`),this.rpcEndpoint.endsWith("/")||(this.rpcEndpoint+="/"),r.onDestruct((()=>Cp(this,void 0,void 0,(function*(){yield(0,Ae.firstValueFrom)(this.onGoingRpcsCounter.pipe((0,Ae.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 Cp(this,void 0,void 0,(function*(){yield(0,Ae.firstValueFrom)(this.socketManager.observeConnectionReady().pipe((0,Ae.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 op()(`${this.rpcEndpoint}${e}`,{method:"POST",body:we(t),headers:r});let i;try{i=yield n.text()}catch(e){i="Cannot read body"}if(!n.ok)throw new Mp(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 Mp 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 $p=Object.create(null);$p.open="0",$p.close="1",$p.ping="2",$p.pong="3",$p.message="4",$p.upgrade="5",$p.noop="6";const Fp=Object.create(null);Object.keys($p).forEach((e=>{Fp[$p[e]]=e}));const Vp={type:"error",data:"parser error"},Lp=({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($p[e]+(t||""))},qp=(e,t)=>{const r=Buffer.isBuffer(e);return"arraybuffer"===t&&r?Bp(e):e},Bp=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},Up=(e,t)=>{if("string"!=typeof e)return{type:"message",data:qp(e,t)};const r=e.charAt(0);if("b"===r){const r=Buffer.from(e.substring(1),"base64");return{type:"message",data:qp(r,t)}}return Fp[r]?e.length>1?{type:Fp[r],data:e.substring(1)}:{type:Fp[r]}:Vp},zp=String.fromCharCode(30);function Qp(e){if(e)return function(e){for(var t in Qp.prototype)e[t]=Qp.prototype[t];return e}(e)}Qp.prototype.on=Qp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Qp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Qp.prototype.off=Qp.prototype.removeListener=Qp.prototype.removeAllListeners=Qp.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},Qp.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},Qp.prototype.emitReserved=Qp.prototype.emit,Qp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Qp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Wp=global;function Hp(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Gp=Wp.setTimeout,Kp=Wp.clearTimeout;function Jp(e,t){t.useNativeTimers?(e.setTimeoutFn=Gp.bind(Wp),e.clearTimeoutFn=Kp.bind(Wp)):(e.setTimeoutFn=Wp.setTimeout.bind(Wp),e.clearTimeoutFn=Wp.clearTimeout.bind(Wp))}var Yp=i(1314);const Zp=Yp("engine.io-client:transport");class Xp extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class ed extends Qp{constructor(e){super(),this.writable=!1,Jp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Xp(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):Zp("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Up(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 td="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),rd={};let nd,id=0,ad=0;function od(e){let t="";do{t=td[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function sd(){const e=od(+new Date);return e!==nd?(id=0,nd=e):e+"."+od(id++)}for(;ad<64;ad++)rd[td[ad]]=ad;function pd(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}var dd=i(4934);const ud=dd||i.t(dd,2),cd=Yp("engine.io-client:polling");function ld(){}const fd=null!=new ud({xdomain:!1}).responseType;class hd extends Qp{constructor(e,t){super(),Jp(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=Hp(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 ud(e);try{cd("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))},cd("xhr data %s",this.data),t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=hd.requestsCount++,hd.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=ld,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete hd.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 md(){for(let e in hd.requests)hd.requests.hasOwnProperty(e)&&hd.requests[e].abort()}hd.requestsCount=0,hd.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",md):"function"==typeof addEventListener&&addEventListener("onpagehide"in Wp?"pagehide":"unload",md,!1)),i(4291),i(1938),i(7204);var vd=i(4965);i(6574);const yd=vd,bd=process.nextTick,gd=Yp("engine.io-client:websocket"),_d="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),wd={websocket:class extends ed{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=_d?{}:Hp(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 yd(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;Lp(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){gd("websocket closed before onclose event")}n&&bd((()=>{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]=sd()),this.supportsBinary||(e.b64=1);const n=pd(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}check(){return!!yd}},polling:class extends ed{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=fd&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{cd("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(cd("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){cd("pre-pause polling complete"),--e||t()}))),this.writable||(cd("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){cd("pre-pause writing complete"),--e||t()})))}else t()}poll(){cd("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){cd("polling got data %s",e),((e,t)=>{const r=e.split(zp),n=[];for(let e=0;e<r.length;e++){const i=Up(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():cd('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{cd("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(cd("transport open - closing"),e()):(cd("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)=>{Lp(e,!1,(e=>{n[a]=e,++i===r&&t(n.join(zp))}))}))})(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]=sd()),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=pd(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 hd(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(){cd("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}}},Sd=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Od=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ed(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=Sd.exec(e||""),a={},o=14;for(;o--;)a[Od[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 Nd=Yp("engine.io-client:socket");class Td extends Qp{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Ed(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=Ed(t.host).host),Jp(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){Nd('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 Nd("options: %j",r),new wd[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Td.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 Nd("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){Nd("setting transport %s",e.name),this.transport&&(Nd("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){Nd('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Td.priorWebsocketSuccess=!1;const n=()=>{r||(Nd('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(Nd('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Td.priorWebsocketSuccess="websocket"===t.name,Nd('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{r||"closed"!==this.readyState&&(Nd("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{Nd('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(),Nd('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&&(Nd('"%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(Nd("socket open"),this.readyState="open",Td.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){Nd("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(Nd('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 Nd('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();Nd("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 Nd("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);e+=2}var t;return Nd("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"),Nd("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){Nd("socket error %j",e),Td.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(Nd('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}}Td.protocol=4,Td.protocol;const xd=Yp("socket.io-client:url"),kd="function"==typeof ArrayBuffer,Pd=Object.prototype.toString,Dd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Pd.call(Blob),Id="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Pd.call(File);function jd(e){return kd&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Dd&&e instanceof Blob||Id&&e instanceof File}function Ad(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ad(e[t]))return!0;return!1}if(jd(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ad(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ad(e[t]))return!0;return!1}function Cd(e){const t=[],r=e.data,n=e;return n.data=Rd(r,t),n.attachments=t.length,{packet:n,buffers:t}}function Rd(e,t){if(!e)return e;if(jd(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]=Rd(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]=Rd(e[n],t));return r}return e}function Md(e,t){return e.data=$d(e.data,t),delete e.attachments,e}function $d(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]=$d(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=$d(e[r],t));return e}const Fd=Yp("socket.io-parser"),Vd=5;var Ld;!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"}(Ld||(Ld={}));class qd{constructor(e){this.replacer=e}encode(e){return Fd("encoding packet %j",e),e.type!==Ld.EVENT&&e.type!==Ld.ACK||!Ad(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ld.EVENT?Ld.BINARY_EVENT:Ld.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ld.BINARY_EVENT&&e.type!==Ld.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)),Fd("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=Cd(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}class Bd extends Qp{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===Ld.BINARY_EVENT;r||t.type===Ld.BINARY_ACK?(t.type=r?Ld.EVENT:Ld.ACK,this.reconstructor=new Ud(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!jd(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===Ld[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Ld.BINARY_EVENT||r.type===Ld.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(!Bd.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return Fd("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 Ld.CONNECT:return"object"==typeof t;case Ld.DISCONNECT:return void 0===t;case Ld.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Ld.EVENT:case Ld.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Ld.ACK:case Ld.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ud{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=Md(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function zd(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Qd=Yp("socket.io-client:socket"),Wd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Hd extends Qp{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=[zd(e,"open",this.onopen.bind(this)),zd(e,"packet",this.onpacket.bind(this)),zd(e,"error",this.onerror.bind(this)),zd(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(Wd.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:Ld.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;Qd("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):Qd("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&&(Qd("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));Qd("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&&(Qd("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(e)):(Qd("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(Qd("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,Qd("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):Qd("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(){Qd("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ld.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){Qd("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 Ld.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 Ld.EVENT:case Ld.BINARY_EVENT:this.onevent(e);break;case Ld.ACK:case Ld.BINARY_ACK:this.onack(e);break;case Ld.DISCONNECT:this.ondisconnect();break;case Ld.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||[];Qd("emitting event %j",t),null!=e.id&&(Qd("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,Qd("sending ack %j",n),t.packet({type:Ld.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(Qd("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):Qd("bad ack %s",e.id)}onconnect(e,t){Qd("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(){Qd("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&&(Qd("performing disconnect (%s)",this.nsp),this.packet({type:Ld.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 Gd(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}Gd.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)},Gd.prototype.reset=function(){this.attempts=0},Gd.prototype.setMin=function(e){this.ms=e},Gd.prototype.setMax=function(e){this.max=e},Gd.prototype.setJitter=function(e){this.jitter=e};const Kd=Yp("socket.io-client:manager");class Jd extends Qp{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,Jp(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 Gd({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(Kd("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Kd("opening %s",this.uri),this.engine=new Td(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=zd(t,"open",(function(){r.onopen(),e&&e()})),i=zd(t,"error",(t=>{Kd("error"),r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;Kd("connect attempt will timeout after %d",e),0===e&&n();const r=this.setTimeoutFn((()=>{Kd("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(){Kd("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(zd(e,"ping",this.onping.bind(this)),zd(e,"data",this.ondata.bind(this)),zd(e,"error",this.onerror.bind(this)),zd(e,"close",this.onclose.bind(this)),zd(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){bd((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){Kd("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new Hd(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 Kd("socket %s is still active, skipping close",e);this._close()}_packet(e){Kd("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(){Kd("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){Kd("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){Kd("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)Kd("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Kd("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(Kd("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(Kd("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(Kd("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 Yd=Yp("socket.io-client"),Zd={};function Xd(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)||(xd("protocol-less url %s",e),e=void 0!==r?r.protocol+"//"+e:"https://"+e),xd("parse %s",e),n=Ed(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=Zd[i]&&a in Zd[i].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?(Yd("ignoring socket cache for %s",n),s=new Jd(n,t)):(Zd[i]||(Yd("new io instance for %s",n),Zd[i]=new Jd(n,t)),s=Zd[i]),r.query&&!t.query&&(t.query=r.queryKey),s.socket(r.path,t)}Object.assign(Xd,{Manager:Jd,Socket:Hd,io:Xd,connect:Xd});const eu=e=>e();var tu=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 ru{constructor(e,t,r=eu,n){this.clientId=e,this.socketIoEndpoint=t,this.messageNotificationWrapper=r,this.destructManager=n,this.webSocketObserver=new Ae.Subject,this.allMessagesObserver=new Ae.Subject,this.connectionReady=new Ae.BehaviorSubject(!1),this.seenMessageIds=new Set,this.firstConnection=!0,this.destructManager.onDestruct((()=>tu(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,Ae.distinctUntilChanged)())}sendMessage(e){(0,Ae.firstValueFrom)(this.connectionReady.pipe((0,Ae.filter)(Boolean))).then((()=>{Fe(this.socket).emit("message",e)}))}connect(){this.socket=Xd(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=Se(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 Ae.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,Ae.tap)((e=>t.push(e))),(0,Ae.debounceTime)(100)).subscribe((()=>tu(this,void 0,void 0,(function*(){const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))))}destruct(){var e;return tu(this,void 0,void 0,(function*(){this.sendMessage({type:"kill"}),this.connectionReady.next(!1),yield(0,Ae.firstValueFrom)((0,Ae.timer)(0)),null===(e=this.socket)||void 0===e||e.disconnect(),this.webSocketObserver.complete(),this.allMessagesObserver.complete()}))}}class nu{constructor(e){this.destructManager=new Bt,$e(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}`,e===Ye.LOCAL&&(r.protocol="http",r.port="8000");const n=r.toString();return n.endsWith("/")?n:n+"/"}(e.region||Ye.AWS_US_EAST_1,e.appId);this.clientId=lt(),this.socketManager=new ru(this.clientId,t,e.messageNotificationWrapper,this.destructManager),this.rpcManager=new Rp(t,this.socketManager,this.destructManager,e.apiKey),this.documentStore=new Qt,this.lockManager=new ft,this.documentIdentityService=new Ut(this.documentStore,this.destructManager),this.documentReferenceFactory=new zt,this.querySubscriptionManager=new jp(this.rpcManager,this.clientId,this.documentStore,this.destructManager,this.documentIdentityService);const r=new cp(this.clientId,this.rpcManager,this.lockManager,this.querySubscriptionManager);this.queryBuilderFactory=new fp(this.querySubscriptionManager,this.documentReferenceFactory,this.documentIdentityService),this.collectionReferenceFactory=new $t(this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService),this.dataManager=new qt(this.documentStore,r,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new Mt(this.clientId,this.rpcManager,this.socketManager),this.namedQueryManager=new lp(this.clientId,this.rpcManager,this.socketManager),this.apiManager=new Rt(this.clientId,this.rpcManager,this.socketManager,e.apiServerUrlOverrideMapping),this.graphqlClientFactory=new dp(this.rpcManager)}static getInstance(e){const t=_e(e);let r=nu.squidInstancesMap.get(t);return r||(r=new nu(e),nu.squidInstancesMap.set(t,r),r)}static getInstances(){return Array.from(nu.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,Ae.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))}executeNamedQuery(e,t,r){return(0,Ae.firstValueFrom)(this.namedQueryManager.executeNamedQueryAndSubscribe(e,t,r))}callApi(e,t,r={}){return(0,Ae.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,t,r))}graphql(e){return this.graphqlClientFactory.get(e)}destruct(){return e=this,t=void 0,n=function*(){return this.destructManager.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}}nu.squidInstancesMap=new Map;class iu{metadata(){return vt.data}cleanup(){return e=this,t=void 0,n=function*(){for(const e of nu.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 au=require("path");var ou=i(7147);class su{constructor(e){this.region=process.env.SQUID_REGION||Ye.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 nu.getInstance({appId:this.context.appId,apiKey:this.backendApiKey,region:this.region})}get assetsDirectory(){const e=au.resolve(this.codeDir||"","public");if(ou.existsSync(e))return e;const t=au.resolve(process.cwd(),"src/public");return ou.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}}})();var o=exports;for(var s in a)o[s]=a[s];a.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
@@ -1,4 +1,4 @@
1
- import { ApiEndpointId, ApiKey, AppId, CollectionName, DocumentData, IntegrationId, QueryName, SquidRegion } from '@squidcloud/common';
1
+ import { ApiEndpointId, ApiKey, AppId, CollectionName, DocumentData, IntegrationId, PartialBy, QueryName, SquidRegion } from '@squidcloud/common';
2
2
  import { CollectionReference } from './collection-reference';
3
3
  import { GraphQLClient } from './graphql-client';
4
4
  import { TransactionId } from './types';
@@ -28,7 +28,7 @@ export declare class Squid {
28
28
  private readonly destructManager;
29
29
  private readonly documentIdentityService;
30
30
  private static readonly squidInstancesMap;
31
- constructor(options: SquidOptions);
31
+ constructor(options: PartialBy<SquidOptions, 'region'>);
32
32
  /**
33
33
  * This method is a factory method for creating a Squid instance
34
34
  */
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@squidcloud/backend",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Squid Cloud's backend SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/backend/src/index.d.ts",
7
7
  "scripts": {
8
8
  "prebuild": "rimraf dist",
9
- "build": "webpack --mode=production"
9
+ "build": "webpack --mode=production",
10
+ "publish:public": "npm version patch && npm run build && npm publish --access public"
10
11
  },
11
12
  "files": [
12
13
  "dist/**/*"