@squidcloud/client 1.0.413 → 1.0.415
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 +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/internal-common/src/public-types/ai-agent.public-types.d.ts +20 -18
- package/dist/internal-common/src/public-types/ai-common.public-types.d.ts +8 -0
- package/dist/internal-common/src/public-types/external-auth/external-auth.public-types.d.ts +39 -0
- package/dist/internal-common/src/public-types/integration.public-types.d.ts +2 -2
- package/dist/typescript-client/src/agent/ai-agent-client-reference.d.ts +19 -6
- package/dist/typescript-client/src/agent/ai-agent-client.d.ts +12 -1
- package/dist/typescript-client/src/ai-client.d.ts +2 -1
- package/dist/typescript-client/src/distributed-lock.manager.d.ts +6 -2
- package/dist/typescript-client/src/external-auth-client.d.ts +36 -0
- package/dist/typescript-client/src/index.d.ts +1 -0
- package/dist/typescript-client/src/public-types.d.ts +1 -0
- package/dist/typescript-client/src/squid.d.ts +12 -0
- package/dist/typescript-client/src/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var e={86:e=>{e.exports=require("ws")},150:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const s=i(261);t.default=s.PromisePool,r(i(273),t),r(i(261),t),r(i(837),t),r(i(426),t),r(i(858),t),r(i(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(261),r=i(172),s=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw r.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}isValidConcurrency(e){return"number"==typeof e&&e>=1}withTaskTimeout(e){return this.meta.taskTimeout=e,this}concurrency(){return this.meta.concurrency}useCorrespondingResults(e){return this.meta.shouldResultsCorrespond=e,this}shouldUseCorrespondingResults(){return this.meta.shouldResultsCorrespond}taskTimeout(){return this.meta.taskTimeout}for(e){return this.meta.items=e,this}items(){return this.meta.items}itemsCount(){const e=this.items();return Array.isArray(e)?e.length:NaN}tasks(){return this.meta.tasks}activeTaskCount(){return this.activeTasksCount()}activeTasksCount(){return this.tasks().length}processedItems(){return this.meta.processedItems}processedCount(){return this.processedItems().length}processedPercentage(){return this.processedCount()/this.itemsCount()*100}results(){return this.meta.results}errors(){return this.meta.errors}withHandler(e){return this.handler=e,this}hasErrorHandler(){return!!this.errorHandler}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers=e,this}onTaskFinished(e){return this.onTaskFinishedHandlers=e,this}hasReachedConcurrencyLimit(){return this.activeTasksCount()>=this.concurrency()}stop(){throw this.markAsStopped(),new o.StopThePromisePoolError}markAsStopped(){return this.meta.stopped=!0,this}isStopped(){return this.meta.stopped}async start(){return await this.validateInputs().prepareResultsArray().process()}validateInputs(){if("function"!=typeof this.handler)throw r.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw r.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw r.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return!!Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()?(this.meta.results=Array(e.length).fill(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new s.PromisePoolError(`Task in promise pool timed out after ${this.taskTimeout()}ms`,e))},this.taskTimeout())}),()=>clearTimeout(t)]}save(e,t){return this.shouldUseCorrespondingResults()?this.results()[t]=e:this.results().push(e),this}removeActive(e){return this.tasks().splice(this.tasks().indexOf(e),1),this}async handleErrorFor(e,t,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof r.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(s.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},261:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class r{constructor(e){this.timeout=void 0,this.concurrency=10,this.items=e??[],this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[],this.shouldResultsCorrespond=!1}withConcurrency(e){return this.concurrency=e,this}static withConcurrency(e){return(new this).withConcurrency(e)}withTaskTimeout(e){return this.timeout=e,this}static withTaskTimeout(e){return(new this).withTaskTimeout(e)}for(e){const t=new r(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=r,r.notRun=Symbol("notRun"),r.failed=Symbol("failed")},273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},426:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};i.r(n),i.d(n,{AI_AGENTS_INTEGRATION_ID:()=>Qe,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Fe,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Re,AI_CHAT_MESSAGE_SOURCE:()=>pe,AI_EMBEDDINGS_MODEL_NAMES:()=>_e,AI_IMAGE_MODEL_NAMES:()=>Ne,AI_PROVIDER_TYPES:()=>me,AI_STATUS_MESSAGE_PARENT_MESSAGE_ID_TAG:()=>ge,AI_STATUS_MESSAGE_RESULT_TAG:()=>fe,ALL_OPERATORS:()=>rt,ANTHROPIC_CHAT_MODEL_NAMES:()=>ve,API_INJECTION_FIELD_TYPES:()=>Pe,ARRAY_OPERATORS:()=>nt,AUTH_INTEGRATION_TYPES:()=>Ge,AdminClient:()=>l,AiAgentClient:()=>ne,AiAgentReference:()=>te,AiAssistantClient:()=>se,AiAudioClient:()=>oe,AiClient:()=>at,AiImageClient:()=>ae,AiKnowledgeBaseClient:()=>le,AiKnowledgeBaseReference:()=>ue,AiMatchMakingClient:()=>he,ApiClient:()=>ut,ApiKeysSecretClient:()=>u,AuthManager:()=>lt,BUILT_IN_AGENT_ID:()=>G,BUILT_IN_DB_INTEGRATION_ID:()=>Ke,BUILT_IN_QUEUE_INTEGRATION_ID:()=>ze,BUILT_IN_STORAGE_INTEGRATION_ID:()=>Je,BackendFunctionManager:()=>Rt,BaseQueryBuilder:()=>Yt,CLIENT_CONNECTION_STATES:()=>ot,CLIENT_ID_GENERATOR_KEY:()=>Bt,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>Lt,Changes:()=>ei,ClientIdService:()=>Pt,CollectionReference:()=>si,CollectionReferenceFactory:()=>ai,ConnectionDetails:()=>ci,DATA_INTEGRATION_TYPES:()=>$e,DEFAULT_SHORT_ID_LENGTH:()=>K,DataManager:()=>mi,DereferencedJoin:()=>ii,DestructManager:()=>Ii,DistributedLockImpl:()=>vi,DistributedLockManager:()=>Si,DocumentReference:()=>Kt,DocumentReferenceFactory:()=>Mi,DocumentStore:()=>Ti,EMPTY_CHAT_ID:()=>re,ENVIRONMENT_IDS:()=>$,ExtractionClient:()=>ki,FETCH_BEYOND_LIMIT:()=>In,FLUX_MODEL_NAMES:()=>qe,GEMINI_CHAT_MODEL_NAMES:()=>Ie,GRAPHQL_INTEGRATION_TYPES:()=>Ve,GROK_CHAT_MODEL_NAMES:()=>Se,GroupedJoin:()=>ri,HTTP_INTEGRATION_TYPES:()=>He,HttpStatus:()=>Le,INTEGRATION_SCHEMA_TYPES:()=>We,INTEGRATION_TYPES:()=>Ue,IntegrationClient:()=>a,JobClient:()=>_i,JoinQueryBuilder:()=>ti,LastUsedValueExecuteFunctionCache:()=>At,LimitUnderflowState:()=>dn,LocalQueryManager:()=>Wi,METRIC_DOMAIN:()=>tt,METRIC_FUNCTIONS:()=>et,METRIC_INTERVAL_ALIGNMENT:()=>it,MatchMaker:()=>de,MutationSender:()=>Ei,NOOP_FN:()=>Dn,NativeQueryManager:()=>Oi,NotificationClient:()=>Ci,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Ce,OPENAI_AUDIO_MODEL_NAMES:()=>De,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Oe,OPENAI_CHAT_MODEL_NAMES:()=>be,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>Te,OPENAI_IMAGE_MODEL_NAMES:()=>Ee,OPEN_AI_CREATE_SPEECH_FORMATS:()=>xe,ObservabilityClient:()=>Ai,Pagination:()=>zt,PersonalStorageClient:()=>Ri,QueryBuilder:()=>Xt,QueryBuilderFactory:()=>Jt,QuerySender:()=>zi,QuerySubscriptionManager:()=>Sn,QueueManagerFactory:()=>Tn,QueueManagerImpl:()=>_n,RAG_TYPES:()=>je,RERANK_PROVIDERS:()=>ye,RateLimiter:()=>En,RpcManager:()=>Ln,SQUID_BUILT_IN_INTEGRATION_IDS:()=>Ye,SQUID_METRIC_NAMES:()=>Xe,SQUID_REGIONS:()=>st,STABLE_DIFFUSION_MODEL_NAMES:()=>Ae,SchedulerClient:()=>Qn,SecretClient:()=>c,SocketManager:()=>Gn,Squid:()=>Zn,SquidClientError:()=>An,StorageClient:()=>zn,VENDOR_AI_CHAT_MODEL_NAMES:()=>we,VOYAGE_EMBEDDING_MODEL_NAMES:()=>ke,WebClient:()=>Jn,WebhookManager:()=>Yn,base64ToFile:()=>ee,compareArgsByReference:()=>Ct,compareArgsBySerializedValue:()=>Dt,deserializeQuery:()=>xi,generateId:()=>W,generateShortId:()=>J,generateShortIds:()=>Y,generateUUID:()=>V,generateUUIDPolyfill:()=>H,getConsoleUrl:()=>o,getCustomizationFlag:()=>Ft,isBuiltInIntegrationId:()=>Ze,isPlaceholderParam:()=>Be,isVendorAiChatModelName:()=>Me,rawSquidHttpDelete:()=>jn,rawSquidHttpGet:()=>Rn,rawSquidHttpPatch:()=>xn,rawSquidHttpPost:()=>Nn,rawSquidHttpPut:()=>Fn,transformFileArgs:()=>qt,tryDeserializing:()=>Bn,visitQueryResults:()=>Fi});const r=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function s(e,t,i,n,s,o){let a="https",c=`${n||t}.${s||e}.${new URL("https://squid.cloud").host}`,u="";/^local/.test(e)&&(a="http",u=r.includes(i.replace(/^\//,"").split("/")[0]||"")||o?"8001":"8000",/android$/.test(e)?c="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(c="localhost"));const l=a+"://"+c+(u?`:${u}`:""),h=i.replace(/^\/+/,"");return h?`${l}/${h}`:l}function o(e,t,i=""){return s(function(e,t){return t||(e.includes("sandbox")?"us-east-1.aws.sandbox":e.includes("local")?"local":e.includes("staging")?"us-central1.gcp.staging":"us-east-1.aws")}(e,t),"console",i)}class a{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async setIntegrationSchema(e,t){await this.rpcManager.put(`${this.iacBaseUrl}/${e}/schema`,t)}async delete(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}async deleteMany(e){await Promise.all(e.map(e=>this.delete(e)))}async upsertIntegration(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e.id}`,e)}}class c{constructor(e){this.rpcManager=e}get apiKeys(){return new u(this.rpcManager)}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}async upsert(e,t){return this.upsertMany([{key:e,value:t}]).then(e=>e[0])}async upsertMany(e){if(0===e.length)return[];const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e,t=!1){const i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}}class u{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)}}class l{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new a(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new c(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}const h=require("rxjs");function d(e){return"function"==typeof e}function p(e){return function(t){if(function(e){return d(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}var g=function(e,t){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},g(e,t)};function f(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}g(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function y(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}function b(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var I,S=((I=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}(function(e){Error.call(e),e.stack=(new Error).stack})).prototype=Object.create(Error.prototype),I.prototype.constructor=I,I);function v(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var w=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,i,n,r;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=y(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(d(c))try{c()}catch(e){r=e instanceof S?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=y(u),h=l.next();!h.done;h=l.next()){var p=h.value;try{M(p)}catch(e){r=null!=r?r:[],e instanceof S?r=b(b([],m(r)),m(e.errors)):r.push(e)}}}catch(e){i={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(r)throw new S(r)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)M(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&v(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&v(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function M(e){d(e)?e():e.unsubscribe()}w.EMPTY;var T={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var r=T.delegate;return(null==r?void 0:r.setTimeout)?r.setTimeout.apply(r,b([e,t],m(i))):setTimeout.apply(void 0,b([e,t],m(i)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function k(){}var _=E("C",void 0,void 0);function E(e,t,i){return{kind:e,value:t,error:i}}var O=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof w||i&&"closed"in i&&d(i.remove)&&d(i.add)&&d(i.unsubscribe))&&t.add(n)):n.destination=N,n}return f(t,e),t.create=function(e,t,i){return new D(e,t,i)},t.prototype.next=function(e){this.isStopped?q(function(e){return E("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?q(E("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?q(_,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(w);Function.prototype.bind;var C=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){A(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){A(e)}else A(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){A(e)}},e}(),D=function(e){function t(t,i,n){var r,s=e.call(this)||this;return r=d(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,s.destination=new C(r),s}return f(t,e),t}(O);function A(e){!function(e){T.setTimeout(function(){throw e})}(e)}function q(e,t){var i=null;i&&T.setTimeout(function(){return i(e,t)})}var N={closed:!0,next:k,error:function(e){throw e},complete:k};function R(e,t,i,n,r){return new F(e,t,i,n,r)}var F=function(e){function t(t,i,n,r,s,o){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=r?function(e){try{r(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return f(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(O);function x(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){n.next(e.call(t,i,r++))}))})}function j(e){return null!=e}let P=e=>new Error(e);function B(e,t,...i){e||function(e,...t){const i=Q(e);if("object"==typeof i)throw i;throw P(i||"Assertion error",...t)}(t,...i)}function L(e,t,...i){return B(e,t,...i),e}function Q(e){return void 0===e?"":"string"==typeof e?e:e()}function U(e,t,i){const n=Q(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}const $=["dev","prod"],G="built_in_agent";function V(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():H()}function H(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function W(){return V()}const K=18,z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function J(e=K,t=""){B(t.length<e,"ID prefix is too long");let i="";for(let t=0;t<e;t++)i+=z.charAt(Math.floor(Math.random()*z.length));return t.length>0&&(i=t+i.substring(t.length)),i}function Y({count:e,length:t,prefix:i}){B(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(J(t||K,i||""));return[...n]}const Z=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function X(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)X(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)X(t);else for(const t in e){if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata filter key ${t} - can only contain letters, numbers, and underscores`);if(Z.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Z.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function ee(e,t,i){const n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new File([r],t,{type:i||"application/octet-stream"})}class te{constructor(e,t,i,n,r,s){this.agentId=e,this.ongoingChatSequences=t,this.rpcManager=i,this.socketManager=n,this.jobClient=r,this.backendFunctionManager=s}async get(){const e=await this.rpcManager.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.rpcManager.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.rpcManager.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){await this.setAgentOptionInPath("instructions",e)}async updateModel(e){await this.setAgentOptionInPath("model",e)}async updateConnectedAgents(e){await this.setAgentOptionInPath("connectedAgents",e)}async updateGuardrails(e){const t=await this.get();B(t,"Agent not found");const i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}async updateCustomGuardrails(e){await this.rpcManager.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.rpcManager.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),r=await L(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:r.transcribedPrompt}}async search(e){B(this.agentId!==G,"Cannot search the built-in agent");const t={options:e,agentId:this.agentId};return(await this.rpcManager.post("ai/chatbot/search",t)).chunks}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);return this.replaceFileTags(n.responseString,n.annotations)}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:i,jobId:t};await this.rpcManager.post("ai/chatbot/askAsync",n)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiStatus"===e.type&&e.agentId===this.agentId),x(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,messageId:e.messageId})))}async getChatHistory(e){const t={agentId:this.agentId,memoryId:e};return(await this.rpcManager.post("ai/chatbot/history",t)).messages}async transcribeAndAsk(e,t,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:ee(r.base64File,`voice.${r.extension}`,r.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:ee(r.base64File,`voice.${r.extension}`,r.mimeType)}}async setAgentOptionInPath(e,t){await this.rpcManager.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const r=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${r}](${n.aiFileUrl.url})`}i=i.replace(`\${id:${e}}`,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&X(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)X(i.contextMetadataFilterForKnowledgeBase[e]);n=n||V(),i={...ie,...i||{}};const r="string"==typeof e;let s="ai/chatbot/";s+=r||t?!r&&t?"transcribeAndAskWithVoiceResponse":r&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:r?e:void 0,options:i,jobId:n},a=r?void 0:[e];return await this.rpcManager.post(s,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&X(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)X(t.contextMetadataFilterForKnowledgeBase[e]);const n=V(),r=void 0===(t={...ie,...t||{}}).smoothTyping||t.smoothTyping;let s="";const o=new h.Subject,a=new h.Subject;this.ongoingChatSequences[n]=a;let c=-1;a.pipe((0,h.tap)(({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)}),(0,h.concatMap)(({value:e,complete:t,annotations:i})=>t?(0,h.of)({value:e,complete:t,annotations:i}):(0,h.of)(e).pipe(r?(0,h.delay)(0):(0,h.tap)(),x(e=>({value:e,complete:!1,annotations:void 0})))),(0,h.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{s+=e,t&&i&&(s=this.replaceFileTags(s,i)),o.next(s)},error:e=>{console.error(e)},complete:()=>{o.complete()}});const u="string"==typeof e;i=i||V();const l={agentId:this.agentId,jobId:i,prompt:u?e:void 0,options:t,clientRequestId:n},d={responseStream:o.pipe((0,h.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,h.share)())};return u?this.rpcManager.post("ai/chatbot/chat",l).catch(e=>{o.error(e),o.complete()}):this.rpcManager.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch(e=>{throw o.error(e),o.complete(),e}),d.serverResponse=this.jobClient.awaitJob(i).catch(e=>{o.error(e),o.complete()}),d}}const ie={smoothTyping:!0,responseFormat:"text"};class ne{constructor(e,t,i,n){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiChatbot"===e.type),x(e=>e)).subscribe(e=>{this.handleChatResponse(e).then()})}agent(e){return new te(e,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)}async listAgents(){return(await this.rpcManager.post("ai/agent/listAgents",{})).agents}async handleChatResponse(e){const t=this.ongoingChatSequences[e.clientRequestId];if(!t)return;const{token:i,complete:n,tokenIndex:r,annotations:s}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:s});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===r?void 0:r,annotations:s});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===r?void 0:r,annotations:s})}}const re="__squid_empty_chat_id";class se{constructor(e){this.rpcManager=e}async createAssistant(e,t,i,n){const r={name:e,instructions:t,functions:i,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",r)).assistantId}async deleteAssistant(e){const t={assistantId:e};await this.rpcManager.post("ai/assistant/deleteAssistant",t)}async createThread(e){const t={assistantId:e};return(await this.rpcManager.post("ai/assistant/createThread",t)).threadId}async deleteThread(e){const t={threadId:e};await this.rpcManager.post("ai/assistant/deleteThread",t)}async queryAssistant(e,t,i,n,r){const s={assistantId:e,threadId:t,prompt:i,fileIds:n,options:r};return(await this.rpcManager.post("ai/assistant/queryAssistant",s)).answer}async addFileToAssistant(e,t){const i={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",i,[t],"file")).fileId}async removeFileFromAssistant(e,t){const i={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",i)}async addFileToThread(e,t){const i={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",i,[t],"file")).fileId}}class oe{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return ee(n.base64File,`audio.${n.extension}`,n.mimeType)}}class ae{constructor(e){this.rpcManager=e}async generate(e,t){const i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function ce(e){for(const t in e){const i=e[t];B("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),B(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class ue{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(e){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId,truncateTextAfter:e})).contexts||[]}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}async getContext(e){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e})).context}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/knowledge-base/deleteContexts",{knowledgeBaseId:this.knowledgeBaseId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&ce(t.metadata);const i=V();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}async searchContextsWithPrompt(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithPrompt",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async searchContextsWithContextId(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithContextId",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async downloadContext(e){const t={knowledgeBaseId:this.knowledgeBaseId,contextId:e};return await this.rpcManager.post("ai/knowledge-base/downloadContext",t)}}class le{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new ue(e,this.rpcManager,this.jobClient)}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async delete(e){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:e})}}class he{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new de(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new de(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class de{constructor(e,t){this.matchMaker=e,this.rpcManager=t,this.id=e.id}async insertEntity(e){await this.rpcManager.post("matchMaking/insertEntity",{matchMakerId:this.id,entity:e})}async insertManyEntities(e){await this.rpcManager.post("matchMaking/insertEntities",{matchMakerId:this.id,entities:e})}async delete(){await this.rpcManager.post("matchMaking/deleteMatchMaker",{matchMakerId:this.id})}async deleteEntity(e){await this.rpcManager.post("matchMaking/deleteEntity",{entityId:e,matchMakerId:this.id})}async findMatches(e,t={}){return(await this.rpcManager.post("matchMaking/findMatches",{matchMakerId:this.id,entityId:e,options:t})).matches}async findMatchesForEntity(e,t={}){return(await this.rpcManager.post("matchMaking/findMatchesForEntity",{matchMakerId:this.id,entity:e,options:t})).matches}async listEntities(e,t={}){return await this.rpcManager.post("matchMaking/listEntities",{categoryId:e,options:t,matchMakerId:this.id})}async getEntity(e){return(await this.rpcManager.post("matchMaking/getEntity",{matchMakerId:this.id,entityId:e})).entity}getMatchMakerDetails(){return this.matchMaker}}const pe=["user","ai"],ge="parent",fe="result",ye=["cohere","none"],me=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],be=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],Ie=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],Se=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4","grok-4-fast-reasoning","grok-4-fast-non-reasoning"],ve=["claude-3-7-sonnet-latest","claude-haiku-4-5-20251001","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-sonnet-4-20250514","claude-sonnet-4-5-20250929"],we=[...be,...ve,...Ie,...Se];function Me(e){return we.includes(e)}const Te=["text-embedding-3-small"],ke=["voyage-3-large"],_e=[...Te,...ke],Ee=["dall-e-3"],Oe=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],Ce=["tts-1","tts-1-hd","gpt-4o-mini-tts"],De=[...Oe,...Ce],Ae=["stable-diffusion-core"],qe=["flux-pro-1.1","flux-kontext-pro"],Ne=[...Ee,...Ae,...qe],Re=[...Oe],Fe=[...Ce],xe=["mp3","opus","aac","flac","wav","pcm"],je=["contextual","basic"],Pe=["secret","regular"];function Be(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Le={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,MOVED_TEMPORARILY:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,REQUEST_TOO_LONG:413,REQUEST_URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,REQUESTED_RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,INSUFFICIENT_SPACE_ON_RESOURCE:419,METHOD_FAILURE:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},Qe="ai_agents",Ue=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","built_in_db","built_in_gcs","built_in_queue","built_in_s3","cassandra","clickhouse","cloudsql","cockroach","cognito","connected_knowledgebases","confluence","confluent","datadog","db2","descope","documentdb","dynamodb","elasticsearch","firebase_auth","firestore","gcs","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce_crm","sap_hana","sentry","servicenow","snowflake","spanner","xata","zendesk","mail","slack","mcp","a2a","legend"],$e=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch","legend"],Ge=["auth0","jwt_rsa","jwt_hmac","cognito","okta","descope","firebase_auth"],Ve=["graphql","linear"],He=["api"],We=["data","api","graphql"],Ke="built_in_db",ze="built_in_queue",Je="built_in_storage",Ye=[Ke,ze,Je];function Ze(e){return Ye.includes(e)}const Xe=["squid_functionExecution_count","squid_functionExecution_time"],et=["sum","max","min","average","median","p95","p99","count"],tt=["user","squid"],it=["align-by-start-time","align-by-end-time"],nt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],rt=[...nt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],st=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],ot=["CONNECTED","DISCONNECTED","REMOVED"];class at{constructor(e,t,i,n){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.backendFunctionManager=n,this.aiAssistantClient=new se(this.rpcManager)}agent(e=G){return this.getAiAgentClient().agent(e)}knowledgeBase(e){return this.getAiKnowledgeBaseClient().knowledgeBase(e)}async listAgents(){return this.getAiAgentClient().listAgents()}async listKnowledgeBases(){return this.getAiKnowledgeBaseClient().listKnowledgeBases()}assistant(){return this.aiAssistantClient}image(){return new ae(this.rpcManager)}audio(){return new oe(this.rpcManager)}matchMaking(){return new he(this.rpcManager)}executeAiQuery(e,t,i){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,i,n){const r={integrationId:e,prompt:t,allowedEndpoints:i,provideExplanation:n};return this.rpcManager.post("ai/query/executeApiQuery",r)}async getApplicationAiSettings(){return(await this.rpcManager.post("ai/settings/getApplicationAiSettings",{})).settings}async setApplicationAiSettings(e){const t={settings:e};await this.rpcManager.post("ai/settings/setApplicationAiSettings",t)}async setAiProviderApiKeySecret(e,t){const i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new ne(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new le(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const ct={headers:{},queryParams:{},pathParams:{}};class ut{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,r){const s={integrationId:e,endpointId:t,body:i,options:{...ct,...this.convertOptionsToStrings(n||{})},overrideMethod:r};return await this.rpcManager.rawPost("api/callApi",s,void 0,void 0,!1)}convertOptionsToStrings(e){return{headers:this.convertToStrings(e.headers),queryParams:this.convertToStrings(e.queryParams),pathParams:this.convertToStrings(e.pathParams)}}convertToStrings(e){if(!e)return{};const t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,String(t)]);return Object.fromEntries(t)}}class lt{constructor(e,t){this.apiKey=e,this.authProvider=t}setAuthProvider(e){this.authProvider=e}async getAuthData(){return{token:await this.getTokenFromAuthProvider(),integrationId:this.authProvider?.integrationId}}getApiKey(){return this.apiKey}async getToken(){if(this.apiKey)return{type:"ApiKey",token:this.apiKey};const e=await this.getTokenFromAuthProvider();return e?{type:"Bearer",token:e,integrationId:this.authProvider?.integrationId}:void 0}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}}const ht=/[.\[\]]/;function dt(e,t){if(!e)return;const i=t.split(ht);let n,r=e;for(;r&&i.length;){const e=i.shift();if(e){if("object"!=typeof r||!(e in r))return;n=r[e],r=n}}return n}function pt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function gt(e,t,i,n="."){const r=t.split(n);let s=e;for(;r.length;){const e=L(r.shift());if(r.length){const t=s[e],i=pt(t)?vt(t)??{}:{};s[e]=i,s=i}else s[e]=i}}function ft(e,t,i="."){const n=t.split(i);let r=e;for(;n.length;){const e=L(n.shift());if(n.length){const t=pt(r[e])?vt(r[e])??{}:{};r[e]=t,r=t}else delete r[e]}}function yt(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function mt(e){return null==e}function bt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const i=typeof e;if(i!==typeof t)return!1;if("object"!==i)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i)||!bt(e[i],t[i]))return!1;return!0}function It(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=St(e[n],t);return i}function St(e,t){const i=t?t(e):void 0;if(void 0!==i)return i;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return It(e,t);if(e instanceof Map)return new Map(It(Array.from(e),t));if(e instanceof Set)return new Set(It(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const r={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(r[i]=St(e[i],t));return r}function vt(e){return"object"!=typeof e||null===e?e:e instanceof Date?new Date(e):Array.isArray(e)?[...e]:e instanceof Map?new Map(Array.from(e)):e instanceof Set?new Set(Array.from(e)):{...e}}function wt(e,t){if(e===t||mt(e)&&mt(t))return 0;if(mt(e))return-1;if(mt(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(B("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(B("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(B("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(B("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function Mt(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function Tt(e){if(Array.isArray(e))return e.map(e=>Tt(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),i={};return t.sort().forEach(t=>{i[t]=Tt(e[t])}),i}function kt(e){return _t(Tt(e))}function _t(e){if(void 0===e)return null;const t=St(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Et(e){return St(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,i=t.$date;return i&&1===Object.keys(t).length?new Date(i):void 0})}function Ot(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=_t(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}}const Ct=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},Dt=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(_t(e[i])!==_t(t[i]))return!1;return!0};class At{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Ct,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function qt(e){const t=[],i=[];let n=0;for(const r of e)if("undefined"!=typeof File)if(r instanceof File){i.push(r);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(Nt(r)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:r.map((e,t)=>(i.push(r[t]),n++))};t.push(e)}else t.push(r);else t.push(r);return{argsArray:t,fileArray:i}}function Nt(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class Rt{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:n,fileArray:r}=qt(i),s="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(n);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?Ct:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===s&&e(t.args,n));if(t)return t.promise}const u=this.createExecuteCallPromise(s,n,r,a,t);return c&&(this.inFlightDedupCalls.push({functionName:s,args:n,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}createExecuteCallPromise(e,t,i,n,r={}){const s=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:_t(t)};return(0,h.firstValueFrom)((0,h.race)((0,h.from)(this.rpcManager.post(s,o,i.length>0?i:[],"files",r)).pipe(x(e=>{if(!e.success)throw new Error(e.payload);const i=Et(e.payload);if(i?.__isSquidBase64File__){const e=i;return ee(e.base64,e.filename,e.mimetype)}return n&&n.set(t,i),i}))))}}function Ft(e){if("undefined"!=typeof globalThis)return globalThis[e]}function xt(){if("undefined"!=typeof window)return window;if(void 0!==i.g)return i.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){xt().SQUID_LOG_DEBUG_ENABLED=e}(function(){let e="";return"undefined"!=typeof window&&window.location?e=new URLSearchParams(window.location.search).get("SQUID_DEBUG")||"":"undefined"!=typeof process&&process.env&&(e=process.env.SQUID_DEBUG||""),"1"===e||"true"===e}());class jt{static debug(...e){(function(){const e=xt();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=xt();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Pt{constructor(e){this.destructManager=e,this.clientTooOldSubject=new h.BehaviorSubject(!1),this.isTenant=!0===xt().squidTenant,this.clientIdSubject=new h.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,h.filter)(e=>e),(0,h.map)(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,h.skip)(1),(0,h.filter)(e=>!e),(0,h.map)(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=xt()[Lt];return e?e():V()}generateClientId(){const e=xt()[Bt];if(e)return e();let t=`${this.isTenant?"tenant-":""}${V()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Bt="SQUID_CLIENT_ID_GENERATOR",Lt="SQUID_CLIENT_REQUEST_ID_GENERATOR",Qt="__squidId";function Ut(e){return Et(e)}function $t(...e){const[t,i,n]=e,r="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return r.integrationId||(r.integrationId=void 0),kt(r)}function Gt(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return bt(e,t);if("!="===i)return!bt(e,t);switch(i){case"<":return!mt(e)&&(!!mt(t)||t<e);case"<=":return!!mt(t)||!mt(e)&&t<=e;case">":return!mt(t)&&(!!mt(e)||t>e);case">=":return!!mt(e)||!mt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Vt(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Vt(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Vt(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Vt(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>L(i,"VALUE_CANNOT_BE_NULL").some(t=>bt(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>L(i,"VALUE_CANNOT_BE_NULL").some(t=>bt(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!L(i,"VALUE_CANNOT_BE_NULL").some(t=>bt(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function Vt(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const n=function(e){let t="";for(let i=0;i<e.length;++i)"\\"===e[i]?i+1<e.length&&["%","_"].includes(e[i+1])?(t+=e[i+1],i++):i+1<e.length&&"\\"===e[i+1]?(t+="\\\\",i++):t+="\\":"%"===e[i]?t+="[\\s\\S]*":"_"===e[i]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[i])&&(t+="\\"),t+=e[i]);return t}(t);return new RegExp(`^${n}$`).test(e)}function Ht(e,t){return`${e}_${t}`}function Wt(e){return"fieldName"in e}class Kt{constructor(e,t,i){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.refId=V()}get squidDocId(){return this._squidDocId}get data(){return St(this.dataRef)}get dataRef(){return L(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=Ut(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`})}get hasData(){return!!this.dataManager.getProperties(this.squidDocId)}async snapshot(){if(this.hasSquidPlaceholderId())throw new Error("Cannot invoke snapshot of a document that was created locally without storing it on the server.");if(this.isTracked()&&this.hasData)return this.data;const e=await this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshot();return L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0}snapshots(){return this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshots().pipe((0,h.map)(e=>(L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0)))}peek(){return this.isTracked()&&this.hasData?this.data:void 0}isDirty(){return this.dataManager.isDirty(this.squidDocId)}async update(e,t){const i={};Object.entries(e).forEach(([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[n]});const n={type:"update",squidDocIdObj:Ut(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:St(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const n={type:"applyNumericFn",fn:"increment",value:t},r={type:"update",squidDocIdObj:Ut(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(r,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async insert(e,t){const i=Ut(this.squidDocId),n=i.integrationId;let r=Et(i.docId);if(r[Qt]&&(r={}),n===Ke&&r.__id)try{const e=Et(r.__id);r={...r,...e}}catch{}const s={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...r}};return this.dataManager.applyOutgoingMutation(s,t)}async delete(e){const t={type:"delete",squidDocIdObj:Ut(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}hasSquidPlaceholderId(){const e=Et(this._squidDocId);if("object"==typeof e&&e.docId){const t=Et(e.docId);if("object"==typeof t&&Object.keys(t).includes(Qt))return!0}return!1}}class zt{constructor(e,t={}){this.internalStateObserver=new h.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new h.BehaviorSubject(!1),this.snapshotSubject=new h.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,B(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,h.switchAll)()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...t},this.goToFirstPage()}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}async prev(){return this.prevInternal(await this.waitForInternalState()),await this.waitForData()}async next(){const{numBefore:e,extractedData:t}=await this.waitForInternalState();return e+this.paginateOptions.pageSize<t.length&&(this.firstElement=t[e+this.paginateOptions.pageSize]),this.internalStateObserver.next(null),this.doNewQuery(t[e],!1),await this.waitForData()}async waitForData(){return this.internalStateToState(await this.waitForInternalState())}observeState(){return this.internalStateObserver.pipe((0,h.filter)(e=>null!==e),(0,h.map)(e=>this.internalStateToState(e)))}async first(){return await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.goToFirstPage(),await this.waitForData()}async refreshPage(){const{extractedData:e}=await this.waitForInternalState();return this.internalStateObserver.next(null),this.onFirstPage?this.goToFirstPage():this.doNewQuery(e[0],!1),await this.waitForData()}async last(){await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.navigatingToLastPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder().snapshots(this.paginateOptions.subscribe).pipe((0,h.map)(e=>e.reverse()));return this.snapshotSubject.next(e),await this.waitForData()}goToFirstPage(){this.onFirstPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).snapshots(this.paginateOptions.subscribe);this.snapshotSubject.next(e)}compareObjects(e,t){if(e===t||mt(e)&&mt(t))return 0;if(mt(e))return-1;if(mt(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:r}of i){const i=wt(dt(e,n),dt(t,n));if(0!==i)return r?i:-i}return 0}async dataReceived(e){const t=e.map(e=>this.templateSnapshotEmitter.extractData(e));if(0===e.length)return void(this.onFirstPage?this.internalStateObserver.next({numBefore:0,numAfter:0,data:e,extractedData:t}):this.goToFirstPage());if(null===this.firstElement)if(null!==this.lastElement){const i=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-i-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const i=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,n=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:dt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,h.map)(e=>e.reverse())))}else{const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize);e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?">=":"<=",value:dt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await(0,h.firstValueFrom)((0,h.race)(this.isDestroyed.pipe((0,h.filter)(Boolean),(0,h.map)(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe((0,h.filter)(e=>null!==e),(0,h.take)(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:r}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(r[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:i>0}}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-i-1],!0)}}Error;class Jt{constructor(e,t,i,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=Ut(e),r=Et(n),s=this.get(t,i);for(const[e,t]of Object.entries(r))s.where(e,"==",t);return s}get(e,t){return new Xt(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class Yt{constructor(){this.containsEmptyInCondition=!1}eq(e,t){return this.where(e,"==",t)}neq(e,t){return this.where(e,"!=",t)}in(e,t){return this.where(e,"in",t)}nin(e,t){return this.where(e,"not in",t)}gt(e,t){return this.where(e,">",t)}gte(e,t){return this.where(e,">=",t)}lt(e,t){return this.where(e,"<",t)}lte(e,t){return this.where(e,"<=",t)}like(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"like_cs":"like",t)}notLike(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"not like_cs":"not like",t)}arrayIncludesSome(e,t){return this.where(e,"array_includes_some",t)}arrayIncludesAll(e,t){return this.where(e,"array_includes_all",t)}arrayNotIncludes(e,t){return this.where(e,"array_not_includes",t)}throwIfInvalidLikePattern(e){if(/\\(?![%_\\])/.test(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class Zt{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1).pipe((0,h.defaultIfEmpty)([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(x(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Zt(this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new zt(this,e)}}class Xt extends Yt{constructor(e,t,i,n,r,s,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,this.documentReferenceFactory=r,this.queryBuilderFactory=s,this.documentIdentityService=o,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return Ot(this.build())}where(e,t,i){if(B(rt.includes(t),`Invalid operator: ${t}`),"in"===t||"not in"===t){const n=Array.isArray(i)?[...i]:[i];"in"===t&&0===n.length&&(this.containsEmptyInCondition=!0);for(const i of n)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:i});return this}return this.query.conditions.push({fieldName:e,operator:t,value:i}),this}limit(e){return function(e){var t;B(function(e){return"number"==typeof e}(t=e),()=>U("Limit needs to be a number","Not a number",t)),-1!==e&&(B(e>0,"query limit has to be greater than 0"),B(Math.floor(e)===e,"query limit has to be an integer"),B(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const i=this.query.sortOrder.map(e=>e.fieldName);return B(bt(t.sort(),i.slice(0,t.length).sort()),"All fields in limitBy must be appear in the first fields in the sortBy list."),this.query.limitBy={limit:e,fields:t,reverseSort:!1},this}sortBy(e,t=!0){const i={asc:t,fieldName:e};return function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,r,s;B((i=t,n=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>n.includes(e))),"Field sort should only contain a fieldName and asc"),B((r=t.asc,s="boolean",Array.isArray(r)?r.every(e=>typeof e===s):typeof r===s),"Asc needs to be boolean")}(i),B(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.sortOrder.push(i),this}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1).pipe((0,h.defaultIfEmpty)([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new h.BehaviorSubject([]);const t=this.build();return this.querySubscriptionManager.processQuery(t,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(x(e=>e.map(e=>{B(1===Object.keys(e).length);const t=$t(L(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)})))}changes(){let e,t=new Set;return this.snapshots().pipe((0,h.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,h.switchMap)(t=>(Object.entries(t).forEach(([t,i])=>{!function(e,t,i){const n=e[t];void 0!==n&&(e[i]=n,delete e[t])}(e||{},t,i)}),h.NEVER)),(0,h.startWith)({}))),x(([i])=>{let n=[];const r=[],s=[];if(e){for(const s of i){const i=s.squidDocId,o=s.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){r.push(s);const n=e[i];delete e[i],t.delete(n)}else n.push(s)}for(const e of t)s.push(e)}else n=i;e={},t=new Set;for(const n of i){const i=n.dataRef;e[n.squidDocId]=i,t.add(i)}return new ei(n,r,s)}))}dereference(){return new Zt(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new Xt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=St(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){return e.length?(this.query.conditions.push({fields:e}),this):this}flipSortOrder(){return this.query.sortOrder=this.query.sortOrder.map(e=>({...e,asc:!e.asc})),this.query.limitBy&&(this.query.limitBy.reverseSort=!this.query.limitBy.reverseSort),this}serialize(){return{type:"simple",dereference:!1,query:this.build()}}extractData(e){return e.dataRef}paginate(e){return new zt(this,e)}mergeConditions(){const e=[],t=Mt(this.query.conditions.filter(Wt)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=Mt(i,e=>e.operator);for(const[i,n]of Object.entries(t)){if("=="===i||"!="===i){e.push(...n);continue}const t=[...n];t.sort((e,t)=>wt(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Wt(e)),...e]}}class ei{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class ti extends Yt{constructor(e,t,i,n,r,s,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=r,this.rootAlias=s,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,i){return this.queryBuilder.where(e,t,i),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}sortBy(e,t=!0){return this.queryBuilder.sortBy(e,t),this}join(e,t,i,n){const r=n?.leftAlias??this.latestAlias,s={...i,leftAlias:r,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[r].push(t),new ti(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:s},this.queryBuilder)}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new h.BehaviorSubject([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,St(this.joins),St(this.joinConditions),e,!1).pipe(x(e=>e.map(e=>{const t={};for(const[i,n]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,r=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,s=n?$t(n.__docId__,e,r):void 0;t[i]=s?this.documentReferenceFactory.create(s,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new ri(this)}dereference(){return new ii(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new ti(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,St(this.leftToRight),St(this.joins),St(this.joinConditions),this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e[this.rootAlias].dataRef}serialize(){return{type:"join",grouped:!1,dereference:!1,root:{alias:this.rootAlias,query:this.build()},leftToRight:this.leftToRight,joins:this.joins,joinConditions:this.joinConditions}}paginate(e){if(this.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new zt(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class ii{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(x(e=>e.map(e=>function(e,t){const i={},n=Object.keys(e);for(const r of n){const n=e[r];i[r]=t(n)}return i}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ii(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}extractData(e){return e[this.joinQueryBuilder.rootAlias]}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new zt(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class ni{constructor(e){this.groupedJoin=e}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(x(e=>e.map(e=>this.dereference(e,this.groupedJoin.joinQueryBuilder.rootAlias))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.groupedJoin.getSortOrders()}clone(){return new ni(this.groupedJoin.clone())}addCompositeCondition(e){return this.groupedJoin.addCompositeCondition(e),this}flipSortOrder(){return this.groupedJoin.flipSortOrder(),this}limit(e){return this.groupedJoin.limit(e),this}getLimit(){return this.groupedJoin.getLimit()}extractData(e){return e[this.groupedJoin.joinQueryBuilder.rootAlias]}serialize(){return{...this.groupedJoin.joinQueryBuilder.serialize(),dereference:!0,grouped:!0}}paginate(e){if(this.groupedJoin.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new zt(this,e)}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const n={[t]:e[t].data};for(const t of i)n[t]=e[t].map(e=>this.dereference(e,t));return n}return e.data}}class ri{constructor(e){this.joinQueryBuilder=e}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(x(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new ni(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ri(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}getLimit(){return this.joinQueryBuilder.getLimit()}extractData(e){return Object.keys(this.joinQueryBuilder.leftToRight).length>1?e[this.joinQueryBuilder.rootAlias].dataRef:e.dataRef}serialize(){return{...this.joinQueryBuilder.serialize(),grouped:!0}}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new zt(this,e)}groupData(e,t){const i=Mt(e,e=>e[t]?.squidDocId);return Object.values(i).filter(e=>void 0!==e[0][t]).map(e=>{const i=this.joinQueryBuilder.leftToRight[t],n=e[0][t];if(0===i.length)return n;const r={[t]:n};for(const t of i)r[t]=this.groupData(e,t);return r})}}class si{constructor(e,t,i,n,r,s){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,this.querySubscriptionManager=r,this.dataManager=s,this.refId=V()}doc(e){if(e&&"string"!=typeof e&&"object"!=typeof e&&!Array.isArray(e))throw new Error("Invalid doc id. Can be only object or string.");if(this.integrationId!==Ke)if(e){if("object"!=typeof e)throw new Error("Invalid doc id. String doc ids are only supported for the built_in_db integration. For all other integrations, the doc id must be an object.")}else e={[Qt]:V()};else e=e&&"string"!=typeof e?{__id:kt(e)}:{__id:e||V()};const t=$t(kt(e),this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)}async insertMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)await this.doc(i.id).insert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof Kt?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new ti(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new oi(...e)}}class oi{constructor(...e){if(0===e.length)throw new Error("At least one query builder must be provided");this.snapshotEmitters=e.map(e=>e.clone());const t=Math.max(...this.snapshotEmitters.map(e=>{const t=e.getLimit();return-1===t?1e3:t}));this.snapshotEmitters.forEach(e=>e.limit(t));const i=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==i.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<i.length;e++)if(t[e].fieldName!==i[e].fieldName||t[e].asc!==i[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){const t=this.snapshotEmitters.map(t=>t.snapshots(e));return this.or(this.snapshotEmitters[0].getSortOrders(),...t)}peek(){throw new Error("peek is not currently supported for merged queries")}clone(){return new oi(...this.snapshotEmitters.map(e=>e.clone()))}getSortOrders(){return this.snapshotEmitters[0].getSortOrders()}addCompositeCondition(e){for(const t of this.snapshotEmitters)t.addCompositeCondition(e);return this}limit(e){return this.snapshotEmitters.forEach(t=>t.limit(e)),this}getLimit(){return this.snapshotEmitters[0].getLimit()}flipSortOrder(){return this.snapshotEmitters.forEach(e=>e.flipSortOrder()),this}serialize(){return{type:"merged",queries:this.snapshotEmitters.map(e=>e.serialize())}}extractData(e){return this.snapshotEmitters[0].extractData(e)}paginate(e){return new zt(this,e)}or(e,...t){return(0,h.combineLatest)([...t]).pipe((0,h.map)(t=>{const i=new Set,n=t.flat(),r=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),r.push(e));return r.sort((t,i)=>{for(const{fieldName:n,asc:r}of e){const e=dt(this.extractData(t),n),s=dt(this.extractData(i),n);if(!Gt(e,s,"=="))return Gt(s,e,"<")?r?-1:1:r?1:-1}return 0}).slice(0,this.getLimit())}))}}class ai{constructor(e,t,i,n){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=n,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let n=i.get(e);return n||(n=new si(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class ci{constructor(e,t){this.clientIdService=e,this.socketManager=t,this.isConnected=!1,this.socketManager.observeConnectionReady().subscribe(e=>{this.isConnected=e})}get connected(){return this.isConnected}get clientId(){return this.clientIdService.getClientId()}observeConnected(){return this.socketManager.observeConnectionReady()}}var ui=i(150);function li(e,t){switch(t.type){case"applyNumericFn":return function(e,t){if("increment"===t.fn)return null==e?t.value:e+t.value;throw new Error("Unknown numeric function: "+JSON.stringify(t))}(e,t);case"applyStringFn":return function(e,t){switch(t.fn){case"trim":return"string"!=typeof e?e:e.trim();case"extendString":return null==e?t.value:e+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?St(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function hi(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function di(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(B("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const i=St(e);t=St(t);for(const[e]of hi(i)){const n=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&n>t.split(".").length)&&delete i.properties[e]}for(const[e,n]of hi(t))i.properties[e]=pi([...i.properties[e]||[],...n]);return i}(e,t);const i=St(e);for(const[e,n]of hi(t)){const t=n;for(const n of t){const t=li(dt(i.properties,e),n);void 0===t?ft(i.properties,e):gt(i.properties,e,t)}}return i}function pi(e){let t=0;for(;t+1<e.length;){const i=gi(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function gi(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(B("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(B("increment"===e.fn,"Unrecognized applyNumericFn"),{type:"applyNumericFn",fn:"increment",value:e.value+t.value}):"update"===e.type?{type:"update",value:e.value+t.value}:t):"extendString"===t.fn?"update"===e.type?{type:"update",value:e.value+t.value}:"applyStringFn"===e.type?"trim"===e.fn?null:{type:"applyStringFn",fn:"extendString",value:e.value+t.value}:t:null}function fi(e){const t={};for(const i of e){const e=`${i.squidDocIdObj.integrationId}/${i.squidDocIdObj.collectionName}/${i.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(i)}const i=[];for(const e in t){const n=t[e].reduce((e,t)=>L(di(e,t),"Merge result cannot be null"));i.push(n)}return i}const yi="dataManager_runInTransaction";class mi{constructor(e,t,i,n,r,s,o,a,c){this.documentStore=e,this.mutationSender=t,this.socketManager=i,this.querySubscriptionManager=n,this.queryBuilderFactory=r,this.lockManager=s,this.destructManager=o,this.documentIdentityService=a,this.querySender=c,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new h.Subject,this.outgoingMutationsEmpty=new h.BehaviorSubject(!0),this.knownDirtyDocs=new Set,this.failedDocsToResync=[],this.refreshDocIdToTimestamp=new Map,this.handleIncomingMessagesForTests=!0,this.destructManager.onDestruct(()=>{this.destruct()}),this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.handleNotifications(),this.startDeleteExpiredTimestampsJob(),this.handleOrphanDocs(),this.outgoingMutationsEmpty.subscribe(e=>{this.querySender.safeToSendQueriesToServer.next(e)})}getProperties(e){return this.documentStore.getDocumentOrUndefined(e)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),i=t&&!t.expireTimestamp?t.timestamp:void 0,n=this.docIdToLocalTimestamp.get(e);return!((!n||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&n===i)}async runInTransaction(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(yi)?this.lockManager.lockSync(yi):await this.lockManager.lock(yi);let i=bi;const n=()=>i!==bi;return new Promise(async(t,r)=>{try{let s;this.currentTransactionId=V();try{s=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(s),reject:r})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(yi)}catch(e){i=n()?i:e}}n()&&r(i)})}async applyOutgoingMutation(e,t){const i=$t(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(yi)||(await this.lockManager.lock(yi),this.lockManager.release(yi)),this.knownDirtyDocs.delete(i);const n=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(n&&!n.sentToServer)n.mutation=L(fi([n.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},n=this.pendingOutgoingMutations.get(i)||[];n.push(t),this.pendingOutgoingMutations.set(i,n),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),n="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const i={...e},n=hi(t);for(const[e,t]of n){const n=t;for(const t of n){const n=li(dt(i,e),t);void 0===n?ft(i,e):gt(i,e,n)}}return i}(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,n)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,n).forEach(e=>this.batchClientRequestIds.add(e)))},t)}isTracked(e){if(this.pendingIncomingUpdates.get(e))return!0;const t=this.pendingOutgoingMutations.get(e);return!(!t||!t.length)||this.querySubscriptionManager.hasOngoingQueryForDocId(e)}isForgotten(e){return this.documentStore.hasData(e)&&!this.isTracked(e)}isLocalOnly(e){return!this.hasBeenAcknowledged(e)&&this.documentStore.hasData(e)}hasBeenAcknowledged(e){return this.docIdToServerTimestamp.has(e)}async runInTransactionSync(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(yi);try{this.currentTransactionId=V();try{return e(this.currentTransactionId)}catch(e){console.error("error while executing callback function in transaction",e)}finally{this.finishTransaction()}}catch(e){console.error("error while executing transaction",e)}finally{this.lockManager.release(yi)}}removeInternalProperties(e){if("delete"===e.type)return e;const t={...e,properties:{...e.properties}};return delete t.properties.__docId__,delete t.properties.__ts__,t}handleNotifications(){this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"mutations"===e.type),x(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t=e.reduce((e,t)=>this.querySubscriptionManager.hasOngoingQuery(t.clientRequestId)?(e[t.squidDocId]={properties:t.doc,timestamp:t.mutationTimestamp},e):e,{});this.applyIncomingUpdates(t)}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId),i={};for(const n of e.docs){const e=$t(n.__docId__,t.collectionName,t.integrationId);i[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(i,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)}).then()}applyIncomingUpdates(e,t){let i=!1;const n=new Set,r=new Set;for(const[t,s]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>s.timestamp?i=!0:o&&o.timestamp>s.timestamp?r.add(t):(this.pendingIncomingUpdates.set(t,s),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of r)this.refreshQueryMapping(e)},t).then(),i}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const i=this.pendingOutgoingMutations.get(e);i&&i.length||(this.updateDocumentFromSnapshot(e,t.properties),this.acknowledgeDocument(e,t.timestamp,!t.properties),this.docIdToLocalTimestamp.set(e,t.timestamp),this.pendingIncomingUpdates.delete(e),this.refreshQueryMapping(e))}refreshQueryMapping(e){const t=this.documentStore.getDocumentOrUndefined(e);this.querySubscriptionManager.setClientRequestIdsForLocalDoc(e,t).forEach(e=>{this.batchClientRequestIds.add(e)}),t&&(this.querySubscriptionManager.findQueriesForDocument(t,e).length||this.forgetDocument(e,!1))}destruct(){this.stopDeleteExpiredTimestampsJob()}stopDeleteExpiredTimestampsJob(){void 0!==this.deleteExpiredTimestampsInterval&&(clearInterval(this.deleteExpiredTimestampsInterval),this.deleteExpiredTimestampsInterval=void 0)}startDeleteExpiredTimestampsJob(){this.deleteExpiredTimestampsInterval=setInterval(()=>{const e=[...this.docIdToServerTimestamp.entries()].filter(([e,t])=>!(!t.expireTimestamp||t.expireTimestamp>Date.now()||this.isTracked(e)));for(const[t]of e)this.docIdToServerTimestamp.delete(t),this.forgetDocument(t,!0)},1e4)}updateDocumentFromSnapshot(e,t){const i=this.documentStore.getDocumentOrUndefined(e);return!(!i&&!t||i===t)&&((!i||!t||kt({...t,__ts__:void 0})!==kt(i))&&(this.documentStore.saveDocument(e,t),!0))}finishTransaction(e){this.currentTransactionId=void 0;const t=[...this.batchClientRequestIds.values()];this.batchClientRequestIds.clear(),this.querySubscriptionManager.notifyAllSubscriptions(t),this.sendAllUnsentOutgoingMutations(e).then()}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await ui.PromisePool.for(t).withConcurrency(t.length||1).useCorrespondingResults().handleError(e=>{throw e}).process(async([e,t])=>{await this.sendMutationsForIntegration([...t],e)}),this.pendingOutgoingMutations.size||this.outgoingMutationsEmpty.next(!0),await this.refreshUpdatedDocuments(),this.hasPendingSentMutations()?(await(0,h.firstValueFrom)(this.pendingOutgoingMutationsChanged.pipe((0,h.filter)(()=>!this.hasPendingSentMutations()))),e?.resolve()):e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:i,idResolutionMap:n={},refreshList:r=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),r.forEach(e=>{this.refreshDocIdToTimestamp.set(n[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);n[e]&&(e=n[e]),this.acknowledgeDocument(e,i),this.isTracked(e)||(this.setExpiration(e,!0),this.forgetDocument(e,!1))}}catch(t){for(const t of e){const e=this.removeOutgoingMutation(t);this.forgetDocument(e,!1),(this.hasBeenAcknowledged(e)||"insert"===t.mutation.type)&&this.failedDocsToResync.push(e)}throw t}}removeOutgoingMutation(e){const t=$t(e.mutation.squidDocIdObj),i=L(this.pendingOutgoingMutations.get(t));return i.splice(i.indexOf(e),1),i.length||this.pendingOutgoingMutations.delete(t),this.pendingOutgoingMutationsChanged.next(),t}async resyncFailedUpdates(){const e=[...this.failedDocsToResync];this.failedDocsToResync.splice(0);for(const t of e){const{docId:e}=Ut(t);this.setExpiration(t,!0);try{const i=e.includes(Qt)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(L(i.length<=1,"Got more than one doc for the same id:"+t),!i.length){this.forgetDocument(t,!1);const e=this.querySubscriptionManager.setClientRequestIdsForLocalDoc(t,void 0);this.querySubscriptionManager.notifyAllSubscriptions(e)}}catch(e){this.querySubscriptionManager.errorOutAllQueries(t,e)}}}async refreshUpdatedDocuments(){const e=[];for(const[t,i]of this.refreshDocIdToTimestamp.entries()){const n=this.docIdToServerTimestamp.get(t)?.timestamp;n&&n>i||e.push(t)}this.refreshDocIdToTimestamp.clear(),await Promise.allSettled(e.map(e=>this.queryBuilderFactory.getForDocument(e).snapshot()))}groupOutgoingMutationsByIntegrationId(){const e={};for(const[,t]of[...this.pendingOutgoingMutations.entries()]){const i=t[t.length-1];if(i&&!i.sentToServer){const t=i.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(i),i.sentToServer=!0}}return Object.entries(e)}handleOrphanDocs(){this.querySubscriptionManager.onOrphanDocuments.subscribe(e=>{for(const t of e)this.isTracked(t)||this.forgetDocument(t,!1)})}acknowledgeDocument(e,t,i=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,i)}setExpiration(e,t){const i=this.docIdToServerTimestamp.get(e);i&&(i.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=$t(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=Ut(n))})}),Object.entries(e).forEach(([e,t])=>{yt(this.pendingOutgoingMutations,e,t),yt(this.docIdToLocalTimestamp,e,t),yt(this.docIdToServerTimestamp,e,t)})}hasPendingSentMutations(){for(const e of this.pendingOutgoingMutations.values())for(const t of e)if(t.sentToServer)return!0;return!1}}const bi=Symbol("undefined");class Ii{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new h.BehaviorSubject(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe((0,h.filter)(Boolean),x(()=>{}))}onPreDestruct(e){this.preDestructors.push(e)}onDestruct(e){this.destructors.push(e)}async destruct(){this.reportDestructed();const e=this.preDestructors.concat(this.destructors);let t=e.shift();for(;t;){try{await t()}catch(e){console.error("Error while destructing Squid",e)}t=e.shift()}}reportDestructed(){this.isDestructing||this.isDestructedSubject.next(!0)}}class Si{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{e||this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.clientRequestId];void 0!==t&&t.release()})}async lock(e,t=2e3){if(this.socketManager.notifyWebSocketIsNeeded(),!await(0,h.firstValueFrom)((0,h.race)((0,h.timer)(this.lockWaitForConnectionThreshold).pipe(x(()=>!1)),this.socketManager.observeConnectionReady().pipe((0,h.filter)(Boolean)),this.destructManager.observeIsDestructing())))return Promise.reject("CLIENT_NOT_CONNECTED");const i=V(),n={type:"acquireLock",payload:{mutex:e,timeoutMillis:t,clientRequestId:i}};this.socketManager.sendMessage(n);const r=await(0,h.firstValueFrom)((0,h.race)((0,h.timer)(t+4e3).pipe((0,h.take)(1),x(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0}}))),this.acquireLockMessagesFromServer.pipe((0,h.filter)(e=>e.payload.clientRequestId===i))));if(this.destructManager.isDestructing)throw new Error("Destructing");if(!r.payload.lockId)throw new Error(`Failed to acquire lock: ${r.payload.error}`);const s=r.payload.lockId,o=new vi(s,i,this.ongoingLocks,this.socketManager);return this.ongoingLocks[s]=o,o}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class vi{constructor(e,t,i,n){this.lockId=e,this.clientRequestId=t,this.ongoingLocks=i,this.socketManager=n,this.released=!1,this.onReleaseSubject=new h.Subject}release(){if(this.released)return;this.released=!0,delete this.ongoingLocks[this.lockId];const e={type:"releaseLock",payload:{lockId:this.lockId,clientRequestId:this.clientRequestId}};this.socketManager.sendMessage(e),this.onReleaseSubject.next()}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}class wi{constructor(e,t){this.documentStore=e,this.destructManager=t,this.changeNotifier=new h.BehaviorSubject({}),this.destructManager.onDestruct(()=>{this.changeNotifier.complete()})}migrate(e){Object.entries(e).forEach(([e,t])=>{this.documentStore.migrateDocId(e,t)}),this.changeNotifier.next(e)}observeChanges(){return this.changeNotifier.asObservable()}}class Mi{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t){let i=this.documents.get(e);if(i)return i;i=new Kt(e,L(this.dataManager,"dataManager not found"),t);const{integrationId:n,collectionName:r}=Ut(e);this.documents.set(e,i);const s=this.getCollectionKey(n,r),o=this.documentsForCollection.get(s)||[];return this.documentsForCollection.set(s,o.concat(i)),i}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const i=this.getCollectionKey(e,t);return(this.documentsForCollection.get(i)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const i=Ut(e),n=Ut(t);yt(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class Ti{constructor(){this.squidDocIdToDoc=new Map}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=St(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),n}return void this.squidDocIdToDoc.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),t}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocument(e){return L(this.getDocumentOrUndefined(e))}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}group(e,t){return Object.values(Mt(e,e=>kt(t.map(t=>dt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=[...e].map(e=>this.squidDocIdToDoc.get(e)).filter(j),{sortOrder:n,limitBy:r}=t,s=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;if(!r)return s.slice(0,o);const{limit:a,fields:c,reverseSort:u}=r,l=this.group(s,c);let h;return h=u?l.map(e=>e.slice(-a)):l.map(e=>e.slice(0,a)),h.flat().slice(0,o)}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;yt(this.squidDocIdToDoc,e,t);const n=Ut(t),r=Et(n.docId);this.saveDocument(t,{...i,...r,__docId__:n.docId})}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:r}of i){const i=wt(dt(e,n),dt(t,n));if(0!==i)return r?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class ki{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const i={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",i,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const i={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",i)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class _i{constructor(e,t,i){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.clientIdService.observeClientId().pipe((0,h.distinctUntilChanged)(),(0,h.skip)(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))jt.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e})})}async getJob(e){return(await this.rpcManager.post("job/getJob",{jobId:e})).job}async awaitJob(e){this.maybeListenToJobs(),await this.socketManager.awaitConnectionReady();const t=this.listeners[e]||new h.ReplaySubject(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}),(0,h.firstValueFrom)(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,i=t.id,n=this.listeners[i];n&&("completed"===t.status?n.next(t.result):"failed"===t.status?n.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}}class Ei{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=fi(e),n=i.map(e=>`sendMutation_${$t(e.squidDocIdObj)}`);await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw jt.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}}class Oi{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Ci{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"userNotification"===e.type),(0,h.map)(e=>e.payload))}async publishNotification(e,t){return await this.rpcManager.post("/notification/publishNotification",{clientIds:t,payload:e})}async publishSystemNotification(e,t){return await this.rpcManager.post("/notification/publishSystemNotification",{clientIds:t,payload:e})}}const Di={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Ai{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!qi.test(e)||e.length>=Ni);B(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const n={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},r=this.rpcManager.post("/observability/metrics",{metrics:[n]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==r),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(r)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...Di,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const i=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:i,noDataBehavior:n}=e,r=void 0===e.fillValue?null:e.fillValue,s=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const r=t-e;let s=t-Math.floor(r/i)*i;return s>e&&(s-=i),s}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const r=t-e;let s=e+Math.floor(r/i)*i;return s>=t&&(s-=i),s}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const i=[];for(let t=0;t<e.groupByTags.length;t++){const n=e.groupByTags[t],r=a[n]?.[0]||"";i.push(r)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===n&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,n]of Object.entries(a)){const r=e.groupByTags.indexOf(i);if(!(r<0))for(let e=0;e<t.length;e++){const i=t[e],s=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===r||e===n.tagValues[t])&&s.delete(n.tagValues[r])}if(0!==s.size)for(const e of s){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[r]=e,t.push(n)}}}for(const n of t){if(0!==n.points.length){const e=n.points[0][0],t=n.points[n.points.length-1][0];B(e>=s,()=>`Invalid first point time: ${e}`),B(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:r,u=Array.isArray(e.fn)?e.fn.map(c):[r];for(let e=s;e<=o;e+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(B(i[0]>e,()=>`Result point has invalid time: ${i[0]}`),t.push([e,...u])):t.push([e,...u])}n.points=t}}(t,i.resultGroups),i}}const qi=/^[a-zA-Z0-9_-]+$/,Ni=1e3;class Ri{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const i={authCode:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/saveAuthCode",i)}async getAccessToken(e){const t={personalStorageConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/getAccessToken",t)}async indexDocumentOrFolder(e,t,i,n){const r={documentOrFolderId:e,metadata:n,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:i};await this.rpcManager.post("personalStorage/indexDocumentOrFolder",r)}async listIndexedDocuments(e,t,i){const n={personalStorageConfig:{identifier:e,integrationId:this.integrationId},agentId:t,type:i};return(await this.rpcManager.post("personalStorage/listIndexedDocuments",n)).documents}async unindexDocument(e,t,i){const n={documentId:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:i};await this.rpcManager.post("personalStorage/unindexDocument",n)}}async function Fi(e,t,i=500){const n=Date.now(),r=e.paginate({pageSize:i,subscribe:!1});let s=0,o=await r.waitForData();for(;;){for(const e of o.data)s++,await t(e.data);if(!o.hasNext)break;o=await r.next()}return{count:s,time:Date.now()-n}}function xi(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:r,integrationId:s}=i;let o=e.collection(r,s).query();return o=ji(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:r,dereference:s,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=ji(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:s}=i,{left:o,right:a,leftAlias:c}=r[t];let l=e.collection(n,s).query();l=ji(l,i),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),s&&o?u.grouped().dereference():s?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:i}=t,{collectionName:n,integrationId:r}=Pi(i[0]),s=i.map(t=>xi(e,t));return e.collection(n,r).or(...s)}(e,t)}}function ji(e,t){const{conditions:i,limit:n,sortOrder:r}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:i,operator:n,value:r}=t;e.where(i,n,r)}e.limit(n);for(const{fieldName:t,asc:i}of r)e.sortBy(t,i);return e}function Pi(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:i}=e.query;return{collectionName:t,integrationId:i}}case"join":{const{collectionName:t,integrationId:i}=e.root.query;return{collectionName:t,integrationId:i}}case"merged":return Pi(e.queries[0])}}const Bi={"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)=>Li(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Li(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Li(e,t)&&Ui(t),"like_cs:like_cs":(e,t)=>Li(e,t),"like:not like":(e,t)=>!Qi(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!Qi(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!Qi(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!Qi(e,t),"not like:like":(e,t)=>Gi(e,t),"not like_cs:like":(e,t)=>Gi(e,t),"not like:like_cs":(e,t)=>Gi(e,t),"not like_cs:like_cs":(e,t)=>Gi(e,t),"not like:not like":(e,t)=>Li(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Li(t,e)&&Ui(e),"not like:not like_cs":(e,t)=>Li(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Li(t,e),"in:like":(e,t)=>e.every(e=>Gt(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Gt(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Gt(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Gt(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&&$i(e)||Vi(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&$i(e)||Vi(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&$i(t)||Vi(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&$i(t)||Vi(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=>Gt(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Gt(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Gt(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Gt(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 Li(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return $i(t.substring(n));const r=e[i],s=t[n];return"%"===r&&"%"===s?Li(e,t,i+1,n+1)||Li(e,t,i+1,n):"%"!==r&&("%"===s?Li(e,t,i,n+1)||Li(e,t,i+1,n):(r===s||"_"===s)&&Li(e,t,i+1,n+1))}function Qi(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return $i(t.substring(n));if(n>=t.length)return $i(e.substring(i));const r=i<e.length?e[i]:"",s=n<t.length?t[n]:"";return"%"===r&&"%"===s?Qi(e,t,i+1,n+1)||Qi(e,t,i,n+1)||Qi(e,t,i+1,n):"%"===r||"%"===s?Qi(e,t,i,n+1)||Qi(e,t,i+1,n):(r===s||"_"===r||"_"===s)&&Qi(e,t,i+1,n+1)}function Ui(e){return!/[a-zA-Z]/.test(e)}function $i(e){return e.split("").every(e=>"%"===e)}function Gi(e,t){return e.length>0&&$i(e)||t.length>0&&$i(t)||Vi(e)&&0===t.length}function Vi(e){let t=!1,i=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}class Hi{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Wt))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){return!e.find((e,t)=>!bt(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,i){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:i})}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(Wt),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),r=-1===e.limit||this.limit>-1&&this.limit<e.limit;return i&&n&&r}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 i=t.fieldName,n=t.operator,r=dt(e,i);if("in"===n){if(t.value.includes(r))continue;return!1}if("not in"!==n){if(!Gt(t.value,r,n))return!1}else if(t.value.includes(r))return!1}return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:r,value:s}=this.parseConditions([t])[0],o=Bi[`${i}:${r}`];return!!o&&o(n,s)}parseConditions(e){const t=[],i=new Map,n=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":i.set(e.fieldName,(i.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)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),n.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}class Wi{constructor(e,t,i){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=i}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:i}=e,n=new Hi(e),r=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),s={};return r.forEach(e=>{s[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(s)),e).map(e=>s[$t(e.__docId__,i,t)])}}function Ki(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){return e.call(t,i,r++)&&n.next(i)}))})}class zi{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.safeToSendQueriesToServer=new h.BehaviorSubject(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new h.BehaviorSubject(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new h.Subject,i=(0,h.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(),i):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Ki(Boolean),(0,h.take)(1)).subscribe(()=>{this.processQueryBatch()})},0),i)}async waitForAllQueriesToFinish(){return(0,h.firstValueFrom)(this.inflightQueriesCount.pipe(Ki(e=>0===e))).then(()=>{})}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=Array.from(e.map(({queryRequest:e})=>e).reduce((e,t)=>(e.set(t.clientRequestId,t),e),new Map).values()),i=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const i=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,r=i.errors[e],s=i.results[e];r?n.error(r):n.next(s)}}catch(e){i.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Ji={d:(e,t)=>{for(var i in t)Ji.o(t,i)&&!Ji.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Yi(e,t,...i){e||function(e,...t){const i=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof i)throw i;throw(e=>new Error(e))(i||"Assertion error",...t)}(t,...i)}function Zi(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Xi(e,t);if(0===t.length)return Yi("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function n(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let r=e;for(let e=0;e<t.length-1&&void 0!==r;e++){const i=t[e];Yi(!Array.isArray(r)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),r=r[i],Yi(void 0===r||"object"==typeof r&&null!==r,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===r?"<null>":typeof r}'`)}const s=t[t.length-1];return Yi(!Array.isArray(r)||n(s),()=>`Invalid array index Path: '${t}`),(null==r?void 0:r[s])===i?e:en(e,t,i)}(e,t.path,t.value);case"delete":return Xi(e,t.path);case"batch":return t.actions.reduce((e,t)=>Zi(e,t),e)}}function Xi(e,t){Yi(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const r=t[n];if(i=i[r],void 0===i)return e;Yi("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,n+1)}', type: ${null===i?"<null>":typeof i}`)}const n=t[t.length-1];return void 0===i[n]?e:en(e,t,void 0)}function en(e,t,i){function n(e,i){Yi(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const r=Object.assign({},e);let s=r;for(let e=0;e<t.length-1;e++){const r=t[e],o=s[r];Yi(void 0===o||"object"==typeof o&&null!==o,()=>`Internal error: sub-path has an invalid type and can't be patched: '${t.slice(0,e+1)}', type: '${null===o?null:typeof o}'`);const a=void 0===o?void 0===i?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return n(s,r),s;s[r]=a,s=a}const o=t[t.length-1];return void 0===i?n(s,o):s[o]=i,r}function tn(e,t){const i=[];if("set"===e.type||"delete"===e.type)i.push(e.path);else if("batch"===e.type)for(const t of e.actions)i.push(...tn(t,"as-is"));return"unique-and-sorted"===t?sn(i):i}function nn(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i])return!1;return!0}function rn(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const n=e[i].localeCompare(t[i]);if(0!==n)return n}return e.length-t.length}),t}function sn(e){const t=rn(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let r=e+1;r<t.length;r++){const s=t[r];n.length===s.length&&nn(n,s)&&(i[r]=void 0,e++)}}return i.filter(e=>void 0!==e)}const on=(an={Observable:()=>h.Observable,Subject:()=>h.Subject},cn={},Ji.d(cn,an),cn);var an,cn;const un=(ln={filter:()=>Ki,map:()=>x},hn={},Ji.d(hn,ln),hn);var ln,hn,dn;class pn{constructor(){this.root={children:new Map,childrenWithValue:0}}get(e){var t;return null===(t=this.getNode(e))||void 0===t?void 0:t.value}getOrSet(e,t){const i=this._buildPath(e);if(void 0!==i.value)return i.value;const n=t(e);return this._setNodeValue(i,n,void 0===n),n}set(e,t){const i=void 0===t?this._findNode(e):this._buildPath(e);i&&this._setNodeValue(i,t,!0)}delete(e){const t=this._findNode(e);if(void 0===t)return;if(void 0===t.parent){if(t!==this.root)throw new Error("Only root node can have no parent.");return this.root.value=void 0,this.root.children.clear(),void(this.root.childrenWithValue=0)}const i=(void 0===t.value?0:1)+t.childrenWithValue;i>0&&this._updateChildrenWithValue(t,-i),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const i=this.getNode(e);return void 0===i?0:i.childrenWithValue+("node-and-children"===t&&void 0!==i.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const i=[];let n=this.root,r=t(n.value,i);if(r!==pn.StopFillToken){this._setNodeValue(n,r,!1);for(let s=0;s<e.length;s++){const o=e[s];i.push(o);let a=n.children.get(o);if(r=t(null==a?void 0:a.value,i),r===pn.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,r,!1),n=a}this._runGc(n)}}visitDfs(e,t,i=[]){const n=this.getNode(i);void 0!==n&&this._visitDfs(e,n,t,[...i])}_visitDfs(e,t,i,n){if("pre-order"===e&&!1===i(t.value,n))return!1;for(const[r,s]of t.children){if(n.push(r),!this._visitDfs(e,s,i,n))return!1;n.pop()}return"in-order"!==e||!1!==i(t.value,n)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const i of e)if(t=t.children.get(i),!t)return;return t}_findNode(e){let t=this.root;for(let i=0;i<e.length&&t;i++)t=t.children.get(e[i]);return t}_buildPath(e){let t=this.root;for(let i=0;i<e.length;i++){const n=e[i];let r=t.children.get(n);r||(r={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,r)),t=r}return t}_setNodeValue(e,t,i){if(e.value!==t){const i=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,i)}i&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let i=e.parent;i;i=i.parent)if(i.childrenWithValue+=t,i.childrenWithValue<0)throw new Error("Internal error: negative counter value!")}_runGc(e){void 0===e.value&&(0===e.childrenWithValue&&e.children.clear(),e.parent&&this._runGc(e.parent))}}pn.StopFillToken=Symbol("Trie.StopFillToken");class gn extends on.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class fn{constructor(e){this.rootState=e,this.observersTrie=new pn,this.batchDepth=0,this.appliedBatchActions=[],this.rootStateBeforeBatchStart=this.rootState,this.stubForUnusedPaths=[]}get state(){return this.rootState}get state$(){return this.observe([])}get(e){return this._get(this.rootState,e)}observe(e,t=[]){return this._observeChanges(e,t,"new-value-only").pipe((0,un.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,i){(null==i?void 0:i(this.get(e),t,e))||this._apply({type:"set",path:e,value:t})}delete(e){this._apply({type:"delete",path:e})}reset(e){this.observersTrie.visitDfs("pre-order",e=>null==e?void 0:e.complete()),this.observersTrie.delete([]),this.rootState=e}runInBatch(e){this.batchDepth++;try{e()}finally{if(this.batchDepth--,0===this.batchDepth&&this.appliedBatchActions.length>0){const e={type:"batch",actions:this.appliedBatchActions};this.appliedBatchActions=[],this._notify(e)}}}_apply(e){0===this.batchDepth&&(this.rootStateBeforeBatchStart=this.rootState),this.rootState=Zi(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=tn(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=sn([...t,...i]),r=new pn;for(const e of n)r.fillPath(e,()=>!0);r.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),r=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:r})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new pn;for(const e of t)null==n||n.set(e,!0);return new on.Observable(t=>{const r=this.observersTrie.getOrSet(e,()=>new gn);r.isAllDetailsMode=r.isAllDetailsMode||"all-details"===i;const s={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(s);const o=r.pipe((0,un.filter)(({action:e})=>void 0===n||tn(e,"as-is").some(e=>!n.get(e))),(0,un.map)(({action:t,value:i,oldValue:n})=>{let s=this.stubForUnusedPaths;if(r.isAllDetailsMode){const i=tn(t,"as-is");s=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=rn(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let r=e+1;r<t.length;r++)nn(t[r],n)&&(i[r]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>nn(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:s}})).subscribe(t);return()=>{o.unsubscribe(),r.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const n=t[e];i=null==i?void 0:i[n]}return i}selectChildPathsWithObservers(e){const t=[];for(const i of e)this.observersTrie.count(i,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,i)=>{e&&t.push([...i])},i);return t}}function yn(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,r=e.length-1){if(r<n)return-1;const s=Math.trunc((n+r)/2);return 0===i(t,e[s])?s:i(t,e[s])>0?yn(e,t,i,s+1,r):yn(e,t,i,n,s-1)}function mn(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==yn(e,t,i))return;let n;for(n=e.length-1;n>=0&&i(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function bn(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=yn(e,t,i);n>-1&&e.splice(n,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(dn||(dn={}));const In=100;class Sn{constructor(e,t,i,n,r,s,o){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=r,this.querySender=s,this.socketManager=o,this.onOrphanDocuments=new h.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new wn,this.queryResultsSubject=new h.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe(()=>{this.refreshOngoingQueries()}),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}dumpSubscriptionInfo(){console.log("Ongoing queries:",this.ongoingQueries),console.log("ClientRequestId to local documents:",this.clientRequestIdToLocalDocuments),console.log("Local documents to clientRequestId:",this.localDocumentToClientRequestIds)}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return L(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);t?.gotInitialResponse&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:i,integrationId:n}=Ut(t),r=this.queryMappingManager.getMapping(i,n);return r?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,r]of Object.entries(e.conditional||{})){const e=Et(i);let s;if(Wt(e)){const i=dt(t,e.fieldName)??null;s=Gt(e.value,i,e.operator)}else s=vn(e,t);if(s)for(const e of r)n.set(e,(n.get(e)||0)+1)}for(const[t,r]of n.entries())r>=e.queriesMetadata[t].condCount&&i.push(t);return i}(r,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=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):[]),r=new Set([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const r=this.clientRequestIdToLocalDocuments.get(t);r&&(r.delete(e),r.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...r]}errorOutAllQueries(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of i){const i=this.ongoingQueries.get(e);i&&(this.destructManager.isDestructing?i.dataSubject.complete():i.dataSubject.error(t),i.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const i of e){const e=this.ongoingQueries.get(i);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(i)||new Set,r=this.documentStore.sortAndLimitDocs(n,e.query),s=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(r,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=L(o?.supportingOngoingQuery);if(s&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case dn.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+In?dn.ENABLED:dn.DISABLED;break;case dn.DISABLED:break;case dn.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=dn.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(r)}for(const e of t){const t=this.collectAllObservables(e);L(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new Hi(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,r,s){return r&&this.socketManager.notifyWebSocketIsNeeded(),(0,h.defer)(()=>{const o=this.createOngoingQueryGraph(e,t,i,n,r,!0);s&&(o.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(o),o.allObservables=new h.ReplaySubject(1);const a=o.allObservables.pipe((0,h.switchMap)(e=>(0,h.combineLatest)(e).pipe(x(e=>this.joinResults(e,n,o)))),Ki(()=>this.allOngoingQueriesGotInitialResult(o)),(0,h.startWith)(void 0),(0,h.pairwise)(),Ki(([e,t])=>!bt(e,t)),x(([,e])=>e),r?(0,h.tap)():(0,h.take)(1),(0,h.finalize)(()=>{o.dataSubject.complete(),o.done=!0,this.completeAllSupportedQueries(o).then(),o.allObservables?.complete()})),c=this.collectAllObservables(o);return o.allObservables.next(c),a}).pipe((0,h.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}unsubscribe(){const e=[...this.ongoingQueries.values()];for(const t of e)t.dataSubject.complete(),t.allObservables?.complete()}hasSubscription(e){return!!this.ongoingQueries.get(e)?.subscribe}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 Hi(e.query);for(const i of this.ongoingQueries.values()){if(e===i)return;if(this.isValidParent(i)&&t.isSubqueryOfQuery(i.query))return i}}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const i=[];for(const n of t){const t=L(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),i.push(n))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=Ht(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,h.finalize)(async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,h.firstValueFrom)((0,h.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Ki(e=>0===e)))),this.queryMappingManager.removeQuery(i).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const i={clientRequestId:t};this.rpcManager.post("query/unsubscribe",i).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)}),Ki(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,i,n,r,s,o={}){if(o[t])return o[t];const a=this.clientIdService.generateClientRequestId(),c=[],u={clientRequestId:a,activated:s,alias:t,query:e,subscribe:r,dataSubject:new h.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new h.BehaviorSubject(0),queryRegistered:new h.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?dn.UNKNOWN:dn.DISABLED};this.registerQueryFinalizer(u),this.ongoingQueries.set(a,u),o[t]=u;for(const[e,s]of Object.entries(n)){const a=s.leftAlias;if(a!==t&&e!==t)continue;const l=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(i[l],l,i,n,r,!1,o);e.joinCondition=s,c.push(e)}else u.supportingOngoingQuery=this.createOngoingQueryGraph(i[l],l,i,n,r,!1,o)}return u}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Ki(Boolean),x(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const n=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let r=n[i.alias].map(e=>({[i.alias]:e}));const s=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<s.length;e++){const i=s[e].alias;o.has(i)||(o.add(i),r=this.join(r,i,n[i],t[i]))}return r}join(e,t,i,n){if(!e.length)return e;const r=Object.keys(e[0]);if(!n||!r.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const s=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);s.has(t)||s.set(t,[]),L(s.get(t)).push(e)}),e.flatMap(e=>{const i=s.get(this.transformKey(e[n.leftAlias]?.[n.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):n.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=L(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){const i=L(t.joinCondition),n=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const r=L(t.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===t.alias),s=new Set(e.map(e=>e[i.left]??null));for(const e of r)e.query.conditions.filter(Wt).filter(e=>e.fieldName===i.right).forEach(e=>{s.delete(e.value)});if(0===s.size)return!1;const o=St(n);o.conditions=o.conditions.filter(e=>!Wt(e)||e.fieldName!==i.right),[...s].forEach(e=>{o.conditions.push({fieldName:i.right,operator:"==",value:e})});const a={...t,query:o,activated:!0,gotInitialResponse:!1,dataSubject:new h.BehaviorSubject(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(a),this.ongoingQueries.set(a.clientRequestId,a),L(t.supportingOngoingQuery).supportedQueries.push(a),this.sendQueryToServerOrUseParentQuery(a),!0}{if(t.activated=!0,n.conditions.filter(Wt).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return r.length?(n.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=L(t.shift());t.push(...e.supportedQueries||[]),await(0,h.firstValueFrom)(e.unsubscribeBlockerCount.pipe(Ki(e=>0===e))),e.dataSubject.complete()}}transformKey(e){return e instanceof Date?`DATE AS string KEY: ${e.toISOString()}`:e}preDestruct(){this.unsubscribe()}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const i=e.query,n=e.clientRequestId,r=Ht(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,r),this.ongoingQueries.set(n,e);const s=t?void 0:this.findValidParentOfOngoingQuery(e);s?this.useParentOngoingQuery(e,s).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new Hi(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,h.firstValueFrom)(t.queryRegistered.pipe(Ki(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",i).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(i=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,i),e.dataSubject.error(i)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const r=(0,h.race)(e.queryRegistered.pipe(Ki(Boolean),(0,h.delay)(2e3),(0,h.take)(1)),this.destructManager.observeIsDestructing().pipe((0,h.take)(1)));t.dataSubject.pipe((0,h.takeWhile)(()=>!e.done),(0,h.takeUntil)(r),Ki(Boolean),(0,h.tap)(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),x(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc($t(i.__docId__,e.query.collectionName,e.query.integrationId),i);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,i=t>0&&e.subscribe?t+In:t,n={query:{...e.query,limit:i},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()):(jt.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 i of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{i.has(t)&&(i.delete(t),i.add(e[t]))});t.forEach(t=>{yt(this.localDocumentToClientRequestIds,t,e[t])})}}function vn(e,t){for(const i of e.fields){const e=dt(t,i.fieldName)??null;if(Gt(i.value,e,i.operator))return!0;if(Gt(i.value,e,"!="))return!1}return!1}class wn{constructor(){this.stateService=new fn({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const r of e.conditions){if(Wt(r)&&["=="].includes(r.operator)){const e=Ot(r.fieldName);n.has(e)||(i++,n.add(e))}else i++;const s=this.getConditionStatePath(e,r),o=[...this.stateService.get(s)||[]];mn(o,t),this.stateService.set(s,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];mn(n,t),this.stateService.set(i,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],i)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const i of t.conditions){const n=this.getConditionStatePath(t,i),r=[...this.stateService.get(n)||[]];bn(r,e),r.length?this.stateService.set(n,r):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];bn(n,e),this.stateService.set(i,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",(i=t,kt(i))];var i}}class Mn{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,h.lastValueFrom)((0,h.combineLatest)(t).pipe((0,h.filter)(e=>!e.includes(!0)),(0,h.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=L(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){B(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new h.BehaviorSubject(!0)}}class Tn{constructor(e,t,i){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)}),i.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let i=this.queueManagers.get(e);i||(i=new Map,this.queueManagers.set(e,i));let n=i.get(t);return n||(n=new _n(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const kn="subscriptionMutex";class _n{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new h.Subject,this.subscriberCount=0,this.lockManager=new Mn}async produce(e){await this.lockManager.lock(kn);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(kn)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),(0,h.defer)(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,h.finalize)(()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}async performSubscribe(){await this.lockManager.lock(kn);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 h.Subject}finally{this.lockManager.release(kn)}}async performUnsubscribe(){await this.lockManager.lock(kn);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(kn)}}}class En{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,h.firstValueFrom)((0,h.interval)(10).pipe((0,h.filter)(()=>this.attemptConsume()),(0,h.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}}const On={TRACE_ID:"x-squid-traceid",SECRET:"x-squid-secret",APP_API_KEY:"x-app-api-key",APP_ID:"x-squid-appid",CLIENT_ID:"x-squid-clientid",CLIENT_VERSION:"x-squid-client-version",SOURCE_IP:"x-squid-source-ip"};function Cn(e="n_"){return`${e}${J(10).toLowerCase()}`}const Dn=e=>e();class An extends Error{constructor(e,t,i,n,r){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=r}}const qn="1.0.413";async function Nn(e){const t=await Pn({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=Bn(t.body),t}async function Rn(e){const t=await Pn({...e,method:"GET",files:[],filesFieldName:""});return t.body=Bn(t.body),t}async function Fn(e){const t=await Pn({...e,method:"PUT"});return t.body=Bn(t.body),t}async function xn(e){const t=await Pn({...e,method:"PATCH"});return t.body=Bn(t.body),t}async function jn(e){const t=await Pn({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=Bn(t.body),t}async function Pn({headers:e,files:t,filesFieldName:i,message:n,url:r,extractErrorMessage:s,method:o}){const a=new Headers(e);a.append(On.TRACE_ID,Cn("c_")),a.append(On.CLIENT_VERSION,qn);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const n of t)e.append(i||"files",n,n.name);e.append("body",_t(n)),c.body=e}else void 0!==n&&(a.append("Content-Type","application/json"),c.body=_t(n));else"DELETE"===o&&void 0!==n&&(a.append("Content-Type","application/json"),c.body=_t(n));try{const e=await fetch(r,c),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=Bn(i);if(!s)throw new An(i,e.status,r,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new An(o,e.status,r,t,n)}const i=await e.text();return jt.debug(`received response from url ${r}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw jt.debug(`Unable to perform fetch request to url: ${r}`,e),e}}function Bn(e){if(e){try{return Et(e)}catch{}return e}}class Ln{constructor(e,t,i,n,r,s){this.region=e,this.appId=t,this.authManager=r,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new h.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")}),i.onDestruct(async()=>{await this.awaitAllSettled()});const o=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new En(60*o,5),ai:new En(20*o,5),secret:new En(20*o,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:i}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return i&&(n+=`; IntegrationId ${i}`),{Authorization:n}}async awaitAllSettled(){await(0,h.firstValueFrom)(this.onGoingRpcCounter.pipe((0,h.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,i=[],n="files",r={}){return(await this.rawPost(e,t,i,n,!0,r)).body}async rawPost(e,t,i=[],n="files",r=!0,o={}){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const a=await this.getAuthHeaders(),c={...this.staticHeaders,...a,...o};jt.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const u=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await Nn({url:u,headers:c,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),r={...this.staticHeaders,...n};let o=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,i])=>{e.append(t,String(i))}),o+=`?${e.toString()}`}return jt.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await Rn({url:o,headers:r,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};jt.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await Fn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};jt.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await xn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),r={...this.staticHeaders,...n};jt.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await jn({url:o,headers:r,message:t,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?L(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?L(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):L(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Qn{constructor(e){this.rpcManager=e}async list(){return(await this.rpcManager.post("/scheduler/listSchedulers",{})).schedulers}async enable(e){await this.update(this.createUpdateSchedulerOptions(e,!0))}async disable(e){await this.update(this.createUpdateSchedulerOptions(e,!1))}async update(e){const t={schedulers:e};await this.rpcManager.post("scheduler/updateSchedulers",t)}createUpdateSchedulerOptions(e,t){return Array.isArray(e)?e.map(e=>({schedulerId:e,enabled:t})):[{schedulerId:e,enabled:t}]}}function Un(){}const $n="undefined"!=typeof process&&process.versions?.node?i(86):xt().WebSocket;class Gn{constructor(e,t,i,n=Dn,r,s){this.clientIdService=e,this.region=t,this.appId=i,this.messageNotificationWrapper=n,this.destructManager=r,this.authManager=s,this.webSocketObserver=new h.Subject,this.allMessagesObserver=new h.Subject,this.connectionReady=new h.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new h.Subject,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new h.BehaviorSubject(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe((0,h.skip)(1),(0,h.filter)(e=>!e),(0,h.switchMap)(()=>(0,h.race)((0,h.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,h.filter)(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?jt.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(jt.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe((0,h.filter)(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe((0,h.filter)(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?jt.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?jt.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(jt.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),jt.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}getClientInfo(){this.sendMessage({type:"getClientInfo"})}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,h.distinctUntilChanged)())}async awaitConnectionReady(){await(0,h.firstValueFrom)(this.observeConnectionReady().pipe((0,h.filter)(Boolean)))}notifyWebSocketIsNeeded(){this.webSocketNeededSubject.next(!0)}sendMessage(e){this.sendMessageAsync(e).then()}disconnectForTest(){this.connectionReady.next(!1),this.socket?.close(4998)}keepAlive(){this.lastTick&&(Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(jt.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageAsync(e){this.webSocketNeededSubject.next(!0),await(0,h.firstValueFrom)(this.connectionReady.pipe((0,h.filter)(Boolean)));const t=await this.authManager.getToken();if(this.connectionReady.value)try{B(this.socket,"Socket is undefined in sendMessageAsync");const i=_t({message:e,authToken:t});jt.debug(this.clientIdService.getClientId(),"Sending message to socket: ",i),this.socket.send(i)}catch(t){this.socket?.connected?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){this.socket?.connected&&this.socket.send(_t({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=s(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();jt.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,r=1;const s={connected:!1,closeCalled:!1,open(){i=new($n?.WebSocket??$n)(e,t.protocols||[]),i.onmessage=t.onmessage?e=>{e.data&&t.onmessage?t.onmessage(e):console.log("No data received from websockets, please contact support@getsquid.ai with this message.")}:Un,i.onopen=function(e){s.connected=!0,(t.onopen||Un)(e),n=0},i.onclose=function(e){if(s.connected=!1,4999!==e.code&&4001!==e.code)return jt.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Un)(e),void s.reconnect(e);(t.onclose||Un)(e)},i.onerror=function(e){s.connected=!1,e&&"ECONNREFUSED"===e.code?s.reconnect(e):s.closeCalled||(t.onerror||Un)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;r&&n++<i?r=setTimeout(function(){(t.onreconnect||Un)(e),jt.debug("WebSocket trying to reconnect..."),s.open()},t.timeoutMillis||1e3):(t.onmaximum||Un)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){s.closeCalled=!0;try{s.connected=!1,clearTimeout(r),r=void 0,i.close(e,t)}catch(e){}}};return s.open(),s}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{jt.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{jt.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):jt.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{jt.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):jt.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return jt.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=Et(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),jt.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new h.Subject;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe((0,h.tap)(e=>t.push(e)),(0,h.debounceTime)(100)).subscribe(async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await(0,h.firstValueFrom)((0,h.timer)(0)),this.connectionReady.next(!1),await(0,h.firstValueFrom)((0,h.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Vn(e){var t,i;i="Invalid application ID",B(function(e){return"string"==typeof e}(t=e),()=>U(i,"Not a string",t));const[n,r,s,o]=e.split("-");return B(!o,`Invalid application ID: ${e}`),{appId:n,environmentId:r??"prod",squidDeveloperId:s}}function Hn(e,t){return`${Vn(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function Wn(e,t,i){return`${Hn(e,t)}${i?`-${i}`:""}`}function Kn(e){const t=Vn(e);return Hn(t.appId,t.environmentId)}class zn{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};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 i={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",i)}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 Jn{constructor(e,t,i,n,r){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n,this.consoleRegion=r}async aiSearch(e){return await this.rpcManager.post("web/aiSearch",{query:e})}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e,t){B(this.apiKey,"API key is required to create a short URL");const i=o(this.region,this.consoleRegion,"openapi/sqd/shorten"),n={url:e,appId:this.appId,secondsToLive:t},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!r.ok)throw console.error("Error making POST request to shorten endpoint",r.statusText),new Error(`${r.statusText}: ${r.text}`);return await r.json()}async createShortUrls(e,t){B(this.apiKey,"API key is required to create a short URL");const i=o(this.region,this.consoleRegion,"openapi/sqd/shortenMany"),n={urls:e,appId:this.appId,secondsToLive:t},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!r.ok)throw console.error("Error making POST request to shortenMany endpoint",r.statusText),new Error(`${r.statusText}: ${r.text}`);return await r.json()}async deleteShortUrl(e){B(this.apiKey,"API key is required to delete a short URL");const t=o(this.region,this.consoleRegion,"openapi/sqd/delete"),i={id:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}async deleteShortUrls(e){B(this.apiKey,"API key is required to delete a short URL");const t=o(this.region,this.consoleRegion,"openapi/sqd/deleteMany"),i={ids:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}}class Yn{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:n={},body:r,files:o=[]}=t,a=await this.rpcManager.getAuthHeaders(),c={...this.rpcManager.getStaticHeaders(),...a,...i};let u=s(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(n&&Object.keys(n).length>0){const e=new URLSearchParams;Object.entries(n).forEach(([t,i])=>{e.append(t,String(i))}),u+=`?${e.toString()}`}const l=new Headers(c);let h;if(l.append(On.TRACE_ID,Cn("c_")),l.append(On.CLIENT_VERSION,qn),o&&o.length>0){const e=new FormData;for(const t of o)e.append("file",t,t.name);r&&"object"==typeof r&&Object.entries(r).forEach(([t,i])=>{e.append(t,String(i))}),h=e}else l.append("Content-Type","application/json"),h=_t(r||{});const d=await fetch(u,{method:"POST",headers:l,body:h}),p={};if(d.headers.forEach((e,t)=>{p[t]=e}),!d.ok){const e=await d.text();let t;try{t=JSON.parse(e)}catch{t=e}const i="string"==typeof t?t:t?.message||d.statusText;throw new An(i,d.status,u,p,t)}const g=await d.text();let f;try{f=JSON.parse(g)}catch{f=g}return f}}class Zn{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Ii,B(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,i=Wn(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Pt(this.destructManager),jt.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new lt(e.apiKey,e.authProvider),this.socketManager=new Gn(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Ln(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Ci(this.socketManager,this.rpcManager),this.jobClient=new _i(this.socketManager,this.rpcManager,this.clientIdService),this.backendFunctionManager=new Rt(this.rpcManager),this.aiClient=new at(this.socketManager,this.rpcManager,this.jobClient,this.backendFunctionManager),this.apiClient=new ut(this.rpcManager),this.documentStore=new Ti,this.lockManager=new Mn,this.distributedLockManager=new Si(this.socketManager,this.destructManager),this.documentIdentityService=new wi(this.documentStore,this.destructManager),this.documentReferenceFactory=new Mi(this.documentIdentityService),this.querySender=new zi(this.rpcManager,this.destructManager),this.observabilityClient=new Ai(this.rpcManager),this.schedulerClient=new Qn(this.rpcManager),this._appId=i,this.querySubscriptionManager=new Sn(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager),this.localQueryManager=new Wi(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new Ei(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Jt(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new mi(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new ai(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.webhookManager=new Yn(this.rpcManager,e.region,i),this.nativeQueryManager=new Oi(this.rpcManager),this._connectionDetails=new ci(this.clientIdService,this.socketManager),this.queueManagerFactory=new Tn(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new l(this.rpcManager,this.options.region,Kn(i),this.options.consoleRegion),this.webClient=new Jn(this.rpcManager,this.options.region,Kn(i),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}static getInstance(e){const t=kt(e);let i=Zn.squidInstancesMap[t];return i||(i=new Zn(e),Zn.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(Zn.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Ke){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),this.backendFunctionManager.executeFunction(e,...t)}executeFunctionWithHeaders(e,t,...i){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...i)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}executeNativeRelationalQuery(e,t,i={}){const n={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativePureQuery(e,t,i={}){const n={type:"pure",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,i){const n={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeElasticQuery(e,t,i,n="_search",r="GET"){const s={type:"elasticsearch",index:t,endpoint:n,method:r,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}ai(){return this._validateNotDestructed(),this.aiClient}job(){return this._validateNotDestructed(),this.jobClient}api(){return this._validateNotDestructed(),this.apiClient}admin(){return this._validateNotDestructed(),this.adminClient}web(){return this._validateNotDestructed(),this.webClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new zn(e,this.rpcManager)}personalStorage(e){return this._validateNotDestructed(),new Ri(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new ki(this.rpcManager)}acquireLock(e){return this._validateNotDestructed(),this.distributedLockManager.lock(e)}async withLock(e,t){const i=await this.acquireLock(e);try{return await t(i)}finally{i.release()}}queue(e,t=ze){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Zn.squidInstancesMap).find(([,e])=>e===this);e&&delete Zn.squidInstancesMap[e[0]]})}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}getNotificationClient(){return this._validateNotDestructed(),this.notificationClient}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,i)=>s(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>Wn(e,t,i)}}_validateNotDestructed(){B(!this.destructManager.isDestructing,"The client was already destructed.")}}var Xn=exports;for(var er in n)Xn[er]=n[er];n.__esModule&&Object.defineProperty(Xn,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{"use strict";var e={86:e=>{e.exports=require("ws")},150:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const s=i(642);t.default=s.PromisePool,r(i(273),t),r(i(642),t),r(i(837),t),r(i(426),t),r(i(858),t),r(i(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(642),r=i(172),s=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw r.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}isValidConcurrency(e){return"number"==typeof e&&e>=1}withTaskTimeout(e){return this.meta.taskTimeout=e,this}concurrency(){return this.meta.concurrency}useCorrespondingResults(e){return this.meta.shouldResultsCorrespond=e,this}shouldUseCorrespondingResults(){return this.meta.shouldResultsCorrespond}taskTimeout(){return this.meta.taskTimeout}for(e){return this.meta.items=e,this}items(){return this.meta.items}itemsCount(){const e=this.items();return Array.isArray(e)?e.length:NaN}tasks(){return this.meta.tasks}activeTaskCount(){return this.activeTasksCount()}activeTasksCount(){return this.tasks().length}processedItems(){return this.meta.processedItems}processedCount(){return this.processedItems().length}processedPercentage(){return this.processedCount()/this.itemsCount()*100}results(){return this.meta.results}errors(){return this.meta.errors}withHandler(e){return this.handler=e,this}hasErrorHandler(){return!!this.errorHandler}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers=e,this}onTaskFinished(e){return this.onTaskFinishedHandlers=e,this}hasReachedConcurrencyLimit(){return this.activeTasksCount()>=this.concurrency()}stop(){throw this.markAsStopped(),new o.StopThePromisePoolError}markAsStopped(){return this.meta.stopped=!0,this}isStopped(){return this.meta.stopped}async start(){return await this.validateInputs().prepareResultsArray().process()}validateInputs(){if("function"!=typeof this.handler)throw r.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw r.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw r.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return!!Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()?(this.meta.results=Array(e.length).fill(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new s.PromisePoolError(`Task in promise pool timed out after ${this.taskTimeout()}ms`,e))},this.taskTimeout())}),()=>clearTimeout(t)]}save(e,t){return this.shouldUseCorrespondingResults()?this.results()[t]=e:this.results().push(e),this}removeActive(e){return this.tasks().splice(this.tasks().indexOf(e),1),this}async handleErrorFor(e,t,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof r.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(s.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},426:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class r{constructor(e){this.timeout=void 0,this.concurrency=10,this.items=e??[],this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[],this.shouldResultsCorrespond=!1}withConcurrency(e){return this.concurrency=e,this}static withConcurrency(e){return(new this).withConcurrency(e)}withTaskTimeout(e){return this.timeout=e,this}static withTaskTimeout(e){return(new this).withTaskTimeout(e)}for(e){const t=new r(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=r,r.notRun=Symbol("notRun"),r.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};i.r(n),i.d(n,{AI_AGENTS_INTEGRATION_ID:()=>Ue,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Ne,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>qe,AI_CHAT_MESSAGE_SOURCE:()=>he,AI_EMBEDDINGS_MODEL_NAMES:()=>Te,AI_IMAGE_MODEL_NAMES:()=>Ae,AI_PROVIDER_TYPES:()=>fe,AI_STATUS_MESSAGE_PARENT_MESSAGE_ID_TAG:()=>de,AI_STATUS_MESSAGE_RESULT_TAG:()=>pe,ALL_OPERATORS:()=>st,ANTHROPIC_CHAT_MODEL_NAMES:()=>Ie,API_INJECTION_FIELD_TYPES:()=>je,ARRAY_OPERATORS:()=>rt,AUTH_INTEGRATION_TYPES:()=>Ve,AdminClient:()=>l,AiAgentClient:()=>te,AiAgentReference:()=>X,AiAssistantClient:()=>ne,AiAudioClient:()=>re,AiClient:()=>ct,AiImageClient:()=>se,AiKnowledgeBaseClient:()=>ce,AiKnowledgeBaseReference:()=>ae,AiMatchMakingClient:()=>ue,ApiClient:()=>lt,ApiKeysSecretClient:()=>u,AuthManager:()=>ht,BUILT_IN_AGENT_ID:()=>Le,BUILT_IN_DB_INTEGRATION_ID:()=>ze,BUILT_IN_QUEUE_INTEGRATION_ID:()=>Je,BUILT_IN_STORAGE_INTEGRATION_ID:()=>Ye,BackendFunctionManager:()=>Ft,BaseQueryBuilder:()=>Zt,CLIENT_CONNECTION_STATES:()=>at,CLIENT_ID_GENERATOR_KEY:()=>Lt,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>Qt,Changes:()=>ti,ClientIdService:()=>Bt,CollectionReference:()=>oi,CollectionReferenceFactory:()=>ci,ConnectionDetails:()=>ui,DATA_INTEGRATION_TYPES:()=>Ge,DEFAULT_SHORT_ID_LENGTH:()=>H,DataManager:()=>bi,DereferencedJoin:()=>ni,DestructManager:()=>Si,DistributedLockImpl:()=>wi,DistributedLockManager:()=>vi,DocumentReference:()=>zt,DocumentReferenceFactory:()=>Ti,DocumentStore:()=>ki,EMPTY_CHAT_ID:()=>ie,ENVIRONMENT_IDS:()=>Be,ExternalAuthClient:()=>_i,ExtractionClient:()=>Ei,FETCH_BEYOND_LIMIT:()=>vn,FLUX_MODEL_NAMES:()=>De,GEMINI_CHAT_MODEL_NAMES:()=>me,GRAPHQL_INTEGRATION_TYPES:()=>He,GROK_CHAT_MODEL_NAMES:()=>be,GroupedJoin:()=>si,HTTP_INTEGRATION_TYPES:()=>We,HttpStatus:()=>Qe,INTEGRATION_SCHEMA_TYPES:()=>Ke,INTEGRATION_TYPES:()=>$e,IntegrationClient:()=>a,JobClient:()=>Ci,JoinQueryBuilder:()=>ii,LastUsedValueExecuteFunctionCache:()=>qt,LimitUnderflowState:()=>gn,LocalQueryManager:()=>zi,METRIC_DOMAIN:()=>it,METRIC_FUNCTIONS:()=>tt,METRIC_INTERVAL_ALIGNMENT:()=>nt,MatchMaker:()=>le,MutationSender:()=>Oi,NOOP_FN:()=>qn,NativeQueryManager:()=>Di,NotificationClient:()=>Ai,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Ee,OPENAI_AUDIO_MODEL_NAMES:()=>Ce,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>_e,OPENAI_CHAT_MODEL_NAMES:()=>ye,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>we,OPENAI_IMAGE_MODEL_NAMES:()=>ke,OPEN_AI_CREATE_SPEECH_FORMATS:()=>Re,ObservabilityClient:()=>Ni,Pagination:()=>Jt,PersonalStorageClient:()=>xi,QueryBuilder:()=>ei,QueryBuilderFactory:()=>Yt,QuerySender:()=>Yi,QuerySubscriptionManager:()=>wn,QueueManagerFactory:()=>_n,QueueManagerImpl:()=>Cn,RAG_TYPES:()=>xe,RERANK_PROVIDERS:()=>ge,RateLimiter:()=>On,RpcManager:()=>Un,SQUID_BUILT_IN_INTEGRATION_IDS:()=>Ze,SQUID_METRIC_NAMES:()=>et,SQUID_REGIONS:()=>ot,STABLE_DIFFUSION_MODEL_NAMES:()=>Oe,SchedulerClient:()=>$n,SecretClient:()=>c,SocketManager:()=>Hn,Squid:()=>er,SquidClientError:()=>Nn,StorageClient:()=>Yn,VENDOR_AI_CHAT_MODEL_NAMES:()=>Se,VOYAGE_EMBEDDING_MODEL_NAMES:()=>Me,WebClient:()=>Zn,WebhookManager:()=>Xn,base64ToFile:()=>Z,compareArgsByReference:()=>Dt,compareArgsBySerializedValue:()=>At,deserializeQuery:()=>Pi,generateId:()=>V,generateShortId:()=>K,generateShortIds:()=>z,generateUUID:()=>$,generateUUIDPolyfill:()=>G,getConsoleUrl:()=>o,getCustomizationFlag:()=>xt,isBuiltInIntegrationId:()=>Xe,isIntegrationModelSpec:()=>Fe,isPlaceholderParam:()=>Pe,isVendorAiChatModelName:()=>ve,rawSquidHttpDelete:()=>Bn,rawSquidHttpGet:()=>xn,rawSquidHttpPatch:()=>Pn,rawSquidHttpPost:()=>Fn,rawSquidHttpPut:()=>jn,transformFileArgs:()=>Nt,tryDeserializing:()=>Qn,visitQueryResults:()=>ji});const r=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function s(e,t,i,n,s,o){let a="https",c=`${n||t}.${s||e}.${new URL("https://squid.cloud").host}`,u="";/^local/.test(e)&&(a="http",u=r.includes(i.replace(/^\//,"").split("/")[0]||"")||o?"8001":"8000",/android$/.test(e)?c="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(c="localhost"));const l=a+"://"+c+(u?`:${u}`:""),h=i.replace(/^\/+/,"");return h?`${l}/${h}`:l}function o(e,t,i=""){return s(function(e,t){return t||(e.includes("sandbox")?"us-east-1.aws.sandbox":e.includes("local")?"local":e.includes("staging")?"us-central1.gcp.staging":"us-east-1.aws")}(e,t),"console",i)}class a{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async setIntegrationSchema(e,t){await this.rpcManager.put(`${this.iacBaseUrl}/${e}/schema`,t)}async delete(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}async deleteMany(e){await Promise.all(e.map(e=>this.delete(e)))}async upsertIntegration(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e.id}`,e)}}class c{constructor(e){this.rpcManager=e}get apiKeys(){return new u(this.rpcManager)}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}async upsert(e,t){return this.upsertMany([{key:e,value:t}]).then(e=>e[0])}async upsertMany(e){if(0===e.length)return[];const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e,t=!1){const i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}}class u{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)}}class l{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new a(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new c(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}const h=require("rxjs");function d(e){return"function"==typeof e}function p(e){return function(t){if(function(e){return d(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}var g=function(e,t){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},g(e,t)};function f(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}g(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function y(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}function b(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var I,S=((I=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}(function(e){Error.call(e),e.stack=(new Error).stack})).prototype=Object.create(Error.prototype),I.prototype.constructor=I,I);function v(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var w=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,i,n,r;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=y(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(d(c))try{c()}catch(e){r=e instanceof S?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=y(u),h=l.next();!h.done;h=l.next()){var p=h.value;try{M(p)}catch(e){r=null!=r?r:[],e instanceof S?r=b(b([],m(r)),m(e.errors)):r.push(e)}}}catch(e){i={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(r)throw new S(r)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)M(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&v(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&v(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function M(e){d(e)?e():e.unsubscribe()}w.EMPTY;var T={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var r=T.delegate;return(null==r?void 0:r.setTimeout)?r.setTimeout.apply(r,b([e,t],m(i))):setTimeout.apply(void 0,b([e,t],m(i)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function k(){}var _=E("C",void 0,void 0);function E(e,t,i){return{kind:e,value:t,error:i}}var C=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof w||i&&"closed"in i&&d(i.remove)&&d(i.add)&&d(i.unsubscribe))&&t.add(n)):n.destination=N,n}return f(t,e),t.create=function(e,t,i){return new D(e,t,i)},t.prototype.next=function(e){this.isStopped?q(function(e){return E("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?q(E("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?q(_,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(w);Function.prototype.bind;var O=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){A(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){A(e)}else A(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){A(e)}},e}(),D=function(e){function t(t,i,n){var r,s=e.call(this)||this;return r=d(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,s.destination=new O(r),s}return f(t,e),t}(C);function A(e){!function(e){T.setTimeout(function(){throw e})}(e)}function q(e,t){var i=null;i&&T.setTimeout(function(){return i(e,t)})}var N={closed:!0,next:k,error:function(e){throw e},complete:k};function R(e,t,i,n,r){return new F(e,t,i,n,r)}var F=function(e){function t(t,i,n,r,s,o){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=r?function(e){try{r(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return f(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(C);function x(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){n.next(e.call(t,i,r++))}))})}function j(e){return null!=e}let P=e=>new Error(e);function B(e,t,...i){e||function(e,...t){const i=Q(e);if("object"==typeof i)throw i;throw P(i||"Assertion error",...t)}(t,...i)}function L(e,t,...i){return B(e,t,...i),e}function Q(e){return void 0===e?"":"string"==typeof e?e:e()}function U(e,t,i){const n=Q(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}function $(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():G()}function G(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function V(){return $()}const H=18,W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function K(e=H,t=""){B(t.length<e,"ID prefix is too long");let i="";for(let t=0;t<e;t++)i+=W.charAt(Math.floor(Math.random()*W.length));return t.length>0&&(i=t+i.substring(t.length)),i}function z({count:e,length:t,prefix:i}){B(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(K(t||H,i||""));return[...n]}const J=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Y(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Y(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Y(t);else for(const t in e){if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata filter key ${t} - can only contain letters, numbers, and underscores`);if(J.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${J.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function Z(e,t,i){const n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new File([r],t,{type:i||"application/octet-stream"})}class X{constructor(e,t,i,n,r,s,o){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=n,this.socketManager=r,this.jobClient=s,this.backendFunctionManager=o}async get(){const e=await this.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){await this.setAgentOptionInPath("instructions",e)}async updateModel(e){await this.setAgentOptionInPath("model",e)}async updateConnectedAgents(e){await this.setAgentOptionInPath("connectedAgents",e)}async updateGuardrails(e){const t=await this.get();B(t,"Agent not found");const i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}async updateCustomGuardrails(e){await this.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}async regenerateApiKey(){return await this.post("ai/agent/regenerateApiKey",{agentId:this.agentId})}async getApiKey(){return await this.post("ai/agent/getApiKey",{agentId:this.agentId})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),r=await L(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:r.transcribedPrompt}}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);return this.replaceFileTags(n.responseString,n.annotations)}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:i,jobId:t};await this.post("ai/chatbot/askAsync",n)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiStatus"===e.type&&e.agentId===this.agentId),x(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,messageId:e.messageId})))}async getChatHistory(e){const t={agentId:this.agentId,memoryId:e};return(await this.post("ai/chatbot/history",t)).messages}async transcribeAndAsk(e,t,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:Z(r.base64File,`voice.${r.extension}`,r.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:Z(r.base64File,`voice.${r.extension}`,r.mimeType)}}async setAgentOptionInPath(e,t){await this.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const r=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${r}](${n.aiFileUrl.url})`}i=i.replace(`\${id:${e}}`,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&Y(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)Y(i.contextMetadataFilterForKnowledgeBase[e]);n=n||$(),i={...ee,...i||{}};const r="string"==typeof e;let s="ai/chatbot/";s+=r||t?!r&&t?"transcribeAndAskWithVoiceResponse":r&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:r?e:void 0,options:i,jobId:n},a=r?void 0:[e];return await this.post(s,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Y(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Y(t.contextMetadataFilterForKnowledgeBase[e]);const n=$(),r=void 0===(t={...ee,...t||{}}).smoothTyping||t.smoothTyping;let s="";const o=new h.Subject,a=new h.Subject;this.ongoingChatSequences[n]=a;let c=-1;a.pipe((0,h.tap)(({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)}),(0,h.concatMap)(({value:e,complete:t,annotations:i})=>t?(0,h.of)({value:e,complete:t,annotations:i}):(0,h.of)(e).pipe(r?(0,h.delay)(0):(0,h.tap)(),x(e=>({value:e,complete:!1,annotations:void 0})))),(0,h.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{s+=e,t&&i&&(s=this.replaceFileTags(s,i)),o.next(s)},error:e=>{console.error(e)},complete:()=>{o.complete()}});const u="string"==typeof e;i=i||$();const l={agentId:this.agentId,jobId:i,prompt:u?e:void 0,options:t,clientRequestId:n},d={responseStream:o.pipe((0,h.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,h.share)())};return u?this.post("ai/chatbot/chat",l).catch(e=>{o.error(e),o.complete()}):this.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch(e=>{throw o.error(e),o.complete(),e}),d.serverResponse=this.jobClient.awaitJob(i).catch(e=>{o.error(e),o.complete()}),d}async post(e,t,i=[],n="files"){const r={};return this.agentApiKey&&(r["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,n,r)}}const ee={smoothTyping:!0,responseFormat:"text"};class te{constructor(e,t,i,n){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiChatbot"===e.type),x(e=>e)).subscribe(e=>{this.handleChatResponse(e).then()})}agent(e,t=void 0){return new X(e,t?.apiKey,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)}async listAgents(){return(await this.rpcManager.post("ai/agent/listAgents",{})).agents}async handleChatResponse(e){const t=this.ongoingChatSequences[e.clientRequestId];if(!t)return;const{token:i,complete:n,tokenIndex:r,annotations:s}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:s});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===r?void 0:r,annotations:s});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===r?void 0:r,annotations:s})}}const ie="__squid_empty_chat_id";class ne{constructor(e){this.rpcManager=e}async createAssistant(e,t,i,n){const r={name:e,instructions:t,functions:i,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",r)).assistantId}async deleteAssistant(e){const t={assistantId:e};await this.rpcManager.post("ai/assistant/deleteAssistant",t)}async createThread(e){const t={assistantId:e};return(await this.rpcManager.post("ai/assistant/createThread",t)).threadId}async deleteThread(e){const t={threadId:e};await this.rpcManager.post("ai/assistant/deleteThread",t)}async queryAssistant(e,t,i,n,r){const s={assistantId:e,threadId:t,prompt:i,fileIds:n,options:r};return(await this.rpcManager.post("ai/assistant/queryAssistant",s)).answer}async addFileToAssistant(e,t){const i={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",i,[t],"file")).fileId}async removeFileFromAssistant(e,t){const i={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",i)}async addFileToThread(e,t){const i={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",i,[t],"file")).fileId}}class re{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return Z(n.base64File,`audio.${n.extension}`,n.mimeType)}}class se{constructor(e){this.rpcManager=e}async generate(e,t){const i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function oe(e){for(const t in e){const i=e[t];B("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),B(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class ae{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(e){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId,truncateTextAfter:e})).contexts||[]}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}async getContext(e){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e})).context}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/knowledge-base/deleteContexts",{knowledgeBaseId:this.knowledgeBaseId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&oe(t.metadata);const i=$();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}async searchContextsWithPrompt(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithPrompt",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async searchContextsWithContextId(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithContextId",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async downloadContext(e){const t={knowledgeBaseId:this.knowledgeBaseId,contextId:e};return await this.rpcManager.post("ai/knowledge-base/downloadContext",t)}}class ce{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new ae(e,this.rpcManager,this.jobClient)}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async delete(e){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:e})}}class ue{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new le(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new le(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class le{constructor(e,t){this.matchMaker=e,this.rpcManager=t,this.id=e.id}async insertEntity(e){await this.rpcManager.post("matchMaking/insertEntity",{matchMakerId:this.id,entity:e})}async insertManyEntities(e){await this.rpcManager.post("matchMaking/insertEntities",{matchMakerId:this.id,entities:e})}async delete(){await this.rpcManager.post("matchMaking/deleteMatchMaker",{matchMakerId:this.id})}async deleteEntity(e){await this.rpcManager.post("matchMaking/deleteEntity",{entityId:e,matchMakerId:this.id})}async findMatches(e,t={}){return(await this.rpcManager.post("matchMaking/findMatches",{matchMakerId:this.id,entityId:e,options:t})).matches}async findMatchesForEntity(e,t={}){return(await this.rpcManager.post("matchMaking/findMatchesForEntity",{matchMakerId:this.id,entity:e,options:t})).matches}async listEntities(e,t={}){return await this.rpcManager.post("matchMaking/listEntities",{categoryId:e,options:t,matchMakerId:this.id})}async getEntity(e){return(await this.rpcManager.post("matchMaking/getEntity",{matchMakerId:this.id,entityId:e})).entity}getMatchMakerDetails(){return this.matchMaker}}const he=["user","ai"],de="parent",pe="result",ge=["cohere","none"],fe=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],ye=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],me=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],be=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4","grok-4-fast-reasoning","grok-4-fast-non-reasoning"],Ie=["claude-3-7-sonnet-latest","claude-haiku-4-5-20251001","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-sonnet-4-20250514","claude-sonnet-4-5-20250929"],Se=[...ye,...Ie,...me,...be];function ve(e){return Se.includes(e)}const we=["text-embedding-3-small"],Me=["voyage-3-large"],Te=[...we,...Me],ke=["dall-e-3"],_e=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],Ee=["tts-1","tts-1-hd","gpt-4o-mini-tts"],Ce=[..._e,...Ee],Oe=["stable-diffusion-core"],De=["flux-pro-1.1","flux-kontext-pro"],Ae=[...ke,...Oe,...De],qe=[..._e],Ne=[...Ee],Re=["mp3","opus","aac","flac","wav","pcm"];function Fe(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const xe=["contextual","basic"],je=["secret","regular"];function Pe(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Be=["dev","prod"],Le="built_in_agent",Qe={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,MOVED_TEMPORARILY:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,REQUEST_TOO_LONG:413,REQUEST_URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,REQUESTED_RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,INSUFFICIENT_SPACE_ON_RESOURCE:419,METHOD_FAILURE:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},Ue="ai_agents",$e=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","built_in_db","built_in_gcs","built_in_queue","built_in_s3","cassandra","clickhouse","cloudsql","cockroach","cognito","connected_knowledgebases","confluence","confluent","datadog","db2","descope","documentdb","dynamodb","elasticsearch","firebase_auth","firestore","gcs","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","keycloak","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce_crm","sap_hana","sentry","servicenow","snowflake","spanner","xata","zendesk","mail","slack","mcp","a2a","legend","ollama"],Ge=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch","legend"],Ve=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth"],He=["graphql","linear"],We=["api"],Ke=["data","api","graphql"],ze="built_in_db",Je="built_in_queue",Ye="built_in_storage",Ze=[ze,Je,Ye];function Xe(e){return Ze.includes(e)}const et=["squid_functionExecution_count","squid_functionExecution_time"],tt=["sum","max","min","average","median","p95","p99","count"],it=["user","squid"],nt=["align-by-start-time","align-by-end-time"],rt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],st=[...rt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],ot=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],at=["CONNECTED","DISCONNECTED","REMOVED"];class ct{constructor(e,t,i,n){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.backendFunctionManager=n,this.aiAssistantClient=new ne(this.rpcManager)}agent(e=Le,t=void 0){return this.getAiAgentClient().agent(e,t)}knowledgeBase(e){return this.getAiKnowledgeBaseClient().knowledgeBase(e)}async listAgents(){return this.getAiAgentClient().listAgents()}async listKnowledgeBases(){return this.getAiKnowledgeBaseClient().listKnowledgeBases()}assistant(){return this.aiAssistantClient}image(){return new se(this.rpcManager)}audio(){return new re(this.rpcManager)}matchMaking(){return new ue(this.rpcManager)}executeAiQuery(e,t,i){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,i,n){const r={integrationId:e,prompt:t,allowedEndpoints:i,provideExplanation:n};return this.rpcManager.post("ai/query/executeApiQuery",r)}async getApplicationAiSettings(){return(await this.rpcManager.post("ai/settings/getApplicationAiSettings",{})).settings}async setApplicationAiSettings(e){const t={settings:e};await this.rpcManager.post("ai/settings/setApplicationAiSettings",t)}async setAiProviderApiKeySecret(e,t){const i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new te(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new ce(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const ut={headers:{},queryParams:{},pathParams:{}};class lt{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,r){const s={integrationId:e,endpointId:t,body:i,options:{...ut,...this.convertOptionsToStrings(n||{})},overrideMethod:r};return await this.rpcManager.rawPost("api/callApi",s,void 0,void 0,!1)}convertOptionsToStrings(e){return{headers:this.convertToStrings(e.headers),queryParams:this.convertToStrings(e.queryParams),pathParams:this.convertToStrings(e.pathParams)}}convertToStrings(e){if(!e)return{};const t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,String(t)]);return Object.fromEntries(t)}}class ht{constructor(e,t){this.apiKey=e,this.authProvider=t}setAuthProvider(e){this.authProvider=e}async getAuthData(){return{token:await this.getTokenFromAuthProvider(),integrationId:this.authProvider?.integrationId}}getApiKey(){return this.apiKey}async getToken(){if(this.apiKey)return{type:"ApiKey",token:this.apiKey};const e=await this.getTokenFromAuthProvider();return e?{type:"Bearer",token:e,integrationId:this.authProvider?.integrationId}:void 0}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}}const dt=/[.\[\]]/;function pt(e,t){if(!e)return;const i=t.split(dt);let n,r=e;for(;r&&i.length;){const e=i.shift();if(e){if("object"!=typeof r||!(e in r))return;n=r[e],r=n}}return n}function gt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ft(e,t,i,n="."){const r=t.split(n);let s=e;for(;r.length;){const e=L(r.shift());if(r.length){const t=s[e],i=gt(t)?wt(t)??{}:{};s[e]=i,s=i}else s[e]=i}}function yt(e,t,i="."){const n=t.split(i);let r=e;for(;n.length;){const e=L(n.shift());if(n.length){const t=gt(r[e])?wt(r[e])??{}:{};r[e]=t,r=t}else delete r[e]}}function mt(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function bt(e){return null==e}function It(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const i=typeof e;if(i!==typeof t)return!1;if("object"!==i)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i)||!It(e[i],t[i]))return!1;return!0}function St(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=vt(e[n],t);return i}function vt(e,t){const i=t?t(e):void 0;if(void 0!==i)return i;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return St(e,t);if(e instanceof Map)return new Map(St(Array.from(e),t));if(e instanceof Set)return new Set(St(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const r={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(r[i]=vt(e[i],t));return r}function wt(e){return"object"!=typeof e||null===e?e:e instanceof Date?new Date(e):Array.isArray(e)?[...e]:e instanceof Map?new Map(Array.from(e)):e instanceof Set?new Set(Array.from(e)):{...e}}function Mt(e,t){if(e===t||bt(e)&&bt(t))return 0;if(bt(e))return-1;if(bt(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(B("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(B("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(B("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(B("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function Tt(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function kt(e){if(Array.isArray(e))return e.map(e=>kt(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),i={};return t.sort().forEach(t=>{i[t]=kt(e[t])}),i}function _t(e){return Et(kt(e))}function Et(e){if(void 0===e)return null;const t=vt(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Ct(e){return vt(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,i=t.$date;return i&&1===Object.keys(t).length?new Date(i):void 0})}function Ot(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=Et(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}}const Dt=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},At=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Et(e[i])!==Et(t[i]))return!1;return!0};class qt{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Dt,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function Nt(e){const t=[],i=[];let n=0;for(const r of e)if("undefined"!=typeof File)if(r instanceof File){i.push(r);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(Rt(r)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:r.map((e,t)=>(i.push(r[t]),n++))};t.push(e)}else t.push(r);else t.push(r);return{argsArray:t,fileArray:i}}function Rt(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class Ft{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:n,fileArray:r}=Nt(i),s="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(n);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?Dt:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===s&&e(t.args,n));if(t)return t.promise}const u=this.createExecuteCallPromise(s,n,r,a,t);return c&&(this.inFlightDedupCalls.push({functionName:s,args:n,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}createExecuteCallPromise(e,t,i,n,r={}){const s=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:Et(t)};return(0,h.firstValueFrom)((0,h.race)((0,h.from)(this.rpcManager.post(s,o,i.length>0?i:[],"files",r)).pipe(x(e=>{if(!e.success)throw new Error(e.payload);const i=Ct(e.payload);if(i?.__isSquidBase64File__){const e=i;return Z(e.base64,e.filename,e.mimetype)}return n&&n.set(t,i),i}))))}}function xt(e){if("undefined"!=typeof globalThis)return globalThis[e]}function jt(){if("undefined"!=typeof window)return window;if(void 0!==i.g)return i.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){jt().SQUID_LOG_DEBUG_ENABLED=e}(function(){let e="";return"undefined"!=typeof window&&window.location?e=new URLSearchParams(window.location.search).get("SQUID_DEBUG")||"":"undefined"!=typeof process&&process.env&&(e=process.env.SQUID_DEBUG||""),"1"===e||"true"===e}());class Pt{static debug(...e){(function(){const e=jt();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=jt();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Bt{constructor(e){this.destructManager=e,this.clientTooOldSubject=new h.BehaviorSubject(!1),this.isTenant=!0===jt().squidTenant,this.clientIdSubject=new h.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,h.filter)(e=>e),(0,h.map)(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,h.skip)(1),(0,h.filter)(e=>!e),(0,h.map)(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=jt()[Qt];return e?e():$()}generateClientId(){const e=jt()[Lt];if(e)return e();let t=`${this.isTenant?"tenant-":""}${$()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Lt="SQUID_CLIENT_ID_GENERATOR",Qt="SQUID_CLIENT_REQUEST_ID_GENERATOR",Ut="__squidId";function $t(e){return Ct(e)}function Gt(...e){const[t,i,n]=e,r="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return r.integrationId||(r.integrationId=void 0),_t(r)}function Vt(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return It(e,t);if("!="===i)return!It(e,t);switch(i){case"<":return!bt(e)&&(!!bt(t)||t<e);case"<=":return!!bt(t)||!bt(e)&&t<=e;case">":return!bt(t)&&(!!bt(e)||t>e);case">=":return!!bt(e)||!bt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Ht(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Ht(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Ht(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Ht(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>L(i,"VALUE_CANNOT_BE_NULL").some(t=>It(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>L(i,"VALUE_CANNOT_BE_NULL").some(t=>It(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!L(i,"VALUE_CANNOT_BE_NULL").some(t=>It(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function Ht(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const n=function(e){let t="";for(let i=0;i<e.length;++i)"\\"===e[i]?i+1<e.length&&["%","_"].includes(e[i+1])?(t+=e[i+1],i++):i+1<e.length&&"\\"===e[i+1]?(t+="\\\\",i++):t+="\\":"%"===e[i]?t+="[\\s\\S]*":"_"===e[i]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[i])&&(t+="\\"),t+=e[i]);return t}(t);return new RegExp(`^${n}$`).test(e)}function Wt(e,t){return`${e}_${t}`}function Kt(e){return"fieldName"in e}class zt{constructor(e,t,i){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.refId=$()}get squidDocId(){return this._squidDocId}get data(){return vt(this.dataRef)}get dataRef(){return L(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=$t(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`})}get hasData(){return!!this.dataManager.getProperties(this.squidDocId)}async snapshot(){if(this.hasSquidPlaceholderId())throw new Error("Cannot invoke snapshot of a document that was created locally without storing it on the server.");if(this.isTracked()&&this.hasData)return this.data;const e=await this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshot();return L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0}snapshots(){return this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshots().pipe((0,h.map)(e=>(L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0)))}peek(){return this.isTracked()&&this.hasData?this.data:void 0}isDirty(){return this.dataManager.isDirty(this.squidDocId)}async update(e,t){const i={};Object.entries(e).forEach(([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[n]});const n={type:"update",squidDocIdObj:$t(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:vt(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const n={type:"applyNumericFn",fn:"increment",value:t},r={type:"update",squidDocIdObj:$t(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(r,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async insert(e,t){const i=$t(this.squidDocId),n=i.integrationId;let r=Ct(i.docId);if(r[Ut]&&(r={}),n===ze&&r.__id)try{const e=Ct(r.__id);r={...r,...e}}catch{}const s={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...r}};return this.dataManager.applyOutgoingMutation(s,t)}async delete(e){const t={type:"delete",squidDocIdObj:$t(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}hasSquidPlaceholderId(){const e=Ct(this._squidDocId);if("object"==typeof e&&e.docId){const t=Ct(e.docId);if("object"==typeof t&&Object.keys(t).includes(Ut))return!0}return!1}}class Jt{constructor(e,t={}){this.internalStateObserver=new h.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new h.BehaviorSubject(!1),this.snapshotSubject=new h.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,B(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,h.switchAll)()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...t},this.goToFirstPage()}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}async prev(){return this.prevInternal(await this.waitForInternalState()),await this.waitForData()}async next(){const{numBefore:e,extractedData:t}=await this.waitForInternalState();return e+this.paginateOptions.pageSize<t.length&&(this.firstElement=t[e+this.paginateOptions.pageSize]),this.internalStateObserver.next(null),this.doNewQuery(t[e],!1),await this.waitForData()}async waitForData(){return this.internalStateToState(await this.waitForInternalState())}observeState(){return this.internalStateObserver.pipe((0,h.filter)(e=>null!==e),(0,h.map)(e=>this.internalStateToState(e)))}async first(){return await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.goToFirstPage(),await this.waitForData()}async refreshPage(){const{extractedData:e}=await this.waitForInternalState();return this.internalStateObserver.next(null),this.onFirstPage?this.goToFirstPage():this.doNewQuery(e[0],!1),await this.waitForData()}async last(){await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.navigatingToLastPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder().snapshots(this.paginateOptions.subscribe).pipe((0,h.map)(e=>e.reverse()));return this.snapshotSubject.next(e),await this.waitForData()}goToFirstPage(){this.onFirstPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).snapshots(this.paginateOptions.subscribe);this.snapshotSubject.next(e)}compareObjects(e,t){if(e===t||bt(e)&&bt(t))return 0;if(bt(e))return-1;if(bt(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:r}of i){const i=Mt(pt(e,n),pt(t,n));if(0!==i)return r?i:-i}return 0}async dataReceived(e){const t=e.map(e=>this.templateSnapshotEmitter.extractData(e));if(0===e.length)return void(this.onFirstPage?this.internalStateObserver.next({numBefore:0,numAfter:0,data:e,extractedData:t}):this.goToFirstPage());if(null===this.firstElement)if(null!==this.lastElement){const i=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-i-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const i=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,n=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:pt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,h.map)(e=>e.reverse())))}else{const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize);e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?">=":"<=",value:pt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await(0,h.firstValueFrom)((0,h.race)(this.isDestroyed.pipe((0,h.filter)(Boolean),(0,h.map)(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe((0,h.filter)(e=>null!==e),(0,h.take)(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:r}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(r[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:i>0}}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-i-1],!0)}}Error;class Yt{constructor(e,t,i,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=$t(e),r=Ct(n),s=this.get(t,i);for(const[e,t]of Object.entries(r))s.where(e,"==",t);return s}get(e,t){return new ei(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class Zt{constructor(){this.containsEmptyInCondition=!1}eq(e,t){return this.where(e,"==",t)}neq(e,t){return this.where(e,"!=",t)}in(e,t){return this.where(e,"in",t)}nin(e,t){return this.where(e,"not in",t)}gt(e,t){return this.where(e,">",t)}gte(e,t){return this.where(e,">=",t)}lt(e,t){return this.where(e,"<",t)}lte(e,t){return this.where(e,"<=",t)}like(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"like_cs":"like",t)}notLike(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"not like_cs":"not like",t)}arrayIncludesSome(e,t){return this.where(e,"array_includes_some",t)}arrayIncludesAll(e,t){return this.where(e,"array_includes_all",t)}arrayNotIncludes(e,t){return this.where(e,"array_not_includes",t)}throwIfInvalidLikePattern(e){if(/\\(?![%_\\])/.test(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class Xt{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1).pipe((0,h.defaultIfEmpty)([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(x(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Xt(this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new Jt(this,e)}}class ei extends Zt{constructor(e,t,i,n,r,s,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,this.documentReferenceFactory=r,this.queryBuilderFactory=s,this.documentIdentityService=o,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return Ot(this.build())}where(e,t,i){if(B(st.includes(t),`Invalid operator: ${t}`),"in"===t||"not in"===t){const n=Array.isArray(i)?[...i]:[i];"in"===t&&0===n.length&&(this.containsEmptyInCondition=!0);for(const i of n)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:i});return this}return this.query.conditions.push({fieldName:e,operator:t,value:i}),this}limit(e){return function(e){var t;B(function(e){return"number"==typeof e}(t=e),()=>U("Limit needs to be a number","Not a number",t)),-1!==e&&(B(e>0,"query limit has to be greater than 0"),B(Math.floor(e)===e,"query limit has to be an integer"),B(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const i=this.query.sortOrder.map(e=>e.fieldName);return B(It(t.sort(),i.slice(0,t.length).sort()),"All fields in limitBy must be appear in the first fields in the sortBy list."),this.query.limitBy={limit:e,fields:t,reverseSort:!1},this}sortBy(e,t=!0){const i={asc:t,fieldName:e};return function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,r,s;B((i=t,n=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>n.includes(e))),"Field sort should only contain a fieldName and asc"),B((r=t.asc,s="boolean",Array.isArray(r)?r.every(e=>typeof e===s):typeof r===s),"Asc needs to be boolean")}(i),B(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.sortOrder.push(i),this}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1).pipe((0,h.defaultIfEmpty)([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new h.BehaviorSubject([]);const t=this.build();return this.querySubscriptionManager.processQuery(t,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(x(e=>e.map(e=>{B(1===Object.keys(e).length);const t=Gt(L(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)})))}changes(){let e,t=new Set;return this.snapshots().pipe((0,h.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,h.switchMap)(t=>(Object.entries(t).forEach(([t,i])=>{!function(e,t,i){const n=e[t];void 0!==n&&(e[i]=n,delete e[t])}(e||{},t,i)}),h.NEVER)),(0,h.startWith)({}))),x(([i])=>{let n=[];const r=[],s=[];if(e){for(const s of i){const i=s.squidDocId,o=s.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){r.push(s);const n=e[i];delete e[i],t.delete(n)}else n.push(s)}for(const e of t)s.push(e)}else n=i;e={},t=new Set;for(const n of i){const i=n.dataRef;e[n.squidDocId]=i,t.add(i)}return new ti(n,r,s)}))}dereference(){return new Xt(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new ei(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=vt(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){return e.length?(this.query.conditions.push({fields:e}),this):this}flipSortOrder(){return this.query.sortOrder=this.query.sortOrder.map(e=>({...e,asc:!e.asc})),this.query.limitBy&&(this.query.limitBy.reverseSort=!this.query.limitBy.reverseSort),this}serialize(){return{type:"simple",dereference:!1,query:this.build()}}extractData(e){return e.dataRef}paginate(e){return new Jt(this,e)}mergeConditions(){const e=[],t=Tt(this.query.conditions.filter(Kt)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=Tt(i,e=>e.operator);for(const[i,n]of Object.entries(t)){if("=="===i||"!="===i){e.push(...n);continue}const t=[...n];t.sort((e,t)=>Mt(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Kt(e)),...e]}}class ti{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class ii extends Zt{constructor(e,t,i,n,r,s,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=r,this.rootAlias=s,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,i){return this.queryBuilder.where(e,t,i),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}sortBy(e,t=!0){return this.queryBuilder.sortBy(e,t),this}join(e,t,i,n){const r=n?.leftAlias??this.latestAlias,s={...i,leftAlias:r,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[r].push(t),new ii(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:s},this.queryBuilder)}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new h.BehaviorSubject([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,vt(this.joins),vt(this.joinConditions),e,!1).pipe(x(e=>e.map(e=>{const t={};for(const[i,n]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,r=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,s=n?Gt(n.__docId__,e,r):void 0;t[i]=s?this.documentReferenceFactory.create(s,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new si(this)}dereference(){return new ni(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new ii(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,vt(this.leftToRight),vt(this.joins),vt(this.joinConditions),this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e[this.rootAlias].dataRef}serialize(){return{type:"join",grouped:!1,dereference:!1,root:{alias:this.rootAlias,query:this.build()},leftToRight:this.leftToRight,joins:this.joins,joinConditions:this.joinConditions}}paginate(e){if(this.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new Jt(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class ni{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(x(e=>e.map(e=>function(e,t){const i={},n=Object.keys(e);for(const r of n){const n=e[r];i[r]=t(n)}return i}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ni(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}extractData(e){return e[this.joinQueryBuilder.rootAlias]}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new Jt(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class ri{constructor(e){this.groupedJoin=e}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(x(e=>e.map(e=>this.dereference(e,this.groupedJoin.joinQueryBuilder.rootAlias))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.groupedJoin.getSortOrders()}clone(){return new ri(this.groupedJoin.clone())}addCompositeCondition(e){return this.groupedJoin.addCompositeCondition(e),this}flipSortOrder(){return this.groupedJoin.flipSortOrder(),this}limit(e){return this.groupedJoin.limit(e),this}getLimit(){return this.groupedJoin.getLimit()}extractData(e){return e[this.groupedJoin.joinQueryBuilder.rootAlias]}serialize(){return{...this.groupedJoin.joinQueryBuilder.serialize(),dereference:!0,grouped:!0}}paginate(e){if(this.groupedJoin.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new Jt(this,e)}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const n={[t]:e[t].data};for(const t of i)n[t]=e[t].map(e=>this.dereference(e,t));return n}return e.data}}class si{constructor(e){this.joinQueryBuilder=e}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(x(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new ri(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new si(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}getLimit(){return this.joinQueryBuilder.getLimit()}extractData(e){return Object.keys(this.joinQueryBuilder.leftToRight).length>1?e[this.joinQueryBuilder.rootAlias].dataRef:e.dataRef}serialize(){return{...this.joinQueryBuilder.serialize(),grouped:!0}}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new Jt(this,e)}groupData(e,t){const i=Tt(e,e=>e[t]?.squidDocId);return Object.values(i).filter(e=>void 0!==e[0][t]).map(e=>{const i=this.joinQueryBuilder.leftToRight[t],n=e[0][t];if(0===i.length)return n;const r={[t]:n};for(const t of i)r[t]=this.groupData(e,t);return r})}}class oi{constructor(e,t,i,n,r,s){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,this.querySubscriptionManager=r,this.dataManager=s,this.refId=$()}doc(e){if(e&&"string"!=typeof e&&"object"!=typeof e&&!Array.isArray(e))throw new Error("Invalid doc id. Can be only object or string.");if(this.integrationId!==ze)if(e){if("object"!=typeof e)throw new Error("Invalid doc id. String doc ids are only supported for the built_in_db integration. For all other integrations, the doc id must be an object.")}else e={[Ut]:$()};else e=e&&"string"!=typeof e?{__id:_t(e)}:{__id:e||$()};const t=Gt(_t(e),this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)}async insertMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)await this.doc(i.id).insert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof zt?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new ii(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new ai(...e)}}class ai{constructor(...e){if(0===e.length)throw new Error("At least one query builder must be provided");this.snapshotEmitters=e.map(e=>e.clone());const t=Math.max(...this.snapshotEmitters.map(e=>{const t=e.getLimit();return-1===t?1e3:t}));this.snapshotEmitters.forEach(e=>e.limit(t));const i=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==i.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<i.length;e++)if(t[e].fieldName!==i[e].fieldName||t[e].asc!==i[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){const t=this.snapshotEmitters.map(t=>t.snapshots(e));return this.or(this.snapshotEmitters[0].getSortOrders(),...t)}peek(){throw new Error("peek is not currently supported for merged queries")}clone(){return new ai(...this.snapshotEmitters.map(e=>e.clone()))}getSortOrders(){return this.snapshotEmitters[0].getSortOrders()}addCompositeCondition(e){for(const t of this.snapshotEmitters)t.addCompositeCondition(e);return this}limit(e){return this.snapshotEmitters.forEach(t=>t.limit(e)),this}getLimit(){return this.snapshotEmitters[0].getLimit()}flipSortOrder(){return this.snapshotEmitters.forEach(e=>e.flipSortOrder()),this}serialize(){return{type:"merged",queries:this.snapshotEmitters.map(e=>e.serialize())}}extractData(e){return this.snapshotEmitters[0].extractData(e)}paginate(e){return new Jt(this,e)}or(e,...t){return(0,h.combineLatest)([...t]).pipe((0,h.map)(t=>{const i=new Set,n=t.flat(),r=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),r.push(e));return r.sort((t,i)=>{for(const{fieldName:n,asc:r}of e){const e=pt(this.extractData(t),n),s=pt(this.extractData(i),n);if(!Vt(e,s,"=="))return Vt(s,e,"<")?r?-1:1:r?1:-1}return 0}).slice(0,this.getLimit())}))}}class ci{constructor(e,t,i,n){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=n,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let n=i.get(e);return n||(n=new oi(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class ui{constructor(e,t){this.clientIdService=e,this.socketManager=t,this.isConnected=!1,this.socketManager.observeConnectionReady().subscribe(e=>{this.isConnected=e})}get connected(){return this.isConnected}get clientId(){return this.clientIdService.getClientId()}observeConnected(){return this.socketManager.observeConnectionReady()}}var li=i(150);function hi(e,t){switch(t.type){case"applyNumericFn":return function(e,t){if("increment"===t.fn)return null==e?t.value:e+t.value;throw new Error("Unknown numeric function: "+JSON.stringify(t))}(e,t);case"applyStringFn":return function(e,t){switch(t.fn){case"trim":return"string"!=typeof e?e:e.trim();case"extendString":return null==e?t.value:e+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?vt(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function di(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function pi(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(B("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const i=vt(e);t=vt(t);for(const[e]of di(i)){const n=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&n>t.split(".").length)&&delete i.properties[e]}for(const[e,n]of di(t))i.properties[e]=gi([...i.properties[e]||[],...n]);return i}(e,t);const i=vt(e);for(const[e,n]of di(t)){const t=n;for(const n of t){const t=hi(pt(i.properties,e),n);void 0===t?yt(i.properties,e):ft(i.properties,e,t)}}return i}function gi(e){let t=0;for(;t+1<e.length;){const i=fi(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function fi(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(B("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(B("increment"===e.fn,"Unrecognized applyNumericFn"),{type:"applyNumericFn",fn:"increment",value:e.value+t.value}):"update"===e.type?{type:"update",value:e.value+t.value}:t):"extendString"===t.fn?"update"===e.type?{type:"update",value:e.value+t.value}:"applyStringFn"===e.type?"trim"===e.fn?null:{type:"applyStringFn",fn:"extendString",value:e.value+t.value}:t:null}function yi(e){const t={};for(const i of e){const e=`${i.squidDocIdObj.integrationId}/${i.squidDocIdObj.collectionName}/${i.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(i)}const i=[];for(const e in t){const n=t[e].reduce((e,t)=>L(pi(e,t),"Merge result cannot be null"));i.push(n)}return i}const mi="dataManager_runInTransaction";class bi{constructor(e,t,i,n,r,s,o,a,c){this.documentStore=e,this.mutationSender=t,this.socketManager=i,this.querySubscriptionManager=n,this.queryBuilderFactory=r,this.lockManager=s,this.destructManager=o,this.documentIdentityService=a,this.querySender=c,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new h.Subject,this.outgoingMutationsEmpty=new h.BehaviorSubject(!0),this.knownDirtyDocs=new Set,this.failedDocsToResync=[],this.refreshDocIdToTimestamp=new Map,this.handleIncomingMessagesForTests=!0,this.destructManager.onDestruct(()=>{this.destruct()}),this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.handleNotifications(),this.startDeleteExpiredTimestampsJob(),this.handleOrphanDocs(),this.outgoingMutationsEmpty.subscribe(e=>{this.querySender.safeToSendQueriesToServer.next(e)})}getProperties(e){return this.documentStore.getDocumentOrUndefined(e)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),i=t&&!t.expireTimestamp?t.timestamp:void 0,n=this.docIdToLocalTimestamp.get(e);return!((!n||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&n===i)}async runInTransaction(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(mi)?this.lockManager.lockSync(mi):await this.lockManager.lock(mi);let i=Ii;const n=()=>i!==Ii;return new Promise(async(t,r)=>{try{let s;this.currentTransactionId=$();try{s=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(s),reject:r})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(mi)}catch(e){i=n()?i:e}}n()&&r(i)})}async applyOutgoingMutation(e,t){const i=Gt(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(mi)||(await this.lockManager.lock(mi),this.lockManager.release(mi)),this.knownDirtyDocs.delete(i);const n=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(n&&!n.sentToServer)n.mutation=L(yi([n.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},n=this.pendingOutgoingMutations.get(i)||[];n.push(t),this.pendingOutgoingMutations.set(i,n),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),n="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const i={...e},n=di(t);for(const[e,t]of n){const n=t;for(const t of n){const n=hi(pt(i,e),t);void 0===n?yt(i,e):ft(i,e,n)}}return i}(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,n)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,n).forEach(e=>this.batchClientRequestIds.add(e)))},t)}isTracked(e){if(this.pendingIncomingUpdates.get(e))return!0;const t=this.pendingOutgoingMutations.get(e);return!(!t||!t.length)||this.querySubscriptionManager.hasOngoingQueryForDocId(e)}isForgotten(e){return this.documentStore.hasData(e)&&!this.isTracked(e)}isLocalOnly(e){return!this.hasBeenAcknowledged(e)&&this.documentStore.hasData(e)}hasBeenAcknowledged(e){return this.docIdToServerTimestamp.has(e)}async runInTransactionSync(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(mi);try{this.currentTransactionId=$();try{return e(this.currentTransactionId)}catch(e){console.error("error while executing callback function in transaction",e)}finally{this.finishTransaction()}}catch(e){console.error("error while executing transaction",e)}finally{this.lockManager.release(mi)}}removeInternalProperties(e){if("delete"===e.type)return e;const t={...e,properties:{...e.properties}};return delete t.properties.__docId__,delete t.properties.__ts__,t}handleNotifications(){this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"mutations"===e.type),x(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t=e.reduce((e,t)=>this.querySubscriptionManager.hasOngoingQuery(t.clientRequestId)?(e[t.squidDocId]={properties:t.doc,timestamp:t.mutationTimestamp},e):e,{});this.applyIncomingUpdates(t)}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId),i={};for(const n of e.docs){const e=Gt(n.__docId__,t.collectionName,t.integrationId);i[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(i,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)}).then()}applyIncomingUpdates(e,t){let i=!1;const n=new Set,r=new Set;for(const[t,s]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>s.timestamp?i=!0:o&&o.timestamp>s.timestamp?r.add(t):(this.pendingIncomingUpdates.set(t,s),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of r)this.refreshQueryMapping(e)},t).then(),i}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const i=this.pendingOutgoingMutations.get(e);i&&i.length||(this.updateDocumentFromSnapshot(e,t.properties),this.acknowledgeDocument(e,t.timestamp,!t.properties),this.docIdToLocalTimestamp.set(e,t.timestamp),this.pendingIncomingUpdates.delete(e),this.refreshQueryMapping(e))}refreshQueryMapping(e){const t=this.documentStore.getDocumentOrUndefined(e);this.querySubscriptionManager.setClientRequestIdsForLocalDoc(e,t).forEach(e=>{this.batchClientRequestIds.add(e)}),t&&(this.querySubscriptionManager.findQueriesForDocument(t,e).length||this.forgetDocument(e,!1))}destruct(){this.stopDeleteExpiredTimestampsJob()}stopDeleteExpiredTimestampsJob(){void 0!==this.deleteExpiredTimestampsInterval&&(clearInterval(this.deleteExpiredTimestampsInterval),this.deleteExpiredTimestampsInterval=void 0)}startDeleteExpiredTimestampsJob(){this.deleteExpiredTimestampsInterval=setInterval(()=>{const e=[...this.docIdToServerTimestamp.entries()].filter(([e,t])=>!(!t.expireTimestamp||t.expireTimestamp>Date.now()||this.isTracked(e)));for(const[t]of e)this.docIdToServerTimestamp.delete(t),this.forgetDocument(t,!0)},1e4)}updateDocumentFromSnapshot(e,t){const i=this.documentStore.getDocumentOrUndefined(e);return!(!i&&!t||i===t)&&((!i||!t||_t({...t,__ts__:void 0})!==_t(i))&&(this.documentStore.saveDocument(e,t),!0))}finishTransaction(e){this.currentTransactionId=void 0;const t=[...this.batchClientRequestIds.values()];this.batchClientRequestIds.clear(),this.querySubscriptionManager.notifyAllSubscriptions(t),this.sendAllUnsentOutgoingMutations(e).then()}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await li.PromisePool.for(t).withConcurrency(t.length||1).useCorrespondingResults().handleError(e=>{throw e}).process(async([e,t])=>{await this.sendMutationsForIntegration([...t],e)}),this.pendingOutgoingMutations.size||this.outgoingMutationsEmpty.next(!0),await this.refreshUpdatedDocuments(),this.hasPendingSentMutations()?(await(0,h.firstValueFrom)(this.pendingOutgoingMutationsChanged.pipe((0,h.filter)(()=>!this.hasPendingSentMutations()))),e?.resolve()):e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:i,idResolutionMap:n={},refreshList:r=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),r.forEach(e=>{this.refreshDocIdToTimestamp.set(n[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);n[e]&&(e=n[e]),this.acknowledgeDocument(e,i),this.isTracked(e)||(this.setExpiration(e,!0),this.forgetDocument(e,!1))}}catch(t){for(const t of e){const e=this.removeOutgoingMutation(t);this.forgetDocument(e,!1),(this.hasBeenAcknowledged(e)||"insert"===t.mutation.type)&&this.failedDocsToResync.push(e)}throw t}}removeOutgoingMutation(e){const t=Gt(e.mutation.squidDocIdObj),i=L(this.pendingOutgoingMutations.get(t));return i.splice(i.indexOf(e),1),i.length||this.pendingOutgoingMutations.delete(t),this.pendingOutgoingMutationsChanged.next(),t}async resyncFailedUpdates(){const e=[...this.failedDocsToResync];this.failedDocsToResync.splice(0);for(const t of e){const{docId:e}=$t(t);this.setExpiration(t,!0);try{const i=e.includes(Ut)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(L(i.length<=1,"Got more than one doc for the same id:"+t),!i.length){this.forgetDocument(t,!1);const e=this.querySubscriptionManager.setClientRequestIdsForLocalDoc(t,void 0);this.querySubscriptionManager.notifyAllSubscriptions(e)}}catch(e){this.querySubscriptionManager.errorOutAllQueries(t,e)}}}async refreshUpdatedDocuments(){const e=[];for(const[t,i]of this.refreshDocIdToTimestamp.entries()){const n=this.docIdToServerTimestamp.get(t)?.timestamp;n&&n>i||e.push(t)}this.refreshDocIdToTimestamp.clear(),await Promise.allSettled(e.map(e=>this.queryBuilderFactory.getForDocument(e).snapshot()))}groupOutgoingMutationsByIntegrationId(){const e={};for(const[,t]of[...this.pendingOutgoingMutations.entries()]){const i=t[t.length-1];if(i&&!i.sentToServer){const t=i.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(i),i.sentToServer=!0}}return Object.entries(e)}handleOrphanDocs(){this.querySubscriptionManager.onOrphanDocuments.subscribe(e=>{for(const t of e)this.isTracked(t)||this.forgetDocument(t,!1)})}acknowledgeDocument(e,t,i=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,i)}setExpiration(e,t){const i=this.docIdToServerTimestamp.get(e);i&&(i.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=Gt(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=$t(n))})}),Object.entries(e).forEach(([e,t])=>{mt(this.pendingOutgoingMutations,e,t),mt(this.docIdToLocalTimestamp,e,t),mt(this.docIdToServerTimestamp,e,t)})}hasPendingSentMutations(){for(const e of this.pendingOutgoingMutations.values())for(const t of e)if(t.sentToServer)return!0;return!1}}const Ii=Symbol("undefined");class Si{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new h.BehaviorSubject(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe((0,h.filter)(Boolean),x(()=>{}))}onPreDestruct(e){this.preDestructors.push(e)}onDestruct(e){this.destructors.push(e)}async destruct(){this.reportDestructed();const e=this.preDestructors.concat(this.destructors);let t=e.shift();for(;t;){try{await t()}catch(e){console.error("Error while destructing Squid",e)}t=e.shift()}}reportDestructed(){this.isDestructing||this.isDestructedSubject.next(!0)}}class vi{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{e||this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.clientRequestId];void 0!==t&&t.release()})}async lock(e,t=2e3){this.socketManager.notifyWebSocketIsNeeded(),B(await(0,h.firstValueFrom)((0,h.race)((0,h.timer)(this.lockWaitForConnectionThreshold).pipe(x(()=>!1)),this.socketManager.observeConnectionReady().pipe((0,h.filter)(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const i=$(),n={type:"acquireLock",payload:{mutex:e,timeoutMillis:t,clientRequestId:i}};this.socketManager.postMessage(n);const r=await(0,h.firstValueFrom)((0,h.race)((0,h.timer)(t+4e3).pipe((0,h.take)(1),x(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:i}}))),this.acquireLockMessagesFromServer.pipe((0,h.filter)(e=>e.payload.clientRequestId===i)))),s=r.payload.lockId;B(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),B(s,()=>`Failed to acquire lock: ${r.payload.error}`);const o=new wi(s,i,this.ongoingLocks,this.socketManager);return this.ongoingLocks[s]=o,o}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class wi{constructor(e,t,i,n){this.lockId=e,this.clientRequestId=t,this.ongoingLocks=i,this.socketManager=n,this.released=!1,this.onReleaseSubject=new h.Subject}async release(){if(this.released)return;this.released=!0,delete this.ongoingLocks[this.lockId];const e={type:"releaseLock",payload:{lockId:this.lockId,clientRequestId:this.clientRequestId}};try{await this.socketManager.sendMessage(e)}finally{this.onReleaseSubject.next(),this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}class Mi{constructor(e,t){this.documentStore=e,this.destructManager=t,this.changeNotifier=new h.BehaviorSubject({}),this.destructManager.onDestruct(()=>{this.changeNotifier.complete()})}migrate(e){Object.entries(e).forEach(([e,t])=>{this.documentStore.migrateDocId(e,t)}),this.changeNotifier.next(e)}observeChanges(){return this.changeNotifier.asObservable()}}class Ti{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t){let i=this.documents.get(e);if(i)return i;i=new zt(e,L(this.dataManager,"dataManager not found"),t);const{integrationId:n,collectionName:r}=$t(e);this.documents.set(e,i);const s=this.getCollectionKey(n,r),o=this.documentsForCollection.get(s)||[];return this.documentsForCollection.set(s,o.concat(i)),i}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const i=this.getCollectionKey(e,t);return(this.documentsForCollection.get(i)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const i=$t(e),n=$t(t);mt(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class ki{constructor(){this.squidDocIdToDoc=new Map}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=vt(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),n}return void this.squidDocIdToDoc.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),t}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocument(e){return L(this.getDocumentOrUndefined(e))}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}group(e,t){return Object.values(Tt(e,e=>_t(t.map(t=>pt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=[...e].map(e=>this.squidDocIdToDoc.get(e)).filter(j),{sortOrder:n,limitBy:r}=t,s=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;if(!r)return s.slice(0,o);const{limit:a,fields:c,reverseSort:u}=r,l=this.group(s,c);let h;return h=u?l.map(e=>e.slice(-a)):l.map(e=>e.slice(0,a)),h.flat().slice(0,o)}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;mt(this.squidDocIdToDoc,e,t);const n=$t(t),r=Ct(n.docId);this.saveDocument(t,{...i,...r,__docId__:n.docId})}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:r}of i){const i=Mt(pt(e,n),pt(t,n));if(0!==i)return r?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class _i{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const i={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",i)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class Ei{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const i={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",i,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const i={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",i)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class Ci{constructor(e,t,i){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.clientIdService.observeClientId().pipe((0,h.distinctUntilChanged)(),(0,h.skip)(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Pt.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e})})}async getJob(e){return(await this.rpcManager.post("job/getJob",{jobId:e})).job}async awaitJob(e){this.maybeListenToJobs(),await this.socketManager.awaitConnectionReady();const t=this.listeners[e]||new h.ReplaySubject(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}),(0,h.firstValueFrom)(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,i=t.id,n=this.listeners[i];n&&("completed"===t.status?n.next(t.result):"failed"===t.status?n.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}}class Oi{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=yi(e),n=i.map(e=>`sendMutation_${Gt(e.squidDocIdObj)}`);await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Pt.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}}class Di{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Ai{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"userNotification"===e.type),(0,h.map)(e=>e.payload))}async publishNotification(e,t){return await this.rpcManager.post("/notification/publishNotification",{clientIds:t,payload:e})}async publishSystemNotification(e,t){return await this.rpcManager.post("/notification/publishSystemNotification",{clientIds:t,payload:e})}}const qi={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Ni{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!Ri.test(e)||e.length>=Fi);B(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const n={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},r=this.rpcManager.post("/observability/metrics",{metrics:[n]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==r),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(r)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...qi,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const i=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:i,noDataBehavior:n}=e,r=void 0===e.fillValue?null:e.fillValue,s=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const r=t-e;let s=t-Math.floor(r/i)*i;return s>e&&(s-=i),s}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const r=t-e;let s=e+Math.floor(r/i)*i;return s>=t&&(s-=i),s}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const i=[];for(let t=0;t<e.groupByTags.length;t++){const n=e.groupByTags[t],r=a[n]?.[0]||"";i.push(r)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===n&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,n]of Object.entries(a)){const r=e.groupByTags.indexOf(i);if(!(r<0))for(let e=0;e<t.length;e++){const i=t[e],s=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===r||e===n.tagValues[t])&&s.delete(n.tagValues[r])}if(0!==s.size)for(const e of s){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[r]=e,t.push(n)}}}for(const n of t){if(0!==n.points.length){const e=n.points[0][0],t=n.points[n.points.length-1][0];B(e>=s,()=>`Invalid first point time: ${e}`),B(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:r,u=Array.isArray(e.fn)?e.fn.map(c):[r];for(let e=s;e<=o;e+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(B(i[0]>e,()=>`Result point has invalid time: ${i[0]}`),t.push([e,...u])):t.push([e,...u])}n.points=t}}(t,i.resultGroups),i}}const Ri=/^[a-zA-Z0-9_-]+$/,Fi=1e3;class xi{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const i={authCode:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/saveAuthCode",i)}async getAccessToken(e){const t={personalStorageConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/getAccessToken",t)}async indexDocumentOrFolder(e,t,i,n){const r={documentOrFolderId:e,metadata:n,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:i};await this.rpcManager.post("personalStorage/indexDocumentOrFolder",r)}async listIndexedDocuments(e,t,i){const n={personalStorageConfig:{identifier:e,integrationId:this.integrationId},agentId:t,type:i};return(await this.rpcManager.post("personalStorage/listIndexedDocuments",n)).documents}async unindexDocument(e,t,i){const n={documentId:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:i};await this.rpcManager.post("personalStorage/unindexDocument",n)}}async function ji(e,t,i=500){const n=Date.now(),r=e.paginate({pageSize:i,subscribe:!1});let s=0,o=await r.waitForData();for(;;){for(const e of o.data)s++,await t(e.data);if(!o.hasNext)break;o=await r.next()}return{count:s,time:Date.now()-n}}function Pi(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:r,integrationId:s}=i;let o=e.collection(r,s).query();return o=Bi(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:r,dereference:s,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=Bi(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:s}=i,{left:o,right:a,leftAlias:c}=r[t];let l=e.collection(n,s).query();l=Bi(l,i),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),s&&o?u.grouped().dereference():s?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:i}=t,{collectionName:n,integrationId:r}=Li(i[0]),s=i.map(t=>Pi(e,t));return e.collection(n,r).or(...s)}(e,t)}}function Bi(e,t){const{conditions:i,limit:n,sortOrder:r}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:i,operator:n,value:r}=t;e.where(i,n,r)}e.limit(n);for(const{fieldName:t,asc:i}of r)e.sortBy(t,i);return e}function Li(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:i}=e.query;return{collectionName:t,integrationId:i}}case"join":{const{collectionName:t,integrationId:i}=e.root.query;return{collectionName:t,integrationId:i}}case"merged":return Li(e.queries[0])}}const Qi={"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)=>Ui(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Ui(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Ui(e,t)&&Gi(t),"like_cs:like_cs":(e,t)=>Ui(e,t),"like:not like":(e,t)=>!$i(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!$i(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!$i(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!$i(e,t),"not like:like":(e,t)=>Hi(e,t),"not like_cs:like":(e,t)=>Hi(e,t),"not like:like_cs":(e,t)=>Hi(e,t),"not like_cs:like_cs":(e,t)=>Hi(e,t),"not like:not like":(e,t)=>Ui(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Ui(t,e)&&Gi(e),"not like:not like_cs":(e,t)=>Ui(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Ui(t,e),"in:like":(e,t)=>e.every(e=>Vt(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Vt(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Vt(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Vt(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&&Vi(e)||Wi(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Vi(e)||Wi(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Vi(t)||Wi(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Vi(t)||Wi(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=>Vt(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Vt(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Vt(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Vt(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 Ui(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return Vi(t.substring(n));const r=e[i],s=t[n];return"%"===r&&"%"===s?Ui(e,t,i+1,n+1)||Ui(e,t,i+1,n):"%"!==r&&("%"===s?Ui(e,t,i,n+1)||Ui(e,t,i+1,n):(r===s||"_"===s)&&Ui(e,t,i+1,n+1))}function $i(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return Vi(t.substring(n));if(n>=t.length)return Vi(e.substring(i));const r=i<e.length?e[i]:"",s=n<t.length?t[n]:"";return"%"===r&&"%"===s?$i(e,t,i+1,n+1)||$i(e,t,i,n+1)||$i(e,t,i+1,n):"%"===r||"%"===s?$i(e,t,i,n+1)||$i(e,t,i+1,n):(r===s||"_"===r||"_"===s)&&$i(e,t,i+1,n+1)}function Gi(e){return!/[a-zA-Z]/.test(e)}function Vi(e){return e.split("").every(e=>"%"===e)}function Hi(e,t){return e.length>0&&Vi(e)||t.length>0&&Vi(t)||Wi(e)&&0===t.length}function Wi(e){let t=!1,i=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}class Ki{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Kt))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){return!e.find((e,t)=>!It(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,i){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:i})}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(Kt),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),r=-1===e.limit||this.limit>-1&&this.limit<e.limit;return i&&n&&r}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 i=t.fieldName,n=t.operator,r=pt(e,i);if("in"===n){if(t.value.includes(r))continue;return!1}if("not in"!==n){if(!Vt(t.value,r,n))return!1}else if(t.value.includes(r))return!1}return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:r,value:s}=this.parseConditions([t])[0],o=Qi[`${i}:${r}`];return!!o&&o(n,s)}parseConditions(e){const t=[],i=new Map,n=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":i.set(e.fieldName,(i.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)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),n.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}class zi{constructor(e,t,i){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=i}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:i}=e,n=new Ki(e),r=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),s={};return r.forEach(e=>{s[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(s)),e).map(e=>s[Gt(e.__docId__,i,t)])}}function Ji(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){return e.call(t,i,r++)&&n.next(i)}))})}class Yi{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.safeToSendQueriesToServer=new h.BehaviorSubject(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new h.BehaviorSubject(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new h.Subject,i=(0,h.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(),i):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Ji(Boolean),(0,h.take)(1)).subscribe(()=>{this.processQueryBatch()})},0),i)}async waitForAllQueriesToFinish(){return(0,h.firstValueFrom)(this.inflightQueriesCount.pipe(Ji(e=>0===e))).then(()=>{})}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=Array.from(e.map(({queryRequest:e})=>e).reduce((e,t)=>(e.set(t.clientRequestId,t),e),new Map).values()),i=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const i=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,r=i.errors[e],s=i.results[e];r?n.error(r):n.next(s)}}catch(e){i.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Zi={d:(e,t)=>{for(var i in t)Zi.o(t,i)&&!Zi.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Xi(e,t,...i){e||function(e,...t){const i=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof i)throw i;throw(e=>new Error(e))(i||"Assertion error",...t)}(t,...i)}function en(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return tn(e,t);if(0===t.length)return Xi("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function n(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let r=e;for(let e=0;e<t.length-1&&void 0!==r;e++){const i=t[e];Xi(!Array.isArray(r)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),r=r[i],Xi(void 0===r||"object"==typeof r&&null!==r,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===r?"<null>":typeof r}'`)}const s=t[t.length-1];return Xi(!Array.isArray(r)||n(s),()=>`Invalid array index Path: '${t}`),(null==r?void 0:r[s])===i?e:nn(e,t,i)}(e,t.path,t.value);case"delete":return tn(e,t.path);case"batch":return t.actions.reduce((e,t)=>en(e,t),e)}}function tn(e,t){Xi(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const r=t[n];if(i=i[r],void 0===i)return e;Xi("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,n+1)}', type: ${null===i?"<null>":typeof i}`)}const n=t[t.length-1];return void 0===i[n]?e:nn(e,t,void 0)}function nn(e,t,i){function n(e,i){Xi(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const r=Object.assign({},e);let s=r;for(let e=0;e<t.length-1;e++){const r=t[e],o=s[r];Xi(void 0===o||"object"==typeof o&&null!==o,()=>`Internal error: sub-path has an invalid type and can't be patched: '${t.slice(0,e+1)}', type: '${null===o?null:typeof o}'`);const a=void 0===o?void 0===i?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return n(s,r),s;s[r]=a,s=a}const o=t[t.length-1];return void 0===i?n(s,o):s[o]=i,r}function rn(e,t){const i=[];if("set"===e.type||"delete"===e.type)i.push(e.path);else if("batch"===e.type)for(const t of e.actions)i.push(...rn(t,"as-is"));return"unique-and-sorted"===t?an(i):i}function sn(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i])return!1;return!0}function on(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const n=e[i].localeCompare(t[i]);if(0!==n)return n}return e.length-t.length}),t}function an(e){const t=on(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let r=e+1;r<t.length;r++){const s=t[r];n.length===s.length&&sn(n,s)&&(i[r]=void 0,e++)}}return i.filter(e=>void 0!==e)}const cn=(un={Observable:()=>h.Observable,Subject:()=>h.Subject},ln={},Zi.d(ln,un),ln);var un,ln;const hn=(dn={filter:()=>Ji,map:()=>x},pn={},Zi.d(pn,dn),pn);var dn,pn,gn;class fn{constructor(){this.root={children:new Map,childrenWithValue:0}}get(e){var t;return null===(t=this.getNode(e))||void 0===t?void 0:t.value}getOrSet(e,t){const i=this._buildPath(e);if(void 0!==i.value)return i.value;const n=t(e);return this._setNodeValue(i,n,void 0===n),n}set(e,t){const i=void 0===t?this._findNode(e):this._buildPath(e);i&&this._setNodeValue(i,t,!0)}delete(e){const t=this._findNode(e);if(void 0===t)return;if(void 0===t.parent){if(t!==this.root)throw new Error("Only root node can have no parent.");return this.root.value=void 0,this.root.children.clear(),void(this.root.childrenWithValue=0)}const i=(void 0===t.value?0:1)+t.childrenWithValue;i>0&&this._updateChildrenWithValue(t,-i),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const i=this.getNode(e);return void 0===i?0:i.childrenWithValue+("node-and-children"===t&&void 0!==i.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const i=[];let n=this.root,r=t(n.value,i);if(r!==fn.StopFillToken){this._setNodeValue(n,r,!1);for(let s=0;s<e.length;s++){const o=e[s];i.push(o);let a=n.children.get(o);if(r=t(null==a?void 0:a.value,i),r===fn.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,r,!1),n=a}this._runGc(n)}}visitDfs(e,t,i=[]){const n=this.getNode(i);void 0!==n&&this._visitDfs(e,n,t,[...i])}_visitDfs(e,t,i,n){if("pre-order"===e&&!1===i(t.value,n))return!1;for(const[r,s]of t.children){if(n.push(r),!this._visitDfs(e,s,i,n))return!1;n.pop()}return"in-order"!==e||!1!==i(t.value,n)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const i of e)if(t=t.children.get(i),!t)return;return t}_findNode(e){let t=this.root;for(let i=0;i<e.length&&t;i++)t=t.children.get(e[i]);return t}_buildPath(e){let t=this.root;for(let i=0;i<e.length;i++){const n=e[i];let r=t.children.get(n);r||(r={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,r)),t=r}return t}_setNodeValue(e,t,i){if(e.value!==t){const i=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,i)}i&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let i=e.parent;i;i=i.parent)if(i.childrenWithValue+=t,i.childrenWithValue<0)throw new Error("Internal error: negative counter value!")}_runGc(e){void 0===e.value&&(0===e.childrenWithValue&&e.children.clear(),e.parent&&this._runGc(e.parent))}}fn.StopFillToken=Symbol("Trie.StopFillToken");class yn extends cn.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class mn{constructor(e){this.rootState=e,this.observersTrie=new fn,this.batchDepth=0,this.appliedBatchActions=[],this.rootStateBeforeBatchStart=this.rootState,this.stubForUnusedPaths=[]}get state(){return this.rootState}get state$(){return this.observe([])}get(e){return this._get(this.rootState,e)}observe(e,t=[]){return this._observeChanges(e,t,"new-value-only").pipe((0,hn.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,i){(null==i?void 0:i(this.get(e),t,e))||this._apply({type:"set",path:e,value:t})}delete(e){this._apply({type:"delete",path:e})}reset(e){this.observersTrie.visitDfs("pre-order",e=>null==e?void 0:e.complete()),this.observersTrie.delete([]),this.rootState=e}runInBatch(e){this.batchDepth++;try{e()}finally{if(this.batchDepth--,0===this.batchDepth&&this.appliedBatchActions.length>0){const e={type:"batch",actions:this.appliedBatchActions};this.appliedBatchActions=[],this._notify(e)}}}_apply(e){0===this.batchDepth&&(this.rootStateBeforeBatchStart=this.rootState),this.rootState=en(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=rn(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=an([...t,...i]),r=new fn;for(const e of n)r.fillPath(e,()=>!0);r.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),r=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:r})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new fn;for(const e of t)null==n||n.set(e,!0);return new cn.Observable(t=>{const r=this.observersTrie.getOrSet(e,()=>new yn);r.isAllDetailsMode=r.isAllDetailsMode||"all-details"===i;const s={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(s);const o=r.pipe((0,hn.filter)(({action:e})=>void 0===n||rn(e,"as-is").some(e=>!n.get(e))),(0,hn.map)(({action:t,value:i,oldValue:n})=>{let s=this.stubForUnusedPaths;if(r.isAllDetailsMode){const i=rn(t,"as-is");s=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=on(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let r=e+1;r<t.length;r++)sn(t[r],n)&&(i[r]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>sn(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:s}})).subscribe(t);return()=>{o.unsubscribe(),r.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const n=t[e];i=null==i?void 0:i[n]}return i}selectChildPathsWithObservers(e){const t=[];for(const i of e)this.observersTrie.count(i,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,i)=>{e&&t.push([...i])},i);return t}}function bn(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,r=e.length-1){if(r<n)return-1;const s=Math.trunc((n+r)/2);return 0===i(t,e[s])?s:i(t,e[s])>0?bn(e,t,i,s+1,r):bn(e,t,i,n,s-1)}function In(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==bn(e,t,i))return;let n;for(n=e.length-1;n>=0&&i(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function Sn(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=bn(e,t,i);n>-1&&e.splice(n,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(gn||(gn={}));const vn=100;class wn{constructor(e,t,i,n,r,s,o){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=r,this.querySender=s,this.socketManager=o,this.onOrphanDocuments=new h.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Tn,this.queryResultsSubject=new h.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe(()=>{this.refreshOngoingQueries()}),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}dumpSubscriptionInfo(){console.log("Ongoing queries:",this.ongoingQueries),console.log("ClientRequestId to local documents:",this.clientRequestIdToLocalDocuments),console.log("Local documents to clientRequestId:",this.localDocumentToClientRequestIds)}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return L(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);t?.gotInitialResponse&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:i,integrationId:n}=$t(t),r=this.queryMappingManager.getMapping(i,n);return r?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,r]of Object.entries(e.conditional||{})){const e=Ct(i);let s;if(Kt(e)){const i=pt(t,e.fieldName)??null;s=Vt(e.value,i,e.operator)}else s=Mn(e,t);if(s)for(const e of r)n.set(e,(n.get(e)||0)+1)}for(const[t,r]of n.entries())r>=e.queriesMetadata[t].condCount&&i.push(t);return i}(r,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=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):[]),r=new Set([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const r=this.clientRequestIdToLocalDocuments.get(t);r&&(r.delete(e),r.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...r]}errorOutAllQueries(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of i){const i=this.ongoingQueries.get(e);i&&(this.destructManager.isDestructing?i.dataSubject.complete():i.dataSubject.error(t),i.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const i of e){const e=this.ongoingQueries.get(i);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(i)||new Set,r=this.documentStore.sortAndLimitDocs(n,e.query),s=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(r,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=L(o?.supportingOngoingQuery);if(s&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case gn.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+vn?gn.ENABLED:gn.DISABLED;break;case gn.DISABLED:break;case gn.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=gn.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(r)}for(const e of t){const t=this.collectAllObservables(e);L(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new Ki(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,r,s){return r&&this.socketManager.notifyWebSocketIsNeeded(),(0,h.defer)(()=>{const o=this.createOngoingQueryGraph(e,t,i,n,r,!0);s&&(o.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(o),o.allObservables=new h.ReplaySubject(1);const a=o.allObservables.pipe((0,h.switchMap)(e=>(0,h.combineLatest)(e).pipe(x(e=>this.joinResults(e,n,o)))),Ji(()=>this.allOngoingQueriesGotInitialResult(o)),(0,h.startWith)(void 0),(0,h.pairwise)(),Ji(([e,t])=>!It(e,t)),x(([,e])=>e),r?(0,h.tap)():(0,h.take)(1),(0,h.finalize)(()=>{o.dataSubject.complete(),o.done=!0,this.completeAllSupportedQueries(o).then(),o.allObservables?.complete()})),c=this.collectAllObservables(o);return o.allObservables.next(c),a}).pipe((0,h.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}unsubscribe(){const e=[...this.ongoingQueries.values()];for(const t of e)t.dataSubject.complete(),t.allObservables?.complete()}hasSubscription(e){return!!this.ongoingQueries.get(e)?.subscribe}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 Ki(e.query);for(const i of this.ongoingQueries.values()){if(e===i)return;if(this.isValidParent(i)&&t.isSubqueryOfQuery(i.query))return i}}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const i=[];for(const n of t){const t=L(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),i.push(n))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=Wt(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,h.finalize)(async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,h.firstValueFrom)((0,h.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Ji(e=>0===e)))),this.queryMappingManager.removeQuery(i).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const i={clientRequestId:t};this.rpcManager.post("query/unsubscribe",i).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)}),Ji(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,i,n,r,s,o={}){if(o[t])return o[t];const a=this.clientIdService.generateClientRequestId(),c=[],u={clientRequestId:a,activated:s,alias:t,query:e,subscribe:r,dataSubject:new h.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new h.BehaviorSubject(0),queryRegistered:new h.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?gn.UNKNOWN:gn.DISABLED};this.registerQueryFinalizer(u),this.ongoingQueries.set(a,u),o[t]=u;for(const[e,s]of Object.entries(n)){const a=s.leftAlias;if(a!==t&&e!==t)continue;const l=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(i[l],l,i,n,r,!1,o);e.joinCondition=s,c.push(e)}else u.supportingOngoingQuery=this.createOngoingQueryGraph(i[l],l,i,n,r,!1,o)}return u}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Ji(Boolean),x(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const n=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let r=n[i.alias].map(e=>({[i.alias]:e}));const s=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<s.length;e++){const i=s[e].alias;o.has(i)||(o.add(i),r=this.join(r,i,n[i],t[i]))}return r}join(e,t,i,n){if(!e.length)return e;const r=Object.keys(e[0]);if(!n||!r.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const s=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);s.has(t)||s.set(t,[]),L(s.get(t)).push(e)}),e.flatMap(e=>{const i=s.get(this.transformKey(e[n.leftAlias]?.[n.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):n.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=L(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){const i=L(t.joinCondition),n=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const r=L(t.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===t.alias),s=new Set(e.map(e=>e[i.left]??null));for(const e of r)e.query.conditions.filter(Kt).filter(e=>e.fieldName===i.right).forEach(e=>{s.delete(e.value)});if(0===s.size)return!1;const o=vt(n);o.conditions=o.conditions.filter(e=>!Kt(e)||e.fieldName!==i.right),[...s].forEach(e=>{o.conditions.push({fieldName:i.right,operator:"==",value:e})});const a={...t,query:o,activated:!0,gotInitialResponse:!1,dataSubject:new h.BehaviorSubject(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(a),this.ongoingQueries.set(a.clientRequestId,a),L(t.supportingOngoingQuery).supportedQueries.push(a),this.sendQueryToServerOrUseParentQuery(a),!0}{if(t.activated=!0,n.conditions.filter(Kt).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return r.length?(n.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=L(t.shift());t.push(...e.supportedQueries||[]),await(0,h.firstValueFrom)(e.unsubscribeBlockerCount.pipe(Ji(e=>0===e))),e.dataSubject.complete()}}transformKey(e){return e instanceof Date?`DATE AS string KEY: ${e.toISOString()}`:e}preDestruct(){this.unsubscribe()}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const i=e.query,n=e.clientRequestId,r=Wt(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,r),this.ongoingQueries.set(n,e);const s=t?void 0:this.findValidParentOfOngoingQuery(e);s?this.useParentOngoingQuery(e,s).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new Ki(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,h.firstValueFrom)(t.queryRegistered.pipe(Ji(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",i).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(i=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,i),e.dataSubject.error(i)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const r=(0,h.race)(e.queryRegistered.pipe(Ji(Boolean),(0,h.delay)(2e3),(0,h.take)(1)),this.destructManager.observeIsDestructing().pipe((0,h.take)(1)));t.dataSubject.pipe((0,h.takeWhile)(()=>!e.done),(0,h.takeUntil)(r),Ji(Boolean),(0,h.tap)(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),x(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(Gt(i.__docId__,e.query.collectionName,e.query.integrationId),i);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,i=t>0&&e.subscribe?t+vn:t,n={query:{...e.query,limit:i},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()):(Pt.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 i of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{i.has(t)&&(i.delete(t),i.add(e[t]))});t.forEach(t=>{mt(this.localDocumentToClientRequestIds,t,e[t])})}}function Mn(e,t){for(const i of e.fields){const e=pt(t,i.fieldName)??null;if(Vt(i.value,e,i.operator))return!0;if(Vt(i.value,e,"!="))return!1}return!1}class Tn{constructor(){this.stateService=new mn({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const r of e.conditions){if(Kt(r)&&["=="].includes(r.operator)){const e=Ot(r.fieldName);n.has(e)||(i++,n.add(e))}else i++;const s=this.getConditionStatePath(e,r),o=[...this.stateService.get(s)||[]];In(o,t),this.stateService.set(s,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];In(n,t),this.stateService.set(i,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],i)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const i of t.conditions){const n=this.getConditionStatePath(t,i),r=[...this.stateService.get(n)||[]];Sn(r,e),r.length?this.stateService.set(n,r):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];Sn(n,e),this.stateService.set(i,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",(i=t,_t(i))];var i}}class kn{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,h.lastValueFrom)((0,h.combineLatest)(t).pipe((0,h.filter)(e=>!e.includes(!0)),(0,h.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=L(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){B(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new h.BehaviorSubject(!0)}}class _n{constructor(e,t,i){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)}),i.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let i=this.queueManagers.get(e);i||(i=new Map,this.queueManagers.set(e,i));let n=i.get(t);return n||(n=new Cn(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const En="subscriptionMutex";class Cn{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new h.Subject,this.subscriberCount=0,this.lockManager=new kn}async produce(e){await this.lockManager.lock(En);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(En)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),(0,h.defer)(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,h.finalize)(()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}async performSubscribe(){await this.lockManager.lock(En);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 h.Subject}finally{this.lockManager.release(En)}}async performUnsubscribe(){await this.lockManager.lock(En);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(En)}}}class On{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,h.firstValueFrom)((0,h.interval)(10).pipe((0,h.filter)(()=>this.attemptConsume()),(0,h.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}}const Dn={TRACE_ID:"x-squid-traceid",SECRET:"x-squid-secret",APP_API_KEY:"x-app-api-key",APP_ID:"x-squid-appid",CLIENT_ID:"x-squid-clientid",CLIENT_VERSION:"x-squid-client-version",SOURCE_IP:"x-squid-source-ip"};function An(e="n_"){return`${e}${K(10).toLowerCase()}`}const qn=e=>e();class Nn extends Error{constructor(e,t,i,n,r){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=r}}const Rn="1.0.415";async function Fn(e){const t=await Ln({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=Qn(t.body),t}async function xn(e){const t=await Ln({...e,method:"GET",files:[],filesFieldName:""});return t.body=Qn(t.body),t}async function jn(e){const t=await Ln({...e,method:"PUT"});return t.body=Qn(t.body),t}async function Pn(e){const t=await Ln({...e,method:"PATCH"});return t.body=Qn(t.body),t}async function Bn(e){const t=await Ln({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=Qn(t.body),t}async function Ln({headers:e,files:t,filesFieldName:i,message:n,url:r,extractErrorMessage:s,method:o}){const a=new Headers(e);a.append(Dn.TRACE_ID,An("c_")),a.append(Dn.CLIENT_VERSION,Rn);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const n of t)e.append(i||"files",n,n.name);e.append("body",Et(n)),c.body=e}else void 0!==n&&(a.append("Content-Type","application/json"),c.body=Et(n));else"DELETE"===o&&void 0!==n&&(a.append("Content-Type","application/json"),c.body=Et(n));try{const e=await fetch(r,c),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=Qn(i);if(!s)throw new Nn(i,e.status,r,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new Nn(o,e.status,r,t,n)}const i=await e.text();return Pt.debug(`received response from url ${r}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Pt.debug(`Unable to perform fetch request to url: ${r}`,e),e}}function Qn(e){if(e){try{return Ct(e)}catch{}return e}}class Un{constructor(e,t,i,n,r,s){this.region=e,this.appId=t,this.authManager=r,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new h.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")}),i.onDestruct(async()=>{await this.awaitAllSettled()});const o=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new On(60*o,5),ai:new On(20*o,5),secret:new On(20*o,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:i}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return i&&(n+=`; IntegrationId ${i}`),{Authorization:n}}async awaitAllSettled(){await(0,h.firstValueFrom)(this.onGoingRpcCounter.pipe((0,h.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,i=[],n="files",r={}){return(await this.rawPost(e,t,i,n,!0,r)).body}async rawPost(e,t,i=[],n="files",r=!0,o={}){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const a=await this.getAuthHeaders(),c={...this.staticHeaders,...a,...o};Pt.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const u=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await Fn({url:u,headers:c,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),r={...this.staticHeaders,...n};let o=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,i])=>{e.append(t,String(i))}),o+=`?${e.toString()}`}return Pt.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await xn({url:o,headers:r,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};Pt.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await jn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};Pt.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await Pn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),r={...this.staticHeaders,...n};Pt.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await Bn({url:o,headers:r,message:t,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?L(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?L(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):L(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class $n{constructor(e){this.rpcManager=e}async list(){return(await this.rpcManager.post("/scheduler/listSchedulers",{})).schedulers}async enable(e){await this.update(this.createUpdateSchedulerOptions(e,!0))}async disable(e){await this.update(this.createUpdateSchedulerOptions(e,!1))}async update(e){const t={schedulers:e};await this.rpcManager.post("scheduler/updateSchedulers",t)}createUpdateSchedulerOptions(e,t){return Array.isArray(e)?e.map(e=>({schedulerId:e,enabled:t})):[{schedulerId:e,enabled:t}]}}function Gn(){}const Vn="undefined"!=typeof process&&process.versions?.node?i(86):jt().WebSocket;class Hn{constructor(e,t,i,n=qn,r,s){this.clientIdService=e,this.region=t,this.appId=i,this.messageNotificationWrapper=n,this.destructManager=r,this.authManager=s,this.webSocketObserver=new h.Subject,this.allMessagesObserver=new h.Subject,this.connectionReady=new h.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new h.Subject,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new h.BehaviorSubject(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe((0,h.skip)(1),(0,h.filter)(e=>!e),(0,h.switchMap)(()=>(0,h.race)((0,h.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,h.filter)(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Pt.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Pt.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe((0,h.filter)(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe((0,h.filter)(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?Pt.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Pt.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Pt.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Pt.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}getClientInfo(){this.postMessage({type:"getClientInfo"})}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,h.distinctUntilChanged)())}async awaitConnectionReady(){await(0,h.firstValueFrom)(this.observeConnectionReady().pipe((0,h.filter)(Boolean)))}notifyWebSocketIsNeeded(){this.webSocketNeededSubject.next(!0)}postMessage(e){this.sendMessageImpl(e)}sendMessage(e){return this.sendMessageImpl(e)}disconnectForTest(){this.connectionReady.next(!1),this.socket?.close(4998)}keepAlive(){this.lastTick&&(Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Pt.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.webSocketNeededSubject.next(!0),await(0,h.firstValueFrom)(this.connectionReady.pipe((0,h.filter)(Boolean)));const t=await this.authManager.getToken();if(this.connectionReady.value)try{B(this.socket,"Socket is undefined in sendMessageAsync");const i=Et({message:e,authToken:t});Pt.debug(this.clientIdService.getClientId(),"Sending message to socket: ",i),this.socket.send(i)}catch(t){this.socket?.connected?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageImpl(e))}else await this.sendMessageImpl(e)}sendKillMessage(){this.socket?.connected&&this.socket.send(Et({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=s(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Pt.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,r=1;const s={connected:!1,closeCalled:!1,open(){i=new(Vn?.WebSocket??Vn)(e,t.protocols||[]),i.onmessage=t.onmessage?e=>{e.data&&t.onmessage?t.onmessage(e):console.log("No data received from websockets, please contact support@getsquid.ai with this message.")}:Gn,i.onopen=function(e){s.connected=!0,(t.onopen||Gn)(e),n=0},i.onclose=function(e){if(s.connected=!1,4999!==e.code&&4001!==e.code)return Pt.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Gn)(e),void s.reconnect(e);(t.onclose||Gn)(e)},i.onerror=function(e){s.connected=!1,e&&"ECONNREFUSED"===e.code?s.reconnect(e):s.closeCalled||(t.onerror||Gn)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;r&&n++<i?r=setTimeout(function(){(t.onreconnect||Gn)(e),Pt.debug("WebSocket trying to reconnect..."),s.open()},t.timeoutMillis||1e3):(t.onmaximum||Gn)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){s.closeCalled=!0;try{s.connected=!1,clearTimeout(r),r=void 0,i.close(e,t)}catch(e){}}};return s.open(),s}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Pt.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Pt.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Pt.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Pt.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Pt.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.postMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return Pt.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=Ct(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Pt.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new h.Subject;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe((0,h.tap)(e=>t.push(e)),(0,h.debounceTime)(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await(0,h.firstValueFrom)((0,h.timer)(0)),this.connectionReady.next(!1),await(0,h.firstValueFrom)((0,h.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Wn(e){var t,i;i="Invalid application ID",B(function(e){return"string"==typeof e}(t=e),()=>U(i,"Not a string",t));const[n,r,s,o]=e.split("-");return B(!o,`Invalid application ID: ${e}`),{appId:n,environmentId:r??"prod",squidDeveloperId:s}}function Kn(e,t){return`${Wn(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function zn(e,t,i){return`${Kn(e,t)}${i?`-${i}`:""}`}function Jn(e){const t=Wn(e);return Kn(t.appId,t.environmentId)}class Yn{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};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 i={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",i)}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 Zn{constructor(e,t,i,n,r){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n,this.consoleRegion=r}async aiSearch(e){return await this.rpcManager.post("web/aiSearch",{query:e})}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e,t){B(this.apiKey,"API key is required to create a short URL");const i=o(this.region,this.consoleRegion,"openapi/sqd/shorten"),n={url:e,appId:this.appId,secondsToLive:t},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!r.ok)throw console.error("Error making POST request to shorten endpoint",r.statusText),new Error(`${r.statusText}: ${r.text}`);return await r.json()}async createShortUrls(e,t){B(this.apiKey,"API key is required to create a short URL");const i=o(this.region,this.consoleRegion,"openapi/sqd/shortenMany"),n={urls:e,appId:this.appId,secondsToLive:t},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!r.ok)throw console.error("Error making POST request to shortenMany endpoint",r.statusText),new Error(`${r.statusText}: ${r.text}`);return await r.json()}async deleteShortUrl(e){B(this.apiKey,"API key is required to delete a short URL");const t=o(this.region,this.consoleRegion,"openapi/sqd/delete"),i={id:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}async deleteShortUrls(e){B(this.apiKey,"API key is required to delete a short URL");const t=o(this.region,this.consoleRegion,"openapi/sqd/deleteMany"),i={ids:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}}class Xn{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:n={},body:r,files:o=[]}=t,a=await this.rpcManager.getAuthHeaders(),c={...this.rpcManager.getStaticHeaders(),...a,...i};let u=s(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(n&&Object.keys(n).length>0){const e=new URLSearchParams;Object.entries(n).forEach(([t,i])=>{e.append(t,String(i))}),u+=`?${e.toString()}`}const l=new Headers(c);let h;if(l.append(Dn.TRACE_ID,An("c_")),l.append(Dn.CLIENT_VERSION,Rn),o&&o.length>0){const e=new FormData;for(const t of o)e.append("file",t,t.name);r&&"object"==typeof r&&Object.entries(r).forEach(([t,i])=>{e.append(t,String(i))}),h=e}else l.append("Content-Type","application/json"),h=Et(r||{});const d=await fetch(u,{method:"POST",headers:l,body:h}),p={};if(d.headers.forEach((e,t)=>{p[t]=e}),!d.ok){const e=await d.text();let t;try{t=JSON.parse(e)}catch{t=e}const i="string"==typeof t?t:t?.message||d.statusText;throw new Nn(i,d.status,u,p,t)}const g=await d.text();let f;try{f=JSON.parse(g)}catch{f=g}return f}}class er{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Si,B(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,i=zn(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Bt(this.destructManager),Pt.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new ht(e.apiKey,e.authProvider),this.socketManager=new Hn(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Un(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Ai(this.socketManager,this.rpcManager),this.jobClient=new Ci(this.socketManager,this.rpcManager,this.clientIdService),this.backendFunctionManager=new Ft(this.rpcManager),this.aiClient=new ct(this.socketManager,this.rpcManager,this.jobClient,this.backendFunctionManager),this.apiClient=new lt(this.rpcManager),this.documentStore=new ki,this.lockManager=new kn,this.distributedLockManager=new vi(this.socketManager,this.destructManager),this.documentIdentityService=new Mi(this.documentStore,this.destructManager),this.documentReferenceFactory=new Ti(this.documentIdentityService),this.querySender=new Yi(this.rpcManager,this.destructManager),this.observabilityClient=new Ni(this.rpcManager),this.schedulerClient=new $n(this.rpcManager),this._appId=i,this.querySubscriptionManager=new wn(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager),this.localQueryManager=new zi(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new Oi(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Yt(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new bi(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new ci(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.webhookManager=new Xn(this.rpcManager,e.region,i),this.nativeQueryManager=new Di(this.rpcManager),this._connectionDetails=new ui(this.clientIdService,this.socketManager),this.queueManagerFactory=new _n(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new l(this.rpcManager,this.options.region,Jn(i),this.options.consoleRegion),this.webClient=new Zn(this.rpcManager,this.options.region,Jn(i),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}static getInstance(e){const t=_t(e);let i=er.squidInstancesMap[t];return i||(i=new er(e),er.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(er.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=ze){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),this.backendFunctionManager.executeFunction(e,...t)}executeFunctionWithHeaders(e,t,...i){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...i)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}executeNativeRelationalQuery(e,t,i={}){const n={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativePureQuery(e,t,i={}){const n={type:"pure",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,i){const n={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeElasticQuery(e,t,i,n="_search",r="GET"){const s={type:"elasticsearch",index:t,endpoint:n,method:r,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}ai(){return this._validateNotDestructed(),this.aiClient}job(){return this._validateNotDestructed(),this.jobClient}api(){return this._validateNotDestructed(),this.apiClient}admin(){return this._validateNotDestructed(),this.adminClient}web(){return this._validateNotDestructed(),this.webClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Yn(e,this.rpcManager)}personalStorage(e){return this._validateNotDestructed(),new xi(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new _i(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new Ei(this.rpcManager)}acquireLock(e){return this._validateNotDestructed(),this.distributedLockManager.lock(e)}async withLock(e,t){const i=await this.acquireLock(e);try{return await t(i)}finally{i.release()}}queue(e,t=Je){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(er.squidInstancesMap).find(([,e])=>e===this);e&&delete er.squidInstancesMap[e[0]]})}get isDestructed(){return this.destructManager.isDestructing}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}getNotificationClient(){return this._validateNotDestructed(),this.notificationClient}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,i)=>s(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>zn(e,t,i)}}_validateNotDestructed(){B(!this.destructManager.isDestructing,"The client was already destructed.")}}var tr=exports;for(var ir in n)tr[ir]=n[ir];n.__esModule&&Object.defineProperty(tr,"__esModule",{value:!0})})();
|