@squidcloud/client 1.0.251 → 1.0.253

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -2,4 +2,4 @@
2
2
  ${e.query}
3
3
  `,variables:e.variables})).data}async mutate(e){return(await this.client.mutate({mutation:Ja`
4
4
  ${e.query}
5
- `})).data}}class iu{constructor(e,t,r){this.rpcManager=e,this.region=t,this.appId=r,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new nu(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class ou{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=gt(e),n=r.map((e=>`sendMutation_${Ke(e.squidDocIdObj)}`));await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw we.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class su{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function au(e,t){switch(t.type){case"simple":return function(e,t){const{query:r,dereference:n}=t,{collectionName:i,integrationId:o}=r;let s=e.collection(i,o).query();return s=uu(s,r),n?s.dereference():s}(e,t);case"join":return function(e,t){const{root:r,joins:n,joinConditions:i,dereference:o,grouped:s}=t,{collectionName:a,integrationId:u}=r.query;let c=e.collection(a,u).joinQuery(r.alias);return c=uu(c,r.query),Object.entries(n).map((([t,r])=>{const{collectionName:n,integrationId:o}=r,{left:s,right:a,leftAlias:u}=i[t];let l=e.collection(n,o).query();l=uu(l,r),c=c.join(l,t,{left:s,right:a},{leftAlias:u})})),o&&s?c.grouped().dereference():o?c.dereference():s?c.grouped():c}(e,t);case"merged":return function(e,t){const{queries:r}=t,{collectionName:n,integrationId:i}=cu(r[0]),o=r.map((t=>au(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function uu(e,t){const{conditions:r,limit:n,sortOrder:i}=t;for(const t of r){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:r,operator:n,value:i}=t;e.where(r,n,i)}e.limit(n);for(const{fieldName:t,asc:r}of i)e.sortBy(t,r);return e}function cu(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:r}=e.query;return{collectionName:t,integrationId:r}}case"join":{const{collectionName:t,integrationId:r}=e.root.query;return{collectionName:t,integrationId:r}}case"merged":return cu(e.queries[0])}}const lu={"in:in":(e,t)=>e.every((e=>t.includes(e))),"in:not in":(e,t)=>e.every((e=>!t.includes(e))),"not in:not in":(e,t)=>t.every((t=>e.includes(t))),">:not in":(e,t)=>t.every((t=>e>=t)),">=:not in":(e,t)=>t.every((t=>e>t)),"<:not in":(e,t)=>t.every((t=>e<=t)),"<=:not in":(e,t)=>t.every((t=>e<t)),">:>":(e,t)=>e>=t,">=:>":(e,t)=>e>t,"in:>":(e,t)=>e.every((e=>e>t)),">:>=":(e,t)=>e>=t,">=:>=":(e,t)=>e>=t,"in:>=":(e,t)=>e.every((e=>e>=t)),"<:<":(e,t)=>e<=t,"<=:<":(e,t)=>e<t,"in:<":(e,t)=>e.every((e=>e<t)),"<:<=":(e,t)=>e<=t,"<=:<=":(e,t)=>e<=t,"in:<=":(e,t)=>e.every((e=>e<=t)),"like:like":(e,t)=>hu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>hu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>hu(e,t)&&fu(t),"like_cs:like_cs":(e,t)=>hu(e,t),"like:not like":(e,t)=>!du(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!du(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!du(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!du(e,t),"not like:like":(e,t)=>vu(e,t),"not like_cs:like":(e,t)=>vu(e,t),"not like:like_cs":(e,t)=>vu(e,t),"not like_cs:like_cs":(e,t)=>vu(e,t),"not like:not like":(e,t)=>hu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>hu(t,e)&&fu(e),"not like:not like_cs":(e,t)=>hu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>hu(t,e),"in:like":(e,t)=>e.every((e=>ut(t,e,"like"))),"in:like_cs":(e,t)=>e.every((e=>ut(t,e,"like_cs"))),"in:not like":(e,t)=>e.every((e=>ut(t,e,"not like"))),"in:not like_cs":(e,t)=>e.every((e=>ut(t,e,"not like_cs"))),"like:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&!!t.find((t=>t.toLowerCase()===e.toLowerCase())),"like_cs:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&t.includes(e),"not like:in":(e,t)=>e.length>0&&pu(e)||yu(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&pu(e)||yu(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&pu(t)||yu(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&pu(t)||yu(t)&&e.includes(""),"not in:not like":(e,t)=>!t.includes("%")&&!t.includes("_")&&!!e.find((e=>e.toLowerCase()===t.toLowerCase())),"not in:not like_cs":(e,t)=>!t.includes("%")&&!t.includes("_")&&e.includes(t),"like:not in":(e,t)=>t.every((t=>ut(e,t,"not like"))),"like_cs:not in":(e,t)=>t.every((t=>ut(e,t,"not like_cs"))),"not like:not in":(e,t)=>t.every((t=>ut(e,t,"like"))),"not like_cs:not in":(e,t)=>t.every((t=>ut(e,t,"like_cs"))),"array_includes_some:array_includes_some":(e,t)=>e.every((e=>t.includes(e))),"array_includes_all:array_includes_all":(e,t)=>e.every((e=>t.includes(e))),"array_not_includes:array_not_includes":(e,t)=>t.every((t=>e.includes(t))),"array_includes_some:array_not_includes":(e,t)=>e.every((e=>!t.includes(e))),"array_not_includes:array_includes_some":(e,t)=>t.every((t=>!e.includes(t))),"array_includes_all:array_includes_some":(e,t)=>e.every((e=>t.includes(e))),"array_includes_some:array_includes_all":(e,t)=>e.every((e=>t.includes(e))),"array_not_includes:array_includes_all":(e,t)=>t.every((t=>!e.includes(t))),"array_includes_all:array_not_includes":(e,t)=>e.every((e=>!t.includes(e)))};function hu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return pu(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?hu(e,t,r+1,n+1)||hu(e,t,r+1,n):"%"!==i&&("%"===o?hu(e,t,r,n+1)||hu(e,t,r+1,n):(i===o||"_"===o)&&hu(e,t,r+1,n+1))}function du(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return pu(t.substring(n));if(n>=t.length)return pu(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?du(e,t,r+1,n+1)||du(e,t,r,n+1)||du(e,t,r+1,n):"%"===i||"%"===o?du(e,t,r,n+1)||du(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&du(e,t,r+1,n+1)}function fu(e){return!/[a-zA-Z]/.test(e)}function pu(e){return e.split("").every((e=>"%"===e))}function vu(e,t){return e.length>0&&pu(e)||t.length>0&&pu(t)||yu(e)&&0===t.length}function yu(e){let t=!1,r=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(r)return!1;r=!0;break;default:return!1}return t&&r}class bu{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Ue))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){const t=e.find(((e,t)=>{var r;return!he(this.query.sortOrder[t],Object.assign(Object.assign({},e),{asc:null===(r=e.asc)||void 0===r||r}))}));return!t}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,r){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:r})}isSubqueryOfCondition(e){return!!this.parsedConditions.filter((t=>t.fieldName===e.fieldName)).find((t=>this.evaluateSubset(t,e)))}isSubqueryOfConditions(e){return this.parseConditions(e).every((e=>this.isSubqueryOfCondition(e)))}isSubqueryOfQuery(e){if(e.collectionName!==this.collectionName||e.integrationId!==this.integrationId)return!1;const t=e.conditions.filter(Ue),r=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),i=-1===e.limit||this.limit>-1&&this.limit<e.limit;return r&&n&&i}getConditionsFor(...e){return this.parsedConditions.filter((t=>e.includes(t.fieldName)))}getConditionsForField(e){return this.parsedConditions.filter((t=>t.fieldName===e))}documentMatchesQuery(e){for(const t of this.parsedConditions){const r=t.fieldName,n=t.operator,i=oe(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!ut(t.value,i,n))return!1}else if(t.value.includes(i))return!1}return!0}evaluateSubset(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=lu[`${r}:${i}`];return!!s&&s(n,o)}evaluateIncludes(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=Array.isArray(n)?n.sort():n,a=Array.isArray(o)?o.sort():o;return i===r&&he(a,s)}parseConditions(e){const t=[],r=new Map,n=new Map;return e.forEach((e=>{switch(e.operator){case"==":case"in":r.set(e.fieldName,(r.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}})),r.forEach(((e,r)=>{t.push({fieldName:r,operator:"in",value:e})})),n.forEach(((e,r)=>{t.push({fieldName:r,operator:"not in",value:e})})),t}}class mu{constructor(e,t,r){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=r}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:r}=e,n=new bu(e),i=this.documentReferenceFactory.getDocumentsForCollection(t,r).filter((e=>n.documentMatchesQuery(e.data))),o={};return i.forEach((e=>{o[e.squidDocId]=e})),this.documentStore.sortAndLimitDocs(new Set(Object.keys(o)),e).map((e=>o[Ke(e.__docId__,r,t)]))}}function gu(e,t){return a((function(r,n){var i=0;r.subscribe(L(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class _u{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new o.BehaviorSubject(!0),this.inflightQueriesCount=new o.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const t=new o.Subject,r=(0,o.firstValueFrom)(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),r):(this.pendingQueryBatchTimeout=setTimeout((()=>{this.safeToSendQueriesToServer.pipe(gu(Boolean),(0,o.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),r)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=e.map((({queryRequest:e})=>e)),r=e.map((({responseSubject:e})=>e));this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const r=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,i=r.errors[e],o=r.results[e];i?n.error(i):n.next(o)}}catch(e){r.forEach((t=>t.error(e)))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}async waitForAllQueriesToFinish(){return(0,o.firstValueFrom)(this.inflightQueriesCount.pipe(gu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Ou,Su=r(4123);function Eu(e,t,r=((e,t)=>e>t?1:e<t?-1:0),n=0,i=e.length-1){if(i<n)return-1;const o=Math.trunc((n+i)/2);return 0===r(t,e[o])?o:r(t,e[o])>0?Eu(e,t,r,o+1,i):Eu(e,t,r,n,o-1)}function wu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==Eu(e,t,r))return;let n;for(n=e.length-1;n>=0&&r(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function Tu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){const n=Eu(e,t,r);n>-1&&e.splice(n,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Ou||(Ou={}));const Iu=100,Au=20;class Mu{constructor(e,t,r,n,i,s){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.querySender=s,this.onOrphanDocuments=new o.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new ku,this.queryResultsSubject=new o.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return(0,V.truthy)(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);(null==t?void 0:t.gotInitialResponse)&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=He(t),i=this.queryMappingManager.getMapping(r,n);return i?function(e,t){var r;const n=[...e.unconditional||[]],i=new Map;for(const[n,o]of Object.entries(e.conditional||{})){const e=_e(n);let s;if(Ue(e)){const n=null!==(r=oe(t,e.fieldName))&&void 0!==r?r:null;s=ut(e.value,n,e.operator)}else s=Fu(e,t);if(s)for(const e of o)i.set(e,(i.get(e)||0)+1)}for(const[t,r]of i.entries())r>=e.queriesMetadata[t].condCount&&n.push(t);return n}(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&&(this.destructManager.isDestructing?r.dataSubject.complete():r.dataSubject.error(t),r.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(r)||new Set,i=this.documentStore.sortAndLimitDocs(n,e.query),o=e.supportedQueries.map((e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(i,e))).some(Boolean);let s=e;for(;!s.allObservables;)s=(0,V.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case Ou.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+Iu?Ou.ENABLED:Ou.DISABLED;break;case Ou.DISABLED:break;case Ou.ENABLED:if(n.size<e.query.limit+Au){e.limitUnderflowState=Ou.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,V.truthy)(e.allObservables).next(t)}}isValidParent(e){if(!e.activated||e.isInFlight||e.isEmptyForJoin||e.done||!e.subscribe||!e.gotInitialResponse||!e.dataSubject.value)return!1;const t=-1===e.query.limit?1e3:e.query.limit;return e.dataSubject.value.length<t}findValidParentOfOngoingQuery(e){if(e.forceFetchFromServer)return;const t=new bu(e.query);for(const r of this.ongoingQueries.values()){if(e===r)return;if(this.isValidParent(r)&&t.isSubqueryOfQuery(r.query))return r}}findValidParentOfQuery(e){const t=new bu(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,s){return(0,o.defer)((()=>{const a=this.createOngoingQueryGraph(e,t,r,n,i,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new o.ReplaySubject(1);const u=a.allObservables.pipe((0,o.switchMap)((e=>(0,o.combineLatest)(e).pipe(Q((e=>this.joinResults(e,n,a)))))),gu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,o.startWith)(void 0),(0,o.pairwise)(),gu((([e,t])=>!he(e,t))),Q((([,e])=>e)),i?(0,o.tap)():(0,o.take)(1),(0,o.finalize)((()=>{var e;a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a).then(),null===(e=a.allObservables)||void 0===e||e.complete()}))),c=this.collectAllObservables(a);return a.allObservables.next(c),u})).pipe((0,o.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=(0,V.truthy)(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}registerQueryFinalizer(e){const t=e.clientRequestId,r=lt(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,o.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,o.firstValueFrom)((0,o.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(gu((e=>0===e))))),this.queryMappingManager.removeQuery(r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch((t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)})),gu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,s,a={}){if(a[t])return a[t];const u=U(),c=[],l={clientRequestId:u,activated:s,alias:t,query:e,subscribe:i,dataSubject:new o.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new o.BehaviorSubject(0),queryRegistered:new o.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:i?Ou.UNKNOWN:Ou.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[t]=l;for(const[e,o]of Object.entries(n)){const s=o.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,a);e.joinCondition=o,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(gu(Boolean),Q((e=>({docs:e,alias:r})))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=e.reduce(((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e)),{});let i=n[r.alias].map((e=>({[r.alias]:e})));const o=this.getOngoingQueriesBfs(r),s=new Set;for(let e=1;e<o.length;e++){const r=o[e].alias;s.has(r)||(s.add(r),i=this.join(i,r,n[r],t[r]))}return i}join(e,t,r,n){if(!e.length)return e;const i=Object.keys(e[0]);if(!n||!i.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const o=new Map;return(r||[]).forEach((e=>{const t=e[n.right];o.has(t)||o.set(t,[]),(0,V.truthy)(o.get(t)).push(e)})),e.flatMap((e=>{var r;const i=o.get(null===(r=e[n.leftAlias])||void 0===r?void 0:r[n.left])||[];return i.length?i.map((r=>Object.assign(Object.assign({},e),{[t]:r}))):n.isInner?[]:[Object.assign(Object.assign({},e),{[t]:void 0})]}))}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=(0,V.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=(0,V.truthy)(t.joinCondition),i=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const s=(0,V.truthy)(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(Ue).filter((e=>e.fieldName===n.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=fe(i);u.conditions=u.conditions.filter((e=>!Ue(e)||e.fieldName!==n.right)),[...a].forEach((e=>{u.conditions.push({fieldName:n.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},t),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new o.BehaviorSubject(null),clientRequestId:U(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,V.truthy)(t.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(t.activated=!0,i.conditions.filter(Ue).filter((e=>e.fieldName===n.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})).map((e=>({fieldName:n.right,operator:"==",value:e})));return r.length?(i.conditions.push(...r),this.sendQueryToServerOrUseParentQuery(t)):t.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=(0,V.truthy)(t.shift());t.push(...e.supportedQueries||[]),await(0,o.firstValueFrom)(e.unsubscribeBlockerCount.pipe(gu((e=>0===e)))),e.dataSubject.complete()}}preDestruct(){this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.dataSubject.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)}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const r=e.query,n=e.clientRequestId,i=lt(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(r,i),this.ongoingQueries.set(n,e);const o=t?void 0:this.findValidParentOfOngoingQuery(e);o?this.useParentOngoingQuery(e,o).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const r={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new bu(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,o.firstValueFrom)(t.queryRegistered.pipe(gu(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",r).then((()=>{e.isInFlight=!1,e.queryRegistered.next(!0)})).catch((r=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,r),e.dataSubject.error(r)),e.done=!0})).finally((()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)}));const i=(0,o.race)(e.queryRegistered.pipe(gu(Boolean),(0,o.delay)(2e3),(0,o.take)(1)),this.destructManager.observeIsDestructing().pipe((0,o.take)(1)));t.dataSubject.pipe((0,o.takeWhile)((()=>!e.done)),(0,o.takeUntil)(i),gu(Boolean),(0,o.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),Q((e=>e.filter((e=>n.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Ke(r.__docId__,e.query.collectionName,e.query.integrationId),r);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,r=t>0&&e.subscribe?t+Iu:t,n={query:Object.assign(Object.assign({},e.query),{limit:r}),clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).then((t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(we.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0}))}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e,!0)}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=>{ce(this.localDocumentToClientRequestIds,t,e[t])}))}}function Fu(e,t){var r;for(const n of e.fields){const e=null!==(r=oe(t,n.fieldName))&&void 0!==r?r:null;if(ut(n.value,e,n.operator))return!0;if(ut(n.value,e,"!="))return!1}return!1}class ku{constructor(){this.stateService=new Su.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(Ue(i)&&["=="].includes(i.operator)){const e=Oe(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];wu(s,t),this.stateService.set(o,s)}if(!e.conditions.length){const r=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(r)||[]];wu(n,t),this.stateService.set(r,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],r)})),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch((()=>{for(const r of t.conditions){const n=this.getConditionStatePath(t,r),i=[...this.stateService.get(n)||[]];Tu(i,e),i.length?this.stateService.set(n,i):this.stateService.delete(n)}if(!t.conditions.length){const r=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(r)||[]];Tu(n,e),this.stateService.set(r,n)}this.stateService.delete(this.getQueryMetadataStatePath(t,e))})),t}getMapping(e,t){return this.stateService.get(["queryMapping",e,t,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",(r=t,me(r))];var r}}class Du{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const t=Object.entries(this.locks).filter((([t])=>e.includes(t))).map((([,e])=>e));await(0,o.lastValueFrom)((0,o.combineLatest)(t).pipe((0,o.filter)((e=>!e.includes(!0))),(0,o.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,V.truthy)(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some((e=>{var t;return null===(t=this.locks[e])||void 0===t?void 0:t.value}))}lockSync(...e){(0,V.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new o.BehaviorSubject(!0)}}class ju{constructor(e,t,r){this.rpcManager=e,this.socketManager=t,this.queueManagers=new Map,this.socketManager.observeNotifications().subscribe((e=>{const t=this.getOrUndefined(e.integrationId,e.topicName);t&&t.onMessages(e.payload)})),r.onPreDestruct((()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()}))}get(e,t){let r=this.queueManagers.get(e);r||(r=new Map,this.queueManagers.set(e,r));let n=r.get(t);return n||(n=new Pu(e,t,this.rpcManager),r.set(t,n)),n}getOrUndefined(e,t){var r;return null===(r=this.queueManagers.get(e))||void 0===r?void 0:r.get(t)}}const xu="subscriptionMutex";class Pu{constructor(e,t,r){this.integrationId=e,this.topicName=t,this.rpcManager=r,this.messagesSubject=new o.Subject,this.subscriberCount=0,this.lockManager=new Du}async produce(e){await this.lockManager.lock(xu);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(xu)}}consume(){return(0,o.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,o.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(xu);try{await this.rpcManager.post("queue/subscribe",{integrationId:this.integrationId,topicName:this.topicName})}catch(e){this.messagesSubject.error(e),this.messagesSubject.complete(),this.subscriberCount=0,this.messagesSubject=new o.Subject}finally{this.lockManager.release(xu)}}async performUnsubscribe(){await this.lockManager.lock(xu);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(xu)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Nu{constructor(e,t){this.capacity=e,this.seconds=t,this.tokens=e,this.refillRatePerMs=e/(1e3*t),this.lastRefillTimestamp=Date.now()}async consume(){this.attemptConsume()||await(0,o.firstValueFrom)((0,o.interval)(10).pipe((0,o.filter)((()=>this.attemptConsume())),(0,o.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}class Cu extends Error{constructor(e,t,r,n,i,o){super(o||`RPC error ${e} ${t} calling ${r}`),this.statusCode=e,this.statusText=t,this.url=r,this.headers=n,this.body=i}}async function Ru(e){const t=await async function({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o}){const s=new Headers(e),a={method:"POST",headers:s,body:void 0};if(t.length){const e=new FormData;for(const n of t){const t=n instanceof Blob?n:n.blob,i=(Blob,n.name);e.append(r,t,i)}e.append("body",ge(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=ge(n);try{const e=await fetch(i,a),t={};if(e.headers.forEach(((e,r)=>{t[r]=e})),!e.ok){const r=await e.text(),n=qu(r);if(!o)throw new Cu(e.status,e.statusText,i,t,n,r);let s;try{s="string"==typeof n?n:(null==n?void 0:n.message)||r}catch(e){}throw s||(s=e.statusText),new Cu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return we.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw we.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=qu(t.body),t}function qu(e){if(e){try{return _e(e)}catch(e){}return e}}class Lu{constructor(e,t,r,n,i,s){this.region=e,this.appId=t,this.authManager=i,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new o.BehaviorSubject(0);for(const[e,t]of Object.entries(n))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),r.onDestruct((async()=>{await this.awaitAllSettled()}));const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Nu(60*a,5),ai:new Nu(20*a,5),secret:new Nu(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:r}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return r&&(n+=`; IntegrationId ${r}`),{Authorization:n}}async awaitAllSettled(){await(0,o.firstValueFrom)(this.onGoingRpcCounter.pipe((0,o.filter)((e=>0===e))))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,r=[],n="files"){return(await this.rawPost(e,t,r,n)).body}async rawPost(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),s=Object.assign(Object.assign({},this.staticHeaders),o);we.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=tu(this.region,this.appId,e);return await Ru({url:a,headers:s,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?(0,V.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,V.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,V.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Bu{constructor(e){this.rpcManager=e}reportMetric(e){const t={metrics:[e]};this.rpcManager.post("/observability/metrics",t)}}class Qu{constructor(e){this.rpcManager=e}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}upsert(e,t){return this.upsertMany([{key:e,value:t}]).then((e=>e[0]))}upsertMany(e){const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e){const t={keys:[e]};return this.rpcManager.post("secret/delete",t)}deleteMany(e){const t={keys:e};return this.rpcManager.post("secret/delete",t)}get apiKeys(){return new Vu(this.rpcManager)}}class Vu{constructor(e){this.rpcManager=e}get(e){const t={key:e};return this.rpcManager.post("secret/api-key/get",t)}getAll(){return this.rpcManager.post("secret/api-key/getAll",{})}upsert(e){const t={key:e};return this.rpcManager.post("secret/api-key/upsert",t)}delete(e){const t={key:e};return this.rpcManager.post("secret/api-key/delete",t)}}const Uu=e=>e();var zu;function Yu(){}const Wu="undefined"!=typeof process&&(null===(zu=process.versions)||void 0===zu?void 0:zu.node)?r(5086):Ee().WebSocket;class $u{constructor(e,t,r,n=Uu,i,s){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=s,this.webSocketObserver=new o.Subject,this.allMessagesObserver=new o.Subject,this.connectionReady=new o.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new o.Subject,this.connectedAtLeastOnce=!1,this.clientTooOldThreshold=3e4,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(),this.lastTick=new Date,this.tickInterval=setInterval((()=>this.tick()),5e3),this.observeConnectionReady().pipe((0,o.skip)(1),(0,o.filter)((e=>!e)),(0,o.switchMap)((()=>(0,o.race)((0,o.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,o.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?we.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(we.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,o.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?we.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?we.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(we.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),we.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(we.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,o.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var t;await(0,o.firstValueFrom)(this.connectionReady.pipe((0,o.filter)(Boolean)));const r=await this.authManager.getToken();if(this.connectionReady.value)try{(0,V.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=ge({message:e,authToken:r});we.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(r){(null===(t=this.socket)||void 0===t?void 0:t.connected)?console.error("Websocket message is ignored due to a non-recoverable error",r):(this.connectionReady.next(!1),await this.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){var e;(null===(e=this.socket)||void 0===e?void 0:e.connected)&&this.socket.send(ge({message:{type:"kill"}}))}closeCurrentSocketSilently(){if(this.socket)try{this.socket.close()}catch(e){}}connect(){this.closeCurrentSocketSilently(),this.connectionReady.value&&this.connectionReady.next(!1);const e=tu(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();we.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const r=`${e}?clientId=${t}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,closeCalled:!1,open(){var i;const s=null!==(i=null==Wu?void 0:Wu.WebSocket)&&void 0!==i?i:Wu;r=new s(e,t.protocols||[]),r.onmessage=t.onmessage?e=>{e.data&&t.onmessage?t.onmessage(e):console.log("No data received from websockets, please contact support@squid.cloud with this message.")}:Yu,r.onopen=function(e){o.connected=!0,(t.onopen||Yu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return we.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Yu)(e),void o.reconnect(e);(t.onclose||Yu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):o.closeCalled||(t.onerror||Yu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Yu)(e),we.debug("WebSocket trying to reconnect..."),o.open()}),t.timeoutMillis||1e3):(t.onmaximum||Yu)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){o.closeCalled=!0;try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(r,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{we.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{we.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{we.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){var e;this.connectionReady.next(!1),null===(e=this.socket)||void 0===e||e.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return we.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=_e(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),we.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new o.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,o.tap)((e=>t.push(e))),(0,o.debounceTime)(100)).subscribe((async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){this.sendKillMessage(),await(0,o.firstValueFrom)((0,o.timer)(0)),this.connectionReady.next(!1),await(0,o.firstValueFrom)((0,o.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Gu(e,t){return`${function(e){(0,V.assertString)(e,"Invalid application ID");const[t,r,n,i]=e.split("-");return(0,V.assertTruthy)(!i,`Invalid application ID: ${e}`),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class Hu{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,r){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:r};await this.rpcManager.post("storage/uploadFile",n,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const r={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",r)}async listDirectoryContents(e){const t={integrationId:this.integrationId,dirPathInBucket:e};return await this.rpcManager.post("storage/listDirectoryContents",t)}async deleteFile(e){await this.deleteFiles([e])}async deleteFiles(e){const t={integrationId:this.integrationId,filePathsInBucket:e};await this.rpcManager.post("storage/deleteFiles",t)}}class Ku{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){return await this.rpcManager.post("documentExtraction/extractDataFromDocumentFile",t,[e])}}class Ju{constructor(e){this.options=e,this.destructManager=new Et,(0,V.assertTruthy)(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,r=function(e,t,r){return`${Gu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return ru(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new Te(this.destructManager),this.authManager=new ne(e.apiKey,e.authProvider),this.socketManager=new $u(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Lu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new X(this.rpcManager,this.socketManager),this.aiClient=new ee(this.aiClientFactory,this.rpcManager),this.apiClient=new re(this.rpcManager),this.documentStore=new Mt,this.lockManager=new Du,this.distributedLockManager=new wt(this.socketManager,this.destructManager),this.documentIdentityService=new It(this.documentStore,this.destructManager),this.documentReferenceFactory=new At(this.documentIdentityService),this.querySender=new _u(this.rpcManager,this.destructManager),this.observabilityClient=new Bu(this.rpcManager),this.querySubscriptionManager=new Mu(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new mu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new ou(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Ze(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new Ot(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new ft(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new Se(this.clientIdService,this.rpcManager),this.nativeQueryManager=new su(this.rpcManager),this.graphqlClientFactory=new iu(this.rpcManager,e.region,r),this.secretClient=new Qu(this.rpcManager),this._connectionDetails=new pt(this.clientIdService,this.socketManager),this.queueManagerFactory=new ju(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=me(e);let r=Ju.squidInstancesMap[t];return r||(r=new Ju(e),Ju.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Ju.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Be.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),(0,o.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))}executeNativeRelationalQuery(e,t,r={}){const n={type:"relational",query:t,params:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,r){const n={type:"mongo",collectionName:t,aggregationPipeline:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}graphql(e){return this._validateNotDestructed(),this.graphqlClientFactory.get(e)}ai(){return this._validateNotDestructed(),this.aiClient}api(){return this._validateNotDestructed(),this.apiClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Hu(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new Ku(this.rpcManager)}get secrets(){return this.secretClient}get observability(){return this.observabilityClient}acquireLock(e){return this._validateNotDestructed(),this.distributedLockManager.lock(e)}async withLock(e,t){const r=await this.acquireLock(e);try{return await t(r)}finally{r.release()}}queue(e,t=Be.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries(Ju.squidInstancesMap).find((([,e])=>e===this));e&&delete Ju.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,V.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,r)=>tu(e,t,r),getStaticHeaders:()=>e.getStaticHeaders()}}}Ju.squidInstancesMap={};var Xu=exports;for(var Zu in n)Xu[Zu]=n[Zu];n.__esModule&&Object.defineProperty(Xu,"__esModule",{value:!0})})();
5
+ `})).data}}class iu{constructor(e,t,r){this.rpcManager=e,this.region=t,this.appId=r,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new nu(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class ou{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=gt(e),n=r.map((e=>`sendMutation_${Ke(e.squidDocIdObj)}`));await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw we.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class su{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function au(e,t){switch(t.type){case"simple":return function(e,t){const{query:r,dereference:n}=t,{collectionName:i,integrationId:o}=r;let s=e.collection(i,o).query();return s=uu(s,r),n?s.dereference():s}(e,t);case"join":return function(e,t){const{root:r,joins:n,joinConditions:i,dereference:o,grouped:s}=t,{collectionName:a,integrationId:u}=r.query;let c=e.collection(a,u).joinQuery(r.alias);return c=uu(c,r.query),Object.entries(n).map((([t,r])=>{const{collectionName:n,integrationId:o}=r,{left:s,right:a,leftAlias:u}=i[t];let l=e.collection(n,o).query();l=uu(l,r),c=c.join(l,t,{left:s,right:a},{leftAlias:u})})),o&&s?c.grouped().dereference():o?c.dereference():s?c.grouped():c}(e,t);case"merged":return function(e,t){const{queries:r}=t,{collectionName:n,integrationId:i}=cu(r[0]),o=r.map((t=>au(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function uu(e,t){const{conditions:r,limit:n,sortOrder:i}=t;for(const t of r){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:r,operator:n,value:i}=t;e.where(r,n,i)}e.limit(n);for(const{fieldName:t,asc:r}of i)e.sortBy(t,r);return e}function cu(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:r}=e.query;return{collectionName:t,integrationId:r}}case"join":{const{collectionName:t,integrationId:r}=e.root.query;return{collectionName:t,integrationId:r}}case"merged":return cu(e.queries[0])}}const lu={"in:in":(e,t)=>e.every((e=>t.includes(e))),"in:not in":(e,t)=>e.every((e=>!t.includes(e))),"not in:not in":(e,t)=>t.every((t=>e.includes(t))),">:not in":(e,t)=>t.every((t=>e>=t)),">=:not in":(e,t)=>t.every((t=>e>t)),"<:not in":(e,t)=>t.every((t=>e<=t)),"<=:not in":(e,t)=>t.every((t=>e<t)),">:>":(e,t)=>e>=t,">=:>":(e,t)=>e>t,"in:>":(e,t)=>e.every((e=>e>t)),">:>=":(e,t)=>e>=t,">=:>=":(e,t)=>e>=t,"in:>=":(e,t)=>e.every((e=>e>=t)),"<:<":(e,t)=>e<=t,"<=:<":(e,t)=>e<t,"in:<":(e,t)=>e.every((e=>e<t)),"<:<=":(e,t)=>e<=t,"<=:<=":(e,t)=>e<=t,"in:<=":(e,t)=>e.every((e=>e<=t)),"like:like":(e,t)=>hu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>hu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>hu(e,t)&&fu(t),"like_cs:like_cs":(e,t)=>hu(e,t),"like:not like":(e,t)=>!du(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!du(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!du(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!du(e,t),"not like:like":(e,t)=>vu(e,t),"not like_cs:like":(e,t)=>vu(e,t),"not like:like_cs":(e,t)=>vu(e,t),"not like_cs:like_cs":(e,t)=>vu(e,t),"not like:not like":(e,t)=>hu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>hu(t,e)&&fu(e),"not like:not like_cs":(e,t)=>hu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>hu(t,e),"in:like":(e,t)=>e.every((e=>ut(t,e,"like"))),"in:like_cs":(e,t)=>e.every((e=>ut(t,e,"like_cs"))),"in:not like":(e,t)=>e.every((e=>ut(t,e,"not like"))),"in:not like_cs":(e,t)=>e.every((e=>ut(t,e,"not like_cs"))),"like:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&!!t.find((t=>t.toLowerCase()===e.toLowerCase())),"like_cs:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&t.includes(e),"not like:in":(e,t)=>e.length>0&&pu(e)||yu(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&pu(e)||yu(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&pu(t)||yu(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&pu(t)||yu(t)&&e.includes(""),"not in:not like":(e,t)=>!t.includes("%")&&!t.includes("_")&&!!e.find((e=>e.toLowerCase()===t.toLowerCase())),"not in:not like_cs":(e,t)=>!t.includes("%")&&!t.includes("_")&&e.includes(t),"like:not in":(e,t)=>t.every((t=>ut(e,t,"not like"))),"like_cs:not in":(e,t)=>t.every((t=>ut(e,t,"not like_cs"))),"not like:not in":(e,t)=>t.every((t=>ut(e,t,"like"))),"not like_cs:not in":(e,t)=>t.every((t=>ut(e,t,"like_cs"))),"array_includes_some:array_includes_some":(e,t)=>e.every((e=>t.includes(e))),"array_includes_all:array_includes_all":(e,t)=>e.every((e=>t.includes(e))),"array_not_includes:array_not_includes":(e,t)=>t.every((t=>e.includes(t))),"array_includes_some:array_not_includes":(e,t)=>e.every((e=>!t.includes(e))),"array_not_includes:array_includes_some":(e,t)=>t.every((t=>!e.includes(t))),"array_includes_all:array_includes_some":(e,t)=>e.every((e=>t.includes(e))),"array_includes_some:array_includes_all":(e,t)=>e.every((e=>t.includes(e))),"array_not_includes:array_includes_all":(e,t)=>t.every((t=>!e.includes(t))),"array_includes_all:array_not_includes":(e,t)=>e.every((e=>!t.includes(e)))};function hu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return pu(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?hu(e,t,r+1,n+1)||hu(e,t,r+1,n):"%"!==i&&("%"===o?hu(e,t,r,n+1)||hu(e,t,r+1,n):(i===o||"_"===o)&&hu(e,t,r+1,n+1))}function du(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return pu(t.substring(n));if(n>=t.length)return pu(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?du(e,t,r+1,n+1)||du(e,t,r,n+1)||du(e,t,r+1,n):"%"===i||"%"===o?du(e,t,r,n+1)||du(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&du(e,t,r+1,n+1)}function fu(e){return!/[a-zA-Z]/.test(e)}function pu(e){return e.split("").every((e=>"%"===e))}function vu(e,t){return e.length>0&&pu(e)||t.length>0&&pu(t)||yu(e)&&0===t.length}function yu(e){let t=!1,r=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(r)return!1;r=!0;break;default:return!1}return t&&r}class bu{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Ue))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){const t=e.find(((e,t)=>{var r;return!he(this.query.sortOrder[t],Object.assign(Object.assign({},e),{asc:null===(r=e.asc)||void 0===r||r}))}));return!t}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,r){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:r})}isSubqueryOfCondition(e){return!!this.parsedConditions.filter((t=>t.fieldName===e.fieldName)).find((t=>this.evaluateSubset(t,e)))}isSubqueryOfConditions(e){return this.parseConditions(e).every((e=>this.isSubqueryOfCondition(e)))}isSubqueryOfQuery(e){if(e.collectionName!==this.collectionName||e.integrationId!==this.integrationId)return!1;const t=e.conditions.filter(Ue),r=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),i=-1===e.limit||this.limit>-1&&this.limit<e.limit;return r&&n&&i}getConditionsFor(...e){return this.parsedConditions.filter((t=>e.includes(t.fieldName)))}getConditionsForField(e){return this.parsedConditions.filter((t=>t.fieldName===e))}documentMatchesQuery(e){for(const t of this.parsedConditions){const r=t.fieldName,n=t.operator,i=oe(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!ut(t.value,i,n))return!1}else if(t.value.includes(i))return!1}return!0}evaluateSubset(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=lu[`${r}:${i}`];return!!s&&s(n,o)}evaluateIncludes(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=Array.isArray(n)?n.sort():n,a=Array.isArray(o)?o.sort():o;return i===r&&he(a,s)}parseConditions(e){const t=[],r=new Map,n=new Map;return e.forEach((e=>{switch(e.operator){case"==":case"in":r.set(e.fieldName,(r.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}})),r.forEach(((e,r)=>{t.push({fieldName:r,operator:"in",value:e})})),n.forEach(((e,r)=>{t.push({fieldName:r,operator:"not in",value:e})})),t}}class mu{constructor(e,t,r){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=r}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:r}=e,n=new bu(e),i=this.documentReferenceFactory.getDocumentsForCollection(t,r).filter((e=>n.documentMatchesQuery(e.data))),o={};return i.forEach((e=>{o[e.squidDocId]=e})),this.documentStore.sortAndLimitDocs(new Set(Object.keys(o)),e).map((e=>o[Ke(e.__docId__,r,t)]))}}function gu(e,t){return a((function(r,n){var i=0;r.subscribe(L(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class _u{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new o.BehaviorSubject(!0),this.inflightQueriesCount=new o.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const t=new o.Subject,r=(0,o.firstValueFrom)(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),r):(this.pendingQueryBatchTimeout=setTimeout((()=>{this.safeToSendQueriesToServer.pipe(gu(Boolean),(0,o.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),r)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=e.map((({queryRequest:e})=>e)),r=e.map((({responseSubject:e})=>e));this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const r=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,i=r.errors[e],o=r.results[e];i?n.error(i):n.next(o)}}catch(e){r.forEach((t=>t.error(e)))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}async waitForAllQueriesToFinish(){return(0,o.firstValueFrom)(this.inflightQueriesCount.pipe(gu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Ou,Su=r(4123);function Eu(e,t,r=((e,t)=>e>t?1:e<t?-1:0),n=0,i=e.length-1){if(i<n)return-1;const o=Math.trunc((n+i)/2);return 0===r(t,e[o])?o:r(t,e[o])>0?Eu(e,t,r,o+1,i):Eu(e,t,r,n,o-1)}function wu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==Eu(e,t,r))return;let n;for(n=e.length-1;n>=0&&r(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function Tu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){const n=Eu(e,t,r);n>-1&&e.splice(n,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Ou||(Ou={}));const Iu=100,Au=20;class Mu{constructor(e,t,r,n,i,s){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.querySender=s,this.onOrphanDocuments=new o.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new ku,this.queryResultsSubject=new o.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return(0,V.truthy)(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);(null==t?void 0:t.gotInitialResponse)&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=He(t),i=this.queryMappingManager.getMapping(r,n);return i?function(e,t){var r;const n=[...e.unconditional||[]],i=new Map;for(const[n,o]of Object.entries(e.conditional||{})){const e=_e(n);let s;if(Ue(e)){const n=null!==(r=oe(t,e.fieldName))&&void 0!==r?r:null;s=ut(e.value,n,e.operator)}else s=Fu(e,t);if(s)for(const e of o)i.set(e,(i.get(e)||0)+1)}for(const[t,r]of i.entries())r>=e.queriesMetadata[t].condCount&&n.push(t);return n}(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&&(this.destructManager.isDestructing?r.dataSubject.complete():r.dataSubject.error(t),r.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(r)||new Set,i=this.documentStore.sortAndLimitDocs(n,e.query),o=e.supportedQueries.map((e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(i,e))).some(Boolean);let s=e;for(;!s.allObservables;)s=(0,V.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case Ou.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+Iu?Ou.ENABLED:Ou.DISABLED;break;case Ou.DISABLED:break;case Ou.ENABLED:if(n.size<e.query.limit+Au){e.limitUnderflowState=Ou.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,V.truthy)(e.allObservables).next(t)}}isValidParent(e){if(!e.activated||e.isInFlight||e.isEmptyForJoin||e.done||!e.subscribe||!e.gotInitialResponse||!e.dataSubject.value)return!1;const t=-1===e.query.limit?1e3:e.query.limit;return e.dataSubject.value.length<t}findValidParentOfOngoingQuery(e){if(e.forceFetchFromServer)return;const t=new bu(e.query);for(const r of this.ongoingQueries.values()){if(e===r)return;if(this.isValidParent(r)&&t.isSubqueryOfQuery(r.query))return r}}findValidParentOfQuery(e){const t=new bu(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,s){return(0,o.defer)((()=>{const a=this.createOngoingQueryGraph(e,t,r,n,i,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new o.ReplaySubject(1);const u=a.allObservables.pipe((0,o.switchMap)((e=>(0,o.combineLatest)(e).pipe(Q((e=>this.joinResults(e,n,a)))))),gu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,o.startWith)(void 0),(0,o.pairwise)(),gu((([e,t])=>!he(e,t))),Q((([,e])=>e)),i?(0,o.tap)():(0,o.take)(1),(0,o.finalize)((()=>{var e;a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a).then(),null===(e=a.allObservables)||void 0===e||e.complete()}))),c=this.collectAllObservables(a);return a.allObservables.next(c),u})).pipe((0,o.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=(0,V.truthy)(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}registerQueryFinalizer(e){const t=e.clientRequestId,r=lt(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,o.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,o.firstValueFrom)((0,o.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(gu((e=>0===e))))),this.queryMappingManager.removeQuery(r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch((t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)})),gu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,s,a={}){if(a[t])return a[t];const u=U(),c=[],l={clientRequestId:u,activated:s,alias:t,query:e,subscribe:i,dataSubject:new o.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new o.BehaviorSubject(0),queryRegistered:new o.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:i?Ou.UNKNOWN:Ou.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[t]=l;for(const[e,o]of Object.entries(n)){const s=o.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,a);e.joinCondition=o,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(gu(Boolean),Q((e=>({docs:e,alias:r})))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=e.reduce(((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e)),{});let i=n[r.alias].map((e=>({[r.alias]:e})));const o=this.getOngoingQueriesBfs(r),s=new Set;for(let e=1;e<o.length;e++){const r=o[e].alias;s.has(r)||(s.add(r),i=this.join(i,r,n[r],t[r]))}return i}join(e,t,r,n){if(!e.length)return e;const i=Object.keys(e[0]);if(!n||!i.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const o=new Map;return(r||[]).forEach((e=>{const t=e[n.right];o.has(t)||o.set(t,[]),(0,V.truthy)(o.get(t)).push(e)})),e.flatMap((e=>{var r;const i=o.get(null===(r=e[n.leftAlias])||void 0===r?void 0:r[n.left])||[];return i.length?i.map((r=>Object.assign(Object.assign({},e),{[t]:r}))):n.isInner?[]:[Object.assign(Object.assign({},e),{[t]:void 0})]}))}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=(0,V.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=(0,V.truthy)(t.joinCondition),i=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const s=(0,V.truthy)(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(Ue).filter((e=>e.fieldName===n.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=fe(i);u.conditions=u.conditions.filter((e=>!Ue(e)||e.fieldName!==n.right)),[...a].forEach((e=>{u.conditions.push({fieldName:n.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},t),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new o.BehaviorSubject(null),clientRequestId:U(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,V.truthy)(t.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(t.activated=!0,i.conditions.filter(Ue).filter((e=>e.fieldName===n.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})).map((e=>({fieldName:n.right,operator:"==",value:e})));return r.length?(i.conditions.push(...r),this.sendQueryToServerOrUseParentQuery(t)):t.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=(0,V.truthy)(t.shift());t.push(...e.supportedQueries||[]),await(0,o.firstValueFrom)(e.unsubscribeBlockerCount.pipe(gu((e=>0===e)))),e.dataSubject.complete()}}preDestruct(){this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.dataSubject.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)}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const r=e.query,n=e.clientRequestId,i=lt(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(r,i),this.ongoingQueries.set(n,e);const o=t?void 0:this.findValidParentOfOngoingQuery(e);o?this.useParentOngoingQuery(e,o).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const r={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new bu(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,o.firstValueFrom)(t.queryRegistered.pipe(gu(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",r).then((()=>{e.isInFlight=!1,e.queryRegistered.next(!0)})).catch((r=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,r),e.dataSubject.error(r)),e.done=!0})).finally((()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)}));const i=(0,o.race)(e.queryRegistered.pipe(gu(Boolean),(0,o.delay)(2e3),(0,o.take)(1)),this.destructManager.observeIsDestructing().pipe((0,o.take)(1)));t.dataSubject.pipe((0,o.takeWhile)((()=>!e.done)),(0,o.takeUntil)(i),gu(Boolean),(0,o.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),Q((e=>e.filter((e=>n.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Ke(r.__docId__,e.query.collectionName,e.query.integrationId),r);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,r=t>0&&e.subscribe?t+Iu:t,n={query:Object.assign(Object.assign({},e.query),{limit:r}),clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).then((t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(we.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0}))}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e,!0)}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=>{ce(this.localDocumentToClientRequestIds,t,e[t])}))}}function Fu(e,t){var r;for(const n of e.fields){const e=null!==(r=oe(t,n.fieldName))&&void 0!==r?r:null;if(ut(n.value,e,n.operator))return!0;if(ut(n.value,e,"!="))return!1}return!1}class ku{constructor(){this.stateService=new Su.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(Ue(i)&&["=="].includes(i.operator)){const e=Oe(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];wu(s,t),this.stateService.set(o,s)}if(!e.conditions.length){const r=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(r)||[]];wu(n,t),this.stateService.set(r,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],r)})),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch((()=>{for(const r of t.conditions){const n=this.getConditionStatePath(t,r),i=[...this.stateService.get(n)||[]];Tu(i,e),i.length?this.stateService.set(n,i):this.stateService.delete(n)}if(!t.conditions.length){const r=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(r)||[]];Tu(n,e),this.stateService.set(r,n)}this.stateService.delete(this.getQueryMetadataStatePath(t,e))})),t}getMapping(e,t){return this.stateService.get(["queryMapping",e,t,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",(r=t,me(r))];var r}}class Du{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const t=Object.entries(this.locks).filter((([t])=>e.includes(t))).map((([,e])=>e));await(0,o.lastValueFrom)((0,o.combineLatest)(t).pipe((0,o.filter)((e=>!e.includes(!0))),(0,o.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,V.truthy)(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some((e=>{var t;return null===(t=this.locks[e])||void 0===t?void 0:t.value}))}lockSync(...e){(0,V.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new o.BehaviorSubject(!0)}}class ju{constructor(e,t,r){this.rpcManager=e,this.socketManager=t,this.queueManagers=new Map,this.socketManager.observeNotifications().subscribe((e=>{const t=this.getOrUndefined(e.integrationId,e.topicName);t&&t.onMessages(e.payload)})),r.onPreDestruct((()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()}))}get(e,t){let r=this.queueManagers.get(e);r||(r=new Map,this.queueManagers.set(e,r));let n=r.get(t);return n||(n=new Pu(e,t,this.rpcManager),r.set(t,n)),n}getOrUndefined(e,t){var r;return null===(r=this.queueManagers.get(e))||void 0===r?void 0:r.get(t)}}const xu="subscriptionMutex";class Pu{constructor(e,t,r){this.integrationId=e,this.topicName=t,this.rpcManager=r,this.messagesSubject=new o.Subject,this.subscriberCount=0,this.lockManager=new Du}async produce(e){await this.lockManager.lock(xu);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(xu)}}consume(){return(0,o.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,o.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(xu);try{await this.rpcManager.post("queue/subscribe",{integrationId:this.integrationId,topicName:this.topicName})}catch(e){this.messagesSubject.error(e),this.messagesSubject.complete(),this.subscriberCount=0,this.messagesSubject=new o.Subject}finally{this.lockManager.release(xu)}}async performUnsubscribe(){await this.lockManager.lock(xu);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(xu)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Nu{constructor(e,t){this.capacity=e,this.seconds=t,this.tokens=e,this.refillRatePerMs=e/(1e3*t),this.lastRefillTimestamp=Date.now()}async consume(){this.attemptConsume()||await(0,o.firstValueFrom)((0,o.interval)(10).pipe((0,o.filter)((()=>this.attemptConsume())),(0,o.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}class Cu extends Error{constructor(e,t,r,n,i,o){super(o||`RPC error ${e} ${t} calling ${r}`),this.statusCode=e,this.statusText=t,this.url=r,this.headers=n,this.body=i}}async function Ru(e){const t=await async function({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o}){const s=new Headers(e),a={method:"POST",headers:s,body:void 0};if(t.length){const e=new FormData;for(const n of t){const t=n instanceof Blob?n:n.blob,i=(Blob,n.name);e.append(r,t,i)}e.append("body",ge(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=ge(n);try{const e=await fetch(i,a),t={};if(e.headers.forEach(((e,r)=>{t[r]=e})),!e.ok){const r=await e.text(),n=qu(r);if(!o)throw new Cu(e.status,e.statusText,i,t,n,r);let s;try{s="string"==typeof n?n:(null==n?void 0:n.message)||r}catch(e){}throw s||(s=e.statusText),new Cu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return we.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw we.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=qu(t.body),t}function qu(e){if(e){try{return _e(e)}catch(e){}return e}}class Lu{constructor(e,t,r,n,i,s){this.region=e,this.appId=t,this.authManager=i,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new o.BehaviorSubject(0);for(const[e,t]of Object.entries(n))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),r.onDestruct((async()=>{await this.awaitAllSettled()}));const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Nu(60*a,5),ai:new Nu(20*a,5),secret:new Nu(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:r}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return r&&(n+=`; IntegrationId ${r}`),{Authorization:n}}async awaitAllSettled(){await(0,o.firstValueFrom)(this.onGoingRpcCounter.pipe((0,o.filter)((e=>0===e))))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,r=[],n="files"){return(await this.rawPost(e,t,r,n)).body}async rawPost(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),s=Object.assign(Object.assign({},this.staticHeaders),o);we.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=tu(this.region,this.appId,e);return await Ru({url:a,headers:s,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?(0,V.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,V.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,V.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Bu{constructor(e){this.rpcManager=e}reportMetric(e){const t={metrics:[e]};this.rpcManager.post("/observability/metrics",t)}}class Qu{constructor(e){this.rpcManager=e}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}upsert(e,t){return this.upsertMany([{key:e,value:t}]).then((e=>e[0]))}upsertMany(e){const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e){const t={keys:[e]};return this.rpcManager.post("secret/delete",t)}deleteMany(e){const t={keys:e};return this.rpcManager.post("secret/delete",t)}get apiKeys(){return new Vu(this.rpcManager)}}class Vu{constructor(e){this.rpcManager=e}get(e){const t={key:e};return this.rpcManager.post("secret/api-key/get",t)}getAll(){return this.rpcManager.post("secret/api-key/getAll",{})}upsert(e){const t={key:e};return this.rpcManager.post("secret/api-key/upsert",t)}delete(e){const t={key:e};return this.rpcManager.post("secret/api-key/delete",t)}}const Uu=e=>e();var zu;function Yu(){}const Wu="undefined"!=typeof process&&(null===(zu=process.versions)||void 0===zu?void 0:zu.node)?r(5086):Ee().WebSocket;class $u{constructor(e,t,r,n=Uu,i,s){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=s,this.webSocketObserver=new o.Subject,this.allMessagesObserver=new o.Subject,this.connectionReady=new o.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new o.Subject,this.connectedAtLeastOnce=!1,this.clientTooOldThreshold=3e4,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(),this.lastTick=new Date,this.tickInterval=setInterval((()=>this.tick()),5e3),this.observeConnectionReady().pipe((0,o.skip)(1),(0,o.filter)((e=>!e)),(0,o.switchMap)((()=>(0,o.race)((0,o.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,o.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?we.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(we.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,o.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?we.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?we.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(we.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),we.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(we.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,o.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var t;await(0,o.firstValueFrom)(this.connectionReady.pipe((0,o.filter)(Boolean)));const r=await this.authManager.getToken();if(this.connectionReady.value)try{(0,V.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=ge({message:e,authToken:r});we.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(r){(null===(t=this.socket)||void 0===t?void 0:t.connected)?console.error("Websocket message is ignored due to a non-recoverable error",r):(this.connectionReady.next(!1),await this.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){var e;(null===(e=this.socket)||void 0===e?void 0:e.connected)&&this.socket.send(ge({message:{type:"kill"}}))}closeCurrentSocketSilently(){if(this.socket)try{this.socket.close()}catch(e){}}connect(){this.closeCurrentSocketSilently(),this.connectionReady.value&&this.connectionReady.next(!1);const e=tu(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();we.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const r=`${e}?clientId=${t}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,closeCalled:!1,open(){var i;const s=null!==(i=null==Wu?void 0:Wu.WebSocket)&&void 0!==i?i:Wu;r=new s(e,t.protocols||[]),r.onmessage=t.onmessage?e=>{e.data&&t.onmessage?t.onmessage(e):console.log("No data received from websockets, please contact support@squid.cloud with this message.")}:Yu,r.onopen=function(e){o.connected=!0,(t.onopen||Yu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return we.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Yu)(e),void o.reconnect(e);(t.onclose||Yu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):o.closeCalled||(t.onerror||Yu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Yu)(e),we.debug("WebSocket trying to reconnect..."),o.open()}),t.timeoutMillis||1e3):(t.onmaximum||Yu)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){o.closeCalled=!0;try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(r,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{we.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{we.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{we.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){var e;this.connectionReady.next(!1),null===(e=this.socket)||void 0===e||e.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return we.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=_e(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),we.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new o.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,o.tap)((e=>t.push(e))),(0,o.debounceTime)(100)).subscribe((async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){this.sendKillMessage(),await(0,o.firstValueFrom)((0,o.timer)(0)),this.connectionReady.next(!1),await(0,o.firstValueFrom)((0,o.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Gu(e,t){return`${function(e){(0,V.assertString)(e,"Invalid application ID");const[t,r,n,i]=e.split("-");return(0,V.assertTruthy)(!i,`Invalid application ID: ${e}`),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class Hu{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,r){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:r};await this.rpcManager.post("storage/uploadFile",n,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const r={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",r)}async listDirectoryContents(e){const t={integrationId:this.integrationId,dirPathInBucket:e};return await this.rpcManager.post("storage/listDirectoryContents",t)}async deleteFile(e){await this.deleteFiles([e])}async deleteFiles(e){const t={integrationId:this.integrationId,filePathsInBucket:e};await this.rpcManager.post("storage/deleteFiles",t)}}class Ku{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e){return await this.rpcManager.post("documentExtraction/extractDataFromDocumentFile",{},[e])}}class Ju{constructor(e){this.options=e,this.destructManager=new Et,(0,V.assertTruthy)(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,r=function(e,t,r){return`${Gu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return ru(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new Te(this.destructManager),this.authManager=new ne(e.apiKey,e.authProvider),this.socketManager=new $u(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Lu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new X(this.rpcManager,this.socketManager),this.aiClient=new ee(this.aiClientFactory,this.rpcManager),this.apiClient=new re(this.rpcManager),this.documentStore=new Mt,this.lockManager=new Du,this.distributedLockManager=new wt(this.socketManager,this.destructManager),this.documentIdentityService=new It(this.documentStore,this.destructManager),this.documentReferenceFactory=new At(this.documentIdentityService),this.querySender=new _u(this.rpcManager,this.destructManager),this.observabilityClient=new Bu(this.rpcManager),this.querySubscriptionManager=new Mu(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new mu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new ou(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Ze(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new Ot(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new ft(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new Se(this.clientIdService,this.rpcManager),this.nativeQueryManager=new su(this.rpcManager),this.graphqlClientFactory=new iu(this.rpcManager,e.region,r),this.secretClient=new Qu(this.rpcManager),this._connectionDetails=new pt(this.clientIdService,this.socketManager),this.queueManagerFactory=new ju(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=me(e);let r=Ju.squidInstancesMap[t];return r||(r=new Ju(e),Ju.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Ju.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Be.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),(0,o.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))}executeNativeRelationalQuery(e,t,r={}){const n={type:"relational",query:t,params:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,r){const n={type:"mongo",collectionName:t,aggregationPipeline:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}graphql(e){return this._validateNotDestructed(),this.graphqlClientFactory.get(e)}ai(){return this._validateNotDestructed(),this.aiClient}api(){return this._validateNotDestructed(),this.apiClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Hu(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new Ku(this.rpcManager)}get secrets(){return this.secretClient}get observability(){return this.observabilityClient}acquireLock(e){return this._validateNotDestructed(),this.distributedLockManager.lock(e)}async withLock(e,t){const r=await this.acquireLock(e);try{return await t(r)}finally{r.release()}}queue(e,t=Be.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries(Ju.squidInstancesMap).find((([,e])=>e===this));e&&delete Ju.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,V.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,r)=>tu(e,t,r),getStaticHeaders:()=>e.getStaticHeaders()}}}Ju.squidInstancesMap={};var Xu=exports;for(var Zu in n)Xu[Zu]=n[Zu];n.__esModule&&Object.defineProperty(Xu,"__esModule",{value:!0})})();
@@ -1,8 +1,3 @@
1
- export interface ExtractDataFromDocumentFileRequest {
2
- extractImages?: boolean;
3
- minImageWidth?: number;
4
- minImageHeight?: number;
5
- }
6
1
  export type DocumentFileDataType = 'image';
7
2
  export interface DocumentFileData {
8
3
  type: DocumentFileDataType;
@@ -16,3 +11,9 @@ export interface ExtractDataFromDocumentResponse {
16
11
  documentPathInBucket?: string;
17
12
  pages: DocumentPageData[];
18
13
  }
14
+ export interface TextOnlyPageData {
15
+ text: string;
16
+ }
17
+ export interface DocumentTextDataResponse {
18
+ pages: TextOnlyPageData[];
19
+ }
@@ -1,6 +1,6 @@
1
1
  import { BlobAndFilename } from './types';
2
- import { ExtractDataFromDocumentFileRequest, ExtractDataFromDocumentResponse } from '../../internal-common/src/public-types/extraction.public-types';
2
+ import { DocumentTextDataResponse } from '../../internal-common/src/public-types/extraction.public-types';
3
3
  export declare class ExtractionClient {
4
4
  private readonly rpcManager;
5
- extractDataFromDocumentFile(file: File | BlobAndFilename, options: ExtractDataFromDocumentFileRequest): Promise<ExtractDataFromDocumentResponse>;
5
+ extractDataFromDocumentFile(file: File | BlobAndFilename): Promise<DocumentTextDataResponse>;
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squidcloud/client",
3
- "version": "1.0.251",
3
+ "version": "1.0.253",
4
4
  "description": "A typescript implementation of the Squid client",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/typescript-client/src/index.d.ts",