UNPKG

@squidcloud/client

Version:

A typescript implementation of the Squid client

1 lines 260 kB
(()=>{"use strict";var e={86:e=>{e.exports=require("ws")},150:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0});const o=r(642);t.default=o.PromisePool,i(r(273),t),i(r(642),t),i(r(837),t),i(r(426),t),i(r(858),t),i(r(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class r 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=r},234:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=r(642),i=r(172),o=r(837),s=r(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 i.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 s.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 i.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 i.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 i.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 i.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach((e=>{if(e&&"function"!=typeof e)throw i.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)})),this.onTaskFinishedHandlers.forEach((e=>{if(e&&"function"!=typeof e)throw i.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 r=this.createTaskFor(e,t).then((e=>{this.save(e,t).removeActive(r)})).catch((async n=>{await this.handleErrorFor(n,e,t),this.removeActive(r)})).finally((()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)}));this.tasks().push(r),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[r,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),r()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise(((r,n)=>{t=setTimeout((()=>{n(new o.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,r){if(this.shouldUseCorrespondingResults()&&(this.results()[r]=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 s.StopThePromisePoolError}isValidationError(e){return e instanceof i.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(o.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,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=r(234);class i{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 i(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=i,i.notRun=Symbol("notRun"),i.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class r 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=r},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class r extends Error{}t.StopThePromisePoolError=r}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};r.r(n),r.d(n,{AI_AGENTS_INTEGRATION_ID:()=>rt,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Ye,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Ke,AI_CHAT_MODEL_NAMES:()=>qe,AI_EMBEDDINGS_MODEL_NAMES:()=>Qe,AI_IMAGE_MODEL_NAMES:()=>ze,AI_PROVIDER_TYPES:()=>je,ALL_OPERATORS:()=>bt,ANTHROPIC_CHAT_MODEL_NAMES:()=>Ne,API_INJECTION_FIELD_TYPES:()=>ht,ARRAY_OPERATORS:()=>vt,AUTH_INTEGRATION_TYPES:()=>ot,AdminClient:()=>Pn,AiAgentClient:()=>J,AiAgentReference:()=>K,AiAssistantClient:()=>i,AiAudioClient:()=>X,AiClient:()=>Dn,AiImageClient:()=>Z,AiMatchMakingClient:()=>xn,ApiClient:()=>te,ApiKeysSecretClient:()=>vn,AuthManager:()=>re,BUILT_IN_AGENT_ID:()=>C,BUILT_IN_DB_INTEGRATION_ID:()=>ut,BUILT_IN_QUEUE_INTEGRATION_ID:()=>lt,BUILT_IN_STORAGE_INTEGRATION_ID:()=>dt,BackendFunctionManager:()=>Oe,BaseQueryBuilder:()=>Pt,CLIENT_CONNECTION_STATES:()=>_t,CLIENT_ID_GENERATOR_KEY:()=>Ae,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>ke,Changes:()=>Dt,ClientIdService:()=>Te,CollectionReference:()=>Lt,CollectionReferenceFactory:()=>Qt,ConnectionDetails:()=>Ut,DATA_INTEGRATION_TYPES:()=>it,DEFAULT_SHORT_ID_LENGTH:()=>Q,DataManager:()=>Yt,DereferencedJoin:()=>Rt,DestructManager:()=>Zt,DistributedLockImpl:()=>er,DistributedLockManager:()=>Xt,DocumentReference:()=>Ot,DocumentReferenceFactory:()=>rr,DocumentStore:()=>nr,EMPTY_CHAT_ID:()=>P,ENVIRONMENT_IDS:()=>x,ExtractionClient:()=>kn,FETCH_BEYOND_LIMIT:()=>$r,FLUX_MODEL_NAMES:()=>He,GEMINI_CHAT_MODEL_NAMES:()=>De,GRAPHQL_INTEGRATION_TYPES:()=>st,GroupedJoin:()=>Ft,HTTP_INTEGRATION_TYPES:()=>at,HttpStatus:()=>tt,INTEGRATION_SCHEMA_TYPES:()=>ct,INTEGRATION_TYPES:()=>nt,IntegrationClient:()=>_n,JoinQueryBuilder:()=>Nt,LastUsedValueExecuteFunctionCache:()=>Ie,LimitUnderflowState:()=>Nr,LocalQueryManager:()=>br,METRIC_DOMAIN:()=>yt,METRIC_FUNCTIONS:()=>ft,METRIC_INTERVAL_ALIGNMENT:()=>gt,MatchMaker:()=>Cn,MutationSender:()=>ir,NOOP_FN:()=>tn,NativeQueryManager:()=>or,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Ge,OPENAI_AUDIO_MODEL_NAMES:()=>Ve,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>$e,OPENAI_CHAT_MODEL_NAMES:()=>Ce,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>Le,OPENAI_IMAGE_MODEL_NAMES:()=>Ue,OPENAI_O1_CHAT_MODEL_NAMES:()=>Pe,OPENAI_REASONING_CHAT_MODEL_NAMES:()=>xe,OPEN_AI_CREATE_SPEECH_FORMATS:()=>Je,ObservabilityClient:()=>pn,Pagination:()=>Mt,PersonalStorageClient:()=>jn,QueryBuilder:()=>Ct,QueryBuilderFactory:()=>jt,QuerySender:()=>_r,QuerySubscriptionManager:()=>Gr,QueueManagerFactory:()=>zr,QueueManagerImpl:()=>Yr,RAG_TYPES:()=>Ze,RERANK_PROVIDERS:()=>Xe,RateLimiter:()=>Jr,RpcManager:()=>dn,SQUID_AI_MODEL_NAMES:()=>Re,SQUID_METRIC_NAMES:()=>pt,SQUID_REGIONS:()=>mt,STABLE_DIFFUSION_MODEL_NAMES:()=>We,SchedulerClient:()=>bn,SecretClient:()=>gn,SocketManager:()=>In,Squid:()=>Rn,SquidClientError:()=>rn,StorageClient:()=>An,VOYAGE_EMBEDDING_MODEL_NAMES:()=>Be,WebClient:()=>Nn,base64ToFile:()=>z,compareArgsByReference:()=>Se,compareArgsBySerializedValue:()=>we,deserializeQuery:()=>ar,generateId:()=>B,generateShortId:()=>$,generateShortIds:()=>G,getConsoleUrl:()=>mn,isGlobalAiChatModelName:()=>Fe,isPlaceholderParam:()=>et,rawSquidHttpDelete:()=>cn,rawSquidHttpGet:()=>on,rawSquidHttpPatch:()=>an,rawSquidHttpPost:()=>nn,rawSquidHttpPut:()=>sn,tryDeserializing:()=>ln,visitQueryResults:()=>sr});class i{constructor(e){this.rpcManager=e}async createAssistant(e,t,r,n){const i={name:e,instructions:t,functions:r,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",i)).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,r,n,i){const o={assistantId:e,threadId:t,prompt:r,fileIds:n,options:i};return(await this.rpcManager.post("ai/assistant/queryAssistant",o)).answer}async addFileToAssistant(e,t){const r={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",r,[t],"file")).fileId}async removeFileFromAssistant(e,t){const r={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",r)}async addFileToThread(e,t){const r={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",r,[t],"file")).fileId}}const o=require("rxjs");function s(e){return"function"==typeof e}function a(e){return function(t){if(function(e){return s(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 c=function(e,t){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},c(e,t)};function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}c(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function l(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.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 d(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}function h(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var p,f=((p=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),p.prototype.constructor=p,p);function y(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var g=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,r,n,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=l(o),c=a.next();!c.done;c=a.next())c.value.remove(this)}catch(t){e={error:t}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(s(u))try{u()}catch(e){i=e instanceof f?e.errors:[e]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var y=l(p),g=y.next();!g.done;g=y.next()){var b=g.value;try{v(b)}catch(e){i=null!=i?i:[],e instanceof f?i=h(h([],d(i)),d(e.errors)):i.push(e)}}}catch(e){r={error:e}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}}if(i)throw new f(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)v(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).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)&&y(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&y(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function v(e){s(e)?e():e.unsubscribe()}g.EMPTY;var b={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var i=b.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,h([e,t],d(r))):setTimeout.apply(void 0,h([e,t],d(r)))},clearTimeout:function(e){var t=b.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function m(){}var _=S("C",void 0,void 0);function S(e,t,r){return{kind:e,value:t,error:r}}var w=function(e){function t(t){var r,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((r=t)instanceof g||r&&"closed"in r&&s(r.remove)&&s(r.add)&&s(r.unsubscribe))&&t.add(n)):n.destination=T,n}return u(t,e),t.create=function(e,t,r){return new O(e,t,r)},t.prototype.next=function(e){this.isStopped?E(function(e){return S("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?E(S("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?E(_,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}(g);Function.prototype.bind;var I=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){M(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){M(e)}else M(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){M(e)}},e}(),O=function(e){function t(t,r,n){var i,o=e.call(this)||this;return i=s(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:t,o.destination=new I(i),o}return u(t,e),t}(w);function M(e){!function(e){b.setTimeout((function(){throw e}))}(e)}function E(e,t){var r=null;r&&b.setTimeout((function(){return r(e,t)}))}var T={closed:!0,next:m,error:function(e){throw e},complete:m};function A(e,t,r,n,i){return new k(e,t,r,n,i)}var k=function(e){function t(t,r,n,i,o,s){var a=e.call(this,t)||this;return a.onFinalize=o,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(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 u(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(w);function j(e,t){return a((function(r,n){var i=0;r.subscribe(A(n,(function(r){n.next(e.call(t,r,i++))})))}))}const P="__squid_empty_chat_id",x=["dev","prod"],C="built_in_agent";function D(e){return null!=e}let N=e=>new Error(e);function R(e,t,...r){e||function(e,...t){const r=F(e);if("object"==typeof r)throw r;throw N(r||"Assertion error",...t)}(t,...r)}function q(e,t,...r){return R(e,t,...r),e}function F(e){return void 0===e?"":"string"==typeof e?e:e()}function L(e,t,r){const n=F(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}>`}(r)}`}function B(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)}))}const Q=18,U="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function $(e=Q,t=""){R(t.length<e,"ID prefix is too long");let r="";for(let t=0;t<e;t++)r+=U.charAt(Math.floor(Math.random()*U.length));return t.length>0&&(r=t+r.substring(t.length)),r}function G({count:e,length:t,prefix:r}){R(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add($(t||Q,r||""));return[...n]}const V=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function W(e){for(const t in e){const r=e[t];if("string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r&&void 0!==r)throw new Error(`Invalid metadata value for key ${t} - cannot be of type ${typeof r}`);if(V.includes(t))throw new Error(`Invalid metadata key ${t} - cannot be an internal key. Internal keys: ${V.join(", ")}`);if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}function H(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)H(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)H(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(V.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${V.join(", ")}`);const r=e[t];if("object"!=typeof r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof r}`)}}function z(e,t,r){const n=atob(e),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);const o=r||"application/octet-stream",s=new Blob([i],{type:o});return new File([s],t,{type:o})}class K{constructor(e,t,r,n,i){this.agentId=e,this.ongoingChatSequences=t,this.statusUpdates=r,this.rpcManager=n,this.socketManager=i}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){const t=await this.get();R(t,"Agent not found"),await this.upsert({...t,options:{...t.options,instructions:e}})}async updateModel(e){const t=await this.get();R(t,"Agent not found"),await this.upsert({...t,options:{...t.options,model:e}})}async updateConnectedAgents(e){const t=await this.get();R(t,"Agent not found"),await this.upsert({...t,options:{...t.options,connectedAgents:e}})}async getContext(e){return await this.rpcManager.post("ai/agent/getContext",{agentId:this.agentId,contextId:e})}async listContexts(){return(await this.rpcManager.post("ai/agent/listContexts",{agentId:this.agentId})).contexts||[]}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/agent/deleteContexts",{agentId:this.agentId,contextIds:e})}async upsertContext(e,t){await this.upsertContexts([e],t?[t]:void 0)}async upsertContexts(e,t){for(const t of e)t.metadata&&W(t.metadata);await this.rpcManager.post("ai/agent/upsertContexts",{agentId:this.agentId,contextRequests:e},t)}async provideFeedback(e){await this.rpcManager.post("ai/agent/provideFeedback",{agentId:this.agentId,feedback:e})}async resetFeedback(){await this.rpcManager.post("ai/agent/resetFeedback",{agentId:this.agentId})}async updateGuardrails(e){const t=await this.get();R(t,"Agent not found"),await this.upsert({...t,options:{...t.options,guardrails:{...t.options?.guardrails,...e}}})}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){return this.chatInternal(e,t).responseStream}async transcribeAndChat(e,t){const r=this.chatInternal(e,t),n=await q(r.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:r.responseStream,transcribedPrompt:n.transcribedPrompt}}async search(e){R(this.agentId!==C,"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){return(await this.askInternal(e,!1,t)).responseString}observeStatusUpdates(e){this.socketManager.notifyWebSocketIsNeeded();const{chatId:t}=e||{};return this.createStatusSubject(t),t?this.statusUpdates[this.agentId][t].asObservable():(0,o.merge)(...Object.values(this.statusUpdates[this.agentId]))}async transcribeAndAsk(e,t){return await this.askInternal(e,!1,t)}async transcribeAndAskWithVoiceResponse(e,t){const r=await this.askInternal(e,!0,t),n=r.voiceResponse;return{responseString:r.responseString,transcribedPrompt:r.transcribedPrompt,voiceResponseFile:z(n.base64File,`voice.${n.extension}`,n.mimeType)}}async askWithVoiceResponse(e,t){const r=await this.askInternal(e,!0,t),n=r.voiceResponse;return{responseString:r.responseString,voiceResponseFile:z(n.base64File,`voice.${n.extension}`,n.mimeType)}}async askInternal(e,t,r){r?.contextMetadataFilter&&H(r.contextMetadataFilter),r={...Y,...r||{}};const n="string"==typeof e;let i="ai/chatbot/";i+=n||t?!n&&t?"transcribeAndAskWithVoiceResponse":n&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:n?e:void 0,options:r},s=n?void 0:[e];return await this.rpcManager.post(i,o,s,"file")}createStatusSubject(e){this.statusUpdates[this.agentId]||(this.statusUpdates[this.agentId]={});const t=e||P;this.statusUpdates[this.agentId][t]||(this.statusUpdates[this.agentId][t]=new o.Subject)}chatInternal(e,t){this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&H(t.contextMetadataFilter);const r=B(),n=void 0===(t={...Y,...t||{}}).smoothTyping||t.smoothTyping;let i="";const s=new o.Subject,a=new o.Subject;this.ongoingChatSequences[r]=a;let c=-1;a.pipe((0,o.tap)((({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)})),(0,o.concatMap)((({value:e,complete:t})=>t?(0,o.of)({value:e,complete:t}):(0,o.of)(e).pipe(n?(0,o.delay)(0):(0,o.tap)(),j((e=>({value:e,complete:!1})))))),(0,o.takeWhile)((({complete:e})=>!e),!0)).subscribe({next:({value:e})=>{i+=e,s.next(i)},error:e=>{console.error(e)},complete:()=>{s.complete()}});const u="string"==typeof e,l={agentId:this.agentId,prompt:u?e:void 0,options:t,clientRequestId:r},d={responseStream:s.pipe((0,o.finalize)((()=>{delete this.ongoingChatSequences[r]})),(0,o.share)())};return u?this.rpcManager.post("ai/chatbot/chat",l).catch((e=>{s.error(e),s.complete()})):d.serverResponse=this.rpcManager.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch((e=>{throw s.error(e),s.complete(),e})),d}}const Y={smoothTyping:!0,responseFormat:"text"};class J{constructor(e,t){this.rpcManager=e,this.socketManager=t,this.ongoingChatSequences={},this.statusUpdates={},this.socketManager.observeNotifications().pipe((0,o.filter)((e=>"aiChatbot"===e.type)),j((e=>e))).subscribe((e=>{this.handleChatResponse(e).then()})),this.socketManager.observeNotifications().pipe((0,o.filter)((e=>"aiStatus"===e.type)),j((e=>e))).subscribe((e=>{this.handleStatusMessage(e).then()}))}agent(e){return new K(e,this.ongoingChatSequences,this.statusUpdates,this.rpcManager,this.socketManager)}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:r,complete:n,tokenIndex:i}=e.payload;if(n&&!r.length)t.next({value:"",complete:!0,tokenIndex:void 0});else if(r.match(/\[.*?]\((.*?)\)/g))t.next({value:r,complete:n,tokenIndex:void 0===i?void 0:i});else for(let e=0;e<r.length;e++)t.next({value:r[e],complete:n&&e===r.length-1,tokenIndex:void 0===i?void 0:i})}async handleStatusMessage(e){const{agentId:t,chatId:r,payload:n}=e,{title:i,tags:o}=n,s=this.getStatusSubject(t,r);s?.next({agentId:t,chatId:r,title:i,tags:o})}getStatusSubject(e,t){if(!this.statusUpdates[e])return;const r=t||P;return this.statusUpdates[e][r]}}class Z{constructor(e){this.rpcManager=e}async generate(e,t){const r={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",r)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}class X{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 r={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",r);return z(n.base64File,`audio.${n.extension}`,n.mimeType)}}const ee={headers:{},queryParams:{},pathParams:{}};class te{constructor(e){this.rpcManager=e}async get(e,t,r){return this.request(e,t,void 0,r,"get")}async post(e,t,r,n){return this.request(e,t,r,n,"post")}async delete(e,t,r,n){return this.request(e,t,r,n,"delete")}async patch(e,t,r,n){return this.request(e,t,r,n,"patch")}async put(e,t,r,n){return this.request(e,t,r,n,"put")}async request(e,t,r,n,i){const o={integrationId:e,endpointId:t,body:r,options:{...ee,...this.convertOptionsToStrings(n||{})},overrideMethod:i};return await this.rpcManager.rawPost("api/callApi",o,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 re{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}}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}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}}const ne=/[.\[\]]/;function ie(e,t){if(!e)return;const r=t.split(ne);let n,i=e;for(;i&&r.length;){const e=r.shift();if(e){if("object"!=typeof i||!(e in i))return;n=i[e],i=n}}return n}function oe(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function se(e,t,r,n="."){const i=t.split(n);let o=e;for(;i.length;){const e=q(i.shift());if(i.length){const t=o[e],r=oe(t)?pe(t)??{}:{};o[e]=r,o=r}else o[e]=r}}function ae(e,t,r="."){const n=t.split(r);let i=e;for(;n.length;){const e=q(n.shift());if(n.length){const t=oe(i[e])?pe(i[e])??{}:{};i[e]=t,i=t}else delete i[e]}}function ce(e,t,r){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(r,n)}}function ue(e){return null==e}function le(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const r=typeof e;if(r!==typeof t)return!1;if("object"!==r)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const r of n)if(!i.includes(r)||!le(e[r],t[r]))return!1;return!0}function de(e,t){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=he(e[n],t);return r}function he(e,t){const r=t?t(e):void 0;if(void 0!==r)return r;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return de(e,t);if(e instanceof Map)return new Map(de(Array.from(e),t));if(e instanceof Set)return new Set(de(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 i={};for(const r in e)Object.hasOwnProperty.call(e,r)&&(i[r]=he(e[r],t));return i}function pe(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 fe(e,t){if(e===t||ue(e)&&ue(t))return 0;if(ue(e))return-1;if(ue(t))return 1;const r=typeof e,n=typeof t;return r!==n?r<n?-1:1:"number"==typeof e?(R("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(R("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(R("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(R("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function ye(e,t){return e.reduce(((e,r)=>{const n=t(r);return e[n]?e[n].push(r):e[n]=[r],e}),{})}function ge(e){if(Array.isArray(e))return e.map((e=>ge(e)));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),r={};return t.sort().forEach((t=>{r[t]=ge(e[t])})),r}function ve(e){return be(ge(e))}function be(e){if(void 0===e)return null;const t=he(e,(e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0));return JSON.stringify(t)}function me(e){return he(JSON.parse(e),(e=>{if(null===e||"object"!=typeof e)return;const t=e,r=t.$date;return r&&1===Object.keys(t).length?new Date(r):void 0}))}function _e(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=be(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let r="";for(let t=0;t<e.length;t++)r+=String.fromCharCode(e[t]);return btoa(r)}}const Se=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},we=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(be(e[r])!==be(t[r]))return!1;return!0};class Ie{constructor(e){this.options=e}get(e){const t=this.cachedEntry,r=this.options.argsComparator||Se,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&r(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}class Oe{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){const{argsArray:r,fileArray:n}=this.transformFileArgs(t),i="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,s=o?.cache;if(s){const e=s.get(r);if(e.found)return Promise.resolve(e.value)}const a="string"==typeof e?void 0:e.deduplication;if(a){const e="boolean"==typeof a?Se:a.argsComparator,t=this.inFlightDedupCalls.find((t=>t.functionName===i&&e(t.args,r)));if(t)return t.promise}const c=this.createExecuteCallPromise(i,r,n,s);return a&&(this.inFlightDedupCalls.push({functionName:i,args:r,promise:c}),c.finally((()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter((e=>e.promise!==c))}))),c}createExecuteCallPromise(e,t,r,n){const i=`backend-function/execute?${encodeURIComponent(e)}`,s={functionName:e,paramsArrayStr:be(t)};return(0,o.firstValueFrom)((0,o.race)((0,o.from)(this.rpcManager.post(i,s,r.length>0?r:[])).pipe(j((e=>{if(!e.success)throw new Error(e.payload);const r=me(e.payload);if(r?.__isSquidBase64File__){const e=r;return new File([Buffer.from(e.base64,"base64")],e.filename,{type:e.mimetype})}return n&&n.set(t,r),r})))))}transformFileArgs(e){const t=[],r=[];let n=0;for(const i of e)if("undefined"!=typeof File)if(i instanceof File){r.push(i);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(this.isArrayOfFiles(i)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:i.map(((e,t)=>(r.push(i[t]),n++)))};t.push(e)}else t.push(i);else t.push(i);return{argsArray:t,fileArray:r}}isArrayOfFiles(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every((e=>e instanceof File))}}function Me(){if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){Me().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 Ee{static debug(...e){(function(){const e=Me();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=Me();return!0===e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Te{constructor(e){this.destructManager=e,this.clientTooOldSubject=new o.BehaviorSubject(!1),this.isTenant=!0===Me().squidTenant,this.clientIdSubject=new o.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct((()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()}))}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,o.filter)((e=>e)),(0,o.map)((()=>{})))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,o.skip)(1),(0,o.filter)((e=>!e)),(0,o.map)((()=>{})))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientId(){const e=Me()[Ae];if(e)return e();let t=`${this.isTenant?"tenant-":""}${B()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}generateClientRequestId(){const e=Me()[ke];return e?e():B()}}const Ae="SQUID_CLIENT_ID_GENERATOR",ke="SQUID_CLIENT_REQUEST_ID_GENERATOR",je=["anthropic","flux","gemini","openai","squid","stability","voyage"],Pe=["o1","o1-mini"],xe=[...Pe,"o3","o3-mini","o4-mini"],Ce=["gpt-4o","gpt-4o-mini","gpt-4.1-nano","gpt-4.1-mini","gpt-4.1",...xe],De=["gemini-1.5-pro","gemini-2.0-flash"],Ne=["claude-3-7-sonnet-latest","claude-opus-4-20250514","claude-sonnet-4-20250514"],Re=["dictionary"],qe=[...Ce,...Ne,...De,...Re];function Fe(e){return qe.includes(e)}const Le=["text-embedding-3-small"],Be=["voyage-3-large"],Qe=[...Le,...Be],Ue=["dall-e-3"],$e=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],Ge=["tts-1","tts-1-hd","gpt-4o-mini-tts"],Ve=[...$e,...Ge],We=["stable-diffusion-core"],He=["flux-pro-1.1"],ze=[...Ue,...We,...He],Ke=[...$e],Ye=[...Ge],Je=["mp3","opus","aac","flac","wav","pcm"],Ze=["contextual","basic"],Xe=["cohere","none"];function et(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const tt={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},rt="ai_agents",nt=["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","confluence","confluent","datadog","db2","descope","documentdb","dynamodb","elasticsearch","firebase_auth","firestore","gcs","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"],it=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch"],ot=["auth0","jwt_rsa","jwt_hmac","cognito","okta","descope","firebase_auth"],st=["graphql","linear"],at=["api","confluence"],ct=["data","api","graphql"],ut="built_in_db",lt="built_in_queue",dt="built_in_storage",ht=["secret","regular"],pt=["squid_functionExecution_count","squid_functionExecution_time"],ft=["sum","max","min","average","median","p95","p99","count"],yt=["user","squid"],gt=["align-by-start-time","align-by-end-time"],vt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],bt=[...vt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],mt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],_t=["CONNECTED","DISCONNECTED","REMOVED"],St="__squidId";function wt(e){return me(e)}function It(...e){const[t,r,n]=e,i="object"==typeof t?t:{docId:t,collectionName:r,integrationId:n};return i.integrationId||(i.integrationId=void 0),ve(i)}class Ot{constructor(e,t,r){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=r,this.refId=B()}get squidDocId(){return this._squidDocId}get data(){return he(this.dataRef)}get dataRef(){return q(this.dataManager.getProperties(this.squidDocId),(()=>{const{collectionName:e,integrationId:t,docId:r}=wt(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:r,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 q(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,o.map)((e=>(q(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)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}async update(e,t){const r={};Object.entries(e).forEach((([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};r[e]=[n]}));const n={type:"update",squidDocIdObj:wt(this.squidDocId),properties:r};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,r){return this.update({[e]:he(t)},r)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,r){const n={type:"applyNumericFn",fn:"increment",value:t},i={type:"update",squidDocIdObj:wt(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(i,r)}decrementInPath(e,t,r){return this.incrementInPath(e,-t,r)}async insert(e,t){const r=wt(this.squidDocId),n=r.integrationId;let i=me(r.docId);if(i[St]&&(i={}),n===ut&&i.__id)try{const e=me(i.__id);i={...i,...e}}catch{}const o={type:"insert",squidDocIdObj:r,properties:{...e,__docId__:r.docId,...i}};return this.dataManager.applyOutgoingMutation(o,t)}async delete(e){const t={type:"delete",squidDocIdObj:wt(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}hasSquidPlaceholderId(){const e=me(this._squidDocId);if("object"==typeof e&&e.docId){const t=me(e.docId);if("object"==typeof t&&Object.keys(t).includes(St))return!0}return!1}}Error;class Mt{constructor(e,t={}){this.internalStateObserver=new o.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new o.BehaviorSubject(!1),this.snapshotSubject=new o.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,R(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,o.switchAll)()).subscribe((e=>this.dataReceived(e))),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...t},this.goToFirstPage()}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||ue(e)&&ue(t))return 0;if(ue(e))return-1;if(ue(t))return 1;const r=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:i}of r){const r=fe(ie(e,n),ie(t,n));if(0!==r)return i?r:-r}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 r=t.filter((e=>1===this.compareObjects(e,this.lastElement))).length;this.firstElement=t[e.length-r-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const r=t.filter((e=>-1===this.compareObjects(e,this.firstElement))).length,n=Math.max(0,e.length-r-this.paginateOptions.pageSize);r!==e.length?this.internalStateObserver.next({numBefore:r,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:r,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:ie(e,t.fieldName)||null})))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,o.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:ie(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,o.firstValueFrom)((0,o.race)(this.isDestroyed.pipe((0,o.filter)(Boolean),(0,o.map)((()=>({data:[],extractedData:[],numBefore:0,numAfter:0})))),this.internalStateObserver.pipe((0,o.filter)((e=>null!==e)),(0,o.take)(1))))}internalStateToState(e){const{data:t,numBefore:r,numAfter:n,extractedData:i}=e;return{data:t.filter(((e,t)=>-1!==this.compareObjects(i[t],this.firstElement))).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:r>0}}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}prevInternal(e){const{numBefore:t,numAfter:r,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-r-1],!0)}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,o.filter)((e=>null!==e)),(0,o.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.