@squidcloud/client 1.0.496 → 1.0.497
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/metric-name.d.ts +1 -1
- package/dist/internal-common/src/public-types/ai-agent.public-types.d.ts +6 -2
- package/dist/internal-common/src/public-types/ai-common.public-types.d.ts +8 -3
- package/dist/internal-common/src/public-types/ai-function.public-types.d.ts +11 -1
- package/dist/internal-common/src/public-types/ai-knowledge-base.public-types.d.ts +22 -8
- package/dist/internal-common/src/types/observability.types.d.ts +17 -0
- package/dist/internal-common/src/types/query.types.d.ts +6 -0
- package/dist/internal-common/src/utils/object.d.ts +2 -0
- package/dist/typescript-client/src/ai-knowledge-base/ai-knowledge-base-client-reference.d.ts +3 -3
- 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={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=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 r=i(642);t.default=r.PromisePool,s(i(273),t),s(i(642),t),s(i(837),t),s(i(426),t),s(i(858),t),s(i(172),t)},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},234(e,t,i){t.PromisePoolExecutor=void 0;const n=i(642),s=i(172),r=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],processedItemsCounter:0,taskTimeout:0,shouldStoreProcessedItems:!0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw s.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}storeProcessedItems(e=!0){return this.meta.shouldStoreProcessedItems=e,this}shouldStoreProcessedItems(){return this.meta.shouldStoreProcessedItems}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}flushProcessedItems(){this.meta.processedItems=[]}incrementProcessedItemsCounter(){this.meta.processedItemsCounter+=1}processedCount(){return this.meta.processedItemsCounter}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 s.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 s.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 s.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 s.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.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}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.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),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 r.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 s.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(r.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},642(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class s{constructor(e){this.shouldStoreProcessedItems=!0,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 s(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}dontStoreProcessedItems(){return this.shouldStoreProcessedItems=!1,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).storeProcessedItems(this.shouldStoreProcessedItems).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},426(e,t){Object.defineProperty(t,"__esModule",{value:!0})},858(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i},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},86(e){e.exports=require("ws")}};const t={};function i(n){const s=t[n];if(void 0!==s)return s.exports;const r=t[n]={exports:{}};return e[n].call(r.exports,r,r.exports,i),r.exports}i.d=(e,t)=>{if(Array.isArray(t))for(var n=0;n<t.length;){var s=t[n++],r=t[n++];i.o(e,s)?0===r&&n++:0===r?Object.defineProperty(e,s,{enumerable:!0,value:t[n++]}):Object.defineProperty(e,s,{enumerable:!0,get:r})}else for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.o=(e,t)=>Object.hasOwn(e,t),i.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let n={};i.r(n),i.d(n,{AGENT_STATUS_TITLE_ACCESSING_KB:()=>u,AGENT_STATUS_TITLE_AGENT_RESPONSE:()=>c,AGENT_STATUS_TITLE_AI_FUNCTION_RESULT:()=>d,AGENT_STATUS_TITLE_CALLING_AI_FUNCTION:()=>l,AGENT_STATUS_TITLE_GREPPING_KB:()=>g,AGENT_STATUS_TITLE_INSPECTING_KB_METADATA:()=>h,AGENT_STATUS_TITLE_QUERYING_KB_GRAPH:()=>p,AGENT_STATUS_TITLE_QUERYING_SPREADSHEET:()=>f,AI_AGENTS_INTEGRATION_ID:()=>fe,AI_AGENT_CONNECTION_EVENT_TYPE:()=>S,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>H,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>G,AI_CHAT_MESSAGE_SOURCE:()=>m,AI_EMBEDDINGS_MODEL_NAMES:()=>q,AI_FILE_PROVIDER_TYPES:()=>_,AI_IMAGE_MODEL_NAMES:()=>$,AI_KB_ACCESS_CONTROL_MODES:()=>X,AI_MODEL_SOURCES:()=>K,AI_PROVIDER_ERROR_TYPE:()=>y,AI_PROVIDER_TYPES:()=>v,AI_VOICE_GREETING_MODES:()=>ae,AI_VOICE_RELAY_PROVIDERS:()=>oe,AI_VOICE_SESSION_EVENT_TYPE:()=>ce,ALL_OPERATORS:()=>je,ANTHROPIC_CHAT_MODEL_NAMES:()=>O,API_INJECTION_FIELD_TYPES:()=>ue,ARRAY_OPERATORS:()=>Fe,AUTH_INTEGRATION_TYPES:()=>Ie,AdminClient:()=>ot,AiAgentClient:()=>Yt,AiAgentReference:()=>zt,AiAudioClient:()=>Zt,AiClient:()=>li,AiFilesClient:()=>ei,AiImageClient:()=>ti,AiKnowledgeBaseClient:()=>ri,AiKnowledgeBaseReference:()=>si,AiMatchMakingClient:()=>oi,AiVoiceClient:()=>ui,AiWebVoiceCall:()=>ci,ApiClient:()=>hi,ApiKeysSecretClient:()=>rt,AuthManager:()=>pi,BEDROCK_EMBEDDING_MODEL_NAMES:()=>N,BUILT_IN_AGENT_ID:()=>he,BUILT_IN_DB_INTEGRATION_ID:()=>_e,BUILT_IN_QUEUE_INTEGRATION_ID:()=>Me,BUILT_IN_STORAGE_INTEGRATION_ID:()=>Ee,BULK_INGESTION_MAX_MULTIPART_FILE_BYTES:()=>ie,BULK_INGESTION_SPEEDS:()=>re,BackendFunctionManager:()=>ji,BaseQueryBuilder:()=>nn,CLIENT_CONNECTION_STATES:()=>xe,CLIENT_ID_GENERATOR_KEY:()=>Ui,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>Qi,CONNECTOR_IDS:()=>pe,Changes:()=>on,ClientIdService:()=>Li,CollectionReference:()=>dn,CollectionReferenceFactory:()=>pn,ConnectionDetails:()=>gn,ConnectorClient:()=>a,DATA_INTEGRATION_TYPES:()=>me,DEFAULT_PII_CLASSIFIER_MODEL:()=>b,DEFAULT_PII_ENTITY_TYPES:()=>I,DEFAULT_SHORT_ID_LENGTH:()=>18,DOC_ID_FIELD:()=>qe,DataManager:()=>$n,DereferencedJoin:()=>cn,DestructManager:()=>Hn,DistributedLockImpl:()=>Kn,DistributedLockManager:()=>Vn,DocumentReference:()=>Zi,DocumentReferenceFactory:()=>Jn,DocumentStore:()=>Yn,EMPTY_CHAT_ID:()=>Xt,ENVIRONMENT_IDS:()=>de,EventsClient:()=>Xn,ExternalAuthClient:()=>Zn,ExtractionClient:()=>es,FETCH_BEYOND_LIMIT:()=>100,FILE_NAME_METADATA_FIELD_NAME:()=>ee,FLUX_MODEL_NAMES:()=>Q,FOLDER_PATH_METADATA_FIELD:()=>te,FOLDER_PATH_METADATA_FIELD_NAME:()=>Z,FUNCTION_AFFINITY_SCOPES:()=>J,GEMINI_CHAT_MODEL_NAMES:()=>T,GRAPHQL_INTEGRATION_TYPES:()=>Se,GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES:()=>50,GREP_KNOWLEDGE_BASE_MAX_MATCHES:()=>200,GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS:()=>500,GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS:()=>500,GROK_CHAT_MODEL_NAMES:()=>k,GroupedJoin:()=>ln,HTTP_INTEGRATION_TYPES:()=>we,HttpStatus:()=>ge,INTEGRATION_SCHEMA_TYPES:()=>ve,INTEGRATION_TYPES:()=>ye,IntegrationClient:()=>nt,JobClient:()=>ts,JoinQueryBuilder:()=>an,LangGraphClient:()=>ns,LangGraphReference:()=>is,LastUsedValueExecuteFunctionCache:()=>Ni,LimitUnderflowState:()=>Qn,LocalQueryManager:()=>As,MAX_UPLOAD_FILE_BYTES:()=>ne,MCP_OAUTH_INTEGRATION_TYPES:()=>be,METRIC_DOMAIN:()=>De,METRIC_FUNCTIONS:()=>Ce,METRIC_INTERVAL_ALIGNMENT:()=>Re,METRIC_NO_DATA_BEHAVIOR:()=>Ne,ManagementClient:()=>ys,MatchMaker:()=>ai,MutationSender:()=>ms,NOOP_FN:()=>os,NativeQueryManager:()=>Is,NotificationClient:()=>bs,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>B,OPENAI_AUDIO_MODEL_NAMES:()=>L,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>x,OPENAI_CHAT_MODEL_NAMES:()=>E,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>D,OPENAI_IMAGE_MODEL_NAMES:()=>P,OPEN_AI_CREATE_SPEECH_FORMATS:()=>V,ObservabilityClient:()=>ws,Pagination:()=>en,QueryBuilder:()=>rn,QueryBuilderFactory:()=>tn,QuerySender:()=>Ds,QuerySubscriptionManager:()=>Zs,QueueManagerFactory:()=>nr,QueueManagerImpl:()=>rr,RAG_TYPES:()=>se,RERANK_PROVIDERS:()=>w,RUN_IN_TRANSACTION_MUTEX:()=>Un,RateLimiter:()=>or,RpcManager:()=>ar,SOURCE_CODE_ANALYZER_MODELS:()=>Ke,SOURCE_CODE_ANALYZE_FUNCTION_ID:()=>He,SOURCE_CODE_CACHE_STRATEGIES:()=>We,SOURCE_CODE_EXECUTION_MODES:()=>ze,SOURCE_CODE_INTEGRATION_TYPES:()=>Ye,SOURCE_CODE_MAX_REPOSITORIES:()=>20,SOURCE_CODE_MAX_SUPPLEMENTAL_INSTRUCTIONS_LENGTH:()=>2e4,SOURCE_CONTROL_PROVIDERS:()=>Je,SQUID_BUILT_IN_INTEGRATION_IDS:()=>ke,SQUID_METRIC_NAMES:()=>Ae,SQUID_REGIONS:()=>Pe,STABLE_DIFFUSION_MODEL_NAMES:()=>U,SchedulerClient:()=>lr,SecretClient:()=>st,SocketManager:()=>pr,Squid:()=>wr,SquidClientError:()=>as,StorageClient:()=>Ir,VECTOR_DB_TYPES:()=>Y,VENDOR_AI_CHAT_MODEL_NAMES:()=>A,VOYAGE_EMBEDDING_MODEL_NAMES:()=>R,WebClient:()=>br,WebhookManager:()=>Sr,assertNotPassiveMode:()=>ur,compareArgsByReference:()=>Di,compareArgsBySerializedValue:()=>Ri,deserializeQuery:()=>Ts,embeddingModelSelectionOf:()=>W,generateId:()=>Ft,generateShortId:()=>Bt,generateShortIds:()=>Lt,generateUUID:()=>Nt,generateUUIDPolyfill:()=>qt,getConsoleUrl:()=>o,getCustomizationFlag:()=>Pi,isAiEmbeddingsModelName:()=>F,isBuiltInIntegrationId:()=>Oe,isFileCapableProviderType:()=>M,isIntegrationDisabled:()=>Te,isIntegrationEmbeddingModelSpec:()=>j,isIntegrationModelSpec:()=>z,isPlaceholderParam:()=>le,isVendorAiChatModelName:()=>C,loadQueryResultDocIds:()=>Es,normalizeBitbucketRepositorySelection:()=>Ze,normalizeGitHubRepositorySelection:()=>Xe,observeAiStatusUpdates:()=>Wt,rawSquidHttpDelete:()=>ps,rawSquidHttpGet:()=>ls,rawSquidHttpPatch:()=>hs,rawSquidHttpPost:()=>us,rawSquidHttpPut:()=>ds,transformFileArgs:()=>qi,tryDeserializing:()=>fs,visitQueryResults:()=>Ms});const s="8000";function r(e,t,i,n,r){let o="https",a=`${n||t}.${r||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=s,/android$/.test(e)?a="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(a="localhost"));const u=o+"://"+a+(c?`:${c}`:""),l=i.replace(/^\/+/,"");return l?`${u}/${l}`:u}function o(e,t,i=""){return r(function(e,t){return t||(e.includes("sandbox")?"squidai.westus3.azure.sandbox":e.includes("local")?"local":e.includes("staging")?"squidai.westus3.azure.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}/connectors`)}async list(){return await this.rpcManager.get(this.iacBaseUrl)??[]}async connect(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e}`,{})}async disconnect(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}}const c="Agent Response",u="Accessing Knowledge Base",l="Calling AI Function",d="AI Function Result",h="Inspecting Knowledge Base Metadata",p="Querying Knowledge Base Graph",g="Searching Knowledge Base Text",f="Querying Spreadsheet",y="AI_PROVIDER_ERROR",m=["user","ai"],I=["email","phoneNumber","creditCard","ssn","iban","passport"],b="gpt-5.6-luna",S="ai-agent-connection-event",w=["cohere","voyage","none"],v=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","openai-compatible","grok","stability","voyage","mistral","textract","azure_document_intelligence","vertex","external"],_=["openai","gemini","anthropic","grok"];function M(e){return _.includes(e)}const E=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra"],T=["gemini-3.1-pro","gemini-3.8-flash","gemini-3.5-flash-lite"],k=["grok-4.6","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],O=["claude-fable-5","claude-fable-5-1","claude-haiku-4-5-20251001","claude-opus-5","claude-sonnet-5"],A=[...E,...O,...T,...k];function C(e){return A.includes(e)}const D=["text-embedding-3-small"],R=["voyage-3-large","voyage-4-large","voyage-4"],N=["titan-embed-text-v2"],q=[...D,...R,...N];function F(e){return q.includes(e)}function j(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const P=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],x=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],B=["tts-1","tts-1-hd","gpt-4o-mini-tts"],L=[...x,...B],U=["stable-diffusion-core"],Q=["flux-pro-1.1","flux-kontext-pro"],$=[...P,...U,...Q],G=[...x],H=[...B],V=["mp3","opus","aac","flac","wav","pcm"],K=["vendor","connector","custom"];function W(e){return void 0!==e.integrationId&&void 0!==e.dimensions?{integrationId:e.integrationId,model:e.modelId,dimensions:e.dimensions}:e.modelId}function z(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const J=["pod","worker"],Y=["postgres","mongoAtlas"],X=["none","enforced"],Z="folderPath",ee="filename",te={name:Z,dataType:"string",required:!1,llmExtraction:!1},ie=104857600,ne=524288e3,se=["contextual","basic"],re=["economy","auto","fast"],oe=["twilio","openai"],ae=["phrase","agent"],ce="ai-voice-session-event",ue=["secret","regular"];function le(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const de=["dev","prod"],he="built_in_agent",pe=["bitbucket","confluence","connect_companion","cotomi","elevenlabs","openai_voice","essentials","freshdesk","generic_site_ingester","github","google_calendar","google_drive","hubspot","sharepoint","jira","jira_jsm","linear","mail","onedrive","outlook","salesforce","servicenow_csm","slack","teams","ticketmind_companion","twilio","zendesk"],ge={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},fe="ai_agents",ye=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","bedrock","azure_blob","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","bitbucket","built_in_azure_blob","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","azure-entra-external-id","azure-entra-id","dynamodb","elasticsearch","firebase_auth","firestore","gcs","generic_site_ingester","github","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jira_jsm","jwt_hmac","jwt_rsa","kafka","keycloak","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","outlook","oracledb","pinecone","postgres","redis","s3","salesforce","sap_hana","sentry","snowflake","spanner","xata","zendesk","servicenow_csm","freshdesk","mail","slack","twilio","elevenlabs","openai_voice","mcp","a2a","legend","teams","openai_compatible","openai_compatible_embedding","sharepoint","vertex"],me=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","snowflake","elasticsearch","legend"],Ie=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id","azure-entra-id"],be=["auth0","azure-entra-id","azure-entra-external-id"],Se=["graphql"],we=["api"],ve=["data","api","graphql"],_e="built_in_db",Me="built_in_queue",Ee="built_in_storage";function Te(e){return!1===e.enabled}const ke=[_e,Me,Ee];function Oe(e){return ke.includes(e)}const Ae=["squid_functionExecution_count","squid_functionExecution_time"],Ce=["sum","max","min","average","median","p95","p99","count"],De=["user","squid"],Re=["align-by-start-time","align-by-end-time"],Ne=["return-no-result-groups","return-result-group-with-default-values"],qe="__docId__",Fe=["in","not in","array_includes_some","array_includes_all","array_not_includes"],je=[...Fe,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],Pe=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],xe=["CONNECTED","DISCONNECTED","REMOVED"];function Be(e){return null!=e}let Le=e=>new Error(e);function Ue(e,t,...i){e||function(e,...t){const i=$e(e);if("object"==typeof i)throw i;throw Le(i||"Assertion error",...t)}(t,...i)}function Qe(e,t,...i){return Ue(e,t,...i),e}function $e(e){return void 0===e?"":"string"==typeof e?e:e()}function Ge(e,t,i){const n=$e(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 He="analyzeCode",Ve=20,Ke=["claude-code","codex"],We=["reuse","recreate"],ze=["read-only","write"],Je=["github","bitbucket"],Ye=["github","bitbucket"];function Xe(e){const t=function(e){const t=new Set,i=new Set;for(const n of e){Ue(Number.isSafeInteger(n.id)&&n.id>0,"GITHUB_REPOSITORY_ID_INVALID"),Ue(!t.has(n.id),"GITHUB_REPOSITORY_IDS_MUST_BE_UNIQUE"),t.add(n.id),Ue(et(n.fullName),"GITHUB_REPOSITORY_NAME_INVALID");const e=n.fullName.toLowerCase();Ue(!i.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),i.add(e),Ue(n.defaultBranch.trim(),"GITHUB_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),tt(n.cloneUrl,n.fullName,!0),tt(n.htmlUrl,n.fullName,!1)}return e}(e.repositories??[]),i=0===t.length?e.repository:void 0,n=t.map(e=>e.fullName);Ue(t.length>0||i,"GITHUB_REPOSITORIES_REQUIRED"),Ue(t.length<=Ve,"GITHUB_REPOSITORY_LIMIT_EXCEEDED");const s=e.defaultRepository??n[0]??i;return Ue(s,"GITHUB_DEFAULT_REPOSITORY_REQUIRED"),Ue(n.some(e=>e.toLowerCase()===s.toLowerCase())||i?.toLowerCase()===s.toLowerCase(),"GITHUB_DEFAULT_REPOSITORY_NOT_ALLOWED"),{...i?{legacyRepository:i}:{},repositories:t,defaultRepository:s}}function Ze(e){const t=e.workspace;Ue(t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),"BITBUCKET_WORKSPACE_INVALID");const i=e.repositories;Ue(i.length>0,"BITBUCKET_REPOSITORIES_REQUIRED"),Ue(i.length<=Ve,"BITBUCKET_REPOSITORY_LIMIT_EXCEEDED");const n=new Set,s=new Set;for(const e of i){const i=e.uuid.trim();Ue(i===e.uuid&&i.length>0,"BITBUCKET_REPOSITORY_ID_INVALID");const r=i.toLowerCase();Ue(!n.has(r),"BITBUCKET_REPOSITORY_IDS_MUST_BE_UNIQUE"),n.add(r);const o=`${t}/`;Ue(e.fullName.toLowerCase().startsWith(o.toLowerCase())&&e.fullName.length>o.length&&!e.fullName.slice(o.length).includes("/")&&!/\s/.test(e.fullName),"BITBUCKET_REPOSITORY_WORKSPACE_MISMATCH");const a=e.fullName.toLowerCase();Ue(!s.has(a),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),s.add(a),Ue(e.defaultBranch.trim(),"BITBUCKET_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),it(e.cloneUrl,e.fullName,!0),it(e.webUrl,e.fullName,!1)}const r=e.defaultRepository;return Ue(r&&i.some(e=>e.fullName.toLowerCase()===r.toLowerCase()),"BITBUCKET_DEFAULT_REPOSITORY_NOT_ALLOWED"),{repositories:i,defaultRepository:r}}function et(e){return/^[^/\s]+\/[^/\s]+$/.test(e)}function tt(e,t,i){let n;try{n=new URL(e)}catch{throw new Error("GITHUB_REPOSITORY_URL_INVALID")}const s=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?github\.com:\d+(?:\/|$)/i.test(e);Ue(!("https:"!==n.protocol||"github.com"!==n.hostname||r||n.username||n.password||n.search||n.hash||n.pathname!==s),"GITHUB_REPOSITORY_URL_INVALID")}function it(e,t,i){let n;try{n=new URL(e)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const s=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(e);Ue(!("https:"!==n.protocol||"bitbucket.org"!==n.hostname||r||n.username||n.password||n.search||n.hash||n.pathname!==s),"BITBUCKET_REPOSITORY_URL_INVALID")}class nt{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e,t){return(await this.rpcManager.get(this.iacBaseUrl)).filter(i=>(!e||i.type===e)&&(t?.includeDisabled||!Te(i)))}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async enable(e){await this.setEnabled(e,!0)}async disable(e){await this.setEnabled(e,!1)}async setEnabled(e,t){const i=await this.get(e);if(!i)throw new Error(`Integration not found: ${e}`);await this.upsertIntegration({...i,enabled:t})}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)}async discoverSourceRepositories(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-source-repositories`,{})}async discoverSourceRepositoriesFromDraft(e){return await this.rpcManager.post(`${this.iacBaseUrl}/discover-source-repositories`,e)}async generateAiDescriptionsForDataSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions`,t)}async generateAiDescriptionsForAssociations(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-associations`,t)}async generateAiDescriptionsForStoredProcedures(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-stored-procedures`,t)}async generateAiDescriptionsForEndpoints(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-endpoints`,t)}async discoverDataConnectionSchema(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-schema`,{})}async testDataConnection(e){return await this.rpcManager.post(`${this.iacBaseUrl}/test-connection`,e)}async discoverGraphQLConnectionSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-graphql-schema`,t)}async discoverOpenApiSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema`,t)}async discoverOpenApiSchemaFromFile(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema-from-file`,{})}}class st{constructor(e){this.rpcManager=e}get apiKeys(){return new rt(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 rt{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 ot{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new nt(this.rpcManager,this.region,this.appId,this.consoleRegion),this.connectorClient=new a(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new st(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}const at=require("rxjs");function ct(e){return"function"==typeof e}function ut(e){return function(t){if(function(e){return ct(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 lt=function(e,t){return lt=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])},lt(e,t)};function dt(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}lt(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function ht(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 pt(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}function gt(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s<r;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create;var ft,yt=((ft=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),ft.prototype.constructor=ft,ft);function mt(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var It=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,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=ht(r),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 r.remove(this);var c=this.initialTeardown;if(ct(c))try{c()}catch(e){s=e instanceof yt?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=ht(u),d=l.next();!d.done;d=l.next()){var h=d.value;try{bt(h)}catch(e){s=null!=s?s:[],e instanceof yt?s=gt(gt([],pt(s)),pt(e.errors)):s.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(s)throw new yt(s)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)bt(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)&&mt(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&mt(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function bt(e){ct(e)?e():e.unsubscribe()}It.EMPTY;var St={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var s=St.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,gt([e,t],pt(i))):setTimeout.apply(void 0,gt([e,t],pt(i)))},clearTimeout:function(e){var t=St.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function wt(){}var vt=_t("C",void 0,void 0);function _t(e,t,i){return{kind:e,value:t,error:i}}var Mt=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof It||i&&"closed"in i&&ct(i.remove)&&ct(i.add)&&ct(i.unsubscribe))&&t.add(n)):n.destination=At,n}return dt(t,e),t.create=function(e,t,i){return new Tt(e,t,i)},t.prototype.next=function(e){this.isStopped?Ot(function(e){return _t("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?Ot(_t("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?Ot(vt,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}(It);Function.prototype.bind;var Et=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){kt(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){kt(e)}else kt(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){kt(e)}},e}(),Tt=function(e){function t(t,i,n){var s,r=e.call(this)||this;return s=ct(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,r.destination=new Et(s),r}return dt(t,e),t}(Mt);function kt(e){!function(e){St.setTimeout(function(){throw e})}(e)}function Ot(e,t){var i=null;i&&St.setTimeout(function(){return i(e,t)})}var At={closed:!0,next:wt,error:function(e){throw e},complete:wt};function Ct(e,t,i,n,s){return new Dt(e,t,i,n,s)}var Dt=function(e){function t(t,i,n,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=s?function(e){try{s(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 dt(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}(Mt);function Rt(e,t){return ut(function(i,n){var s=0;i.subscribe(Ct(n,function(i){n.next(e.call(t,i,s++))}))})}function Nt(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():qt()}function qt(){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 Ft(){return Nt()}const jt=18,Pt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xt(){return Pt.charAt(Math.floor(Math.random()*Pt.length))}function Bt(e=jt,t="",i=""){Ue(t.length<e,"ID prefix is too long"),Ue(!t||!i||i.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let n="";for(let t=0;t<e;t++)n+=xt();if(t.length>0&&(n=t+n.substring(t.length)),i)for(;n.charAt(t.length)===i[t.length];)n=n.substring(0,t.length)+xt()+n.substring(t.length+1);return n}function Lt({count:e,length:t,prefix:i}){Ue(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(Bt(t||jt,i||""));return[...n]}const Ut=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Qt(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Qt(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Qt(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(Ut.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Ut.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 $t(e,t,i){const n=atob(e),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return new File([s],t,{type:i||"application/octet-stream"})}const Gt={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",PROXY_HOP:"x-squid-proxy-hop",CLIENT_VERSION:"x-squid-client-version",SOURCE_IP:"x-squid-source-ip",INTEGRATION_ACCESS_TOKENS:"x-squid-integration-access-tokens",POD_IP:"x-squid-pod-ip",INSTANCE_ID:"x-squid-instance-id",EXPECTED_INSTANCE_ID:"x-squid-expected-instance-id",WORKER_KEY:"x-squid-worker-key"};function Ht(e){return JSON.stringify(e)}function Vt(e){return e&&Object.keys(e).length?{[Gt.INTEGRATION_ACCESS_TOKENS]:Ht(e)}:{}}function Kt(e){if(!e)return{headers:{},options:void 0};const{integrationAccessTokens:t,...i}=e;return{headers:Vt(t),options:i}}function Wt(e,t){const{agentId:i,jobId:n}=t;return e.notifyWebSocketIsNeeded(),e.observeNotifications().pipe((0,at.filter)(e=>"aiStatus"===e.type&&(void 0===i||e.agentId===i)),(0,at.filter)(e=>!n||e.jobId===n),(0,at.map)(e=>({agentId:e.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,body:e.payload.body,parentStatusUpdateId:e.payload.parentStatusUpdateId,messageId:e.payload.statusUpdateId??e.messageId})))}Error;class zt{constructor(e,t,i,n,s,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=n,this.socketManager=s,this.jobClient=r,this.backendFunctionManager=o,this.getMetricAnnotations=a}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();Ue(t,"Agent not found");const i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}async updatePii(e){const t=await this.get();Ue(t,"Agent not found");const i={onDetect:"off",...t.options?.pii,...e};await this.setAgentOptionInPath("pii",i)}async updateMcpServer(e){await this.post("ai/agent/setMcpServer",{agentId:this.agentId,mcpServer:e})}async generateMcpDescriptions(){return await this.post("ai/agent/generateMcpDescriptions",{agentId:this.agentId})}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})}async listRevisions(){return await this.post("ai/agent/listRevisions",{agentId:this.agentId})}async restoreRevision(e){await this.post("ai/agent/restoreRevision",{agentId:this.agentId,revisionNumber:e})}async deleteRevision(e){await this.post("ai/agent/deleteRevision",{agentId:this.agentId,revisionNumber:e})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),s=await Qe(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:s.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{headers:n,options:s}=Kt(i),r={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(s),jobId:t};await this.post("ai/chatbot/askAsync",r,[],"files",n)}observeStatusUpdates(e){return Wt(this.socketManager,{agentId:this.agentId,jobId:e})}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),s=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:$t(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:$t(s.base64File,`voice.${s.extension}`,s.mimeType)}}async setAgentOptionInPath(e,t){await this.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async addConnectedIntegration(e){await this.post("ai/agent/addConnectedIntegration",{agentId:this.agentId,integrationId:e.integrationId,integrationType:e.integrationType,description:e.description??""})}async addConnectedAgent(e){await this.post("ai/agent/addConnectedAgent",{agentId:this.agentId,connectedAgentId:e.agentId,description:e.description})}async addConnectedKnowledgeBase(e){await this.post("ai/agent/addConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e.knowledgeBaseId,description:e.description,includeMetadata:e.includeMetadata})}async addFunction(e){await this.post("ai/agent/addFunction",{agentId:this.agentId,functionId:e})}async removeConnectedAgent(e){await this.post("ai/agent/removeConnectedAgent",{agentId:this.agentId,connectedAgentId:e})}async removeConnectedIntegration(e){await this.post("ai/agent/removeConnectedIntegration",{agentId:this.agentId,integrationId:e})}async removeConnectedKnowledgeBase(e){await this.post("ai/agent/removeConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e})}async removeFunction(e){await this.post("ai/agent/removeFunction",{agentId:this.agentId,functionId:e})}async setAgentDescription(e){await this.post("ai/agent/setAgentDescription",{agentId:this.agentId,description:e})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}async build(e,t,i){const n={agentId:this.agentId,request:e,memoryId:t,options:i};return await this.backendFunctionManager.executeFunction("buildAgent",n)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const s=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${s}](${n.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&Qt(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)Qt(i.contextMetadataFilterForKnowledgeBase[e]);n=n||Nt();const{headers:s,options:r}=Kt(i);i=this.withMetricAnnotations({...Jt,...r||{}});const o="string"==typeof e;let a="ai/chatbot/";a+=o||t?!o&&t?"transcribeAndAskWithVoiceResponse":o&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const c={agentId:this.agentId,prompt:o?e:void 0,options:i,jobId:n},u=o?void 0:[e];return await this.post(a,c,u,"file",s),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Qt(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Qt(t.contextMetadataFilterForKnowledgeBase[e]);const n=Nt(),{headers:s,options:r}=Kt(t),o=void 0===(t=this.withMetricAnnotations({...Jt,...r||{}})).smoothTyping||t.smoothTyping;let a="";const c=new at.Subject,u=new at.Subject;this.ongoingChatSequences[n]=u;let l=-1;u.pipe((0,at.tap)(({tokenIndex:e})=>{void 0!==e&&e<l&&console.warn("Received token index out of order",e,l),void 0!==e&&(l=e)}),(0,at.concatMap)(({value:e,complete:t,annotations:i})=>t?(0,at.of)({value:e,complete:t,annotations:i}):(0,at.of)(e).pipe((()=>{const e=globalThis.document,t="object"==typeof e&&null!==e&&!0===e.hidden;return o&&!t})()?(0,at.delay)(0):(0,at.tap)(),Rt(e=>({value:e,complete:!1,annotations:void 0})))),(0,at.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{a+=e,t&&i&&(a=this.replaceFileTags(a,i)),c.next(a)},error:e=>{console.error(e)},complete:()=>{c.complete()}});const d="string"==typeof e;i=i||Nt();const h={agentId:this.agentId,jobId:i,prompt:d?e:void 0,options:t,clientRequestId:n},p={responseStream:c.pipe((0,at.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,at.share)())};let g;return g=d?this.post("ai/chatbot/chat",h,[],"files",s).catch(e=>{c.error(e),c.complete()}):this.post("ai/chatbot/transcribeAndChat",h,[e],"file",s).catch(e=>{throw c.error(e),c.complete(),e}),p.serverResponse=g.then(()=>this.jobClient.awaitJob(i)).catch(e=>{c.error(e),c.complete()}),p}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,i=[],n="files",s={}){const r={...s};return this.agentApiKey&&(r["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,n,r)}}const Jt={smoothTyping:!0,responseFormat:"text"};class Yt{constructor(e,t,i,n,s=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,this.getMetricAnnotations=s,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,at.filter)(e=>"aiChatbot"===e.type),Rt(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new zt(e,t?.apiKey,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)}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:s,annotations:r}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const Xt="__squid_empty_chat_id";class Zt{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 $t(n.base64File,`audio.${n.extension}`,n.mimeType)}}class ei{constructor(e,t){this.provider=e,this.rpcManager=t}async uploadFile(e){const t={provider:this.provider,expirationInSeconds:e.expirationInSeconds};return(await this.rpcManager.post("ai/files/uploadFile",t,[e.file],"file")).fileId}async deleteFile(e){const t={fileId:e,provider:this.provider};return(await this.rpcManager.post("ai/files/deleteFile",t)).deleted}}class ti{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 ii(e){for(const t in e){const i=e[t];Ue("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),Ue(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}const ni=new Set(["completed","failed","cancelled"]);class si{constructor(e,t,i,n,s){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i,this.socketManager=n,this.clientIdService=s}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 generateMetadataFieldDescriptions(e){return this.rpcManager.post("ai/knowledge-base/generateMetadataFieldDescriptions",{knowledgeBaseId:this.knowledgeBaseId,fieldNames:e?.fieldNames,overwriteExisting:e?.overwriteExisting})}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 listContextsPage(e){return this.rpcManager.post("ai/knowledge-base/listContextsPage",{id:this.knowledgeBaseId,truncateTextAfter:e?.truncateTextAfter,offset:e?.offset,limit:e?.limit,search:e?.search})}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}async getContext(e,t){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e,truncateTextAfter:t?.truncateTextAfter})).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 setContextScopes(e,t){const{updatedChunkCount:i}=await this.rpcManager.post("ai/knowledge-base/setContextScopes",{knowledgeBaseId:this.knowledgeBaseId,contextId:e,scopes:t});return i}async upsertContext(e,t){const{failures:i,contextIds:n,graphIndexingSkippedContextIds:s,imageFailures:r}=await this.upsertContexts([e],t?[t]:void 0);if(i.length>0)return{failure:i[0]};const o=n?.[0],a=void 0!==o&&(s?.includes(o)??!1),c=r?.find(e=>e.contextId===o);return{...a?{graphIndexingSkipped:a}:{},...c?{imageFailures:c.imageFailures,imageFailureCount:c.imageFailureCount}:{}}}async upsertContexts(e,t,i){for(const t of e)t.metadata&&ii(t.metadata);const n=Nt();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:n},t),i?.onUploaded?.(),await this.jobClient.awaitJob(n)}async bulkUpsertContexts(e,t,i){return this.rpcManager.post("ai/knowledge-base/bulk/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contexts:e,speed:i?.speed},t)}async createBulkUploadUrls(e){return this.rpcManager.post("ai/knowledge-base/bulk/createUploadUrls",{files:e.map(e=>({fileName:e}))})}async getBulkIngestionJob(e){return this.rpcManager.post("ai/knowledge-base/bulk/getJob",{jobId:e})}async cancelBulkIngestionJob(e){await this.rpcManager.post("ai/knowledge-base/bulk/cancelJob",{jobId:e})}observeBulkIngestionJob(e){return new at.Observable(t=>{const i=()=>{this.rpcManager.post("ai/knowledge-base/bulk/subscribeToJob",{jobId:e}).catch(e=>t.error(e))};t.add(this.socketManager.observeNotifications().pipe((0,at.filter)(e=>"bulkIngestionStatus"===e.type),(0,at.filter)(t=>t.payload.jobId===e)).subscribe(e=>{t.next(e.payload),ni.has(e.payload.state)&&t.complete()})),t.add(this.clientIdService.observeClientId().pipe((0,at.distinctUntilChanged)(),(0,at.skip)(1)).subscribe(()=>i())),this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.awaitConnectionReady().then(i).catch(e=>t.error(e))})}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 searchWithGraphContext(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return this.rpcManager.post("ai/knowledge-base/search",t)}async grep(e,t){return this.rpcManager.post("ai/knowledge-base/grep",{knowledgeBaseId:this.knowledgeBaseId,pattern:e,options:t})}async queryGraph(e){return this.rpcManager.post("ai/knowledge-base/queryGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async getGraphStatus(){return this.rpcManager.post("ai/knowledge-base/getGraphStatus",{knowledgeBaseId:this.knowledgeBaseId})}async rebuildGraph(e){await this.rpcManager.post("ai/knowledge-base/rebuildGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async exploreGraph(e){return this.rpcManager.post("ai/knowledge-base/exploreGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}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 ri{constructor(e,t,i,n){this.rpcManager=e,this.jobClient=t,this.socketManager=i,this.clientIdService=n}knowledgeBase(e){return new si(e,this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)}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 oi{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new ai(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new ai(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class ai{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}}class ci{constructor(e,t,i,n){this.sessionId=e,this.callId=t,this.peer=i,this.microphone=n,this.eventListeners=new Set,this.endListeners=new Set,this.ended=!1}static async start(e,t){const i=globalThis,n=i.RTCPeerConnection,s=i.navigator?.mediaDevices;if(!n||!s)throw new Error("A web voice call needs a browser with WebRTC support");const{sink:r,...o}=t,a=await s.getUserMedia({audio:!0}),c=new n,u=r??i.document?.createElement("audio");u&&(u.autoplay=!0),c.ontrack=e=>{u&&(u.srcObject=e.streams[0],u.play().catch(()=>{}))};for(const e of a.getAudioTracks())c.addTrack(e,a);const l=c.createDataChannel("oai-events"),d=await c.createOffer();let h;await c.setLocalDescription(d),l.onmessage=e=>{try{h?.dispatch(JSON.parse(e.data))}catch{}},c.onconnectionstatechange=()=>{["failed","closed","disconnected"].includes(c.connectionState)&&h?.finish()};const p=await e.startOpenAiWebCall({...o,sdp:d.sdp??""});return await c.setRemoteDescription({type:"answer",sdp:p.sdp}),h=new ci(p.sessionId,p.callId,c,a),h}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}onTurn(e){return this.onEvent(t=>{const i="string"==typeof t.transcript?t.transcript.trim():"";i&&("conversation.item.input_audio_transcription.completed"===t.type?e({role:"user",text:i,at:(new Date).toISOString()}):"response.output_audio_transcript.done"===t.type&&e({role:"agent",text:i,at:(new Date).toISOString()}))})}onEnd(e){return this.endListeners.add(e),()=>this.endListeners.delete(e)}setMuted(e){for(const t of this.microphone.getAudioTracks())t.enabled=!e}stop(){this.finish()}dispatch(e){for(const t of this.eventListeners)t(e)}finish(){if(!this.ended){this.ended=!0;for(const e of this.microphone.getTracks())e.stop();this.peer.close();for(const e of this.endListeners)e()}}}class ui{constructor(e){this.rpcManager=e}async createSession(e){return this.rpcManager.post("ai/voice/createSession",e)}async answerOpenAiCall(e){return this.rpcManager.post("ai/voice/openai/answer",e)}async startOpenAiWebCall(e){return this.rpcManager.post("ai/voice/openai/webCall",e)}async startWebCall(e){return ci.start(this,e)}}class li{constructor(e,t,i,n,s,r=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.clientIdService=n,this.backendFunctionManager=s,this.getMetricAnnotations=r}agent(e=he,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()}async listFunctions(){const e=await this.rpcManager.post("/application/getBundleMetadata",{});return Object.values(e.aiFunctions||{})}async listChatModels(e){return(await this.rpcManager.post("ai/settings/listChatModels",e??{})).models}async listEmbeddingModels(e){return(await this.rpcManager.post("ai/settings/listEmbeddingModels",e??{})).models}image(){return new ti(this.rpcManager)}audio(){return new Zt(this.rpcManager)}voice(){return new ui(this.rpcManager)}matchMaking(){return new oi(this.rpcManager)}files(e){return new ei(e,this.rpcManager)}executeAiQuery(e,t,i,n){const{accessToken:s,...r}=i??{},o={integrationId:e,prompt:t,options:r},a=Vt(s?{[e]:s}:void 0);return this.rpcManager.post("ai/query/executeDataQuery",o,[],"files",a,n)}executeAiApiCall(e,t,i,n){const s={integrationId:e,prompt:t,options:i,sessionContext:n};return this.rpcManager.post("ai/query/executeApiQuery",s)}executeAiSpreadsheetQuery(e,t,i,n){const s={prompt:e,files:t,options:i,sessionContext:n};return this.rpcManager.post("ai/query/executeSpreadsheetQuery",s)}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}observeStatusUpdates(e){return Wt(this.socketManager,{jobId:e})}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Yt(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new ri(this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)),this.aiKnowledgeBaseClient}}const di={headers:{},queryParams:{},pathParams:{}};class hi{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,s){const r={integrationId:e,endpointId:t,body:i,options:{...di,...this.convertOptionsToStrings(n||{})},overrideMethod:s};return await this.rpcManager.rawPost("api/callApi",r,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 pi{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 gi=/[.\[\]]/;function fi(e,t){if(!e)return;const i=t.split(gi);let n,s=e;for(;s&&i.length;){const e=i.shift();if(e){if("object"!=typeof s||!(e in s))return;n=s[e],s=n}}return n}function yi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function mi(e,t,i,n="."){const s=t.split(n);let r=e;for(;s.length;){const e=Qe(s.shift());if(s.length){const t=r[e],i=yi(t)?_i(t)??{}:{};r[e]=i,r=i}else r[e]=i}}function Ii(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function bi(e){return null==e}function Si(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),s=Object.keys(t);if(n.length!==s.length)return!1;for(const i of n)if(!s.includes(i)||!Si(e[i],t[i]))return!1;return!0}function wi(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=vi(e[n],t);return i}function vi(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 wi(e,t);if(e instanceof Map)return new Map(wi(Array.from(e),t));if(e instanceof Set)return new Set(wi(Array.from(e),t));if(ArrayBuffer.isView(e))return n=e,"undefined"!=typeof Buffer&&n instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const s={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(s[i]=vi(e[i],t));return s}function _i(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 Mi(e,t){if(e===t||bi(e)&&bi(t))return 0;if(bi(e))return-1;if(bi(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(Ue("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(Ue("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(Ue("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(Ue("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function Ei(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function Ti(e){if(Array.isArray(e))return e.map(e=>Ti(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]=Ti(e[t])}),i}function ki(e){return Oi(Ti(e))}function Oi(e){if(void 0===e)return null;const t=vi(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Ai(e){return vi(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 Ci(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=Oi(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 Di=(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},Ri=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Oi(e[i])!==Oi(t[i]))return!1;return!0};class Ni{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Di,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 qi(e){const t=[],i=[];let n=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){i.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(Fi(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(i.push(s[t]),n++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:i}}function Fi(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class ji{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:n,fileArray:s}=qi(i),r="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?Di:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,n));if(t)return t.promise}const u=this.createExecuteCallPromise(r,n,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:n,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,i,n,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:Oi(t)},a=Ai((await this.rpcManager.post(r,o,i.length>0?i:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return $t(e.base64,e.filename,e.mimetype)}return n&&n.set(t,a),a}}function Pi(e){if("undefined"!=typeof globalThis)return globalThis[e]}function xi(){if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}void 0===xi()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){xi().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 Bi{static debug(...e){(function(){const e=xi();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=xi();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Li{constructor(e){this.destructManager=e,this.clientTooOldSubject=new at.BehaviorSubject(!1),this.isTenant=!0===xi().squidTenant,this.clientIdSubject=new at.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,at.filter)(e=>e),(0,at.map)(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,at.skip)(1),(0,at.filter)(e=>!e),(0,at.map)(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=xi()[Qi];return e?e():Nt()}generateClientId(){const e=xi()[Ui];if(e)return e();let t=`${this.isTenant?"tenant-":""}${Nt()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Ui="SQUID_CLIENT_ID_GENERATOR",Qi="SQUID_CLIENT_REQUEST_ID_GENERATOR",$i="__squidId";function Gi(e){return Ai(e)}function Hi(...e){const[t,i,n]=e,s="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return s.integrationId||(s.integrationId=void 0),ki(s)}function Vi(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return Si(e,t);if("!="===i)return!Si(e,t);switch(i){case"<":return!bi(e)&&(!!bi(t)||t<e);case"<=":return!!bi(t)||!bi(e)&&t<=e;case">":return!bi(t)&&(!!bi(e)||t>e);case">=":return!!bi(e)||!bi(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Ki(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Ki(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Ki(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Ki(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>Qe(i,"VALUE_CANNOT_BE_NULL").some(t=>Si(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>Qe(i,"VALUE_CANNOT_BE_NULL").some(t=>Si(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!Qe(i,"VALUE_CANNOT_BE_NULL").some(t=>Si(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function Ki(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 Wi(e,t){return`${e}_${t}`}function zi(e){return"fieldName"in e}function Ji(e){return"docIds"in e}function Yi(e,t,i){const n=e.docIds.some(e=>Object.entries(e).every(([e,n])=>Vi(n,i(t,e)??null,"==")));switch(e.operator){case"==":case"in":return n;case"!=":case"not in":return!n}}function Xi(e,t,i,n){const s=e,r=n(t,qe);if("string"!=typeof r)return Vi(s,r??null,i);let o;try{o=Ai(r)}catch{return Vi(s,r,i)}if(!o||"object"!=typeof o||Array.isArray(o))return Vi(s,r,i);const a=Object.keys(o);if(1===a.length&&"__id"===a[0]){const e=o.__id,t=function(e){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=Object.keys(e);return 1===t.length&&"__id"===t[0]?e.__id:ki(e)}if("string"==typeof e)try{const t=Ai(e);if(t&&"object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);if(1===e.length&&"__id"===e[0])return t.__id}}catch{}return e}(s);return Vi(t,e,i)}if(1===a.length){const e=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const i=Object.keys(e);if(1===i.length&&i[0]===t)return e[t]}if("string"==typeof e)try{const i=Ai(e);if(i&&"object"==typeof i&&!Array.isArray(i)){const e=Object.keys(i);if(1===e.length&&e[0]===t)return i[t]}}catch{}return e}(s,a[0]);return Vi(e,o[a[0]],i)}return"object"!=typeof s||null===s||Array.isArray(s)?Vi(s,r,i):Vi(ki(s),r,i)}class Zi{constructor(e,t,i,n,s){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.projectFields=n,this.identityReference=s,this.refId=Nt()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this.identityReference?.squidDocId??this._squidDocId}get data(){return vi(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=Qe(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=Gi(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`});return this.projectFields?this.applyProjection(e):e}get hasData(){return this.dataManager.hasSufficientData(this.squidDocId,this.projectFields)}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 Qe(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,at.map)(e=>(Qe(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:Gi(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:vi(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},s={type:"update",squidDocIdObj:Gi(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(s,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async upsert(e,t){const i=Gi(this.squidDocId),n=i.integrationId;let s=Ai(i.docId);if(s[$i]&&(s={}),n===_e&&s.__id)try{const e=Ai(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...s}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:Gi(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)}applyProjection(e){const t={},i=Qe(this.projectFields,"applyProjection called without projectFields"),{integrationId:n}=Gi(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const s=n===_e?"__id":"__docId__";if(s in e){const i=e[s];if("string"==typeof i&&i.startsWith("{"))try{const e=Ai(i);if("object"==typeof e&&null!==e)for(const[i,n]of Object.entries(e))i in t||(t[i]=n)}catch{}}for(const n of i)if(n.includes(".")){const i=fi(e,n);void 0!==i&&mi(t,n,i)}else n in e&&(t[n]=e[n]);return t}hasSquidPlaceholderId(){const e=Ai(this.squidDocId);if("object"==typeof e&&e.docId){const t=Ai(e.docId);if("object"==typeof t&&Object.keys(t).includes($i))return!0}return!1}}class en{constructor(e,t={}){this.internalStateObserver=new at.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new at.BehaviorSubject(!1),this.snapshotSubject=new at.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,Ue(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,at.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,at.filter)(e=>null!==e),(0,at.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,at.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||bi(e)&&bi(t))return 0;if(bi(e))return-1;if(bi(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:s}of i){const i=Mi(fi(e,n),fi(t,n));if(0!==i)return s?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:fi(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,at.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:fi(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,at.firstValueFrom)((0,at.race)(this.isDestroyed.pipe((0,at.filter)(Boolean),(0,at.map)(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe((0,at.filter)(e=>null!==e),(0,at.take)(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[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)}}class tn{constructor(e,t,i,n,s){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n,this.mutationSender=s}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=Gi(e),s=Ai(n),r=this.get(t,i);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new rn(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService,this.mutationSender)}}class nn{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)}docId(e){return this.eq(qe,e)}docIds(e){return this.in(qe,e)}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 sn{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return(0,at.firstValueFrom)(this.snapshots(!1).pipe((0,at.defaultIfEmpty)([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(Rt(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new sn(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}projectFields(e){const t=this.queryBuilder.projectFields(e);return new sn(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new en(this,e)}}class rn extends nn{constructor(e,t,i,n,s,r,o,a){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,this.documentReferenceFactory=s,this.queryBuilderFactory=r,this.documentIdentityService=o,this.mutationSender=a,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return Ci(this.build())}where(e,t,i){if(Ue(je.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&e!==qe&&!this.query.projectFields.includes(e))throw new Error(`Cannot filter by field '${e}' that is not included in projectFields.`);if("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;Ue(function(e){return"number"==typeof e}(t=e),()=>Ge("Limit needs to be a number","Not a number",t)),-1!==e&&(Ue(e>0,"query limit has to be greater than 0"),Ue(Math.floor(e)===e,"query limit has to be an integer"),Ue(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 Ue(Si(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};if(function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,s,r;Ue((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"),Ue((s=t.asc,r="boolean",Array.isArray(s)?s.every(e=>typeof e===r):typeof s===r),"Asc needs to be boolean")}(i),Ue(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.projectFields&&e!==qe&&!this.query.projectFields.includes(e))throw new Error(`Cannot sort by field '${e}' that is not included in projectFields.`);return this.query.sortOrder.push(i),this}projectFields(e){if(0===e.length&&"built_in_db"!==this.integrationId)throw new Error(`Empty projectFields is only allowed for built_in_db integration. For '${this.integrationId}', you must specify at least one field to project.`);if(this.query.projectFields)for(const t of e)if(!this.query.projectFields.includes(t))throw new Error(`Cannot project field '${t}' that is not in the existing projection. Subsequent projectFields calls must be subsets of the previous projection.`);const t=e;for(const e of this.query.sortOrder)if(e.fieldName!==qe&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(zi(e)){if(e.fieldName!==qe&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else if(Ji(e));else for(const i of e.fields)if(i.fieldName!==qe&&!t.includes(i.fieldName))throw new Error(`Cannot set projectFields without including filter field '${i.fieldName}'.`);const i=this.clone();return i.query.projectFields=[...e],i}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return(0,at.firstValueFrom)(this.snapshots(!1).pipe((0,at.defaultIfEmpty)([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new at.BehaviorSubject([]);const t=this.build(),i=t.projectFields;return this.querySubscriptionManager.processQuery(t,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(Rt(e=>e.map(e=>{Ue(1===Object.keys(e).length);const t=e[this.collectionName],n=Hi(Qe(t).__docId__,this.collectionName,this.integrationId),s=this.querySubscriptionManager.detachedRecords.delete(e),r=this.documentReferenceFactory.create(n,this.queryBuilderFactory,i,s);return s&&r.setInMemoryData(t),r})))}changes(){let e,t=new Set;return this.snapshots().pipe((0,at.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,at.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)}),at.NEVER)),(0,at.startWith)({}))),Rt(([i])=>{let n=[];const s=[],r=[];if(e){for(const r of i){const i=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){s.push(r);const n=e[i];delete e[i],t.delete(n)}else n.push(r)}for(const e of t)r.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 on(n,s,r)}))}async delete(){return this.validateQueryDeleteModifiers(),this.containsEmptyInCondition?{deletedCount:0}:(Ue(this.mutationSender,"Query delete is not available on this query builder."),this.mutationSender.deleteQuery(this.build()))}dereference(){return new sn(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new rn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService,this.mutationSender);return e.query=vi(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){if(!e.length)return this;if(this.query.projectFields)for(const t of e)if(t.fieldName!==qe&&!this.query.projectFields.includes(t.fieldName))throw new Error(`Cannot filter by field '${t.fieldName}' that is not included in projectFields.`);return this.query.conditions.push({fields:e}),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 en(this,e)}validateQueryDeleteModifiers(){Ue(0===this.query.sortOrder.length&&-1===this.query.limit&&!this.query.limitBy,"query.delete() does not currently support sortBy, limit, or limitBy.")}mergeConditions(){const e=[],t=Ei(this.query.conditions.filter(zi)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=Ei(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)=>Mi(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!zi(e)),...e]}}class on{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class an extends nn{constructor(e,t,i,n,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=s,this.rootAlias=r,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}projectFields(e){throw new Error("projectFields is not yet supported for join queries")}join(e,t,i,n){const s=n?.leftAlias??this.latestAlias,r={...i,leftAlias:s,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new an(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:r},this.queryBuilder)}snapshot(){return(0,at.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new at.BehaviorSubject([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,vi(this.joins),vi(this.joinConditions),e,!1).pipe(Rt(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,s=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,r=n?Hi(n.__docId__,e,s):void 0;t[i]=r?this.documentReferenceFactory.create(r,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new ln(this)}dereference(){return new cn(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new an(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,vi(this.leftToRight),vi(this.joins),vi(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 en(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class cn{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return(0,at.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(Rt(e=>e.map(e=>function(e,t){const i={},n=Object.keys(e);for(const s of n){const n=e[s];i[s]=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 cn(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 en(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class un{constructor(e){this.groupedJoin=e}snapshot(){return(0,at.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(Rt(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 un(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 en(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 ln{constructor(e){this.joinQueryBuilder=e}snapshot(){return(0,at.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(Rt(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new un(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ln(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 en(this,e)}groupData(e,t){const i=Ei(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 s={[t]:n};for(const t of i)s[t]=this.groupData(e,t);return s})}}class dn{constructor(e,t,i,n,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,this.querySubscriptionManager=s,this.dataManager=r,this.refId=Nt()}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!==_e)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={[$i]:Nt()};else e=e&&"string"!=typeof e?{__id:ki(e)}:{__id:e||Nt()};const t=Hi(ki(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).upsert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof Zi?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new an(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new hn(...e)}}class hn{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,at.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 hn(...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 en(this,e)}or(e,...t){return(0,at.combineLatest)([...t]).pipe((0,at.map)(t=>{const i=new Set,n=t.flat(),s=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),s.push(e));return s.sort((t,i)=>{for(const{fieldName:n,asc:s}of e){const e=fi(this.extractData(t),n),r=fi(this.extractData(i),n);if(!Vi(e,r,"=="))return Vi(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class pn{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 dn(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class gn{constructor(e,t,i){this.clientIdService=e,this.socketManager=t,this.runtimeOptions=i,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 fn=i(150);const yn={"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=>Sn(e,t)),">=:not in":(e,t)=>t.every(t=>bn(e,t)),"<:not in":(e,t)=>t.every(t=>In(e,t)),"<=:not in":(e,t)=>t.every(t=>mn(e,t)),">:>":(e,t)=>Sn(e,t),">=:>":(e,t)=>bn(e,t),"in:>":(e,t)=>e.every(e=>bn(e,t)),">:>=":(e,t)=>Sn(e,t),">=:>=":(e,t)=>Sn(e,t),"in:>=":(e,t)=>e.every(e=>Sn(e,t)),"<:<":(e,t)=>In(e,t),"<=:<":(e,t)=>mn(e,t),"in:<":(e,t)=>e.every(e=>mn(e,t)),"<:<=":(e,t)=>In(e,t),"<=:<=":(e,t)=>In(e,t),"in:<=":(e,t)=>e.every(e=>In(e,t)),"like:like":(e,t)=>wn(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>wn(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>wn(e,t)&&_n(t),"like_cs:like_cs":(e,t)=>wn(e,t),"like:not like":(e,t)=>!vn(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!vn(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!vn(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!vn(e,t),"not like:like":(e,t)=>En(e,t),"not like_cs:like":(e,t)=>En(e,t),"not like:like_cs":(e,t)=>En(e,t),"not like_cs:like_cs":(e,t)=>En(e,t),"not like:not like":(e,t)=>wn(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>wn(t,e)&&_n(e),"not like:not like_cs":(e,t)=>wn(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>wn(t,e),"in:like":(e,t)=>e.every(e=>Vi(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Vi(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Vi(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Vi(t,e,"not like_cs")),"like:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&_n(e)&&t.includes(e),"like_cs:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&t.includes(e),"not like:in":(e,t)=>e.length>0&&Mn(e)||Tn(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Mn(e)||Tn(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Mn(t)||Tn(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Mn(t)||Tn(t)&&e.includes(""),"not in:not like":(e,t)=>!t.includes("%")&&!t.includes("_")&&_n(t)&&e.includes(t),"not in:not like_cs":(e,t)=>!t.includes("%")&&!t.includes("_")&&e.includes(t),"like:not in":(e,t)=>t.every(t=>Vi(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Vi(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Vi(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Vi(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)=>t.every(t=>e.includes(t)),"array_not_includes:array_not_includes":(e,t)=>t.every(t=>e.includes(t)),"array_includes_all:array_includes_some":(e,t)=>e.some(e=>t.includes(e)),"array_includes_some:array_includes_all":(e,t)=>e.every(e=>t.every(t=>e===t))};function mn(e,t){return bi(e)?!bi(t):!bi(t)&&e<t}function In(e,t){return bi(e)||!bi(t)&&e<=t}function bn(e,t){return mn(t,e)}function Sn(e,t){return In(t,e)}function wn(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return Mn(t.substring(n));const s=e[i],r=t[n];return"%"===s&&"%"===r?wn(e,t,i+1,n+1)||wn(e,t,i+1,n):"%"!==s&&("%"===r?wn(e,t,i,n+1)||wn(e,t,i+1,n):(s===r||"_"===r)&&wn(e,t,i+1,n+1))}function vn(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return Mn(t.substring(n));if(n>=t.length)return Mn(e.substring(i));const s=i<e.length?e[i]:"",r=n<t.length?t[n]:"";return"%"===s&&"%"===r?vn(e,t,i+1,n+1)||vn(e,t,i,n+1)||vn(e,t,i+1,n):"%"===s||"%"===r?vn(e,t,i,n+1)||vn(e,t,i+1,n):(s===r||"_"===s||"_"===r)&&vn(e,t,i+1,n+1)}function _n(e){return e===e.toLowerCase()&&e===e.toUpperCase()}function Mn(e){return e.split("").every(e=>"%"===e)}function En(e,t){return e.length>0&&Mn(e)||t.length>0&&Mn(t)||Tn(e)&&0===t.length}function Tn(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}function kn(e,t){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(const n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Si(e[n],t[n]))return!1}return!0}function On(e,t){return t.every(t=>{const i=Object.keys(t).sort();if(i.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(i[t]!==e[t])return!1;return!0})}class An{constructor(e){this.query=e,this.query=e;const t=this.query.conditions.filter(zi),i=this.query.conditions.filter(Ji),n=i.flatMap(e=>function(e){if("=="!==e.operator&&"in"!==e.operator)return[];if(0===e.docIds.length)return[];const t=[],i=e.docIds[0];for(const n of Object.keys(i)){const s=i[n];e.docIds.every(e=>Object.prototype.hasOwnProperty.call(e,n)&&Si(e[n],s))&&t.push({fieldName:n,operator:"==",value:s})}return t}(e));this.exactSimpleConditions=this.parseConditions(t),this.exactDocIdConditions=i,this.subqueryConditions=this.parseConditions([...t,...n])}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}get projectFields(){return this.query.projectFields}sortedBy(e){return!e.find((e,t)=>!Si(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.subqueryConditions.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;for(const t of e.conditions.filter(Ji))if(!this.childImpliesParentDocIdCondition(t))return!1;const t=e.conditions.filter(zi),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return i&&n&&s&&r}childImpliesParentDocIdCondition(e){const t=e.docIds;if(0===t.length)return!1;const i="=="===e.operator||"in"===e.operator,n=Object.keys(t[0]).sort(),s=[];for(const e of this.query.conditions)Ji(e)&&s.push(...e.docIds);if(!On(n,t)||!On(n,s))return!1;const r=this.buildChildEffectiveTupleSet();return i?void 0!==r.allowed&&r.allowed.every(e=>t.some(t=>kn(e,t))):void 0!==r.allowed?r.allowed.every(e=>!t.some(t=>kn(e,t))):t.every(e=>r.excluded.some(t=>kn(e,t)))}buildChildEffectiveTupleSet(){let e;const t=[];for(const i of this.query.conditions)if(Ji(i))if("=="===i.operator||"in"===i.operator)e=void 0===e?[...i.docIds]:e.filter(e=>i.docIds.some(t=>kn(e,t)));else for(const e of i.docIds)t.some(t=>kn(t,e))||t.push(e);return void 0!==e&&t.length>0&&(e=e.filter(e=>!t.some(t=>kn(e,t)))),{allowed:e,excluded:t}}isProjectFieldsSubset(e,t){if(!t)return!0;if(!e)return!1;const i=new Set(t);return e.every(e=>i.has(e))}getConditionsFor(...e){return this.subqueryConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.subqueryConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.exactSimpleConditions){const i=t.fieldName,n=t.operator;if(i===qe){const i=t.value;if("in"===n||"not in"===n){const t=(Array.isArray(i)?i:[i]).some(t=>Xi(t,e,"==",fi));if(!("in"===n?t:!t))return!1;continue}if(!Xi(i,e,n,fi))return!1;continue}const s=fi(e,i);if("in"===n){if(t.value.includes(s))continue;return!1}if("not in"!==n){if(!Vi(t.value,s,n))return!1}else if(t.value.includes(s))return!1}for(const t of this.exactDocIdConditions)if(!Yi(t,e,fi))return!1;return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=yn[`${i}:${s}`];return!!o&&o(n,r)}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}}function Cn(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Dn(e,t){let i=e;for(const e of t.split(".")){if(!Cn(i))return;i=i[e]}return i}function Rn(e,t,i){const n=t.split(".");let s=e;for(const[e,r]of n.entries()){if(e===n.length-1)return void(s[r]=i);const o=s[r];if(null!=o&&!Cn(o))throw new Error(`Cannot set path ${t}, ${r} is not an object`);const a=Cn(o)?{...o}:{};s[r]=a,s=a}}function Nn(e,t){const i=t.split(".");let n=e;for(const[e,t]of i.entries()){if(e===i.length-1)return void delete n[t];const s=n[t];if(!Cn(s))return;const r={...s};n[t]=r,n=r}}function qn(e,t){switch(t.type){case"applyNumericFn":return function(e,t){if("increment"===t.fn)return"number"==typeof e?e+t.value:t.value;throw new Error("Unknown numeric function: "+JSON.stringify(t))}(e,t);case"applyStringFn":return function(e,t){const i="string"==typeof e?e:null;switch(t.fn){case"trim":return null===i?null:i.trim();case"extendString":return null===i?t.value:i+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?vi(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Fn(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function jn(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(Ue("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const i=vi(e);t=vi(t);for(const[e]of Fn(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 Fn(t))i.properties[e]=Pn([...i.properties[e]||[],...n]);return i}(e,t);const i=vi(e);for(const[e,n]of Fn(t)){const t=n;for(const n of t){const t=i.properties,s=qn(Dn(t,e),n);void 0===s?Nn(t,e):Rn(t,e,s)}}return i}function Pn(e){let t=0;for(;t+1<e.length;){const i=xn(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function xn(e,t){if("removeProperty"===t.type||"update"===t.type)return t;if("applyNumericFn"===t.type){if(Ue("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type)return Ue("increment"===e.fn,"Unrecognized applyNumericFn"),{type:"applyNumericFn",fn:"increment",value:e.value+t.value};if("update"===e.type){if("number"!=typeof e.value)throw new Error("Cannot increment a value that is not a number");return{type:"update",value:e.value+t.value}}return t}if("extendString"===t.fn){if("update"===e.type){if("string"!=typeof e.value)throw new Error("Cannot extend a value that is not a string");return{type:"update",value:e.value+t.value}}return"applyStringFn"===e.type&&"extendString"===e.fn?{type:"applyStringFn",fn:"extendString",value:e.value+t.value}:t}return null}function Bn(e,t){if(!e)return;const i={...e},n=Fn(t);for(const[e,t]of n){const n=t;for(const t of n){const n=qn(Dn(i,e),t);void 0===n?Nn(i,e):Rn(i,e,n)}}return i}function Ln(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)=>Qe(jn(e,t),"Merge result cannot be null"));i.push(n)}return i}const Un="dataManager_runInTransaction";var Qn;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Qn||(Qn={}));class $n{constructor(e,t,i,n,s,r,o,a,c){this.documentStore=e,this.mutationSender=t,this.socketManager=i,this.querySubscriptionManager=n,this.queryBuilderFactory=s,this.lockManager=r,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 at.Subject,this.outgoingMutationsEmpty=new at.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)}hasSufficientData(e,t){return this.documentStore.hasSufficientData(e,t)}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 executeDetachedQuery(e){const t=this.currentTransactionId,i={query:e,clientRequestId:Nt(),subscribe:!1},n=await this.querySender.sendQueryDirect(i);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(n.docs,e)}async reRunQueryThroughNormalPipeline(e){await(0,at.firstValueFrom)(this.outgoingMutationsEmpty.pipe((0,at.filter)(Boolean),(0,at.take)(1)));const t={query:e,clientRequestId:Nt(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}predictUpdate(e,t){try{return Bn(e,t)}catch{return e}}applyPendingMutationsToQueryResult(e,t){const i=new An(t),n=new Map;for(const i of e){const e=Hi(i.__docId__,t.collectionName,t.integrationId);n.set(e,i)}for(const[e,s]of this.pendingOutgoingMutations){const r=Gi(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of s){const s=n.get(e);if("delete"===t.type)n.delete(e);else if("update"===t.type){if(s){const r=this.predictUpdate(s,t);r&&i.documentMatchesQuery(r)?n.set(e,r):n.delete(e)}}else if("insert"===t.type){const s={...t.properties,__docId__:r.docId};i.documentMatchesQuery(s)&&n.set(e,s)}}}const s=Array.from(n.values()),{sortOrder:r}=t;s.sort((e,t)=>{for(const{fieldName:i,asc:n}of r){const s=Mi(fi(e,i),fi(t,i));if(0!==s)return n?s:-s}return 0});const o=t.limit<0?2e3:t.limit;return s.slice(0,o)}async runInTransaction(e,t){if(t)return Ue(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(Un)?this.lockManager.lockSync(Un):await this.lockManager.lock(Un);let i=Gn;const n=()=>i!==Gn;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=Nt();try{r=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(Un)}catch(e){i=n()?i:e}}n()&&s(i)})}async applyOutgoingMutation(e,t){const i=Hi(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(Un)||(await this.lockManager.lock(Un),this.lockManager.release(Un)),this.knownDirtyDocs.delete(i);const n=this.removeInternalProperties(e),s=this.pendingOutgoingMutations.get(i)?.slice(-1)[0],r=s&&!s.sentToServer?Qe(Ln([s.mutation,n])[0],"Failed to reduce mutations"):void 0;if("update"===e.type&&Bn(this.documentStore.getDocumentOrUndefined(i),e),s&&r)s.mutation=r,this.outgoingMutationsEmpty.next(!1);else{const e={mutation:n,sentToServer:!1},t=this.pendingOutgoingMutations.get(i)||[];t.push(e),this.pendingOutgoingMutations.set(i,t),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?t&&this.predictUpdate(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 Ue(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(Un);try{this.currentTransactionId=Nt();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(Un)}}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,at.filter)(e=>"mutations"===e.type),Rt(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,at.filter)(Boolean),(0,at.take)(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,at.filter)(Boolean),(0,at.take)(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t={},i=[];for(const n of e){if(!this.querySubscriptionManager.hasOngoingQuery(n.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(n.clientRequestId),s=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(n.clientRequestId);s&&r?i.push({squidDocId:n.squidDocId,item:{properties:n.doc,timestamp:n.mutationTimestamp,clientRequestId:n.clientRequestId,projectFields:e.projectFields}}):t[n.squidDocId]={properties:n.doc,timestamp:n.mutationTimestamp}}Object.keys(t).length>0&&this.applyIncomingUpdates(t),i.length>0&&this.runInTransactionSync(()=>{this.applyProjectedUpdates(i)})}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId);if(null!==t.projectFields&&void 0!==t.projectFields){const i=[];for(const n of e.docs){const s=Hi(n.__docId__,t.collectionName,t.integrationId);i.push({squidDocId:s,item:{properties:n,timestamp:n.__ts__,clientRequestId:e.clientRequestId,projectFields:t.projectFields}})}this.runInTransactionSync(()=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyProjectedUpdates(i)})}else{const i={};for(const n of e.docs){const e=Hi(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)})}}applyIncomingUpdates(e,t){let i=!1;const n=new Set,s=new Set;for(const[t,r]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>r.timestamp?i=!0:o&&o.timestamp>r.timestamp?(r.properties&&this.documentStore.adoptMissingFields(t,r.properties),s.add(t)):(this.pendingIncomingUpdates.set(t,r),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),i}applyProjectedUpdates(e){for(const{squidDocId:t,item:i}of e){const e=Qe(i.clientRequestId,"clientRequestId required for projected updates"),n=this.pendingOutgoingMutations.get(t);if(n&&n.length)continue;const s=this.docIdToServerTimestamp.get(t);s&&s.timestamp>i.timestamp?(this.querySubscriptionManager.addDocToQuery(t,e),this.batchClientRequestIds.add(e)):(this.acknowledgeDocument(t,i.timestamp,!i.properties),this.docIdToLocalTimestamp.set(t,i.timestamp),i.properties?(this.documentStore.saveProjectedDocument(t,i.properties,i.projectFields),this.querySubscriptionManager.addDocToQuery(t,e)):this.querySubscriptionManager.removeDocFromQuery(t,e),this.batchClientRequestIds.add(e))}}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||ki({...t,__ts__:void 0})!==ki(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)}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await fn.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(),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:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),s.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=Hi(e.mutation.squidDocIdObj),i=Qe(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}=Gi(t);this.setExpiration(t,!0);try{const i=e.includes($i)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(Qe(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),this.pendingIncomingUpdates.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=Hi(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=Gi(n))})}),Object.entries(e).forEach(([e,t])=>{Ii(this.pendingOutgoingMutations,e,t),Ii(this.docIdToLocalTimestamp,e,t),Ii(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 Gn=Symbol("undefined");class Hn{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new at.BehaviorSubject(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe((0,at.filter)(Boolean),Rt(()=>{}))}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 Vn{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,at.filter)(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,at.filter)(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{if(e)return;const t=Object.keys(this.ongoingLocks);t.length>0&&(console.warn(`DistributedLockManager: WebSocket disconnected, releasing ${t.length} lock(s)`),Bi.debug(`DistributedLockManager: released lock(s): [${t.join(", ")}]`)),this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.lockId];t?.release()})}async lock(e,t){"number"==typeof t&&(t={acquisitionTimeoutMillis:t});const i=t?.acquisitionTimeoutMillis??2e3,n=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),Ue(await(0,at.firstValueFrom)((0,at.race)((0,at.timer)(this.lockWaitForConnectionThreshold).pipe(Rt(()=>!1)),this.socketManager.observeConnectionReady().pipe((0,at.filter)(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const s=Nt(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:i,maxHoldTimeMillis:n,clientRequestId:s}};this.socketManager.postMessage(r);const o=await(0,at.firstValueFrom)((0,at.race)((0,at.timer)(i+4e3).pipe((0,at.take)(1),Rt(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:s}}))),this.acquireLockMessagesFromServer.pipe((0,at.filter)(e=>e.payload.clientRequestId===s)))),a=o.payload.lockId;Ue(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),Ue(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new Kn(a,e,s,this.ongoingLocks,this.socketManager);return this.ongoingLocks[a]=c,c}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class Kn{constructor(e,t,i,n,s){this.lockId=e,this.resourceId=t,this.clientRequestId=i,this.ongoingLocks=n,this.socketManager=s,this.released=!1,this.onReleaseSubject=new at.ReplaySubject(1)}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}},t=this.socketManager.sendMessage(e),i=await(0,at.firstValueFrom)((0,at.race)((0,at.from)(t.then(Wn,Wn)),this.socketManager.observeConnectionReady().pipe((0,at.filter)(e=>!e),Rt(()=>!1))));if(this.onReleaseSubject.next(),!i)return t.catch(()=>{}),void this.onReleaseSubject.complete();try{await t}finally{this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}function Wn(){return!0}class zn{constructor(e,t){this.documentStore=e,this.destructManager=t,this.changeNotifier=new at.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 Jn{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t,i,n=!1){if(i||n)return new Zi(e,Qe(this.dataManager,"dataManager not found"),t,i,n?this.create(e,t):void 0);let s=this.documents.get(e);if(s)return s;s=new Zi(e,Qe(this.dataManager,"dataManager not found"),t);const{integrationId:r,collectionName:o}=Gi(e);this.documents.set(e,s);const a=this.getCollectionKey(r,o),c=this.documentsForCollection.get(a)||[];return this.documentsForCollection.set(a,c.concat(s)),s}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=Gi(e),n=Gi(t);Ii(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class Yn{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,i){const n=this.squidDocIdToDoc.get(e);if(n){const i=this.mergeDocuments(n,t),s=this.removeInternalProperties(i);this.squidDocIdToDoc.set(e,s)}else{const i=this.removeInternalProperties(t);this.squidDocIdToDoc.set(e,i)}if(i?.length){const t=this.squidDocIdToProjectedFields.get(e);if(void 0!==t)for(const e of i)t.add(e);else n||this.squidDocIdToProjectedFields.set(e,new Set(i))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const i=vi(e);for(const e of Object.keys(t)){const n=t[e],s=i[e];null===n||"object"!=typeof n||Array.isArray(n)||null===s||"object"!=typeof s||Array.isArray(s)?i[e]=n:i[e]=this.mergeDocuments(s,n)}return i}adoptMissingFields(e,t){const i=this.squidDocIdToDoc.get(e);if(!i)return;const n=Object.keys(t).filter(e=>"__ts__"!==e&&!(e in i));if(!n.length)return;const s=vi(i);for(const e of n)s[e]=t[e];this.squidDocIdToDoc.set(e,s);const r=this.squidDocIdToProjectedFields.get(e);if(r)for(const e of n)r.add(e)}deleteDocument(e){this.squidDocIdToDoc.delete(e),this.squidDocIdToProjectedFields.delete(e)}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=vi(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}hasSufficientData(e,t){if(!this.squidDocIdToDoc.has(e))return!1;const i=this.squidDocIdToProjectedFields.get(e);return void 0===i||!!t?.length&&t.every(e=>i.has(e))}group(e,t){return Object.values(Ei(e,e=>ki(t.map(t=>fi(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(Be),{sortOrder:n,limitBy:s}=t,r=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;let a;if(s){const{limit:e,fields:t,reverseSort:i}=s,n=this.group(r,t);let c;c=i?n.map(t=>t.slice(-e)):n.map(t=>t.slice(0,e)),a=c.flat().slice(0,o)}else a=r.slice(0,o);return null!==t.projectFields&&void 0!==t.projectFields&&(a=a.map(e=>this.projectDocument(e,t.projectFields))),a}projectDocument(e,t){const i={};"__id"in e&&(i.__id=e.__id),"__docId__"in e&&(i.__docId__=e.__docId__);for(const n of t)if(n.includes(".")){const t=fi(e,n);void 0!==t&&mi(i,n,t)}else n in e&&(i[n]=e[n]);return i}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;Ii(this.squidDocIdToDoc,e,t),Ii(this.squidDocIdToProjectedFields,e,t);const n=Gi(t),s=Ai(n.docId);this.saveDocument(t,{...i,...s,__docId__:n.docId})}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:s}of i){const i=Mi(fi(e,n),fi(t,n));if(0!==i)return s?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class Xn{constructor(e){this.rpcManager=e}async emit(e){const t={event:e};await this.rpcManager.post("events/emit",t)}}class Zn{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 es{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 ts{constructor(e,t,i,n,s){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.ownedJobs=new Set,n.onDestruct(async()=>{this.stopKeepAlive();const e=[...this.ownedJobs];this.ownedJobs.clear(),await Promise.all(e.map(e=>this.resolveJob(e,"failed",void 0,"Client shut down").catch(()=>{})))}),s.isPassiveMode||this.clientIdService.observeClientId().pipe((0,at.distinctUntilChanged)(),(0,at.skip)(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Bi.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(t=>{const i=this.listeners[e];i&&(i.error(t),delete this.listeners[e])})})}async startJob(e){await this.rpcManager.post("job/startJob",{jobId:e}),this.ownedJobs.add(e),this.ensureKeepAlive()}async completeJob(e,t){await this.resolveJob(e,"completed",t)}async failJob(e,t){await this.resolveJob(e,"failed",void 0,t)}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 at.ReplaySubject(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(i=>{t.error(i),delete this.listeners[e]}),(0,at.firstValueFrom)(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe((0,at.filter)(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,i=t.id,n=this.listeners[i];if(n){if("completed"===t.status)n.next(t.result);else if("failed"===t.status){const e=Object.assign(new Error(t.error||"Job failed"),{errorType:t.errorType});n.error(e)}else console.error("Unexpected job status:",t.status,"for jobId:",i);delete this.listeners[i]}}))}async resolveJob(e,t,i,n){try{await this.rpcManager.post("job/resolveJob",{jobId:e,status:t,result:i,error:n})}finally{this.ownedJobs.delete(e),this.ownedJobs.size||this.stopKeepAlive()}}ensureKeepAlive(){void 0===this.keepAliveHandle&&(this.keepAliveHandle=setInterval(()=>{if(!this.ownedJobs.size)return void this.stopKeepAlive();const e={jobIds:[...this.ownedJobs]};this.rpcManager.post("job/keepAlive",e).catch(e=>Bi.debug("Job keep-alive failed:",e))},15e3))}stopKeepAlive(){void 0!==this.keepAliveHandle&&(clearInterval(this.keepAliveHandle),this.keepAliveHandle=void 0)}}class is{constructor(e,t,i){this.graphId=e,this.rpcManager=t,this.jobClient=i}async invoke(e={}){const t=Nt();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),await this.jobClient.awaitJob(t)}async invokeAsync(e={}){const t=Nt();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),t}async resume(e,t){const i=Nt();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),await this.jobClient.awaitJob(i)}async resumeAsync(e,t){const i=Nt();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),i}async getState(e){return this.rpcManager.post("langgraph/getState",{graphId:this.graphId,threadId:e})}async deleteThread(e){await this.rpcManager.post("langgraph/deleteThread",{graphId:this.graphId,threadId:e})}}class ns{constructor(e,t){this.rpcManager=e,this.jobClient=t}graph(e){return new is(e,this.rpcManager,this.jobClient)}}const ss="squid_mgmt_";function rs(e="n_"){return`${e}${Bt(10).toLowerCase()}`}const os=e=>e();class as extends Error{constructor(e,t,i,n,s){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=s}}const cs="1.0.496";async function us(e){return gs({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage,abortSignal:e.abortSignal})}async function ls(e){return gs({...e,method:"GET",files:[],filesFieldName:""})}async function ds(e){return gs({...e,method:"PUT"})}async function hs(e){return gs({...e,method:"PATCH"})}async function ps(e){return gs({...e,method:"DELETE",files:[],filesFieldName:""})}async function gs(e){const t=await async function({headers:e,files:t,filesFieldName:i,message:n,url:s,extractErrorMessage:r,method:o,abortSignal:a}){const c=new Headers(e);c.append(Gt.TRACE_ID,rs("c_")),c.append(Gt.CLIENT_VERSION,cs);const u={method:o,headers:c,body:void 0,signal:a};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",Oi(n)),u.body=e}else void 0!==n&&(c.append("Content-Type","application/json"),u.body=Oi(n));else"DELETE"===o&&void 0!==n&&(c.append("Content-Type","application/json"),u.body=Oi(n));try{const e=await fetch(s,u),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=fs(i);if(!r)throw new as(i,e.status,s,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new as(o,e.status,s,t,n)}const i=await e.text();return Bi.debug(`received response from url ${s}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Bi.debug(`Unable to perform fetch request to url: ${s}`,e),e}}(e);return t.body=fs(t.body),t}function fs(e){if(e){try{return Ai(e)}catch{}return e}}class ys{constructor(e){Ue(e.apiKey.startsWith(ss),`Invalid management API key format. Key must start with '${ss}'`),this.apiKey=e.apiKey,this.consoleRegion=e.consoleRegion}async createOrganization(e){return this.callApi("POST","organizations",e)}async createApplication(e){return this.callApi("POST","applications",e)}async deleteApplication(e){await this.callApi("DELETE",`applications/${e}`)}async renameOrganization(e){await this.callApi("PATCH",`organizations/${e.organizationId}`,{name:e.name})}async renameApplication(e){await this.callApi("PATCH",`applications/${e.appId}`,{name:e.name})}async callApi(e,t,i){const n=r(this.consoleRegion,"console",`openapi/iac/management/${t}`),s={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await us({url:n,headers:s,message:i,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await hs({url:n,headers:s,message:i,extractErrorMessage:!0})).body:(await ps({url:n,headers:s,message:i,extractErrorMessage:!0})).body}}class ms{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=Ln(e),n=i.map(e=>`sendMutation_${Hi(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 Bi.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}async deleteQuery(e){const t=`deleteQuery_${e.integrationId}_${e.collectionName}`;await this.lockManager.lock(t),await this.querySender.waitForAllQueriesToFinish();try{const t={query:e};return await this.rpcManager.post("mutation/deleteQuery",t)}catch(t){throw Bi.debug("Error while deleting query results",{error:t,query:JSON.stringify(e,null,2)}),t}finally{this.lockManager.release(t)}}}class Is{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class bs{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,at.filter)(e=>"userNotification"===e.type),(0,at.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 Ss={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class ws{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!vs.test(e)||e.length>=_s);Ue(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},s=this.rpcManager.post("/observability/metrics",{metrics:[n]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==s),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(s)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...Ss,...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,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const s=t-e;let r=t-Math.floor(s/i)*i;return r>e&&(r-=i),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const s=t-e;let r=e+Math.floor(s/i)*i;return r>=t&&(r-=i),r}(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],s=a[n]?.[0]||"";i.push(s)}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 s=e.groupByTags.indexOf(i);if(!(s<0))for(let e=0;e<t.length;e++){const i=t[e],r=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===s||e===n.tagValues[t])&&r.delete(n.tagValues[s])}if(0!==r.size)for(const e of r){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[s]=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];Ue(e>=r,()=>`Invalid first point time: ${e}`),Ue(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:s,u=Array.isArray(e.fn)?e.fn.map(c):[s];for(let e=r;e<=o;e+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(Ue(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 vs=/^[a-zA-Z0-9_-]+$/,_s=1e3;async function Ms(e,t,i=500,n){const s=Date.now(),r=e.paginate({pageSize:i,subscribe:!1});let o=0,a=0,c=await r.waitForData();for(n?.({pageIndex:a,documentCount:c.data.length,totalLoaded:o+c.data.length});;){for(const e of c.data)o++,await t(e.data);if(!c.hasNext)break;c=await r.next(),a++,n?.({pageIndex:a,documentCount:c.data.length,totalLoaded:o+c.data.length})}return{count:o,time:Date.now()-s}}async function Es(e,t=500,i){const n=[],s=e.paginate({pageSize:t,subscribe:!1});let r=0,o=await s.waitForData();for(i?.({pageIndex:r,documentCount:o.data.length,totalLoaded:n.length+o.data.length});;){for(const e of o.data){const t=Gi(e.squidDocId),i=Ai(t.docId),s=t.integrationId===_e?i.__id:i;n.push(s)}if(!o.hasNext)break;o=await s.next(),r++,i?.({pageIndex:r,documentCount:o.data.length,totalLoaded:n.length+o.data.length})}return n}function Ts(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:s,integrationId:r}=i;let o=e.collection(s,r).query();return o=ks(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=ks(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:r}=i,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(n,r).query();l=ks(l,i),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),r&&o?u.grouped().dereference():r?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:i}=t,{collectionName:n,integrationId:s}=Os(i[0]),r=i.map(t=>Ts(e,t));return e.collection(n,s).or(...r)}(e,t)}}function ks(e,t){const{conditions:i,limit:n,sortOrder:s}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");if("docIds"in t)throw new Error("DocId conditions are not supported in query serialization.");const{fieldName:i,operator:n,value:s}=t;e.where(i,n,s)}e.limit(n);for(const{fieldName:t,asc:i}of s)e.sortBy(t,i);return e}function Os(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 Os(e.queries[0])}}class As{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 An(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[Hi(e.__docId__,i,t)])}}function Cs(e,t){return ut(function(i,n){var s=0;i.subscribe(Ct(n,function(i){return e.call(t,i,s++)&&n.next(i)}))})}class Ds{constructor(e,t,i){this.rpcManager=e,this.destructManager=t,this.webSocketConnectionReady$=i,this.safeToSendQueriesToServer=new at.BehaviorSubject(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new at.BehaviorSubject(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new at.Subject,i=(0,at.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.gateForCurrentBatch().subscribe(()=>{this.processQueryBatch()})},0),i)}gateForCurrentBatch(){return this.pendingQueryRequests.some(({queryRequest:e})=>e.subscribe)&&this.webSocketConnectionReady$?(0,at.combineLatest)([this.safeToSendQueriesToServer,this.webSocketConnectionReady$]).pipe(Cs(([e,t])=>e&&t),(0,at.take)(1),Rt(()=>!0)):this.safeToSendQueriesToServer.pipe(Cs(Boolean),(0,at.take)(1))}async sendQueryDirect(e){const t=await this.rpcManager.post("query/batchQueries",[e]),i=t.errors[e.clientRequestId];if(i)throw i;return t.results[e.clientRequestId]}async waitForAllQueriesToFinish(){return(0,at.firstValueFrom)(this.inflightQueriesCount.pipe(Cs(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,s=i.errors[e],r=i.results[e];s?n.error(s):n.next(r)}}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 Rs={d:(e,t)=>{for(var i in t)Rs.o(t,i)&&!Rs.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Ns(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 qs(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Fs(e,t);if(0===t.length)return Ns("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 s=e;for(let e=0;e<t.length-1&&void 0!==s;e++){const i=t[e];Ns(!Array.isArray(s)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),s=s[i],Ns(void 0===s||"object"==typeof s&&null!==s,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===s?"<null>":typeof s}'`)}const r=t[t.length-1];return Ns(!Array.isArray(s)||n(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===i?e:js(e,t,i)}(e,t.path,t.value);case"delete":return Fs(e,t.path);case"batch":return t.actions.reduce((e,t)=>qs(e,t),e)}}function Fs(e,t){Ns(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const s=t[n];if(i=i[s],void 0===i)return e;Ns("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:js(e,t,void 0)}function js(e,t,i){function n(e,i){Ns(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];Ns(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(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===i?n(r,o):r[o]=i,s}function Ps(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(...Ps(t,"as-is"));return"unique-and-sorted"===t?Ls(i):i}function xs(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 Bs(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 Ls(e){const t=Bs(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];n.length===r.length&&xs(n,r)&&(i[s]=void 0,e++)}}return i.filter(e=>void 0!==e)}const Us=(Qs={Observable:()=>at.Observable,Subject:()=>at.Subject},$s={},Rs.d($s,Qs),$s);var Qs,$s;const Gs=(Hs={filter:()=>Cs,map:()=>Rt},Vs={},Rs.d(Vs,Hs),Vs);var Hs,Vs;class Ks{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,s=t(n.value,i);if(s!==Ks.StopFillToken){this._setNodeValue(n,s,!1);for(let r=0;r<e.length;r++){const o=e[r];i.push(o);let a=n.children.get(o);if(s=t(null==a?void 0:a.value,i),s===Ks.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,s,!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[s,r]of t.children){if(n.push(s),!this._visitDfs(e,r,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 s=t.children.get(n);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,s)),t=s}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))}}Ks.StopFillToken=Symbol("Trie.StopFillToken");class Ws extends Us.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class zs{constructor(e){this.rootState=e,this.observersTrie=new Ks,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,Gs.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=qs(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Ps(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=Ls([...t,...i]),s=new Ks;for(const e of n)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),s=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new Ks;for(const e of t)null==n||n.set(e,!0);return new Us.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new Ws);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===i;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,Gs.filter)(({action:e})=>void 0===n||Ps(e,"as-is").some(e=>!n.get(e))),(0,Gs.map)(({action:t,value:i,oldValue:n})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const i=Ps(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=Bs(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++)xs(t[s],n)&&(i[s]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>xs(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.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 Js(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,s=e.length-1){if(s<n)return-1;const r=Math.trunc((n+s)/2);return 0===i(t,e[r])?r:i(t,e[r])>0?Js(e,t,i,r+1,s):Js(e,t,i,n,r-1)}function Ys(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==Js(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 Xs(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=Js(e,t,i);n>-1&&e.splice(n,1)}class Zs{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,i,n,s,r,o,a){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=s,this.querySender=r,this.socketManager=o,this.lockManager=a,this.onOrphanDocuments=new at.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new tr,this.queryResultsSubject=new at.Subject,this.detachedRecords=new Set,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientTooOld().subscribe(()=>{this.invalidateOngoingQueryRegistrations()}),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 Qe(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}=Gi(t),s=this.queryMappingManager.getMapping(i,n);return s?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,s]of Object.entries(e.conditional||{})){const e=Ai(i);let r;if(zi(e))if(e.fieldName===qe)r=Xi(e.value,t,e.operator,fi);else{const i=fi(t,e.fieldName)??null;r=Vi(e.value,i,e.operator)}else r=Ji(e)?Yi(e,t,fi):er(e,t);if(r)for(const e of s)n.set(e,(n.get(e)||0)+1)}for(const[t,s]of n.entries())s>=e.queriesMetadata[t].condCount&&i.push(t);return i}(s,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):[]),s=new Set([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.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[...s]}addDocToQuery(e,t){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)}removeDocFromQuery(e,t){const i=this.localDocumentToClientRequestIds.get(e);let n=!i;i&&(i.delete(t),i.size||(this.localDocumentToClientRequestIds.delete(e),n=!0));const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n&&this.documentStore.deleteDocument(e)}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,s=this.documentStore.sortAndLimitDocs(n,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(s,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=Qe(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case Qn.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+100?Qn.ENABLED:Qn.DISABLED;break;case Qn.DISABLED:break;case Qn.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=Qn.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(s)}for(const e of t){const t=this.collectAllObservables(e);Qe(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new An(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,s,r,o){s&&this.socketManager.notifyWebSocketIsNeeded();const a=Object.keys(i).length>0;return s||a||!this.detachedQueryExecutor||this.lockManager.canGetLock(Un)?(0,at.defer)(()=>{const a=this.createOngoingQueryGraph(e,t,i,n,s,!0,{},o);r&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new at.ReplaySubject(1);const c=a.allObservables.pipe((0,at.switchMap)(e=>(0,at.combineLatest)(e).pipe(Rt(e=>this.joinResults(e,n,a)))),Cs(()=>this.allOngoingQueriesGotInitialResult(a)),(0,at.startWith)(void 0),(0,at.pairwise)(),Cs(([e,t])=>!Si(e,t)),Rt(([,e])=>e),s?(0,at.tap)():(0,at.take)(1),(0,at.finalize)(()=>{a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a),a.allObservables?.complete()})),u=this.collectAllObservables(a);return a.allObservables.next(u),c}).pipe((0,at.share)()):(0,at.from)(this.detachedQueryExecutor(e)).pipe(Rt(e=>e.map(e=>{const i={[t]:e};return this.detachedRecords.add(i),i})))}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 An(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=Qe(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=Wi(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,at.finalize)(async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,at.firstValueFrom)((0,at.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Cs(e=>0===e)))),this.queryMappingManager.removeQuery(i),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)}),Cs(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,i,n,s,r,o={},a){if(o[t])return o[t];const c=r&&a?a:this.clientIdService.generateClientRequestId(),u=[],l={clientRequestId:c,activated:r,alias:t,query:e,subscribe:s,dataSubject:new at.BehaviorSubject(null),supportedQueries:u,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new at.BehaviorSubject(0),queryRegistered:new at.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:s?Qn.UNKNOWN:Qn.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(c,l),o[t]=l;for(const[e,r]of Object.entries(n)){const a=r.leftAlias;if(a!==t&&e!==t)continue;const c=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(i[c],c,i,n,s,!1,o);e.joinCondition=r,u.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(i[c],c,i,n,s,!1,o)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Cs(Boolean),Rt(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 s=n[i.alias].map(e=>({[i.alias]:e}));const r=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<r.length;e++){const i=r[e].alias;o.has(i)||(o.add(i),s=this.join(s,i,n[i],t[i]))}return s}join(e,t,i,n){if(!e.length)return e;const s=Object.keys(e[0]);if(!n||!s.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);r.has(t)||r.set(t,[]),Qe(r.get(t)).push(e)}),e.flatMap(e=>{const i=r.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=Qe(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){const i=Qe(t.joinCondition),n=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const s=Qe(t.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===t.alias),r=new Set(e.map(e=>e[i.left]??null));for(const e of s)e.query.conditions.filter(zi).filter(e=>e.fieldName===i.right).forEach(e=>{r.delete(e.value)});if(0===r.size)return!1;const o=vi(n);o.conditions=o.conditions.filter(e=>!zi(e)||e.fieldName!==i.right),[...r].forEach(e=>{o.conditions.push({fieldName:i.right,operator:"==",value:e})});const a={...t,query:o,activated:!0,gotInitialResponse:!1,dataSubject:new at.BehaviorSubject(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(a),this.ongoingQueries.set(a.clientRequestId,a),Qe(t.supportingOngoingQuery).supportedQueries.push(a),this.sendQueryToServerOrUseParentQuery(a),!0}{if(t.activated=!0,n.conditions.filter(zi).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const s=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return s.length?(n.conditions.push(...s),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=Qe(t.shift());t.push(...e.supportedQueries||[]),await(0,at.firstValueFrom)(e.unsubscribeBlockerCount.pipe(Cs(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,s=Wi(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,s),this.ongoingQueries.set(n,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new An(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,at.firstValueFrom)(t.queryRegistered.pipe(Cs(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 s=(0,at.race)(e.queryRegistered.pipe(Cs(Boolean),(0,at.delay)(2e3),(0,at.take)(1)),this.destructManager.observeIsDestructing().pipe((0,at.take)(1)));t.dataSubject.pipe((0,at.takeWhile)(()=>!e.done),(0,at.takeUntil)(s),Cs(Boolean),(0,at.tap)(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),Rt(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(Hi(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+100: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()):(Bi.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}invalidateOngoingQueryRegistrations(){for(const e of this.ongoingQueries.values())e.queryRegistered.next(!1)}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=>{Ii(this.localDocumentToClientRequestIds,t,e[t])})}}function er(e,t){for(const i of e.fields){const e=fi(t,i.fieldName)??null;if(Vi(i.value,e,i.operator))return!0;if(Vi(i.value,e,"!="))return!1}return!1}class tr{constructor(){this.stateService=new zs({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const s of e.conditions){if(zi(s)&&["=="].includes(s.operator)){const e=Ci(s.fieldName);n.has(e)||(i++,n.add(e))}else i++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];Ys(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];Ys(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),s=[...this.stateService.get(n)||[]];Xs(s,e),s.length?this.stateService.set(n,s):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];Xs(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,ki(i))];var i}}class ir{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,at.lastValueFrom)((0,at.combineLatest)(t).pipe((0,at.filter)(e=>!e.includes(!0)),(0,at.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=Qe(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){Ue(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new at.BehaviorSubject(!0)}}class nr{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 rr(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const sr="subscriptionMutex";class rr{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new at.Subject,this.subscriberCount=0,this.lockManager=new ir}async produce(e){await this.lockManager.lock(sr);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(sr)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),(0,at.defer)(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,at.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(sr);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 at.Subject}finally{this.lockManager.release(sr)}}async performUnsubscribe(){await this.lockManager.lock(sr);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(sr)}}}class or{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,at.firstValueFrom)((0,at.interval)(10).pipe((0,at.filter)(()=>this.attemptConsume()),(0,at.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}class ar{constructor(e,t,i,n,s,r){this.region=e,this.appId=t,this.authManager=s,this.clientIdService=r,this.staticHeaders={},this.onGoingRpcCounter=new at.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 or(60*o,5),ai:new or(20*o,5),secret:new or(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,at.firstValueFrom)(this.onGoingRpcCounter.pipe((0,at.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",s={},r){return(await this.rawPost(e,t,i,n,!0,s,r)).body}async rawPost(e,t,i=[],n="files",s=!0,o={},a){return this.runRawRequest(e,o,async o=>{Bi.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await us({url:c,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s,abortSignal:a})})}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){return this.runRawRequest(e,{},async n=>{let s=e.startsWith("http://")||e.startsWith("https://")?e:r(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))}),s+=`?${e.toString()}`}return Bi.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await ls({url:s,headers:n,extractErrorMessage:i})})}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="files",s=!0){return this.runRawRequest(e,{},async o=>{Bi.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await ds({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})})}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="files",s=!0){return this.runRawRequest(e,{},async o=>{Bi.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await hs({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})})}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){return this.runRawRequest(e,{},async n=>{Bi.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const s=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await ps({url:s,headers:n,message:t,extractErrorMessage:i})})}async runRawRequest(e,t,i){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),s={...this.staticHeaders,...n,...t};return await i(s)}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?Qe(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?Qe(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):Qe(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}const cr="This operation is not available in passive mode. Use active mode for real-time features.";function ur(e){Ue(!e.isPassiveMode,cr)}class lr{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 dr(){}const hr="undefined"!=typeof process&&process.versions?.node?i(86):xi().WebSocket;class pr{constructor(e,t,i,n=os,s,r,o){this.clientIdService=e,this.region=t,this.appId=i,this.messageNotificationWrapper=n,this.destructManager=s,this.authManager=r,this.runtimeOptions=o,this.webSocketObserver=new at.Subject,this.allMessagesObserver=new at.Subject,this.connectionReady=new at.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new at.Subject,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new at.BehaviorSubject(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe((0,at.filter)(Boolean),(0,at.take)(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe((0,at.skip)(1),(0,at.filter)(e=>!e),(0,at.switchMap)(()=>(0,at.race)((0,at.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,at.filter)(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Bi.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Bi.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe((0,at.filter)(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe((0,at.filter)(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?Bi.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Bi.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Bi.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Bi.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,at.distinctUntilChanged)())}async awaitConnectionReady(){ur(this.runtimeOptions),await(0,at.firstValueFrom)(this.observeConnectionReady().pipe((0,at.filter)(Boolean)))}notifyWebSocketIsNeeded(){ur(this.runtimeOptions),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&&(Bi.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.notifyWebSocketIsNeeded();try{await(0,at.firstValueFrom)((0,at.race)(this.connectionReady.pipe((0,at.filter)(Boolean)),(0,at.timer)(12e4).pipe((0,at.tap)(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))).pipe((0,at.takeUntil)(this.destructSubject)))}catch(e){if(this.destructManager.isDestructing)return;throw e}const t=await this.authManager.getToken();if(this.connectionReady.value)try{Ue(this.socket,"Socket is undefined in sendMessageAsync");const i=Oi({message:e,authToken:t});Bi.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(Oi({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=r(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Bi.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,s=1;const r={connected:!1,closeCalled:!1,open(){i=new(hr?.WebSocket??hr)(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.")}:dr,i.onopen=function(e){r.connected=!0,(t.onopen||dr)(e),n=0},i.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return Bi.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||dr)(e),void r.reconnect(e);(t.onclose||dr)(e)},i.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||dr)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&n++<i?s=setTimeout(function(){(t.onreconnect||dr)(e),Bi.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||dr)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,i.close(e,t)}catch(e){}}};return r.open(),r}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Bi.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Bi.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Bi.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Bi.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Bi.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 Bi.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=Ai(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Bi.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new at.Subject;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe((0,at.tap)(e=>t.push(e)),(0,at.debounceTime)(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await(0,at.firstValueFrom)((0,at.timer)(0)),this.connectionReady.next(!1),await(0,at.firstValueFrom)((0,at.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function gr(e){var t,i;i="Invalid application ID",Ue(function(e){return"string"==typeof e}(t=e),()=>Ge(i,"Not a string",t));const n=e.split("-");Ue(n.length<4,`Invalid application ID: ${e}`);const[s,r,o]=n;return{appId:s,environmentId:r??"prod",squidDeveloperId:o}}function fr(e,t){return`${gr(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function yr(e,t,i){return`${fr(e,t)}${i?`-${i}`:""}`}function mr(e){const t=gr(e);return fr(t.appId,t.environmentId)}class Ir{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 br{constructor(e,t,i,n,s){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n,this.consoleRegion=s}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}async aiSearch(e,t,i){return await this.rpcManager.post("web/aiSearch",{query:e,allowedDomains:i},[],"files",{},t)}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e){Ue(this.apiKey,"API key is required to create a short URL");const t="string"==typeof e?{url:e}:e,i={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shorten",i,"create short URL","json")}async createShortUrls(e){Ue(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,i={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shortenMany",i,"create short URLs","json")}async deleteShortUrl(e){Ue(this.apiKey,"API key is required to delete a short URL");const t={id:e,appId:this.appId};await this.postShortUrlApi("delete",t,"delete short URL","ignore")}async deleteShortUrls(e){Ue(this.apiKey,"API key is required to delete a short URL");const t={ids:e,appId:this.appId};await this.postShortUrlApi("deleteMany",t,"delete short URLs","ignore")}async postShortUrlApi(e,t,i,n){const s=o(this.region,this.consoleRegion,`openapi/sqd/${e}`),r=await fetch(s,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(t)});if("ignore"===n)return void Ue(r.ok,`Failed to ${i} (${r.status}): ${r.statusText}`);const a=await r.text();return Ue(r.ok,`Failed to ${i} (${r.status}): ${a}`),JSON.parse(a)}}class Sr{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:n={},body:s,files:o=[]}=t,a=await this.rpcManager.getAuthHeaders(),c={...this.rpcManager.getStaticHeaders(),...a,...i};let u=r(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 d;if(l.append(Gt.TRACE_ID,rs("c_")),l.append(Gt.CLIENT_VERSION,cs),o&&o.length>0){const e=new FormData;for(const t of o)e.append("file",t,t.name);s&&"object"==typeof s&&Object.entries(s).forEach(([t,i])=>{e.append(t,String(i))}),d=e}else l.append("Content-Type","application/json"),d=Oi(s||{});const h=await fetch(u,{method:"POST",headers:l,body:d}),p={};if(h.headers.forEach((e,t)=>{p[t]=e}),!h.ok){const e=await h.text();let t;try{t=JSON.parse(e)}catch{t=e}const i="string"==typeof t?t:t?.message||h.statusText;throw new as(i,h.status,u,p,t)}const g=await h.text();let f;try{f=JSON.parse(g)}catch{f=g}return f}getWebhookUrl(e){return r(this.region,this.appId,e?`webhooks/${encodeURIComponent(e)}`:"webhooks")}}class wr{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Hn,Ue(e.appId,"APP_ID_MUST_BE_PROVIDED"),this.runtimeOptions={isPassiveMode:e.isPassiveMode??!1};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=yr(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Li(this.destructManager),Bi.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new pi(e.apiKey,e.authProvider),this.socketManager=new pr(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new ar(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new bs(this.socketManager,this.rpcManager),this.jobClient=new ts(this.socketManager,this.rpcManager,this.clientIdService,this.destructManager,this.runtimeOptions),this.langGraphClient=new ns(this.rpcManager,this.jobClient),this.backendFunctionManager=new ji(this.rpcManager),this.aiClient=new li(this.socketManager,this.rpcManager,this.jobClient,this.clientIdService,this.backendFunctionManager,()=>this.metricAnnotations),this.apiClient=new hi(this.rpcManager),this.eventsClient=new Xn(this.rpcManager),this.documentStore=new Yn,this.lockManager=new ir,this.distributedLockManager=new Vn(this.socketManager,this.destructManager),this.documentIdentityService=new zn(this.documentStore,this.destructManager),this.documentReferenceFactory=new Jn(this.documentIdentityService),this.querySender=new Ds(this.rpcManager,this.destructManager,this.socketManager.observeConnectionReady()),this.observabilityClient=new ws(this.rpcManager),this.schedulerClient=new lr(this.rpcManager),this._appId=i,this.querySubscriptionManager=new Zs(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new As(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new ms(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new tn(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService,n),this.dataManager=new $n(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new pn(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new Sr(this.rpcManager,e.region,i),this.nativeQueryManager=new Is(this.rpcManager),this._connectionDetails=new gn(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new nr(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new ot(this.rpcManager,this.options.region,mr(i),this.options.consoleRegion),this.webClient=new br(this.rpcManager,this.options.region,mr(i),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}get isDestructed(){return this.destructManager.isDestructing}static getInstance(e){const t=ki(e);let i=wr.squidInstancesMap[t];return i||(i=new wr(e),wr.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(wr.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=_e){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)}getWebhookUrl(e){return this._validateNotDestructed(),this.webhookManager.getWebhookUrl(e)}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",s="GET"){const r={type:"elasticsearch",index:t,endpoint:n,method:s,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(r)}ai(){return this._validateNotDestructed(),this.aiClient}setMetricAnnotations(e){this.metricAnnotations=e?{...e}:void 0}job(){return this._validateNotDestructed(),this.jobClient}langGraph(e){return this._validateNotDestructed(),this.langGraphClient.graph(e)}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 Ir(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new Zn(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new es(this.rpcManager)}events(){return this._validateNotDestructed(),this.eventsClient}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,i){const n=await this.acquireLock(e,i);try{return await t(n)}finally{n.release()}}queue(e,t=Me){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(wr.squidInstancesMap).find(([,e])=>e===this);e&&delete wr.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)=>r(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>yr(e,t,i)}}_validateNotDestructed(){Ue(!this.destructManager.isDestructing,"The client was already destructed.")}}const vr=exports;for(var _r in n)vr[_r]=n[_r];n.__esModule&&Object.defineProperty(vr,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{"use strict";var e={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=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 r=i(642);t.default=r.PromisePool,s(i(273),t),s(i(642),t),s(i(837),t),s(i(426),t),s(i(858),t),s(i(172),t)},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},234(e,t,i){t.PromisePoolExecutor=void 0;const n=i(642),s=i(172),r=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],processedItemsCounter:0,taskTimeout:0,shouldStoreProcessedItems:!0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw s.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}storeProcessedItems(e=!0){return this.meta.shouldStoreProcessedItems=e,this}shouldStoreProcessedItems(){return this.meta.shouldStoreProcessedItems}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}flushProcessedItems(){this.meta.processedItems=[]}incrementProcessedItemsCounter(){this.meta.processedItemsCounter+=1}processedCount(){return this.meta.processedItemsCounter}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 s.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 s.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 s.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 s.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.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}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.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),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 r.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 s.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(r.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},642(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class s{constructor(e){this.shouldStoreProcessedItems=!0,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 s(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}dontStoreProcessedItems(){return this.shouldStoreProcessedItems=!1,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).storeProcessedItems(this.shouldStoreProcessedItems).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},426(e,t){Object.defineProperty(t,"__esModule",{value:!0})},858(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i},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},86(e){e.exports=require("ws")}};const t={};function i(n){const s=t[n];if(void 0!==s)return s.exports;const r=t[n]={exports:{}};return e[n].call(r.exports,r,r.exports,i),r.exports}i.d=(e,t)=>{if(Array.isArray(t))for(var n=0;n<t.length;){var s=t[n++],r=t[n++];i.o(e,s)?0===r&&n++:0===r?Object.defineProperty(e,s,{enumerable:!0,value:t[n++]}):Object.defineProperty(e,s,{enumerable:!0,get:r})}else for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.o=(e,t)=>Object.hasOwn(e,t),i.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let n={};i.r(n),i.d(n,{AGENT_STATUS_TITLE_ACCESSING_KB:()=>u,AGENT_STATUS_TITLE_AGENT_RESPONSE:()=>c,AGENT_STATUS_TITLE_AI_FUNCTION_RESULT:()=>d,AGENT_STATUS_TITLE_CALLING_AI_FUNCTION:()=>l,AGENT_STATUS_TITLE_GREPPING_KB:()=>g,AGENT_STATUS_TITLE_INSPECTING_KB_METADATA:()=>h,AGENT_STATUS_TITLE_QUERYING_KB_GRAPH:()=>p,AGENT_STATUS_TITLE_QUERYING_SPREADSHEET:()=>f,AI_AGENTS_INTEGRATION_ID:()=>ye,AI_AGENT_CONNECTION_EVENT_TYPE:()=>S,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>V,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>H,AI_CHAT_MESSAGE_SOURCE:()=>m,AI_CODE_INTERPRETER_PROVIDER_TYPES:()=>E,AI_EMBEDDINGS_MODEL_NAMES:()=>F,AI_FILE_PROVIDER_TYPES:()=>_,AI_IMAGE_MODEL_NAMES:()=>G,AI_KB_ACCESS_CONTROL_MODES:()=>Z,AI_MODEL_SOURCES:()=>W,AI_PROVIDER_ERROR_TYPE:()=>y,AI_PROVIDER_TYPES:()=>v,AI_VOICE_GREETING_MODES:()=>ce,AI_VOICE_RELAY_PROVIDERS:()=>ae,AI_VOICE_SESSION_EVENT_TYPE:()=>ue,ALL_OPERATORS:()=>Pe,ANTHROPIC_CHAT_MODEL_NAMES:()=>A,API_INJECTION_FIELD_TYPES:()=>le,ARRAY_OPERATORS:()=>je,AUTH_INTEGRATION_TYPES:()=>be,AdminClient:()=>at,AiAgentClient:()=>Xt,AiAgentReference:()=>Jt,AiAudioClient:()=>ei,AiClient:()=>di,AiFilesClient:()=>ti,AiImageClient:()=>ii,AiKnowledgeBaseClient:()=>oi,AiKnowledgeBaseReference:()=>ri,AiMatchMakingClient:()=>ai,AiVoiceClient:()=>li,AiWebVoiceCall:()=>ui,ApiClient:()=>pi,ApiKeysSecretClient:()=>ot,AuthManager:()=>gi,BEDROCK_EMBEDDING_MODEL_NAMES:()=>q,BUILT_IN_AGENT_ID:()=>pe,BUILT_IN_DB_INTEGRATION_ID:()=>Me,BUILT_IN_QUEUE_INTEGRATION_ID:()=>Ee,BUILT_IN_STORAGE_INTEGRATION_ID:()=>Te,BULK_INGESTION_MAX_MULTIPART_FILE_BYTES:()=>ne,BULK_INGESTION_SPEEDS:()=>oe,BackendFunctionManager:()=>Pi,BaseQueryBuilder:()=>rn,CLIENT_CONNECTION_STATES:()=>Be,CLIENT_ID_GENERATOR_KEY:()=>Qi,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>$i,CONNECTOR_IDS:()=>ge,Changes:()=>cn,ClientIdService:()=>Ui,CollectionReference:()=>pn,CollectionReferenceFactory:()=>fn,ConnectionDetails:()=>yn,ConnectorClient:()=>a,DATA_INTEGRATION_TYPES:()=>Ie,DEFAULT_PII_CLASSIFIER_MODEL:()=>b,DEFAULT_PII_ENTITY_TYPES:()=>I,DEFAULT_SHORT_ID_LENGTH:()=>18,DOC_ID_FIELD:()=>Fe,DataManager:()=>Jn,DereferencedJoin:()=>ln,DestructManager:()=>Xn,DistributedLockImpl:()=>es,DistributedLockManager:()=>Zn,DocumentReference:()=>tn,DocumentReferenceFactory:()=>ns,DocumentStore:()=>ss,EMPTY_CHAT_ID:()=>Zt,ENVIRONMENT_IDS:()=>he,EventsClient:()=>rs,ExternalAuthClient:()=>os,ExtractionClient:()=>as,FETCH_BEYOND_LIMIT:()=>100,FILE_NAME_METADATA_FIELD_NAME:()=>te,FLUX_MODEL_NAMES:()=>$,FOLDER_PATH_METADATA_FIELD:()=>ie,FOLDER_PATH_METADATA_FIELD_NAME:()=>ee,FUNCTION_AFFINITY_SCOPES:()=>Y,GEMINI_CHAT_MODEL_NAMES:()=>k,GRAPHQL_INTEGRATION_TYPES:()=>we,GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES:()=>50,GREP_KNOWLEDGE_BASE_MAX_MATCHES:()=>200,GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS:()=>500,GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS:()=>500,GROK_CHAT_MODEL_NAMES:()=>O,GroupedJoin:()=>hn,HTTP_INTEGRATION_TYPES:()=>ve,HttpStatus:()=>fe,INTEGRATION_SCHEMA_TYPES:()=>_e,INTEGRATION_TYPES:()=>me,IntegrationClient:()=>st,JobClient:()=>cs,JoinQueryBuilder:()=>un,LangGraphClient:()=>ls,LangGraphReference:()=>us,LastUsedValueExecuteFunctionCache:()=>qi,LimitUnderflowState:()=>zn,LocalQueryManager:()=>js,MAX_UPLOAD_FILE_BYTES:()=>se,MCP_OAUTH_INTEGRATION_TYPES:()=>Se,METRIC_DOMAIN:()=>Re,METRIC_FUNCTIONS:()=>De,METRIC_INTERVAL_ALIGNMENT:()=>Ne,METRIC_NO_DATA_BEHAVIOR:()=>qe,ManagementClient:()=>_s,MatchMaker:()=>ci,MutationSender:()=>Ms,NOOP_FN:()=>ps,NativeQueryManager:()=>Es,NotificationClient:()=>Ts,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>L,OPENAI_AUDIO_MODEL_NAMES:()=>U,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>B,OPENAI_CHAT_MODEL_NAMES:()=>T,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>R,OPENAI_IMAGE_MODEL_NAMES:()=>x,OPEN_AI_CREATE_SPEECH_FORMATS:()=>K,ObservabilityClient:()=>Os,Pagination:()=>nn,QueryBuilder:()=>an,QueryBuilderFactory:()=>sn,QuerySender:()=>xs,QuerySubscriptionManager:()=>or,QueueManagerFactory:()=>lr,QueueManagerImpl:()=>hr,RAG_TYPES:()=>re,RERANK_PROVIDERS:()=>w,RUN_IN_TRANSACTION_MUTEX:()=>Wn,RateLimiter:()=>pr,RpcManager:()=>gr,SOURCE_CODE_ANALYZER_MODELS:()=>We,SOURCE_CODE_ANALYZE_FUNCTION_ID:()=>Ve,SOURCE_CODE_CACHE_STRATEGIES:()=>ze,SOURCE_CODE_EXECUTION_MODES:()=>Je,SOURCE_CODE_INTEGRATION_TYPES:()=>Xe,SOURCE_CODE_MAX_REPOSITORIES:()=>20,SOURCE_CODE_MAX_SUPPLEMENTAL_INSTRUCTIONS_LENGTH:()=>2e4,SOURCE_CONTROL_PROVIDERS:()=>Ye,SQUID_BUILT_IN_INTEGRATION_IDS:()=>Oe,SQUID_METRIC_NAMES:()=>Ce,SQUID_REGIONS:()=>xe,STABLE_DIFFUSION_MODEL_NAMES:()=>Q,SchedulerClient:()=>mr,SecretClient:()=>rt,SocketManager:()=>Sr,Squid:()=>Or,SquidClientError:()=>gs,StorageClient:()=>Er,VECTOR_DB_TYPES:()=>X,VENDOR_AI_CHAT_MODEL_NAMES:()=>C,VOYAGE_EMBEDDING_MODEL_NAMES:()=>N,WebClient:()=>Tr,WebhookManager:()=>kr,assertNotPassiveMode:()=>yr,compareArgsByReference:()=>Ri,compareArgsBySerializedValue:()=>Ni,deserializeQuery:()=>Ns,embeddingModelSelectionOf:()=>z,generateId:()=>jt,generateShortId:()=>Lt,generateShortIds:()=>Ut,generateUUID:()=>qt,generateUUIDPolyfill:()=>Ft,getConsoleUrl:()=>o,getCustomizationFlag:()=>xi,isAiEmbeddingsModelName:()=>j,isBuiltInIntegrationId:()=>Ae,isFileCapableProviderType:()=>M,isIntegrationDisabled:()=>ke,isIntegrationEmbeddingModelSpec:()=>P,isIntegrationModelSpec:()=>J,isPlaceholderParam:()=>de,isVendorAiChatModelName:()=>D,loadQueryResultDocIds:()=>Rs,normalizeBitbucketRepositorySelection:()=>et,normalizeGitHubRepositorySelection:()=>Ze,observeAiStatusUpdates:()=>zt,rawSquidHttpDelete:()=>Ss,rawSquidHttpGet:()=>ms,rawSquidHttpPatch:()=>bs,rawSquidHttpPost:()=>ys,rawSquidHttpPut:()=>Is,transformFileArgs:()=>Fi,tryDeserializing:()=>vs,visitQueryResults:()=>Ds});const s="8000";function r(e,t,i,n,r){let o="https",a=`${n||t}.${r||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=s,/android$/.test(e)?a="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(a="localhost"));const u=o+"://"+a+(c?`:${c}`:""),l=i.replace(/^\/+/,"");return l?`${u}/${l}`:u}function o(e,t,i=""){return r(function(e,t){return t||(e.includes("sandbox")?"squidai.westus3.azure.sandbox":e.includes("local")?"local":e.includes("staging")?"squidai.westus3.azure.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}/connectors`)}async list(){return await this.rpcManager.get(this.iacBaseUrl)??[]}async connect(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e}`,{})}async disconnect(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}}const c="Agent Response",u="Accessing Knowledge Base",l="Calling AI Function",d="AI Function Result",h="Inspecting Knowledge Base Metadata",p="Querying Knowledge Base Graph",g="Searching Knowledge Base Text",f="Querying Spreadsheet",y="AI_PROVIDER_ERROR",m=["user","ai"],I=["email","phoneNumber","creditCard","ssn","iban","passport"],b="gpt-5.6-luna",S="ai-agent-connection-event",w=["cohere","voyage","none"],v=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","openai-compatible","grok","stability","voyage","mistral","textract","azure_document_intelligence","vertex","external"],_=["openai","gemini","anthropic","grok"];function M(e){return _.includes(e)}const E=["openai","anthropic","gemini"],T=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna"],k=["gemini-3.1-pro","gemini-3.8-flash","gemini-3.5-flash-lite"],O=["grok-4.6","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],A=["claude-fable-5","claude-fable-5-1","claude-haiku-4-5-20251001","claude-opus-5-5","claude-sonnet-5"],C=[...T,...A,...k,...O];function D(e){return C.includes(e)}const R=["text-embedding-3-small"],N=["voyage-3-large","voyage-4-large","voyage-4"],q=["titan-embed-text-v2"],F=[...R,...N,...q];function j(e){return F.includes(e)}function P(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const x=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],B=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],L=["tts-1","tts-1-hd","gpt-4o-mini-tts"],U=[...B,...L],Q=["stable-diffusion-core"],$=["flux-pro-1.1","flux-kontext-pro"],G=[...x,...Q,...$],H=[...B],V=[...L],K=["mp3","opus","aac","flac","wav","pcm"],W=["vendor","connector","custom"];function z(e){return void 0!==e.integrationId&&void 0!==e.dimensions?{integrationId:e.integrationId,model:e.modelId,dimensions:e.dimensions}:e.modelId}function J(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const Y=["pod","worker"],X=["postgres","mongoAtlas"],Z=["none","enforced"],ee="folderPath",te="filename",ie={name:ee,dataType:"string",required:!1,llmExtraction:!1},ne=104857600,se=524288e3,re=["contextual","basic"],oe=["economy","auto","fast"],ae=["twilio","openai"],ce=["phrase","agent"],ue="ai-voice-session-event",le=["secret","regular"];function de(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const he=["dev","prod"],pe="built_in_agent",ge=["bitbucket","confluence","connect_companion","cotomi","elevenlabs","openai_voice","essentials","freshdesk","generic_site_ingester","github","google_calendar","google_drive","hubspot","sharepoint","jira","jira_jsm","linear","mail","onedrive","outlook","salesforce","servicenow_csm","slack","teams","ticketmind_companion","twilio","zendesk"],fe={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},ye="ai_agents",me=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","bedrock","azure_blob","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","bitbucket","built_in_azure_blob","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","azure-entra-external-id","azure-entra-id","dynamodb","elasticsearch","firebase_auth","firestore","gcs","generic_site_ingester","github","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jira_jsm","jwt_hmac","jwt_rsa","kafka","keycloak","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","outlook","oracledb","pinecone","postgres","redis","s3","salesforce","sap_hana","sentry","snowflake","spanner","xata","zendesk","servicenow_csm","freshdesk","mail","slack","twilio","elevenlabs","openai_voice","mcp","a2a","legend","teams","openai_compatible","openai_compatible_embedding","sharepoint","vertex"],Ie=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","snowflake","elasticsearch","legend"],be=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id","azure-entra-id"],Se=["auth0","azure-entra-id","azure-entra-external-id"],we=["graphql"],ve=["api"],_e=["data","api","graphql"],Me="built_in_db",Ee="built_in_queue",Te="built_in_storage";function ke(e){return!1===e.enabled}const Oe=[Me,Ee,Te];function Ae(e){return Oe.includes(e)}const Ce=["squid_functionExecution_count","squid_functionExecution_time"],De=["sum","max","min","average","median","p95","p99","count"],Re=["user","squid"],Ne=["align-by-start-time","align-by-end-time"],qe=["return-no-result-groups","return-result-group-with-default-values"],Fe="__docId__",je=["in","not in","array_includes_some","array_includes_all","array_not_includes"],Pe=[...je,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],xe=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],Be=["CONNECTED","DISCONNECTED","REMOVED"];function Le(e){return null!=e}let Ue=e=>new Error(e);function Qe(e,t,...i){e||function(e,...t){const i=Ge(e);if("object"==typeof i)throw i;throw Ue(i||"Assertion error",...t)}(t,...i)}function $e(e,t,...i){return Qe(e,t,...i),e}function Ge(e){return void 0===e?"":"string"==typeof e?e:e()}function He(e,t,i){const n=Ge(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 Ve="analyzeCode",Ke=20,We=["claude-code","codex"],ze=["reuse","recreate"],Je=["read-only","write"],Ye=["github","bitbucket"],Xe=["github","bitbucket"];function Ze(e){const t=function(e){const t=new Set,i=new Set;for(const n of e){Qe(Number.isSafeInteger(n.id)&&n.id>0,"GITHUB_REPOSITORY_ID_INVALID"),Qe(!t.has(n.id),"GITHUB_REPOSITORY_IDS_MUST_BE_UNIQUE"),t.add(n.id),Qe(tt(n.fullName),"GITHUB_REPOSITORY_NAME_INVALID");const e=n.fullName.toLowerCase();Qe(!i.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),i.add(e),Qe(n.defaultBranch.trim(),"GITHUB_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),it(n.cloneUrl,n.fullName,!0),it(n.htmlUrl,n.fullName,!1)}return e}(e.repositories??[]),i=0===t.length?e.repository:void 0,n=t.map(e=>e.fullName);Qe(t.length>0||i,"GITHUB_REPOSITORIES_REQUIRED"),Qe(t.length<=Ke,"GITHUB_REPOSITORY_LIMIT_EXCEEDED");const s=e.defaultRepository??n[0]??i;return Qe(s,"GITHUB_DEFAULT_REPOSITORY_REQUIRED"),Qe(n.some(e=>e.toLowerCase()===s.toLowerCase())||i?.toLowerCase()===s.toLowerCase(),"GITHUB_DEFAULT_REPOSITORY_NOT_ALLOWED"),{...i?{legacyRepository:i}:{},repositories:t,defaultRepository:s}}function et(e){const t=e.workspace;Qe(t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),"BITBUCKET_WORKSPACE_INVALID");const i=e.repositories;Qe(i.length>0,"BITBUCKET_REPOSITORIES_REQUIRED"),Qe(i.length<=Ke,"BITBUCKET_REPOSITORY_LIMIT_EXCEEDED");const n=new Set,s=new Set;for(const e of i){const i=e.uuid.trim();Qe(i===e.uuid&&i.length>0,"BITBUCKET_REPOSITORY_ID_INVALID");const r=i.toLowerCase();Qe(!n.has(r),"BITBUCKET_REPOSITORY_IDS_MUST_BE_UNIQUE"),n.add(r);const o=`${t}/`;Qe(e.fullName.toLowerCase().startsWith(o.toLowerCase())&&e.fullName.length>o.length&&!e.fullName.slice(o.length).includes("/")&&!/\s/.test(e.fullName),"BITBUCKET_REPOSITORY_WORKSPACE_MISMATCH");const a=e.fullName.toLowerCase();Qe(!s.has(a),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),s.add(a),Qe(e.defaultBranch.trim(),"BITBUCKET_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),nt(e.cloneUrl,e.fullName,!0),nt(e.webUrl,e.fullName,!1)}const r=e.defaultRepository;return Qe(r&&i.some(e=>e.fullName.toLowerCase()===r.toLowerCase()),"BITBUCKET_DEFAULT_REPOSITORY_NOT_ALLOWED"),{repositories:i,defaultRepository:r}}function tt(e){return/^[^/\s]+\/[^/\s]+$/.test(e)}function it(e,t,i){let n;try{n=new URL(e)}catch{throw new Error("GITHUB_REPOSITORY_URL_INVALID")}const s=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?github\.com:\d+(?:\/|$)/i.test(e);Qe(!("https:"!==n.protocol||"github.com"!==n.hostname||r||n.username||n.password||n.search||n.hash||n.pathname!==s),"GITHUB_REPOSITORY_URL_INVALID")}function nt(e,t,i){let n;try{n=new URL(e)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const s=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(e);Qe(!("https:"!==n.protocol||"bitbucket.org"!==n.hostname||r||n.username||n.password||n.search||n.hash||n.pathname!==s),"BITBUCKET_REPOSITORY_URL_INVALID")}class st{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e,t){return(await this.rpcManager.get(this.iacBaseUrl)).filter(i=>(!e||i.type===e)&&(t?.includeDisabled||!ke(i)))}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async enable(e){await this.setEnabled(e,!0)}async disable(e){await this.setEnabled(e,!1)}async setEnabled(e,t){const i=await this.get(e);if(!i)throw new Error(`Integration not found: ${e}`);await this.upsertIntegration({...i,enabled:t})}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)}async discoverSourceRepositories(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-source-repositories`,{})}async discoverSourceRepositoriesFromDraft(e){return await this.rpcManager.post(`${this.iacBaseUrl}/discover-source-repositories`,e)}async generateAiDescriptionsForDataSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions`,t)}async generateAiDescriptionsForAssociations(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-associations`,t)}async generateAiDescriptionsForStoredProcedures(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-stored-procedures`,t)}async generateAiDescriptionsForEndpoints(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-endpoints`,t)}async discoverDataConnectionSchema(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-schema`,{})}async testDataConnection(e){return await this.rpcManager.post(`${this.iacBaseUrl}/test-connection`,e)}async discoverGraphQLConnectionSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-graphql-schema`,t)}async discoverOpenApiSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema`,t)}async discoverOpenApiSchemaFromFile(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema-from-file`,{})}}class rt{constructor(e){this.rpcManager=e}get apiKeys(){return new ot(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 ot{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 at{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new st(this.rpcManager,this.region,this.appId,this.consoleRegion),this.connectorClient=new a(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new rt(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}const ct=require("rxjs");function ut(e){return"function"==typeof e}function lt(e){return function(t){if(function(e){return ut(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 dt=function(e,t){return dt=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])},dt(e,t)};function ht(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}dt(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function pt(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 gt(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}function ft(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s<r;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create;var yt,mt=((yt=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),yt.prototype.constructor=yt,yt);function It(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var bt=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,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=pt(r),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 r.remove(this);var c=this.initialTeardown;if(ut(c))try{c()}catch(e){s=e instanceof mt?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=pt(u),d=l.next();!d.done;d=l.next()){var h=d.value;try{St(h)}catch(e){s=null!=s?s:[],e instanceof mt?s=ft(ft([],gt(s)),gt(e.errors)):s.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(s)throw new mt(s)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)St(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)&&It(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&It(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function St(e){ut(e)?e():e.unsubscribe()}bt.EMPTY;var wt={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var s=wt.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,ft([e,t],gt(i))):setTimeout.apply(void 0,ft([e,t],gt(i)))},clearTimeout:function(e){var t=wt.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function vt(){}var _t=Mt("C",void 0,void 0);function Mt(e,t,i){return{kind:e,value:t,error:i}}var Et=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof bt||i&&"closed"in i&&ut(i.remove)&&ut(i.add)&&ut(i.unsubscribe))&&t.add(n)):n.destination=Ct,n}return ht(t,e),t.create=function(e,t,i){return new kt(e,t,i)},t.prototype.next=function(e){this.isStopped?At(function(e){return Mt("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?At(Mt("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?At(_t,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}(bt);Function.prototype.bind;var Tt=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){Ot(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Ot(e)}else Ot(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Ot(e)}},e}(),kt=function(e){function t(t,i,n){var s,r=e.call(this)||this;return s=ut(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,r.destination=new Tt(s),r}return ht(t,e),t}(Et);function Ot(e){!function(e){wt.setTimeout(function(){throw e})}(e)}function At(e,t){var i=null;i&&wt.setTimeout(function(){return i(e,t)})}var Ct={closed:!0,next:vt,error:function(e){throw e},complete:vt};function Dt(e,t,i,n,s){return new Rt(e,t,i,n,s)}var Rt=function(e){function t(t,i,n,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=s?function(e){try{s(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 ht(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}(Et);function Nt(e,t){return lt(function(i,n){var s=0;i.subscribe(Dt(n,function(i){n.next(e.call(t,i,s++))}))})}function qt(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():Ft()}function Ft(){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 jt(){return qt()}const Pt=18,xt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Bt(){return xt.charAt(Math.floor(Math.random()*xt.length))}function Lt(e=Pt,t="",i=""){Qe(t.length<e,"ID prefix is too long"),Qe(!t||!i||i.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let n="";for(let t=0;t<e;t++)n+=Bt();if(t.length>0&&(n=t+n.substring(t.length)),i)for(;n.charAt(t.length)===i[t.length];)n=n.substring(0,t.length)+Bt()+n.substring(t.length+1);return n}function Ut({count:e,length:t,prefix:i}){Qe(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(Lt(t||Pt,i||""));return[...n]}const Qt=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function $t(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)$t(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)$t(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(Qt.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Qt.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 Gt(e,t,i){const n=atob(e),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return new File([s],t,{type:i||"application/octet-stream"})}const Ht={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",PROXY_HOP:"x-squid-proxy-hop",CLIENT_VERSION:"x-squid-client-version",SOURCE_IP:"x-squid-source-ip",INTEGRATION_ACCESS_TOKENS:"x-squid-integration-access-tokens",POD_IP:"x-squid-pod-ip",INSTANCE_ID:"x-squid-instance-id",EXPECTED_INSTANCE_ID:"x-squid-expected-instance-id",WORKER_KEY:"x-squid-worker-key"};function Vt(e){return JSON.stringify(e)}function Kt(e){return e&&Object.keys(e).length?{[Ht.INTEGRATION_ACCESS_TOKENS]:Vt(e)}:{}}function Wt(e){if(!e)return{headers:{},options:void 0};const{integrationAccessTokens:t,...i}=e;return{headers:Kt(t),options:i}}function zt(e,t){const{agentId:i,jobId:n}=t;return e.notifyWebSocketIsNeeded(),e.observeNotifications().pipe((0,ct.filter)(e=>"aiStatus"===e.type&&(void 0===i||e.agentId===i)),(0,ct.filter)(e=>!n||e.jobId===n),(0,ct.map)(e=>({agentId:e.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,body:e.payload.body,parentStatusUpdateId:e.payload.parentStatusUpdateId,messageId:e.payload.statusUpdateId??e.messageId})))}Error;class Jt{constructor(e,t,i,n,s,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=n,this.socketManager=s,this.jobClient=r,this.backendFunctionManager=o,this.getMetricAnnotations=a}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();Qe(t,"Agent not found");const i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}async updatePii(e){const t=await this.get();Qe(t,"Agent not found");const i={onDetect:"off",...t.options?.pii,...e};await this.setAgentOptionInPath("pii",i)}async updateMcpServer(e){await this.post("ai/agent/setMcpServer",{agentId:this.agentId,mcpServer:e})}async generateMcpDescriptions(){return await this.post("ai/agent/generateMcpDescriptions",{agentId:this.agentId})}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})}async listRevisions(){return await this.post("ai/agent/listRevisions",{agentId:this.agentId})}async restoreRevision(e){await this.post("ai/agent/restoreRevision",{agentId:this.agentId,revisionNumber:e})}async deleteRevision(e){await this.post("ai/agent/deleteRevision",{agentId:this.agentId,revisionNumber:e})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),s=await $e(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:s.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{headers:n,options:s}=Wt(i),r={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(s),jobId:t};await this.post("ai/chatbot/askAsync",r,[],"files",n)}observeStatusUpdates(e){return zt(this.socketManager,{agentId:this.agentId,jobId:e})}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),s=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:Gt(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:Gt(s.base64File,`voice.${s.extension}`,s.mimeType)}}async setAgentOptionInPath(e,t){await this.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async addConnectedIntegration(e){await this.post("ai/agent/addConnectedIntegration",{agentId:this.agentId,integrationId:e.integrationId,integrationType:e.integrationType,description:e.description??""})}async addConnectedAgent(e){await this.post("ai/agent/addConnectedAgent",{agentId:this.agentId,connectedAgentId:e.agentId,description:e.description})}async addConnectedKnowledgeBase(e){await this.post("ai/agent/addConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e.knowledgeBaseId,description:e.description,includeMetadata:e.includeMetadata})}async addFunction(e){await this.post("ai/agent/addFunction",{agentId:this.agentId,functionId:e})}async removeConnectedAgent(e){await this.post("ai/agent/removeConnectedAgent",{agentId:this.agentId,connectedAgentId:e})}async removeConnectedIntegration(e){await this.post("ai/agent/removeConnectedIntegration",{agentId:this.agentId,integrationId:e})}async removeConnectedKnowledgeBase(e){await this.post("ai/agent/removeConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e})}async removeFunction(e){await this.post("ai/agent/removeFunction",{agentId:this.agentId,functionId:e})}async setAgentDescription(e){await this.post("ai/agent/setAgentDescription",{agentId:this.agentId,description:e})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}async build(e,t,i){const n={agentId:this.agentId,request:e,memoryId:t,options:i};return await this.backendFunctionManager.executeFunction("buildAgent",n)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const s=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${s}](${n.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&$t(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)$t(i.contextMetadataFilterForKnowledgeBase[e]);n=n||qt();const{headers:s,options:r}=Wt(i);i=this.withMetricAnnotations({...Yt,...r||{}});const o="string"==typeof e;let a="ai/chatbot/";a+=o||t?!o&&t?"transcribeAndAskWithVoiceResponse":o&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const c={agentId:this.agentId,prompt:o?e:void 0,options:i,jobId:n},u=o?void 0:[e];return await this.post(a,c,u,"file",s),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&$t(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)$t(t.contextMetadataFilterForKnowledgeBase[e]);const n=qt(),{headers:s,options:r}=Wt(t),o=void 0===(t=this.withMetricAnnotations({...Yt,...r||{}})).smoothTyping||t.smoothTyping;let a="";const c=new ct.Subject,u=new ct.Subject;this.ongoingChatSequences[n]=u;let l=-1;u.pipe((0,ct.tap)(({tokenIndex:e})=>{void 0!==e&&e<l&&console.warn("Received token index out of order",e,l),void 0!==e&&(l=e)}),(0,ct.concatMap)(({value:e,complete:t,annotations:i})=>t?(0,ct.of)({value:e,complete:t,annotations:i}):(0,ct.of)(e).pipe((()=>{const e=globalThis.document,t="object"==typeof e&&null!==e&&!0===e.hidden;return o&&!t})()?(0,ct.delay)(0):(0,ct.tap)(),Nt(e=>({value:e,complete:!1,annotations:void 0})))),(0,ct.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{a+=e,t&&i&&(a=this.replaceFileTags(a,i)),c.next(a)},error:e=>{console.error(e)},complete:()=>{c.complete()}});const d="string"==typeof e;i=i||qt();const h={agentId:this.agentId,jobId:i,prompt:d?e:void 0,options:t,clientRequestId:n},p={responseStream:c.pipe((0,ct.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,ct.share)())};let g;return g=d?this.post("ai/chatbot/chat",h,[],"files",s).catch(e=>{c.error(e),c.complete()}):this.post("ai/chatbot/transcribeAndChat",h,[e],"file",s).catch(e=>{throw c.error(e),c.complete(),e}),p.serverResponse=g.then(()=>this.jobClient.awaitJob(i)).catch(e=>{c.error(e),c.complete()}),p}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,i=[],n="files",s={}){const r={...s};return this.agentApiKey&&(r["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,n,r)}}const Yt={smoothTyping:!0,responseFormat:"text"};class Xt{constructor(e,t,i,n,s=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,this.getMetricAnnotations=s,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,ct.filter)(e=>"aiChatbot"===e.type),Nt(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new Jt(e,t?.apiKey,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)}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:s,annotations:r}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const Zt="__squid_empty_chat_id";class ei{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 Gt(n.base64File,`audio.${n.extension}`,n.mimeType)}}class ti{constructor(e,t){this.provider=e,this.rpcManager=t}async uploadFile(e){const t={provider:this.provider,expirationInSeconds:e.expirationInSeconds};return(await this.rpcManager.post("ai/files/uploadFile",t,[e.file],"file")).fileId}async deleteFile(e){const t={fileId:e,provider:this.provider};return(await this.rpcManager.post("ai/files/deleteFile",t)).deleted}}class ii{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 ni(e){for(const t in e){const i=e[t];Qe("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),Qe(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}const si=new Set(["completed","failed","cancelled"]);class ri{constructor(e,t,i,n,s){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i,this.socketManager=n,this.clientIdService=s}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 generateMetadataFieldDescriptions(e){return this.rpcManager.post("ai/knowledge-base/generateMetadataFieldDescriptions",{knowledgeBaseId:this.knowledgeBaseId,fieldNames:e?.fieldNames,overwriteExisting:e?.overwriteExisting})}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 listContextsPage(e){return this.rpcManager.post("ai/knowledge-base/listContextsPage",{id:this.knowledgeBaseId,truncateTextAfter:e?.truncateTextAfter,offset:e?.offset,limit:e?.limit,search:e?.search})}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}async getContext(e,t){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e,truncateTextAfter:t?.truncateTextAfter})).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 setContextScopes(e,t){const{updatedChunkCount:i}=await this.rpcManager.post("ai/knowledge-base/setContextScopes",{knowledgeBaseId:this.knowledgeBaseId,contextId:e,scopes:t});return i}async upsertContext(e,t){const{failures:i,contextIds:n,graphIndexingSkippedContextIds:s,imageFailures:r}=await this.upsertContexts([e],t?[t]:void 0);if(i.length>0)return{failure:i[0]};const o=n?.[0],a=void 0!==o&&(s?.includes(o)??!1),c=r?.find(e=>e.contextId===o);return{...a?{graphIndexingSkipped:a}:{},...c?{imageFailures:c.imageFailures,imageFailureCount:c.imageFailureCount}:{}}}async upsertContexts(e,t,i){for(const t of e)t.metadata&&ni(t.metadata);const n=qt();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:n},t),i?.onUploaded?.(),await this.jobClient.awaitJob(n)}async bulkUpsertContexts(e,t,i){return this.rpcManager.post("ai/knowledge-base/bulk/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contexts:e,speed:i?.speed},t)}async createBulkUploadUrls(e){return this.rpcManager.post("ai/knowledge-base/bulk/createUploadUrls",{files:e.map(e=>({fileName:e}))})}async getBulkIngestionJob(e){return this.rpcManager.post("ai/knowledge-base/bulk/getJob",{jobId:e})}async cancelBulkIngestionJob(e){await this.rpcManager.post("ai/knowledge-base/bulk/cancelJob",{jobId:e})}observeBulkIngestionJob(e){return new ct.Observable(t=>{const i=()=>{this.rpcManager.post("ai/knowledge-base/bulk/subscribeToJob",{jobId:e}).catch(e=>t.error(e))};t.add(this.socketManager.observeNotifications().pipe((0,ct.filter)(e=>"bulkIngestionStatus"===e.type),(0,ct.filter)(t=>t.payload.jobId===e)).subscribe(e=>{t.next(e.payload),si.has(e.payload.state)&&t.complete()})),t.add(this.clientIdService.observeClientId().pipe((0,ct.distinctUntilChanged)(),(0,ct.skip)(1)).subscribe(()=>i())),this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.awaitConnectionReady().then(i).catch(e=>t.error(e))})}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 searchWithGraphContext(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return this.rpcManager.post("ai/knowledge-base/search",t)}async grep(e,t){return this.rpcManager.post("ai/knowledge-base/grep",{knowledgeBaseId:this.knowledgeBaseId,pattern:e,options:t})}async queryGraph(e){return this.rpcManager.post("ai/knowledge-base/queryGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async getGraphStatus(){return this.rpcManager.post("ai/knowledge-base/getGraphStatus",{knowledgeBaseId:this.knowledgeBaseId})}async rebuildGraph(e){await this.rpcManager.post("ai/knowledge-base/rebuildGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async exploreGraph(e){return this.rpcManager.post("ai/knowledge-base/exploreGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}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 oi{constructor(e,t,i,n){this.rpcManager=e,this.jobClient=t,this.socketManager=i,this.clientIdService=n}knowledgeBase(e){return new ri(e,this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)}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 ai{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new ci(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new ci(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class ci{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}}class ui{constructor(e,t,i,n){this.sessionId=e,this.callId=t,this.peer=i,this.microphone=n,this.eventListeners=new Set,this.endListeners=new Set,this.ended=!1}static async start(e,t){const i=globalThis,n=i.RTCPeerConnection,s=i.navigator?.mediaDevices;if(!n||!s)throw new Error("A web voice call needs a browser with WebRTC support");const{sink:r,...o}=t,a=await s.getUserMedia({audio:!0}),c=new n,u=r??i.document?.createElement("audio");u&&(u.autoplay=!0),c.ontrack=e=>{u&&(u.srcObject=e.streams[0],u.play().catch(()=>{}))};for(const e of a.getAudioTracks())c.addTrack(e,a);const l=c.createDataChannel("oai-events"),d=await c.createOffer();let h;await c.setLocalDescription(d),l.onmessage=e=>{try{h?.dispatch(JSON.parse(e.data))}catch{}},c.onconnectionstatechange=()=>{["failed","closed","disconnected"].includes(c.connectionState)&&h?.finish()};const p=await e.startOpenAiWebCall({...o,sdp:d.sdp??""});return await c.setRemoteDescription({type:"answer",sdp:p.sdp}),h=new ui(p.sessionId,p.callId,c,a),h}onEvent(e){return this.eventListeners.add(e),()=>this.eventListeners.delete(e)}onTurn(e){return this.onEvent(t=>{const i="string"==typeof t.transcript?t.transcript.trim():"";i&&("conversation.item.input_audio_transcription.completed"===t.type?e({role:"user",text:i,at:(new Date).toISOString()}):"response.output_audio_transcript.done"===t.type&&e({role:"agent",text:i,at:(new Date).toISOString()}))})}onEnd(e){return this.endListeners.add(e),()=>this.endListeners.delete(e)}setMuted(e){for(const t of this.microphone.getAudioTracks())t.enabled=!e}stop(){this.finish()}dispatch(e){for(const t of this.eventListeners)t(e)}finish(){if(!this.ended){this.ended=!0;for(const e of this.microphone.getTracks())e.stop();this.peer.close();for(const e of this.endListeners)e()}}}class li{constructor(e){this.rpcManager=e}async createSession(e){return this.rpcManager.post("ai/voice/createSession",e)}async answerOpenAiCall(e){return this.rpcManager.post("ai/voice/openai/answer",e)}async startOpenAiWebCall(e){return this.rpcManager.post("ai/voice/openai/webCall",e)}async startWebCall(e){return ui.start(this,e)}}class di{constructor(e,t,i,n,s,r=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.clientIdService=n,this.backendFunctionManager=s,this.getMetricAnnotations=r}agent(e=pe,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()}async listFunctions(){const e=await this.rpcManager.post("/application/getBundleMetadata",{});return Object.values(e.aiFunctions||{})}async listChatModels(e){return(await this.rpcManager.post("ai/settings/listChatModels",e??{})).models}async listEmbeddingModels(e){return(await this.rpcManager.post("ai/settings/listEmbeddingModels",e??{})).models}image(){return new ii(this.rpcManager)}audio(){return new ei(this.rpcManager)}voice(){return new li(this.rpcManager)}matchMaking(){return new ai(this.rpcManager)}files(e){return new ti(e,this.rpcManager)}executeAiQuery(e,t,i,n){const{accessToken:s,...r}=i??{},o={integrationId:e,prompt:t,options:r},a=Kt(s?{[e]:s}:void 0);return this.rpcManager.post("ai/query/executeDataQuery",o,[],"files",a,n)}executeAiApiCall(e,t,i,n){const s={integrationId:e,prompt:t,options:i,sessionContext:n};return this.rpcManager.post("ai/query/executeApiQuery",s)}executeAiSpreadsheetQuery(e,t,i,n){const s={prompt:e,files:t,options:i,sessionContext:n};return this.rpcManager.post("ai/query/executeSpreadsheetQuery",s)}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}observeStatusUpdates(e){return zt(this.socketManager,{jobId:e})}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Xt(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new oi(this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)),this.aiKnowledgeBaseClient}}const hi={headers:{},queryParams:{},pathParams:{}};class pi{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,s){const r={integrationId:e,endpointId:t,body:i,options:{...hi,...this.convertOptionsToStrings(n||{})},overrideMethod:s};return await this.rpcManager.rawPost("api/callApi",r,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 gi{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 fi=/[.\[\]]/;function yi(e,t){if(!e)return;const i=t.split(fi);let n,s=e;for(;s&&i.length;){const e=i.shift();if(e){if("object"!=typeof s||!(e in s))return;n=s[e],s=n}}return n}function mi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ii(e,t,i,n="."){const s=t.split(n);let r=e;for(;s.length;){const e=$e(s.shift());if(s.length){const t=r[e],i=mi(t)?Mi(t)??{}:{};r[e]=i,r=i}else r[e]=i}}function bi(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function Si(e){return null==e}function wi(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),s=Object.keys(t);if(n.length!==s.length)return!1;for(const i of n)if(!s.includes(i)||!wi(e[i],t[i]))return!1;return!0}function vi(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=_i(e[n],t);return i}function _i(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 vi(e,t);if(e instanceof Map)return new Map(vi(Array.from(e),t));if(e instanceof Set)return new Set(vi(Array.from(e),t));if(ArrayBuffer.isView(e))return n=e,"undefined"!=typeof Buffer&&n instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const s={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(s[i]=_i(e[i],t));return s}function Mi(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 Ei(e,t){if(e===t||Si(e)&&Si(t))return 0;if(Si(e))return-1;if(Si(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(Qe("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(Qe("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(Qe("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(Qe("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function Ti(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function ki(e){if(Array.isArray(e))return e.map(e=>ki(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]=ki(e[t])}),i}function Oi(e){return Ai(ki(e))}function Ai(e){if(void 0===e)return null;const t=_i(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Ci(e){return _i(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 Di(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=Ai(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 Ri=(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},Ni=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Ai(e[i])!==Ai(t[i]))return!1;return!0};class qi{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Ri,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 Fi(e){const t=[],i=[];let n=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){i.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(ji(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(i.push(s[t]),n++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:i}}function ji(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class Pi{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:n,fileArray:s}=Fi(i),r="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?Ri:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,n));if(t)return t.promise}const u=this.createExecuteCallPromise(r,n,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:n,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,i,n,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:Ai(t)},a=Ci((await this.rpcManager.post(r,o,i.length>0?i:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return Gt(e.base64,e.filename,e.mimetype)}return n&&n.set(t,a),a}}function xi(e){if("undefined"!=typeof globalThis)return globalThis[e]}function Bi(){if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}void 0===Bi()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){Bi().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 Li{static debug(...e){(function(){const e=Bi();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=Bi();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Ui{constructor(e){this.destructManager=e,this.clientTooOldSubject=new ct.BehaviorSubject(!1),this.isTenant=!0===Bi().squidTenant,this.clientIdSubject=new ct.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,ct.filter)(e=>e),(0,ct.map)(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,ct.skip)(1),(0,ct.filter)(e=>!e),(0,ct.map)(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=Bi()[$i];return e?e():qt()}generateClientId(){const e=Bi()[Qi];if(e)return e();let t=`${this.isTenant?"tenant-":""}${qt()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Qi="SQUID_CLIENT_ID_GENERATOR",$i="SQUID_CLIENT_REQUEST_ID_GENERATOR",Gi="__squidId";function Hi(e){return Ci(e)}function Vi(...e){const[t,i,n]=e,s="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return s.integrationId||(s.integrationId=void 0),Oi(s)}function Ki(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return wi(e,t);if("!="===i)return!wi(e,t);switch(i){case"<":return!Si(e)&&(!!Si(t)||t<e);case"<=":return!!Si(t)||!Si(e)&&t<=e;case">":return!Si(t)&&(!!Si(e)||t>e);case">=":return!!Si(e)||!Si(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Wi(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Wi(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Wi(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Wi(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>$e(i,"VALUE_CANNOT_BE_NULL").some(t=>wi(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>$e(i,"VALUE_CANNOT_BE_NULL").some(t=>wi(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!$e(i,"VALUE_CANNOT_BE_NULL").some(t=>wi(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function Wi(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 zi(e){for(let t=0;t<e.length;t++)if("\\"===e[t]){if(!["%","_","\\"].includes(e[t+1]))return!0;t++}return!1}function Ji(e,t){return`${e}_${t}`}function Yi(e){return"fieldName"in e}function Xi(e){return"docIds"in e}function Zi(e,t,i){const n=e.docIds.some(e=>Object.entries(e).every(([e,n])=>Ki(n,i(t,e)??null,"==")));switch(e.operator){case"==":case"in":return n;case"!=":case"not in":return!n}}function en(e,t,i,n){const s=e,r=n(t,Fe);if("string"!=typeof r)return Ki(s,r??null,i);let o;try{o=Ci(r)}catch{return Ki(s,r,i)}if(!o||"object"!=typeof o||Array.isArray(o))return Ki(s,r,i);const a=Object.keys(o);if(1===a.length&&"__id"===a[0]){const e=o.__id,t=function(e){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=Object.keys(e);return 1===t.length&&"__id"===t[0]?e.__id:Oi(e)}if("string"==typeof e)try{const t=Ci(e);if(t&&"object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);if(1===e.length&&"__id"===e[0])return t.__id}}catch{}return e}(s);return Ki(t,e,i)}if(1===a.length){const e=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const i=Object.keys(e);if(1===i.length&&i[0]===t)return e[t]}if("string"==typeof e)try{const i=Ci(e);if(i&&"object"==typeof i&&!Array.isArray(i)){const e=Object.keys(i);if(1===e.length&&e[0]===t)return i[t]}}catch{}return e}(s,a[0]);return Ki(e,o[a[0]],i)}return"object"!=typeof s||null===s||Array.isArray(s)?Ki(s,r,i):Ki(Oi(s),r,i)}class tn{constructor(e,t,i,n,s){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.projectFields=n,this.identityReference=s,this.refId=qt()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this.identityReference?.squidDocId??this._squidDocId}get data(){return _i(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=$e(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=Hi(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`});return this.projectFields?this.applyProjection(e):e}get hasData(){return this.dataManager.hasSufficientData(this.squidDocId,this.projectFields)}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 $e(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,ct.map)(e=>($e(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:Hi(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:_i(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},s={type:"update",squidDocIdObj:Hi(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(s,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async upsert(e,t){const i=Hi(this.squidDocId),n=i.integrationId;let s=Ci(i.docId);if(s[Gi]&&(s={}),n===Me&&s.__id)try{const e=Ci(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...s}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:Hi(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)}applyProjection(e){const t={},i=$e(this.projectFields,"applyProjection called without projectFields"),{integrationId:n}=Hi(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const s=n===Me?"__id":"__docId__";if(s in e){const i=e[s];if("string"==typeof i&&i.startsWith("{"))try{const e=Ci(i);if("object"==typeof e&&null!==e)for(const[i,n]of Object.entries(e))i in t||(t[i]=n)}catch{}}for(const n of i)if(n.includes(".")){const i=yi(e,n);void 0!==i&&Ii(t,n,i)}else n in e&&(t[n]=e[n]);return t}hasSquidPlaceholderId(){const e=Ci(this.squidDocId);if("object"==typeof e&&e.docId){const t=Ci(e.docId);if("object"==typeof t&&Object.keys(t).includes(Gi))return!0}return!1}}class nn{constructor(e,t={}){this.internalStateObserver=new ct.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new ct.BehaviorSubject(!1),this.snapshotSubject=new ct.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,Qe(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,ct.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,ct.filter)(e=>null!==e),(0,ct.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,ct.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||Si(e)&&Si(t))return 0;if(Si(e))return-1;if(Si(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:s}of i){const i=Ei(yi(e,n),yi(t,n));if(0!==i)return s?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:yi(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,ct.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:yi(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,ct.firstValueFrom)((0,ct.race)(this.isDestroyed.pipe((0,ct.filter)(Boolean),(0,ct.map)(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe((0,ct.filter)(e=>null!==e),(0,ct.take)(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[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)}}class sn{constructor(e,t,i,n,s){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n,this.mutationSender=s}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=Hi(e),s=Ci(n),r=this.get(t,i);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new an(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService,this.mutationSender)}}class rn{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)}docId(e){return this.eq(Fe,e)}docIds(e){return this.in(Fe,e)}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(zi(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class on{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return(0,ct.firstValueFrom)(this.snapshots(!1).pipe((0,ct.defaultIfEmpty)([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(Nt(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new on(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}projectFields(e){const t=this.queryBuilder.projectFields(e);return new on(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new nn(this,e)}}class an extends rn{constructor(e,t,i,n,s,r,o,a){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,this.documentReferenceFactory=s,this.queryBuilderFactory=r,this.documentIdentityService=o,this.mutationSender=a,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return Di(this.build())}where(e,t,i){if(Qe(Pe.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&e!==Fe&&!this.query.projectFields.includes(e))throw new Error(`Cannot filter by field '${e}' that is not included in projectFields.`);if("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;Qe(function(e){return"number"==typeof e}(t=e),()=>He("Limit needs to be a number","Not a number",t)),-1!==e&&(Qe(e>0,"query limit has to be greater than 0"),Qe(Math.floor(e)===e,"query limit has to be an integer"),Qe(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 Qe(wi(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};if(function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,s,r;Qe((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"),Qe((s=t.asc,r="boolean",Array.isArray(s)?s.every(e=>typeof e===r):typeof s===r),"Asc needs to be boolean")}(i),Qe(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.projectFields&&e!==Fe&&!this.query.projectFields.includes(e))throw new Error(`Cannot sort by field '${e}' that is not included in projectFields.`);return this.query.sortOrder.push(i),this}projectFields(e){if(0===e.length&&"built_in_db"!==this.integrationId)throw new Error(`Empty projectFields is only allowed for built_in_db integration. For '${this.integrationId}', you must specify at least one field to project.`);if(this.query.projectFields)for(const t of e)if(!this.query.projectFields.includes(t))throw new Error(`Cannot project field '${t}' that is not in the existing projection. Subsequent projectFields calls must be subsets of the previous projection.`);const t=e;for(const e of this.query.sortOrder)if(e.fieldName!==Fe&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(Yi(e)){if(e.fieldName!==Fe&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else if(Xi(e));else for(const i of e.fields)if(i.fieldName!==Fe&&!t.includes(i.fieldName))throw new Error(`Cannot set projectFields without including filter field '${i.fieldName}'.`);const i=this.clone();return i.query.projectFields=[...e],i}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return(0,ct.firstValueFrom)(this.snapshots(!1).pipe((0,ct.defaultIfEmpty)([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new ct.BehaviorSubject([]);const t=this.build(),i=t.projectFields;return this.querySubscriptionManager.processQuery(t,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(Nt(e=>e.map(e=>{Qe(1===Object.keys(e).length);const t=e[this.collectionName],n=Vi($e(t).__docId__,this.collectionName,this.integrationId),s=this.querySubscriptionManager.detachedRecords.delete(e),r=this.documentReferenceFactory.create(n,this.queryBuilderFactory,i,s);return s&&r.setInMemoryData(t),r})))}changes(){let e,t=new Set;return this.snapshots().pipe((0,ct.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,ct.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)}),ct.NEVER)),(0,ct.startWith)({}))),Nt(([i])=>{let n=[];const s=[],r=[];if(e){for(const r of i){const i=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){s.push(r);const n=e[i];delete e[i],t.delete(n)}else n.push(r)}for(const e of t)r.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 cn(n,s,r)}))}async delete(){return this.validateQueryDeleteModifiers(),this.containsEmptyInCondition?{deletedCount:0}:(Qe(this.mutationSender,"Query delete is not available on this query builder."),this.mutationSender.deleteQuery(this.build()))}dereference(){return new on(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new an(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService,this.mutationSender);return e.query=_i(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){if(!e.length)return this;if(this.query.projectFields)for(const t of e)if(t.fieldName!==Fe&&!this.query.projectFields.includes(t.fieldName))throw new Error(`Cannot filter by field '${t.fieldName}' that is not included in projectFields.`);return this.query.conditions.push({fields:e}),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 nn(this,e)}validateQueryDeleteModifiers(){Qe(0===this.query.sortOrder.length&&-1===this.query.limit&&!this.query.limitBy,"query.delete() does not currently support sortBy, limit, or limitBy.")}mergeConditions(){const e=[],t=Ti(this.query.conditions.filter(Yi)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=Ti(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)=>Ei(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Yi(e)),...e]}}class cn{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class un extends rn{constructor(e,t,i,n,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=s,this.rootAlias=r,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}projectFields(e){throw new Error("projectFields is not yet supported for join queries")}join(e,t,i,n){const s=n?.leftAlias??this.latestAlias,r={...i,leftAlias:s,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new un(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:r},this.queryBuilder)}snapshot(){return(0,ct.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new ct.BehaviorSubject([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,_i(this.joins),_i(this.joinConditions),e,!1).pipe(Nt(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,s=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,r=n?Vi(n.__docId__,e,s):void 0;t[i]=r?this.documentReferenceFactory.create(r,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new hn(this)}dereference(){return new ln(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new un(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,_i(this.leftToRight),_i(this.joins),_i(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 nn(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class ln{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return(0,ct.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(Nt(e=>e.map(e=>function(e,t){const i={},n=Object.keys(e);for(const s of n){const n=e[s];i[s]=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 ln(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 nn(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class dn{constructor(e){this.groupedJoin=e}snapshot(){return(0,ct.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(Nt(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 dn(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 nn(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 hn{constructor(e){this.joinQueryBuilder=e}snapshot(){return(0,ct.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(Nt(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new dn(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new hn(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 nn(this,e)}groupData(e,t){const i=Ti(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 s={[t]:n};for(const t of i)s[t]=this.groupData(e,t);return s})}}class pn{constructor(e,t,i,n,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,this.querySubscriptionManager=s,this.dataManager=r,this.refId=qt()}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!==Me)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={[Gi]:qt()};else e=e&&"string"!=typeof e?{__id:Oi(e)}:{__id:e||qt()};const t=Vi(Oi(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).upsert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof tn?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new un(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new gn(...e)}}class gn{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,ct.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 gn(...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 nn(this,e)}or(e,...t){return(0,ct.combineLatest)([...t]).pipe((0,ct.map)(t=>{const i=new Set,n=t.flat(),s=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),s.push(e));return s.sort((t,i)=>{for(const{fieldName:n,asc:s}of e){const e=yi(this.extractData(t),n),r=yi(this.extractData(i),n);if(!Ki(e,r,"=="))return Ki(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class fn{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 pn(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class yn{constructor(e,t,i){this.clientIdService=e,this.socketManager=t,this.runtimeOptions=i,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 mn=i(150);const In={"in:in":(e,t)=>e.every(e=>t.includes(e)),"in:not in":(e,t)=>e.every(e=>t.every(t=>function(e,t){return Si(e)||Si(t)?Si(e)!==Si(t):wn(e,t)&&!wi(e,t)&&!(Number.isNaN(e)&&Number.isNaN(t))}(e,t))),"not in:not in":(e,t)=>t.every(t=>e.includes(t)),">:not in":(e,t)=>t.every(t=>Mn(e,t)),">=:not in":(e,t)=>t.every(t=>_n(e,t)),"<:not in":(e,t)=>t.every(t=>Sn(e,t)),"<=:not in":(e,t)=>t.every(t=>bn(e,t)),">:>":(e,t)=>Mn(e,t),">=:>":(e,t)=>_n(e,t),"in:>":(e,t)=>e.every(e=>_n(e,t)),">:>=":(e,t)=>Mn(e,t),">=:>=":(e,t)=>Mn(e,t),"in:>=":(e,t)=>e.every(e=>Mn(e,t)),"<:<":(e,t)=>Sn(e,t),"<=:<":(e,t)=>bn(e,t),"in:<":(e,t)=>e.every(e=>bn(e,t)),"<:<=":(e,t)=>Sn(e,t),"<=:<=":(e,t)=>Sn(e,t),"in:<=":(e,t)=>e.every(e=>Sn(e,t)),"like:like":(e,t)=>Tn(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Tn(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Tn(e,t)&&Cn(t),"like_cs:like_cs":(e,t)=>Tn(e,t),"like:not like":(e,t)=>!On(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!On(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!On(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!On(e,t),"not like:not like":(e,t)=>Tn(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Tn(t,e)&&Cn(e),"not like:not like_cs":(e,t)=>Tn(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Tn(t,e),"in:like":(e,t)=>e.every(e=>Ki(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Ki(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>vn(e)&&Ki(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>vn(e)&&Ki(t,e,"not like_cs")),"like:in":(e,t)=>Dn(e)&&Cn(e)&&t.includes(e),"like_cs:in":(e,t)=>Dn(e)&&t.includes(e),"not in:not like":(e,t)=>Dn(t)&&Cn(t)&&e.includes(t),"not in:not like_cs":(e,t)=>Dn(t)&&e.includes(t),"like:not in":(e,t)=>t.every(t=>Ki(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Ki(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Ki(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Ki(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)=>t.every(t=>e.includes(t)),"array_not_includes:array_not_includes":(e,t)=>t.every(t=>e.includes(t)),"array_includes_all:array_includes_some":(e,t)=>e.some(e=>t.includes(e)),"array_includes_some:array_includes_all":(e,t)=>e.every(e=>t.every(t=>e===t))};function bn(e,t){return Si(e)?!Si(t):!Si(t)&&wn(e,t)&&e<t}function Sn(e,t){return!!Si(e)||!Si(t)&&wn(e,t)&&e<=t}function wn(e,t){return typeof e==typeof t&&e instanceof Date==t instanceof Date}function vn(e){return Si(e)||"string"==typeof e}function _n(e,t){return bn(t,e)}function Mn(e,t){return Sn(t,e)}function En(e){const t=[];for(let i=0;i<e.length;i++){const n=e[i],s=e[i+1];"\\"!==n||"%"!==s&&"_"!==s?"\\"===n&&"\\"===s?(t.push(n),i++):t.push(n):(t.push(n+s),i++)}return t}function Tn(e,t){return kn(En(e),En(t))}function kn(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return Nn(t.slice(n));const s=e[i],r=t[n];return"%"===s&&"%"===r?kn(e,t,i+1,n+1)||kn(e,t,i+1,n):"%"!==s&&("%"===r?kn(e,t,i,n+1)||kn(e,t,i+1,n):(s===r||"_"===r)&&kn(e,t,i+1,n+1))}function On(e,t){return An(En(e),En(t))}function An(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return Nn(t.slice(n));if(n>=t.length)return Nn(e.slice(i));const s=e[i],r=t[n];return"%"===s&&"%"===r?An(e,t,i+1,n+1)||An(e,t,i,n+1)||An(e,t,i+1,n):"%"===s||"%"===r?An(e,t,i,n+1)||An(e,t,i+1,n):(s===r||"_"===s||"_"===r)&&An(e,t,i+1,n+1)}function Cn(e){return e===e.toLowerCase()&&e===e.toUpperCase()}function Dn(e){return!/[%_\\]/.test(e)}function Rn(e,t){return e.includes("like")&&"string"==typeof t&&zi(t)}function Nn(e){return e.every(e=>"%"===e)}function qn(e,t){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(const n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!wi(e[n],t[n]))return!1}return!0}function Fn(e,t){return t.every(t=>{const i=Object.keys(t).sort();if(i.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(i[t]!==e[t])return!1;return!0})}class jn{constructor(e){this.query=e,this.query=e;const t=this.query.conditions.filter(Yi),i=this.query.conditions.filter(Xi),n=i.flatMap(e=>function(e){if("=="!==e.operator&&"in"!==e.operator)return[];if(0===e.docIds.length)return[];const t=[],i=e.docIds[0];for(const n of Object.keys(i)){const s=i[n];e.docIds.every(e=>Object.prototype.hasOwnProperty.call(e,n)&&wi(e[n],s))&&t.push({fieldName:n,operator:"==",value:s})}return t}(e));this.exactSimpleConditions=this.parseConditions(t),this.exactDocIdConditions=i,this.subqueryConditions=this.parseConditions([...t,...n])}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}get projectFields(){return this.query.projectFields}sortedBy(e){return!e.find((e,t)=>!wi(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.subqueryConditions.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;for(const t of e.conditions.filter(Xi))if(!this.childImpliesParentDocIdCondition(t))return!1;const t=e.conditions.filter(Yi),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return i&&n&&s&&r}childImpliesParentDocIdCondition(e){const t=e.docIds;if(0===t.length)return!1;const i="=="===e.operator||"in"===e.operator,n=Object.keys(t[0]).sort(),s=[];for(const e of this.query.conditions)Xi(e)&&s.push(...e.docIds);if(!Fn(n,t)||!Fn(n,s))return!1;const r=this.buildChildEffectiveTupleSet();return i?void 0!==r.allowed&&r.allowed.every(e=>t.some(t=>qn(e,t))):void 0!==r.allowed?r.allowed.every(e=>!t.some(t=>qn(e,t))):t.every(e=>r.excluded.some(t=>qn(e,t)))}buildChildEffectiveTupleSet(){let e;const t=[];for(const i of this.query.conditions)if(Xi(i))if("=="===i.operator||"in"===i.operator)e=void 0===e?[...i.docIds]:e.filter(e=>i.docIds.some(t=>qn(e,t)));else for(const e of i.docIds)t.some(t=>qn(t,e))||t.push(e);return void 0!==e&&t.length>0&&(e=e.filter(e=>!t.some(t=>qn(e,t)))),{allowed:e,excluded:t}}isProjectFieldsSubset(e,t){if(!t)return!0;if(!e)return!1;const i=new Set(t);return e.every(e=>i.has(e))}getConditionsFor(...e){return this.subqueryConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.subqueryConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.exactSimpleConditions){const i=t.fieldName,n=t.operator;if(i===Fe){const i=t.value;if("in"===n||"not in"===n){const t=(Array.isArray(i)?i:[i]).some(t=>en(t,e,"==",yi));if(!("in"===n?t:!t))return!1;continue}if(!en(i,e,n,yi))return!1;continue}const s=yi(e,i);if("in"===n){if(t.value.includes(s))continue;return!1}if("not in"!==n){if(!Ki(t.value,s,n))return!1}else if(t.value.includes(s))return!1}for(const t of this.exactDocIdConditions)if(!Zi(t,e,yi))return!1;return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=In[`${i}:${s}`];return!!o&&!Rn(i,n)&&!Rn(s,r)&&o(n,r)}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}}function Pn(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function xn(e,t){let i=e;for(const e of t.split(".")){if(!Pn(i))return;i=i[e]}return i}function Bn(e,t,i){const n=t.split(".");let s=e;for(const[e,r]of n.entries()){if(e===n.length-1)return void(s[r]=i);const o=s[r];if(null!=o&&!Pn(o))throw new Error(`Cannot set path ${t}, ${r} is not an object`);const a=Pn(o)?{...o}:{};s[r]=a,s=a}}function Ln(e,t){const i=t.split(".");let n=e;for(const[e,t]of i.entries()){if(e===i.length-1)return void delete n[t];const s=n[t];if(!Pn(s))return;const r={...s};n[t]=r,n=r}}function Un(e,t){switch(t.type){case"applyNumericFn":return function(e,t){if("increment"===t.fn)return"number"==typeof e?e+t.value:t.value;throw new Error("Unknown numeric function: "+JSON.stringify(t))}(e,t);case"applyStringFn":return function(e,t){const i="string"==typeof e?e:null;switch(t.fn){case"trim":return null===i?null:i.trim();case"extendString":return null===i?t.value:i+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?_i(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Qn(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function $n(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(Qe("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const i=_i(e);t=_i(t);for(const[e]of Qn(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 Qn(t))i.properties[e]=Gn([...i.properties[e]||[],...n]);return i}(e,t);const i=_i(e);for(const[e,n]of Qn(t)){const t=n;for(const n of t){const t=i.properties,s=Un(xn(t,e),n);void 0===s?Ln(t,e):Bn(t,e,s)}}return i}function Gn(e){let t=0;for(;t+1<e.length;){const i=Hn(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function Hn(e,t){if("removeProperty"===t.type||"update"===t.type)return t;if("applyNumericFn"===t.type){if(Qe("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type)return Qe("increment"===e.fn,"Unrecognized applyNumericFn"),{type:"applyNumericFn",fn:"increment",value:e.value+t.value};if("update"===e.type){if("number"!=typeof e.value)throw new Error("Cannot increment a value that is not a number");return{type:"update",value:e.value+t.value}}return t}if("extendString"===t.fn){if("update"===e.type){if("string"!=typeof e.value)throw new Error("Cannot extend a value that is not a string");return{type:"update",value:e.value+t.value}}return"applyStringFn"===e.type&&"extendString"===e.fn?{type:"applyStringFn",fn:"extendString",value:e.value+t.value}:t}return null}function Vn(e,t){if(!e)return;const i={...e},n=Qn(t);for(const[e,t]of n){const n=t;for(const t of n){const n=Un(xn(i,e),t);void 0===n?Ln(i,e):Bn(i,e,n)}}return i}function Kn(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)=>$e($n(e,t),"Merge result cannot be null"));i.push(n)}return i}const Wn="dataManager_runInTransaction";var zn;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(zn||(zn={}));class Jn{constructor(e,t,i,n,s,r,o,a,c){this.documentStore=e,this.mutationSender=t,this.socketManager=i,this.querySubscriptionManager=n,this.queryBuilderFactory=s,this.lockManager=r,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 ct.Subject,this.outgoingMutationsEmpty=new ct.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)}hasSufficientData(e,t){return this.documentStore.hasSufficientData(e,t)}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 executeDetachedQuery(e){const t=this.currentTransactionId,i={query:e,clientRequestId:qt(),subscribe:!1},n=await this.querySender.sendQueryDirect(i);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(n.docs,e)}async reRunQueryThroughNormalPipeline(e){await(0,ct.firstValueFrom)(this.outgoingMutationsEmpty.pipe((0,ct.filter)(Boolean),(0,ct.take)(1)));const t={query:e,clientRequestId:qt(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}predictUpdate(e,t){try{return Vn(e,t)}catch{return e}}applyPendingMutationsToQueryResult(e,t){const i=new jn(t),n=new Map;for(const i of e){const e=Vi(i.__docId__,t.collectionName,t.integrationId);n.set(e,i)}for(const[e,s]of this.pendingOutgoingMutations){const r=Hi(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of s){const s=n.get(e);if("delete"===t.type)n.delete(e);else if("update"===t.type){if(s){const r=this.predictUpdate(s,t);r&&i.documentMatchesQuery(r)?n.set(e,r):n.delete(e)}}else if("insert"===t.type){const s={...t.properties,__docId__:r.docId};i.documentMatchesQuery(s)&&n.set(e,s)}}}const s=Array.from(n.values()),{sortOrder:r}=t;s.sort((e,t)=>{for(const{fieldName:i,asc:n}of r){const s=Ei(yi(e,i),yi(t,i));if(0!==s)return n?s:-s}return 0});const o=t.limit<0?2e3:t.limit;return s.slice(0,o)}async runInTransaction(e,t){if(t)return Qe(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(Wn)?this.lockManager.lockSync(Wn):await this.lockManager.lock(Wn);let i=Yn;const n=()=>i!==Yn;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=qt();try{r=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(Wn)}catch(e){i=n()?i:e}}n()&&s(i)})}async applyOutgoingMutation(e,t){const i=Vi(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(Wn)||(await this.lockManager.lock(Wn),this.lockManager.release(Wn)),this.knownDirtyDocs.delete(i);const n=this.removeInternalProperties(e),s=this.pendingOutgoingMutations.get(i)?.slice(-1)[0],r=s&&!s.sentToServer?$e(Kn([s.mutation,n])[0],"Failed to reduce mutations"):void 0;if("update"===e.type&&Vn(this.documentStore.getDocumentOrUndefined(i),e),s&&r)s.mutation=r,this.outgoingMutationsEmpty.next(!1);else{const e={mutation:n,sentToServer:!1},t=this.pendingOutgoingMutations.get(i)||[];t.push(e),this.pendingOutgoingMutations.set(i,t),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?t&&this.predictUpdate(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 Qe(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(Wn);try{this.currentTransactionId=qt();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(Wn)}}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,ct.filter)(e=>"mutations"===e.type),Nt(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,ct.filter)(Boolean),(0,ct.take)(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,ct.filter)(Boolean),(0,ct.take)(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t={},i=[];for(const n of e){if(!this.querySubscriptionManager.hasOngoingQuery(n.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(n.clientRequestId),s=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(n.clientRequestId);s&&r?i.push({squidDocId:n.squidDocId,item:{properties:n.doc,timestamp:n.mutationTimestamp,clientRequestId:n.clientRequestId,projectFields:e.projectFields}}):t[n.squidDocId]={properties:n.doc,timestamp:n.mutationTimestamp}}Object.keys(t).length>0&&this.applyIncomingUpdates(t),i.length>0&&this.runInTransactionSync(()=>{this.applyProjectedUpdates(i)})}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId);if(null!==t.projectFields&&void 0!==t.projectFields){const i=[];for(const n of e.docs){const s=Vi(n.__docId__,t.collectionName,t.integrationId);i.push({squidDocId:s,item:{properties:n,timestamp:n.__ts__,clientRequestId:e.clientRequestId,projectFields:t.projectFields}})}this.runInTransactionSync(()=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId,e.docs),this.batchClientRequestIds.add(e.clientRequestId),this.applyProjectedUpdates(i)})}else{const i={};for(const n of e.docs){const e=Vi(n.__docId__,t.collectionName,t.integrationId);i[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId,e.docs),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(i,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}}applyIncomingUpdates(e,t){let i=!1;const n=new Set,s=new Set;for(const[t,r]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>r.timestamp?i=!0:o&&o.timestamp>r.timestamp?(r.properties&&this.documentStore.adoptMissingFields(t,r.properties),s.add(t)):(this.pendingIncomingUpdates.set(t,r),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),i}applyProjectedUpdates(e){for(const{squidDocId:t,item:i}of e){const e=$e(i.clientRequestId,"clientRequestId required for projected updates"),n=this.pendingOutgoingMutations.get(t);if(n&&n.length)continue;const s=this.docIdToServerTimestamp.get(t);s&&s.timestamp>i.timestamp?(this.querySubscriptionManager.addDocToQuery(t,e),this.batchClientRequestIds.add(e)):(this.acknowledgeDocument(t,i.timestamp,!i.properties),this.docIdToLocalTimestamp.set(t,i.timestamp),i.properties?(this.documentStore.saveProjectedDocument(t,i.properties,i.projectFields),this.querySubscriptionManager.addDocToQuery(t,e)):this.querySubscriptionManager.removeDocFromQuery(t,e),this.batchClientRequestIds.add(e))}}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||Oi({...t,__ts__:void 0})!==Oi(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)}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await mn.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(),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:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),s.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=Vi(e.mutation.squidDocIdObj),i=$e(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}=Hi(t);this.setExpiration(t,!0);try{const i=e.includes(Gi)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if($e(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),this.pendingIncomingUpdates.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=Vi(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=Hi(n))})}),Object.entries(e).forEach(([e,t])=>{bi(this.pendingOutgoingMutations,e,t),bi(this.docIdToLocalTimestamp,e,t),bi(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 Yn=Symbol("undefined");class Xn{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new ct.BehaviorSubject(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe((0,ct.filter)(Boolean),Nt(()=>{}))}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 Zn{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,ct.filter)(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,ct.filter)(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{if(e)return;const t=Object.keys(this.ongoingLocks);t.length>0&&(console.warn(`DistributedLockManager: WebSocket disconnected, releasing ${t.length} lock(s)`),Li.debug(`DistributedLockManager: released lock(s): [${t.join(", ")}]`)),this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.lockId];t?.release()})}async lock(e,t){"number"==typeof t&&(t={acquisitionTimeoutMillis:t});const i=t?.acquisitionTimeoutMillis??2e3,n=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),Qe(await(0,ct.firstValueFrom)((0,ct.race)((0,ct.timer)(this.lockWaitForConnectionThreshold).pipe(Nt(()=>!1)),this.socketManager.observeConnectionReady().pipe((0,ct.filter)(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const s=qt(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:i,maxHoldTimeMillis:n,clientRequestId:s}};this.socketManager.postMessage(r);const o=await(0,ct.firstValueFrom)((0,ct.race)((0,ct.timer)(i+4e3).pipe((0,ct.take)(1),Nt(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:s}}))),this.acquireLockMessagesFromServer.pipe((0,ct.filter)(e=>e.payload.clientRequestId===s)))),a=o.payload.lockId;Qe(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),Qe(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new es(a,e,s,this.ongoingLocks,this.socketManager);return this.ongoingLocks[a]=c,c}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class es{constructor(e,t,i,n,s){this.lockId=e,this.resourceId=t,this.clientRequestId=i,this.ongoingLocks=n,this.socketManager=s,this.released=!1,this.onReleaseSubject=new ct.ReplaySubject(1)}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}},t=this.socketManager.sendMessage(e),i=await(0,ct.firstValueFrom)((0,ct.race)((0,ct.from)(t.then(ts,ts)),this.socketManager.observeConnectionReady().pipe((0,ct.filter)(e=>!e),Nt(()=>!1))));if(this.onReleaseSubject.next(),!i)return t.catch(()=>{}),void this.onReleaseSubject.complete();try{await t}finally{this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}function ts(){return!0}class is{constructor(e,t){this.documentStore=e,this.destructManager=t,this.changeNotifier=new ct.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 ns{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t,i,n=!1){if(i||n)return new tn(e,$e(this.dataManager,"dataManager not found"),t,i,n?this.create(e,t):void 0);let s=this.documents.get(e);if(s)return s;s=new tn(e,$e(this.dataManager,"dataManager not found"),t);const{integrationId:r,collectionName:o}=Hi(e);this.documents.set(e,s);const a=this.getCollectionKey(r,o),c=this.documentsForCollection.get(a)||[];return this.documentsForCollection.set(a,c.concat(s)),s}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=Hi(e),n=Hi(t);bi(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class ss{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,i){const n=this.squidDocIdToDoc.get(e);if(n){const i=this.mergeDocuments(n,t),s=this.removeInternalProperties(i);this.squidDocIdToDoc.set(e,s)}else{const i=this.removeInternalProperties(t);this.squidDocIdToDoc.set(e,i)}if(i?.length){const t=this.squidDocIdToProjectedFields.get(e);if(void 0!==t)for(const e of i)t.add(e);else n||this.squidDocIdToProjectedFields.set(e,new Set(i))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const i=_i(e);for(const e of Object.keys(t)){const n=t[e],s=i[e];null===n||"object"!=typeof n||Array.isArray(n)||null===s||"object"!=typeof s||Array.isArray(s)?i[e]=n:i[e]=this.mergeDocuments(s,n)}return i}adoptMissingFields(e,t){const i=this.squidDocIdToDoc.get(e);if(!i)return;const n=Object.keys(t).filter(e=>"__ts__"!==e&&!(e in i));if(!n.length)return;const s=_i(i);for(const e of n)s[e]=t[e];this.squidDocIdToDoc.set(e,s);const r=this.squidDocIdToProjectedFields.get(e);if(r)for(const e of n)r.add(e)}deleteDocument(e){this.squidDocIdToDoc.delete(e),this.squidDocIdToProjectedFields.delete(e)}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=_i(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}hasSufficientData(e,t){if(!this.squidDocIdToDoc.has(e))return!1;const i=this.squidDocIdToProjectedFields.get(e);return void 0===i||!!t?.length&&t.every(e=>i.has(e))}group(e,t){return Object.values(Ti(e,e=>Oi(t.map(t=>yi(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(Le),{sortOrder:n,limitBy:s}=t,r=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;let a;if(s){const{limit:e,fields:t,reverseSort:i}=s,n=this.group(r,t);let c;c=i?n.map(t=>t.slice(-e)):n.map(t=>t.slice(0,e)),a=c.flat().slice(0,o)}else a=r.slice(0,o);return null!==t.projectFields&&void 0!==t.projectFields&&(a=a.map(e=>this.projectDocument(e,t.projectFields))),a}projectDocument(e,t){const i={};"__id"in e&&(i.__id=e.__id),"__docId__"in e&&(i.__docId__=e.__docId__);for(const n of t)if(n.includes(".")){const t=yi(e,n);void 0!==t&&Ii(i,n,t)}else n in e&&(i[n]=e[n]);return i}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;bi(this.squidDocIdToDoc,e,t),bi(this.squidDocIdToProjectedFields,e,t);const n=Hi(t),s=Ci(n.docId);this.saveDocument(t,{...i,...s,__docId__:n.docId})}countDocsUpTo(e,t,i){let n=0;for(const s of e){const e=this.squidDocIdToDoc.get(s);e&&this.compareSquidDocs(e,t,i)<=0&&n++}return n}findLastDoc(e,t){let i;for(const n of e)(!i||this.compareSquidDocs(n,i,t)>0)&&(i=n);return i}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:s}of i){const i=Ei(yi(e,n),yi(t,n));if(0!==i)return s?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class rs{constructor(e){this.rpcManager=e}async emit(e){const t={event:e};await this.rpcManager.post("events/emit",t)}}class os{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 as{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 cs{constructor(e,t,i,n,s){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.ownedJobs=new Set,n.onDestruct(async()=>{this.stopKeepAlive();const e=[...this.ownedJobs];this.ownedJobs.clear(),await Promise.all(e.map(e=>this.resolveJob(e,"failed",void 0,"Client shut down").catch(()=>{})))}),s.isPassiveMode||this.clientIdService.observeClientId().pipe((0,ct.distinctUntilChanged)(),(0,ct.skip)(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Li.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(t=>{const i=this.listeners[e];i&&(i.error(t),delete this.listeners[e])})})}async startJob(e){await this.rpcManager.post("job/startJob",{jobId:e}),this.ownedJobs.add(e),this.ensureKeepAlive()}async completeJob(e,t){await this.resolveJob(e,"completed",t)}async failJob(e,t){await this.resolveJob(e,"failed",void 0,t)}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 ct.ReplaySubject(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(i=>{t.error(i),delete this.listeners[e]}),(0,ct.firstValueFrom)(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe((0,ct.filter)(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,i=t.id,n=this.listeners[i];if(n){if("completed"===t.status)n.next(t.result);else if("failed"===t.status){const e=Object.assign(new Error(t.error||"Job failed"),{errorType:t.errorType});n.error(e)}else console.error("Unexpected job status:",t.status,"for jobId:",i);delete this.listeners[i]}}))}async resolveJob(e,t,i,n){try{await this.rpcManager.post("job/resolveJob",{jobId:e,status:t,result:i,error:n})}finally{this.ownedJobs.delete(e),this.ownedJobs.size||this.stopKeepAlive()}}ensureKeepAlive(){void 0===this.keepAliveHandle&&(this.keepAliveHandle=setInterval(()=>{if(!this.ownedJobs.size)return void this.stopKeepAlive();const e={jobIds:[...this.ownedJobs]};this.rpcManager.post("job/keepAlive",e).catch(e=>Li.debug("Job keep-alive failed:",e))},15e3))}stopKeepAlive(){void 0!==this.keepAliveHandle&&(clearInterval(this.keepAliveHandle),this.keepAliveHandle=void 0)}}class us{constructor(e,t,i){this.graphId=e,this.rpcManager=t,this.jobClient=i}async invoke(e={}){const t=qt();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),await this.jobClient.awaitJob(t)}async invokeAsync(e={}){const t=qt();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),t}async resume(e,t){const i=qt();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),await this.jobClient.awaitJob(i)}async resumeAsync(e,t){const i=qt();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),i}async getState(e){return this.rpcManager.post("langgraph/getState",{graphId:this.graphId,threadId:e})}async deleteThread(e){await this.rpcManager.post("langgraph/deleteThread",{graphId:this.graphId,threadId:e})}}class ls{constructor(e,t){this.rpcManager=e,this.jobClient=t}graph(e){return new us(e,this.rpcManager,this.jobClient)}}const ds="squid_mgmt_";function hs(e="n_"){return`${e}${Lt(10).toLowerCase()}`}const ps=e=>e();class gs extends Error{constructor(e,t,i,n,s){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=s}}const fs="1.0.497";async function ys(e){return ws({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage,abortSignal:e.abortSignal})}async function ms(e){return ws({...e,method:"GET",files:[],filesFieldName:""})}async function Is(e){return ws({...e,method:"PUT"})}async function bs(e){return ws({...e,method:"PATCH"})}async function Ss(e){return ws({...e,method:"DELETE",files:[],filesFieldName:""})}async function ws(e){const t=await async function({headers:e,files:t,filesFieldName:i,message:n,url:s,extractErrorMessage:r,method:o,abortSignal:a}){const c=new Headers(e);c.append(Ht.TRACE_ID,hs("c_")),c.append(Ht.CLIENT_VERSION,fs);const u={method:o,headers:c,body:void 0,signal:a};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",Ai(n)),u.body=e}else void 0!==n&&(c.append("Content-Type","application/json"),u.body=Ai(n));else"DELETE"===o&&void 0!==n&&(c.append("Content-Type","application/json"),u.body=Ai(n));try{const e=await fetch(s,u),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=vs(i);if(!r)throw new gs(i,e.status,s,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new gs(o,e.status,s,t,n)}const i=await e.text();return Li.debug(`received response from url ${s}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Li.debug(`Unable to perform fetch request to url: ${s}`,e),e}}(e);return t.body=vs(t.body),t}function vs(e){if(e){try{return Ci(e)}catch{}return e}}class _s{constructor(e){Qe(e.apiKey.startsWith(ds),`Invalid management API key format. Key must start with '${ds}'`),this.apiKey=e.apiKey,this.consoleRegion=e.consoleRegion}async createOrganization(e){return this.callApi("POST","organizations",e)}async createApplication(e){return this.callApi("POST","applications",e)}async deleteApplication(e){await this.callApi("DELETE",`applications/${e}`)}async renameOrganization(e){await this.callApi("PATCH",`organizations/${e.organizationId}`,{name:e.name})}async renameApplication(e){await this.callApi("PATCH",`applications/${e.appId}`,{name:e.name})}async callApi(e,t,i){const n=r(this.consoleRegion,"console",`openapi/iac/management/${t}`),s={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await ys({url:n,headers:s,message:i,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await bs({url:n,headers:s,message:i,extractErrorMessage:!0})).body:(await Ss({url:n,headers:s,message:i,extractErrorMessage:!0})).body}}class Ms{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=Kn(e),n=i.map(e=>`sendMutation_${Vi(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 Li.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}async deleteQuery(e){const t=`deleteQuery_${e.integrationId}_${e.collectionName}`;await this.lockManager.lock(t),await this.querySender.waitForAllQueriesToFinish();try{const t={query:e};return await this.rpcManager.post("mutation/deleteQuery",t)}catch(t){throw Li.debug("Error while deleting query results",{error:t,query:JSON.stringify(e,null,2)}),t}finally{this.lockManager.release(t)}}}class Es{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Ts{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,ct.filter)(e=>"userNotification"===e.type),(0,ct.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 ks={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Os{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!As.test(e)||e.length>=Cs);Qe(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},s=this.rpcManager.post("/observability/metrics",{metrics:[n]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==s),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(s)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...ks,...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,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const s=t-e;let r=t-Math.floor(s/i)*i;return r>e&&(r-=i),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const s=t-e;let r=e+Math.floor(s/i)*i;return r>=t&&(r-=i),r}(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],s=a[n]?.[0]||"";i.push(s)}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 s=e.groupByTags.indexOf(i);if(!(s<0))for(let e=0;e<t.length;e++){const i=t[e],r=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===s||e===n.tagValues[t])&&r.delete(n.tagValues[s])}if(0!==r.size)for(const e of r){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[s]=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];Qe(e>=r,()=>`Invalid first point time: ${e}`),Qe(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:s,u=Array.isArray(e.fn)?e.fn.map(c):[s];for(let e=r;e<=o;e+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(Qe(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 As=/^[a-zA-Z0-9_-]+$/,Cs=1e3;async function Ds(e,t,i=500,n){const s=Date.now(),r=e.paginate({pageSize:i,subscribe:!1});let o=0,a=0,c=await r.waitForData();for(n?.({pageIndex:a,documentCount:c.data.length,totalLoaded:o+c.data.length});;){for(const e of c.data)o++,await t(e.data);if(!c.hasNext)break;c=await r.next(),a++,n?.({pageIndex:a,documentCount:c.data.length,totalLoaded:o+c.data.length})}return{count:o,time:Date.now()-s}}async function Rs(e,t=500,i){const n=[],s=e.paginate({pageSize:t,subscribe:!1});let r=0,o=await s.waitForData();for(i?.({pageIndex:r,documentCount:o.data.length,totalLoaded:n.length+o.data.length});;){for(const e of o.data){const t=Hi(e.squidDocId),i=Ci(t.docId),s=t.integrationId===Me?i.__id:i;n.push(s)}if(!o.hasNext)break;o=await s.next(),r++,i?.({pageIndex:r,documentCount:o.data.length,totalLoaded:n.length+o.data.length})}return n}function Ns(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:s,integrationId:r}=i;let o=e.collection(s,r).query();return o=qs(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=qs(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:r}=i,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(n,r).query();l=qs(l,i),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),r&&o?u.grouped().dereference():r?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:i}=t,{collectionName:n,integrationId:s}=Fs(i[0]),r=i.map(t=>Ns(e,t));return e.collection(n,s).or(...r)}(e,t)}}function qs(e,t){const{conditions:i,limit:n,sortOrder:s}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");if("docIds"in t)throw new Error("DocId conditions are not supported in query serialization.");const{fieldName:i,operator:n,value:s}=t;e.where(i,n,s)}e.limit(n);for(const{fieldName:t,asc:i}of s)e.sortBy(t,i);return e}function Fs(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 Fs(e.queries[0])}}class js{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 jn(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[Vi(e.__docId__,i,t)])}}function Ps(e,t){return lt(function(i,n){var s=0;i.subscribe(Dt(n,function(i){return e.call(t,i,s++)&&n.next(i)}))})}class xs{constructor(e,t,i){this.rpcManager=e,this.destructManager=t,this.webSocketConnectionReady$=i,this.safeToSendQueriesToServer=new ct.BehaviorSubject(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new ct.BehaviorSubject(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new ct.Subject,i=(0,ct.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.gateForCurrentBatch().subscribe(()=>{this.processQueryBatch()})},0),i)}gateForCurrentBatch(){return this.pendingQueryRequests.some(({queryRequest:e})=>e.subscribe)&&this.webSocketConnectionReady$?(0,ct.combineLatest)([this.safeToSendQueriesToServer,this.webSocketConnectionReady$]).pipe(Ps(([e,t])=>e&&t),(0,ct.take)(1),Nt(()=>!0)):this.safeToSendQueriesToServer.pipe(Ps(Boolean),(0,ct.take)(1))}async sendQueryDirect(e){const t=await this.rpcManager.post("query/batchQueries",[e]),i=t.errors[e.clientRequestId];if(i)throw i;return t.results[e.clientRequestId]}async waitForAllQueriesToFinish(){return(0,ct.firstValueFrom)(this.inflightQueriesCount.pipe(Ps(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,s=i.errors[e],r=i.results[e];s?n.error(s):n.next(r)}}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 Bs={d:(e,t)=>{for(var i in t)Bs.o(t,i)&&!Bs.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Ls(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 Us(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Qs(e,t);if(0===t.length)return Ls("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 s=e;for(let e=0;e<t.length-1&&void 0!==s;e++){const i=t[e];Ls(!Array.isArray(s)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),s=s[i],Ls(void 0===s||"object"==typeof s&&null!==s,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===s?"<null>":typeof s}'`)}const r=t[t.length-1];return Ls(!Array.isArray(s)||n(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===i?e:$s(e,t,i)}(e,t.path,t.value);case"delete":return Qs(e,t.path);case"batch":return t.actions.reduce((e,t)=>Us(e,t),e)}}function Qs(e,t){Ls(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const s=t[n];if(i=i[s],void 0===i)return e;Ls("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:$s(e,t,void 0)}function $s(e,t,i){function n(e,i){Ls(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];Ls(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(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===i?n(r,o):r[o]=i,s}function Gs(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(...Gs(t,"as-is"));return"unique-and-sorted"===t?Ks(i):i}function Hs(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 Vs(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 Ks(e){const t=Vs(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];n.length===r.length&&Hs(n,r)&&(i[s]=void 0,e++)}}return i.filter(e=>void 0!==e)}const Ws=(zs={Observable:()=>ct.Observable,Subject:()=>ct.Subject},Js={},Bs.d(Js,zs),Js);var zs,Js;const Ys=(Xs={filter:()=>Ps,map:()=>Nt},Zs={},Bs.d(Zs,Xs),Zs);var Xs,Zs;class er{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,s=t(n.value,i);if(s!==er.StopFillToken){this._setNodeValue(n,s,!1);for(let r=0;r<e.length;r++){const o=e[r];i.push(o);let a=n.children.get(o);if(s=t(null==a?void 0:a.value,i),s===er.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,s,!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[s,r]of t.children){if(n.push(s),!this._visitDfs(e,r,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 s=t.children.get(n);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,s)),t=s}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))}}er.StopFillToken=Symbol("Trie.StopFillToken");class tr extends Ws.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class ir{constructor(e){this.rootState=e,this.observersTrie=new er,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,Ys.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=Us(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Gs(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=Ks([...t,...i]),s=new er;for(const e of n)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),s=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new er;for(const e of t)null==n||n.set(e,!0);return new Ws.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new tr);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===i;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,Ys.filter)(({action:e})=>void 0===n||Gs(e,"as-is").some(e=>!n.get(e))),(0,Ys.map)(({action:t,value:i,oldValue:n})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const i=Gs(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=Vs(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++)Hs(t[s],n)&&(i[s]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>Hs(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.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 nr(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,s=e.length-1){if(s<n)return-1;const r=Math.trunc((n+s)/2);return 0===i(t,e[r])?r:i(t,e[r])>0?nr(e,t,i,r+1,s):nr(e,t,i,n,r-1)}function sr(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==nr(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 rr(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=nr(e,t,i);n>-1&&e.splice(n,1)}class or{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,i,n,s,r,o,a){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=s,this.querySender=r,this.socketManager=o,this.lockManager=a,this.onOrphanDocuments=new ct.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new cr,this.queryResultsSubject=new ct.Subject,this.detachedRecords=new Set,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientTooOld().subscribe(()=>{this.invalidateOngoingQueryRegistrations()}),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 $e(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e,t){const i=this.ongoingQueries.get(e);i?.gotInitialResponse&&this.removeClientRequestIdMapping(e),i&&(i.gotInitialResponse=!0,i.isInFlight=!1,t&&i.subscribe&&i.query.limit>0&&this.setLimitWindow(i,t))}findQueriesForDocument(e,t){const{collectionName:i,integrationId:n}=Hi(t),s=this.queryMappingManager.getMapping(i,n);return s?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,s]of Object.entries(e.conditional||{})){const e=Ci(i);let r;if(Yi(e))if(e.fieldName===Fe)r=en(e.value,t,e.operator,yi);else{const i=yi(t,e.fieldName)??null;r=Ki(e.value,i,e.operator)}else r=Xi(e)?Zi(e,t,yi):ar(e,t);if(r)for(const e of s)n.set(e,(n.get(e)||0)+1)}for(const[t,s]of n.entries())s>=e.queriesMetadata[t].condCount&&i.push(t);return i}(s,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):[]),s=new Set([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.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[...s]}addDocToQuery(e,t){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)}removeDocFromQuery(e,t){const i=this.localDocumentToClientRequestIds.get(e);let n=!i;i&&(i.delete(t),i.size||(this.localDocumentToClientRequestIds.delete(e),n=!0));const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n&&this.documentStore.deleteDocument(e)}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,s=this.documentStore.sortAndLimitDocs(n,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(s,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=$e(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case zn.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+100?zn.ENABLED:zn.DISABLED;break;case zn.DISABLED:break;case zn.ENABLED:{const{limitWindowEnd:t,query:i}=e;if((t?this.documentStore.countDocsUpTo(n,t,i.sortOrder):n.size)<i.limit+20){e.limitUnderflowState=zn.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}}e.dataSubject.next(s)}for(const e of t){const t=this.collectAllObservables(e);$e(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new jn(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,s,r,o){s&&this.socketManager.notifyWebSocketIsNeeded();const a=Object.keys(i).length>0;return s||a||!this.detachedQueryExecutor||this.lockManager.canGetLock(Wn)?(0,ct.defer)(()=>{const a=this.createOngoingQueryGraph(e,t,i,n,s,!0,{},o);r&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new ct.ReplaySubject(1);const c=a.allObservables.pipe((0,ct.switchMap)(e=>(0,ct.combineLatest)(e).pipe(Nt(e=>this.joinResults(e,n,a)))),Ps(()=>this.allOngoingQueriesGotInitialResult(a)),(0,ct.startWith)(void 0),(0,ct.pairwise)(),Ps(([e,t])=>!wi(e,t)),Nt(([,e])=>e),s?(0,ct.tap)():(0,ct.take)(1),(0,ct.finalize)(()=>{a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a),a.allObservables?.complete()})),u=this.collectAllObservables(a);return a.allObservables.next(u),c}).pipe((0,ct.share)()):(0,ct.from)(this.detachedQueryExecutor(e)).pipe(Nt(e=>e.map(e=>{const i={[t]:e};return this.detachedRecords.add(i),i})))}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 jn(e.query);for(const i of this.ongoingQueries.values()){if(e===i)return;if(this.isValidParent(i)&&t.isSubqueryOfQuery(i.query))return i}}setLimitWindow(e,t){const{limit:i,sortOrder:n}=e.query,s=this.documentStore.findLastDoc(t,n),r=void 0!==s&&n.length>0&&n.every(({fieldName:e})=>void 0!==yi(s,e));e.limitWindowEnd=r?s:void 0,e.limitUnderflowState=t.length===i+100?zn.ENABLED:zn.DISABLED}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const i=[];for(const n of t){const t=$e(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=Ji(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,ct.finalize)(async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,ct.firstValueFrom)((0,ct.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Ps(e=>0===e)))),this.queryMappingManager.removeQuery(i),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)}),Ps(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,i,n,s,r,o={},a){if(o[t])return o[t];const c=r&&a?a:this.clientIdService.generateClientRequestId(),u=[],l={clientRequestId:c,activated:r,alias:t,query:e,subscribe:s,dataSubject:new ct.BehaviorSubject(null),supportedQueries:u,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new ct.BehaviorSubject(0),queryRegistered:new ct.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:s?zn.UNKNOWN:zn.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(c,l),o[t]=l;for(const[e,r]of Object.entries(n)){const a=r.leftAlias;if(a!==t&&e!==t)continue;const c=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(i[c],c,i,n,s,!1,o);e.joinCondition=r,u.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(i[c],c,i,n,s,!1,o)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Ps(Boolean),Nt(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 s=n[i.alias].map(e=>({[i.alias]:e}));const r=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<r.length;e++){const i=r[e].alias;o.has(i)||(o.add(i),s=this.join(s,i,n[i],t[i]))}return s}join(e,t,i,n){if(!e.length)return e;const s=Object.keys(e[0]);if(!n||!s.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);r.has(t)||r.set(t,[]),$e(r.get(t)).push(e)}),e.flatMap(e=>{const i=r.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=$e(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){const i=$e(t.joinCondition),n=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const s=$e(t.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===t.alias),r=new Set(e.map(e=>e[i.left]??null));for(const e of s)e.query.conditions.filter(Yi).filter(e=>e.fieldName===i.right).forEach(e=>{r.delete(e.value)});if(0===r.size)return!1;const o=_i(n);o.conditions=o.conditions.filter(e=>!Yi(e)||e.fieldName!==i.right),[...r].forEach(e=>{o.conditions.push({fieldName:i.right,operator:"==",value:e})});const a={...t,query:o,activated:!0,gotInitialResponse:!1,dataSubject:new ct.BehaviorSubject(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(a),this.ongoingQueries.set(a.clientRequestId,a),$e(t.supportingOngoingQuery).supportedQueries.push(a),this.sendQueryToServerOrUseParentQuery(a),!0}{if(t.activated=!0,n.conditions.filter(Yi).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const s=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return s.length?(n.conditions.push(...s),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=$e(t.shift());t.push(...e.supportedQueries||[]),await(0,ct.firstValueFrom)(e.unsubscribeBlockerCount.pipe(Ps(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,s=Ji(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,s),this.ongoingQueries.set(n,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new jn(e.query);e.limitWindowEnd=void 0,t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,ct.firstValueFrom)(t.queryRegistered.pipe(Ps(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 s=(0,ct.race)(e.queryRegistered.pipe(Ps(Boolean),(0,ct.delay)(2e3),(0,ct.take)(1)),this.destructManager.observeIsDestructing().pipe((0,ct.take)(1)));t.dataSubject.pipe((0,ct.takeWhile)(()=>!e.done),(0,ct.takeUntil)(s),Ps(Boolean),(0,ct.tap)(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),Nt(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(Vi(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+100: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()):(Li.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}invalidateOngoingQueryRegistrations(){for(const e of this.ongoingQueries.values())e.queryRegistered.next(!1)}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=>{bi(this.localDocumentToClientRequestIds,t,e[t])})}}function ar(e,t){for(const i of e.fields){const e=yi(t,i.fieldName)??null;if(Ki(i.value,e,i.operator))return!0;if(Ki(i.value,e,"!="))return!1}return!1}class cr{constructor(){this.stateService=new ir({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const s of e.conditions){if(Yi(s)&&["=="].includes(s.operator)){const e=Di(s.fieldName);n.has(e)||(i++,n.add(e))}else i++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];sr(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];sr(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),s=[...this.stateService.get(n)||[]];rr(s,e),s.length?this.stateService.set(n,s):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];rr(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,Oi(i))];var i}}class ur{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,ct.lastValueFrom)((0,ct.combineLatest)(t).pipe((0,ct.filter)(e=>!e.includes(!0)),(0,ct.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=$e(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){Qe(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new ct.BehaviorSubject(!0)}}class lr{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 hr(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const dr="subscriptionMutex";class hr{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new ct.Subject,this.subscriberCount=0,this.lockManager=new ur}async produce(e){await this.lockManager.lock(dr);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(dr)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),(0,ct.defer)(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,ct.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(dr);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 ct.Subject}finally{this.lockManager.release(dr)}}async performUnsubscribe(){await this.lockManager.lock(dr);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(dr)}}}class pr{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,ct.firstValueFrom)((0,ct.interval)(10).pipe((0,ct.filter)(()=>this.attemptConsume()),(0,ct.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}class gr{constructor(e,t,i,n,s,r){this.region=e,this.appId=t,this.authManager=s,this.clientIdService=r,this.staticHeaders={},this.onGoingRpcCounter=new ct.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 pr(60*o,5),ai:new pr(20*o,5),secret:new pr(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,ct.firstValueFrom)(this.onGoingRpcCounter.pipe((0,ct.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",s={},r){return(await this.rawPost(e,t,i,n,!0,s,r)).body}async rawPost(e,t,i=[],n="files",s=!0,o={},a){return this.runRawRequest(e,o,async o=>{Li.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await ys({url:c,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s,abortSignal:a})})}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){return this.runRawRequest(e,{},async n=>{let s=e.startsWith("http://")||e.startsWith("https://")?e:r(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))}),s+=`?${e.toString()}`}return Li.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await ms({url:s,headers:n,extractErrorMessage:i})})}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="files",s=!0){return this.runRawRequest(e,{},async o=>{Li.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await Is({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})})}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="files",s=!0){return this.runRawRequest(e,{},async o=>{Li.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await bs({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})})}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){return this.runRawRequest(e,{},async n=>{Li.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const s=e.startsWith("http://")||e.startsWith("https://")?e:r(this.region,this.appId,e);return await Ss({url:s,headers:n,message:t,extractErrorMessage:i})})}async runRawRequest(e,t,i){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),s={...this.staticHeaders,...n,...t};return await i(s)}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?$e(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?$e(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):$e(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}const fr="This operation is not available in passive mode. Use active mode for real-time features.";function yr(e){Qe(!e.isPassiveMode,fr)}class mr{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 Ir(){}const br="undefined"!=typeof process&&process.versions?.node?i(86):Bi().WebSocket;class Sr{constructor(e,t,i,n=ps,s,r,o){this.clientIdService=e,this.region=t,this.appId=i,this.messageNotificationWrapper=n,this.destructManager=s,this.authManager=r,this.runtimeOptions=o,this.webSocketObserver=new ct.Subject,this.allMessagesObserver=new ct.Subject,this.connectionReady=new ct.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new ct.Subject,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new ct.BehaviorSubject(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe((0,ct.filter)(Boolean),(0,ct.take)(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe((0,ct.skip)(1),(0,ct.filter)(e=>!e),(0,ct.switchMap)(()=>(0,ct.race)((0,ct.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,ct.filter)(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Li.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Li.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe((0,ct.filter)(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe((0,ct.filter)(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?Li.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Li.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Li.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Li.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,ct.distinctUntilChanged)())}async awaitConnectionReady(){yr(this.runtimeOptions),await(0,ct.firstValueFrom)(this.observeConnectionReady().pipe((0,ct.filter)(Boolean)))}notifyWebSocketIsNeeded(){yr(this.runtimeOptions),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&&(Li.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.notifyWebSocketIsNeeded();try{await(0,ct.firstValueFrom)((0,ct.race)(this.connectionReady.pipe((0,ct.filter)(Boolean)),(0,ct.timer)(12e4).pipe((0,ct.tap)(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))).pipe((0,ct.takeUntil)(this.destructSubject)))}catch(e){if(this.destructManager.isDestructing)return;throw e}const t=await this.authManager.getToken();if(this.connectionReady.value)try{Qe(this.socket,"Socket is undefined in sendMessageAsync");const i=Ai({message:e,authToken:t});Li.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(Ai({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=r(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Li.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,s=1;const r={connected:!1,closeCalled:!1,open(){i=new(br?.WebSocket??br)(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.")}:Ir,i.onopen=function(e){r.connected=!0,(t.onopen||Ir)(e),n=0},i.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return Li.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Ir)(e),void r.reconnect(e);(t.onclose||Ir)(e)},i.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||Ir)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&n++<i?s=setTimeout(function(){(t.onreconnect||Ir)(e),Li.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||Ir)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,i.close(e,t)}catch(e){}}};return r.open(),r}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Li.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Li.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Li.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Li.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Li.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 Li.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=Ci(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Li.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new ct.Subject;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe((0,ct.tap)(e=>t.push(e)),(0,ct.debounceTime)(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await(0,ct.firstValueFrom)((0,ct.timer)(0)),this.connectionReady.next(!1),await(0,ct.firstValueFrom)((0,ct.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function wr(e){var t,i;i="Invalid application ID",Qe(function(e){return"string"==typeof e}(t=e),()=>He(i,"Not a string",t));const n=e.split("-");Qe(n.length<4,`Invalid application ID: ${e}`);const[s,r,o]=n;return{appId:s,environmentId:r??"prod",squidDeveloperId:o}}function vr(e,t){return`${wr(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function _r(e,t,i){return`${vr(e,t)}${i?`-${i}`:""}`}function Mr(e){const t=wr(e);return vr(t.appId,t.environmentId)}class Er{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 Tr{constructor(e,t,i,n,s){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n,this.consoleRegion=s}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}async aiSearch(e,t,i){return await this.rpcManager.post("web/aiSearch",{query:e,allowedDomains:i},[],"files",{},t)}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e){Qe(this.apiKey,"API key is required to create a short URL");const t="string"==typeof e?{url:e}:e,i={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shorten",i,"create short URL","json")}async createShortUrls(e){Qe(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,i={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shortenMany",i,"create short URLs","json")}async deleteShortUrl(e){Qe(this.apiKey,"API key is required to delete a short URL");const t={id:e,appId:this.appId};await this.postShortUrlApi("delete",t,"delete short URL","ignore")}async deleteShortUrls(e){Qe(this.apiKey,"API key is required to delete a short URL");const t={ids:e,appId:this.appId};await this.postShortUrlApi("deleteMany",t,"delete short URLs","ignore")}async postShortUrlApi(e,t,i,n){const s=o(this.region,this.consoleRegion,`openapi/sqd/${e}`),r=await fetch(s,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(t)});if("ignore"===n)return void Qe(r.ok,`Failed to ${i} (${r.status}): ${r.statusText}`);const a=await r.text();return Qe(r.ok,`Failed to ${i} (${r.status}): ${a}`),JSON.parse(a)}}class kr{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:n={},body:s,files:o=[]}=t,a=await this.rpcManager.getAuthHeaders(),c={...this.rpcManager.getStaticHeaders(),...a,...i};let u=r(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 d;if(l.append(Ht.TRACE_ID,hs("c_")),l.append(Ht.CLIENT_VERSION,fs),o&&o.length>0){const e=new FormData;for(const t of o)e.append("file",t,t.name);s&&"object"==typeof s&&Object.entries(s).forEach(([t,i])=>{e.append(t,String(i))}),d=e}else l.append("Content-Type","application/json"),d=Ai(s||{});const h=await fetch(u,{method:"POST",headers:l,body:d}),p={};if(h.headers.forEach((e,t)=>{p[t]=e}),!h.ok){const e=await h.text();let t;try{t=JSON.parse(e)}catch{t=e}const i="string"==typeof t?t:t?.message||h.statusText;throw new gs(i,h.status,u,p,t)}const g=await h.text();let f;try{f=JSON.parse(g)}catch{f=g}return f}getWebhookUrl(e){return r(this.region,this.appId,e?`webhooks/${encodeURIComponent(e)}`:"webhooks")}}class Or{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Xn,Qe(e.appId,"APP_ID_MUST_BE_PROVIDED"),this.runtimeOptions={isPassiveMode:e.isPassiveMode??!1};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=_r(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Ui(this.destructManager),Li.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new gi(e.apiKey,e.authProvider),this.socketManager=new Sr(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new gr(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Ts(this.socketManager,this.rpcManager),this.jobClient=new cs(this.socketManager,this.rpcManager,this.clientIdService,this.destructManager,this.runtimeOptions),this.langGraphClient=new ls(this.rpcManager,this.jobClient),this.backendFunctionManager=new Pi(this.rpcManager),this.aiClient=new di(this.socketManager,this.rpcManager,this.jobClient,this.clientIdService,this.backendFunctionManager,()=>this.metricAnnotations),this.apiClient=new pi(this.rpcManager),this.eventsClient=new rs(this.rpcManager),this.documentStore=new ss,this.lockManager=new ur,this.distributedLockManager=new Zn(this.socketManager,this.destructManager),this.documentIdentityService=new is(this.documentStore,this.destructManager),this.documentReferenceFactory=new ns(this.documentIdentityService),this.querySender=new xs(this.rpcManager,this.destructManager,this.socketManager.observeConnectionReady()),this.observabilityClient=new Os(this.rpcManager),this.schedulerClient=new mr(this.rpcManager),this._appId=i,this.querySubscriptionManager=new or(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new js(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new Ms(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new sn(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService,n),this.dataManager=new Jn(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new fn(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new kr(this.rpcManager,e.region,i),this.nativeQueryManager=new Es(this.rpcManager),this._connectionDetails=new yn(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new lr(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new at(this.rpcManager,this.options.region,Mr(i),this.options.consoleRegion),this.webClient=new Tr(this.rpcManager,this.options.region,Mr(i),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}get isDestructed(){return this.destructManager.isDestructing}static getInstance(e){const t=Oi(e);let i=Or.squidInstancesMap[t];return i||(i=new Or(e),Or.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(Or.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Me){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)}getWebhookUrl(e){return this._validateNotDestructed(),this.webhookManager.getWebhookUrl(e)}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",s="GET"){const r={type:"elasticsearch",index:t,endpoint:n,method:s,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(r)}ai(){return this._validateNotDestructed(),this.aiClient}setMetricAnnotations(e){this.metricAnnotations=e?{...e}:void 0}job(){return this._validateNotDestructed(),this.jobClient}langGraph(e){return this._validateNotDestructed(),this.langGraphClient.graph(e)}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 Er(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new os(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new as(this.rpcManager)}events(){return this._validateNotDestructed(),this.eventsClient}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,i){const n=await this.acquireLock(e,i);try{return await t(n)}finally{n.release()}}queue(e,t=Ee){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Or.squidInstancesMap).find(([,e])=>e===this);e&&delete Or.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)=>r(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>_r(e,t,i)}}_validateNotDestructed(){Qe(!this.destructManager.isDestructing,"The client was already destructed.")}}const Ar=exports;for(var Cr in n)Ar[Cr]=n[Cr];n.__esModule&&Object.defineProperty(Ar,"__esModule",{value:!0})})();
|