@squidcloud/client 1.0.502 → 1.0.504

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.
Files changed (62) hide show
  1. package/dist/cjs/index.js +1 -1
  2. package/dist/esm/index.js +1 -1
  3. package/dist/internal-common/src/public-types/ai-agent.public-types.d.ts +28 -2
  4. package/dist/internal-common/src/public-types/ai-common.public-types.d.ts +3 -3
  5. package/dist/internal-common/src/public-types/ai-knowledge-base.public-types.d.ts +30 -8
  6. package/dist/internal-common/src/public-types/ai-query.public-types.d.ts +5 -0
  7. package/dist/internal-common/src/public-types/ai-voice.public-types.d.ts +16 -0
  8. package/dist/internal-common/src/public-types/context.public-types.d.ts +2 -0
  9. package/dist/internal-common/src/public-types/extraction.public-types.d.ts +1 -1
  10. package/dist/internal-common/src/public-types/integration.public-types.d.ts +1 -1
  11. package/dist/internal-common/src/public-types/langgraph.public-types.d.ts +86 -0
  12. package/dist/internal-common/src/public-types/session.public-types.d.ts +82 -0
  13. package/dist/typescript-client/src/agent/ai-agent-client.types.d.ts +4 -4
  14. package/dist/typescript-client/src/ai-knowledge-base/ai-knowledge-base-client-reference.d.ts +1 -1
  15. package/dist/typescript-client/src/index.d.ts +1 -0
  16. package/dist/typescript-client/src/langgraph-client.d.ts +23 -1
  17. package/dist/typescript-client/src/public-types.d.ts +1 -0
  18. package/dist/typescript-client/src/session-client.d.ts +21 -0
  19. package/dist/typescript-client/src/squid.d.ts +12 -0
  20. package/dist/typescript-client/src/version.d.ts +1 -1
  21. package/package.json +1 -1
  22. package/dist/internal-common/src/ai/system-openai-compatible.d.ts +0 -35
  23. package/dist/internal-common/src/metric-name.d.ts +0 -5
  24. package/dist/internal-common/src/public-types-backend/api-call.public-context.d.ts +0 -30
  25. package/dist/internal-common/src/public-types-backend/mutation.public-context.d.ts +0 -161
  26. package/dist/internal-common/src/public-types-backend/native-query.public-context.d.ts +0 -75
  27. package/dist/internal-common/src/public-types-backend/query.public-context.d.ts +0 -193
  28. package/dist/internal-common/src/types/ai-agent.types.d.ts +0 -304
  29. package/dist/internal-common/src/types/ai-knowledge-base.types.d.ts +0 -798
  30. package/dist/internal-common/src/types/ai-matchmaking.types.d.ts +0 -19
  31. package/dist/internal-common/src/types/backend-function.types.d.ts +0 -1
  32. package/dist/internal-common/src/types/communication.types.d.ts +0 -1
  33. package/dist/internal-common/src/types/document.types.d.ts +0 -1
  34. package/dist/internal-common/src/types/file.types.d.ts +0 -6
  35. package/dist/internal-common/src/types/headers.types.d.ts +0 -45
  36. package/dist/internal-common/src/types/management-api-key.types.d.ts +0 -92
  37. package/dist/internal-common/src/types/mutation.types.d.ts +0 -1
  38. package/dist/internal-common/src/types/notification.types.d.ts +0 -19
  39. package/dist/internal-common/src/types/observability.types.d.ts +0 -296
  40. package/dist/internal-common/src/types/query.types.d.ts +0 -21
  41. package/dist/internal-common/src/types/secret.types.d.ts +0 -7
  42. package/dist/internal-common/src/types/socket.types.d.ts +0 -1
  43. package/dist/internal-common/src/types/stage.d.ts +0 -9
  44. package/dist/internal-common/src/types/time-units.d.ts +0 -1
  45. package/dist/internal-common/src/types/url-shortener.types.d.ts +0 -45
  46. package/dist/internal-common/src/utils/array.d.ts +0 -7
  47. package/dist/internal-common/src/utils/connector-path-status.d.ts +0 -27
  48. package/dist/internal-common/src/utils/e2e-test-utils.d.ts +0 -2
  49. package/dist/internal-common/src/utils/file-utils.d.ts +0 -2
  50. package/dist/internal-common/src/utils/global.utils.d.ts +0 -1
  51. package/dist/internal-common/src/utils/http-utils.d.ts +0 -15
  52. package/dist/internal-common/src/utils/http.d.ts +0 -4
  53. package/dist/internal-common/src/utils/integration-access-tokens.d.ts +0 -15
  54. package/dist/internal-common/src/utils/lock.manager.d.ts +0 -14
  55. package/dist/internal-common/src/utils/metric-utils.d.ts +0 -4
  56. package/dist/internal-common/src/utils/metrics.types.d.ts +0 -7
  57. package/dist/internal-common/src/utils/object.d.ts +0 -93
  58. package/dist/internal-common/src/utils/serialization.d.ts +0 -30
  59. package/dist/internal-common/src/utils/squid.constants.d.ts +0 -3
  60. package/dist/internal-common/src/utils/trace-id-generator.d.ts +0 -1
  61. package/dist/internal-common/src/utils/validation.d.ts +0 -21
  62. package/dist/internal-common/src/websocket.impl.d.ts +0 -26
package/dist/esm/index.js CHANGED
@@ -1 +1 @@
1
- import*as e from"ws";import{BehaviorSubject as t,NEVER as n,Observable as i,ReplaySubject as s,Subject as r,auditTime as o,combineLatest as a,combineLatestWith as c,concatMap as u,defaultIfEmpty as l,defer as d,delay as h,distinctUntilChanged as p,filter as g,finalize as f,first as y,firstValueFrom as m,from as b,interval as I,lastValueFrom as w,map as v,of as S,pairwise as M,race as k,share as T,skip as _,startWith as E,switchAll as D,switchMap as C,take as O,takeUntil as q,takeWhile as A,tap as R,timer as N}from"rxjs";var j={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0});const r=n(642);t.default=r.PromisePool,s(n(273),t),s(n(642),t),s(n(837),t),s(n(426),t),s(n(858),t),s(n(172),t)},837(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class n 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=n},234(e,t,n){t.PromisePoolExecutor=void 0;const i=n(642),s=n(172),r=n(837),o=n(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(i.PromisePool.notRun)),this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=i.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 n=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(n)}).catch(async i=>{await this.handleErrorFor(i,e,t),this.removeActive(n)}).finally(()=>{this.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),this.runOnTaskFinishedHandlers(e)});this.tasks().push(n),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[n,i]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),n()]).finally(i)}createTaskTimeout(e){let t;return[async()=>new Promise((n,i)=>{t=setTimeout(()=>{i(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,n){if(this.shouldUseCorrespondingResults()&&(this.results()[n]=i.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,n){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const i=n(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 i.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 n extends Error{}t.StopThePromisePoolError=n},172(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class n 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=n},220(t){t.exports=e}};const F={};function x(e){const t=F[e];if(void 0!==t)return t.exports;const n=F[e]={exports:{}};return j[e].call(n.exports,n,n.exports,x),n.exports}function B(e,t,n,i,s){let r="https",o=`${i||t}.${s||e}.${new URL("https://squid.cloud").host}`,a="";/^local/.test(e)&&(r="http",a="8000",/android$/.test(e)?o="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(o="localhost"));const c=r+"://"+o+(a?`:${a}`:""),u=n.replace(/^\/+/,"");return u?`${c}/${u}`:c}function P(e,t,n=""){return B(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",n)}x.d=(e,t)=>{if(Array.isArray(t))for(var n=0;n<t.length;){var i=t[n++],s=t[n++];x.o(e,i)?0===s&&n++:0===s?Object.defineProperty(e,i,{enumerable:!0,value:t[n++]}):Object.defineProperty(e,i,{enumerable:!0,get:s})}else for(var i in t)x.o(t,i)&&!x.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},x.o=(e,t)=>Object.hasOwn(e,t);class U{constructor(e,t,n,i){this.rpcManager=e,this.iacBaseUrl=P(t,i,`openapi/iac/applications/${n}/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 L={sharepoint:{functionName:"getSharePointPathStatus",buildArgs:(e,t)=>[{integrationId:e,path:t}]}},Q="Agent Response",$="Accessing Knowledge Base",G="Calling AI Function",H="AI Function Result",K="Inspecting Knowledge Base Metadata",W="Querying Knowledge Base Graph",V="Searching Knowledge Base Text",J="Querying Spreadsheet",z="AI_PROVIDER_ERROR",Y=["user","ai"],X=["email","phoneNumber","creditCard","ssn","iban","passport"],Z="gpt-6-luna",ee="ai-agent-connection-event",te=["cohere","voyage","none"],ne=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","openai-compatible","grok","stability","voyage","mistral","textract","azure_document_intelligence","vertex","external"],ie=["openai","gemini","anthropic","grok"];function se(e){return ie.includes(e)}const re=["openai","anthropic","gemini"],oe=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-luna","gpt-6.1-sol"],ae=["gemini-3.1-pro","gemini-3.8-flash","gemini-3.5-flash-lite"],ce=["grok-4.6","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],ue=["claude-fable-5","claude-fable-5-1","claude-haiku-4-5-20251001","claude-opus-5-5","claude-sonnet-5-5"],le=[...oe,...ue,...ae,...ce];function de(e){return le.includes(e)}const he=["text-embedding-3-small"],pe=["voyage-3-large","voyage-4-large","voyage-4"],ge=["titan-embed-text-v2"],fe=[...he,...pe,...ge];function ye(e){return fe.includes(e)}function me(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const be=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],Ie=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],we=["tts-1","tts-1-hd","gpt-4o-mini-tts"],ve=[...Ie,...we],Se=["stable-diffusion-core"],Me=["flux-pro-1.1","flux-kontext-pro"],ke=[...be,...Se,...Me],Te=[...Ie],_e=[...we],Ee=["mp3","opus","aac","flac","wav","pcm"],De=["vendor","connector","custom"];function Ce(e){return void 0!==e.integrationId&&void 0!==e.dimensions?{integrationId:e.integrationId,model:e.modelId,dimensions:e.dimensions}:e.modelId}function Oe(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const qe=["pod","worker"],Ae=["postgres","mongoAtlas"],Re=["none","enforced"],Ne="folderPath",je="filename",Fe={name:Ne,dataType:"string",required:!1,llmExtraction:!1},xe=104857600,Be=524288e3,Pe=["contextual","basic"],Ue=["economy","auto","fast"],Le=["twilio","openai"],Qe=["phrase","agent"],$e="ai-voice-session-event",Ge=["secret","regular"];function He(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Ke=["dev","prod"],We="built_in_agent",Ve=["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"],Je={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},ze="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"],Xe=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","snowflake","elasticsearch","legend"],Ze=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id","azure-entra-id"],et=["auth0","azure-entra-id","azure-entra-external-id"],tt=["graphql"],nt=["api"],it=["data","api","graphql"],st="built_in_db",rt="built_in_queue",ot="built_in_storage";function at(e){return!1===e.enabled}const ct=[st,rt,ot];function ut(e){return ct.includes(e)}const lt=["squid_functionExecution_count","squid_functionExecution_time"],dt=["sum","max","min","average","median","p95","p99","count"],ht=["user","squid"],pt=["align-by-start-time","align-by-end-time"],gt=["return-no-result-groups","return-result-group-with-default-values"],ft="__docId__",yt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],mt=[...yt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],bt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],It=["CONNECTED","DISCONNECTED","REMOVED"];function wt(e){return null!=e}let vt=e=>new Error(e);function St(e,t,...n){e||function(e,...t){const n=kt(e);if("object"==typeof n)throw n;throw vt(n||"Assertion error",...t)}(t,...n)}function Mt(e,t,...n){return St(e,t,...n),e}function kt(e){return void 0===e?"":"string"==typeof e?e:e()}function Tt(e,t,n){const i=kt(e);if("object"==typeof i)throw i;return`${i?`${i}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(n)}`}const _t="analyzeCode",Et=["claude-code","codex"],Dt=["reuse","recreate"],Ct=["read-only","write"],Ot=["github","bitbucket"],qt=["github","bitbucket"];function At(e){const t=function(e){const t=new Set,n=new Set;for(const i of e){St(Number.isSafeInteger(i.id)&&i.id>0,"GITHUB_REPOSITORY_ID_INVALID"),St(!t.has(i.id),"GITHUB_REPOSITORY_IDS_MUST_BE_UNIQUE"),t.add(i.id),St(Nt(i.fullName),"GITHUB_REPOSITORY_NAME_INVALID");const e=i.fullName.toLowerCase();St(!n.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),n.add(e),St(i.defaultBranch.trim(),"GITHUB_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),jt(i.cloneUrl,i.fullName,!0),jt(i.htmlUrl,i.fullName,!1)}return e}(e.repositories??[]),n=0===t.length?e.repository:void 0,i=t.map(e=>e.fullName);St(t.length>0||n,"GITHUB_REPOSITORIES_REQUIRED"),St(t.length<=20,"GITHUB_REPOSITORY_LIMIT_EXCEEDED");const s=e.defaultRepository??i[0]??n;return St(s,"GITHUB_DEFAULT_REPOSITORY_REQUIRED"),St(i.some(e=>e.toLowerCase()===s.toLowerCase())||n?.toLowerCase()===s.toLowerCase(),"GITHUB_DEFAULT_REPOSITORY_NOT_ALLOWED"),{...n?{legacyRepository:n}:{},repositories:t,defaultRepository:s}}function Rt(e){const t=e.workspace;St(t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),"BITBUCKET_WORKSPACE_INVALID");const n=e.repositories;St(n.length>0,"BITBUCKET_REPOSITORIES_REQUIRED"),St(n.length<=20,"BITBUCKET_REPOSITORY_LIMIT_EXCEEDED");const i=new Set,s=new Set;for(const e of n){const n=e.uuid.trim();St(n===e.uuid&&n.length>0,"BITBUCKET_REPOSITORY_ID_INVALID");const r=n.toLowerCase();St(!i.has(r),"BITBUCKET_REPOSITORY_IDS_MUST_BE_UNIQUE"),i.add(r);const o=`${t}/`;St(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();St(!s.has(a),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),s.add(a),St(e.defaultBranch.trim(),"BITBUCKET_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),Ft(e.cloneUrl,e.fullName,!0),Ft(e.webUrl,e.fullName,!1)}const r=e.defaultRepository;return St(r&&n.some(e=>e.fullName.toLowerCase()===r.toLowerCase()),"BITBUCKET_DEFAULT_REPOSITORY_NOT_ALLOWED"),{repositories:n,defaultRepository:r}}function Nt(e){return/^[^/\s]+\/[^/\s]+$/.test(e)}function jt(e,t,n){let i;try{i=new URL(e)}catch{throw new Error("GITHUB_REPOSITORY_URL_INVALID")}const s=`/${t}${n?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?github\.com:\d+(?:\/|$)/i.test(e);St(!("https:"!==i.protocol||"github.com"!==i.hostname||r||i.username||i.password||i.search||i.hash||i.pathname!==s),"GITHUB_REPOSITORY_URL_INVALID")}function Ft(e,t,n){let i;try{i=new URL(e)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const s=`/${t}${n?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(e);St(!("https:"!==i.protocol||"bitbucket.org"!==i.hostname||r||i.username||i.password||i.search||i.hash||i.pathname!==s),"BITBUCKET_REPOSITORY_URL_INVALID")}class xt{constructor(e,t,n,i,s){this.rpcManager=e,this.backendFunctionManager=s,this.iacBaseUrl=P(t,i,`openapi/iac/applications/${n}/integrations`)}async list(e,t){return(await this.rpcManager.get(this.iacBaseUrl)).filter(n=>(!e||n.type===e)&&(t?.includeDisabled||!at(n)))}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getPathStatus(e,t){const n=await this.get(e);if(!n)throw new Error(`Integration not found: ${e}`);return async function(e,t,n,i){const s=L[t];if(!s)return{supported:!1};const r=await e.executeFunction(s.functionName,...s.buildArgs(n,i));return{supported:!0,knowledgeBaseId:r.knowledgeBaseId,entries:r.entries,truncated:r.truncated}}(this.backendFunctionManager,n.type,e,t)}async enable(e){await this.setEnabled(e,!0)}async disable(e){await this.setEnabled(e,!1)}async setEnabled(e,t){const n=await this.get(e);if(!n)throw new Error(`Integration not found: ${e}`);await this.upsertIntegration({...n,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 startRelationshipInference(e,t){const{jobId:n}=await this.rpcManager.post(`${this.iacBaseUrl}/${e}/infer-relationships`,t??{});return n}async getRelationshipInference(e){const{run:t}=await this.rpcManager.get(`${this.iacBaseUrl}/${e}/infer-relationships`);return t}async cancelRelationshipInference(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}/infer-relationships`)}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 Bt{constructor(e){this.rpcManager=e}get apiKeys(){return new Pt(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 n={keys:[e],force:t};return this.rpcManager.post("secret/delete",n)}async deleteMany(e,t=!1){if(0===e.length)return;const n={keys:e,force:t};return this.rpcManager.post("secret/delete",n)}}class Pt{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 Ut{constructor(e,t,n,i,s){this.rpcManager=e,this.region=t,this.appId=n,this.consoleRegion=i,this.backendFunctionManager=s,this.integrationClient=new xt(this.rpcManager,this.region,this.appId,this.consoleRegion,this.backendFunctionManager),this.connectorClient=new U(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new Bt(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}function Lt(e){return"function"==typeof e}function Qt(e){return function(t){if(function(e){return Lt(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 $t=function(e,t){return $t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},$t(e,t)};function Gt(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}$t(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function Ht(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Kt(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,s,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function Wt(e,t,n){if(n||2===arguments.length)for(var i,s=0,r=t.length;s<r;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}Object.create,Object.create;var Vt,Jt=((Vt=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),Vt.prototype.constructor=Vt,Vt);function zt(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Yt=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,n,i,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(Lt(c))try{c()}catch(e){s=e instanceof Jt?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{Xt(h)}catch(e){s=null!=s?s:[],e instanceof Jt?s=Wt(Wt([],Kt(s)),Kt(e.errors)):s.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}if(s)throw new Jt(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Xt(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).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)&&zt(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&zt(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function Xt(e){Lt(e)?e():e.unsubscribe()}Yt.EMPTY;var Zt={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var s=Zt.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,Wt([e,t],Kt(n))):setTimeout.apply(void 0,Wt([e,t],Kt(n)))},clearTimeout:function(e){var t=Zt.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function en(){}var tn=nn("C",void 0,void 0);function nn(e,t,n){return{kind:e,value:t,error:n}}var sn=function(e){function t(t){var n,i=e.call(this)||this;return i.isStopped=!1,t?(i.destination=t,((n=t)instanceof Yt||n&&"closed"in n&&Lt(n.remove)&&Lt(n.add)&&Lt(n.unsubscribe))&&t.add(i)):i.destination=un,i}return Gt(t,e),t.create=function(e,t,n){return new on(e,t,n)},t.prototype.next=function(e){this.isStopped?cn(function(e){return nn("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?cn(nn("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?cn(tn,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}(Yt);Function.prototype.bind;var rn=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){an(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){an(e)}else an(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){an(e)}},e}(),on=function(e){function t(t,n,i){var s,r=e.call(this)||this;return s=Lt(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=i?i:void 0}:t,r.destination=new rn(s),r}return Gt(t,e),t}(sn);function an(e){!function(e){Zt.setTimeout(function(){throw e})}(e)}function cn(e,t){var n=null;n&&Zt.setTimeout(function(){return n(e,t)})}var un={closed:!0,next:en,error:function(e){throw e},complete:en};function ln(e,t,n,i,s){return new dn(e,t,n,i,s)}var dn=function(e){function t(t,n,i,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=n?function(e){try{n(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=i?function(){try{i()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return Gt(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(sn);function hn(e,t){return Qt(function(n,i){var s=0;n.subscribe(ln(i,function(n){i.next(e.call(t,n,s++))}))})}function pn(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():gn()}function gn(){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 fn(){return pn()}function yn(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function mn(e=18,t="",n=""){St(t.length<e,"ID prefix is too long"),St(!t||!n||n.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let i="";for(let t=0;t<e;t++)i+=yn();if(t.length>0&&(i=t+i.substring(t.length)),n)for(;i.charAt(t.length)===n[t.length];)i=i.substring(0,t.length)+yn()+i.substring(t.length+1);return i}function bn({count:e,length:t,prefix:n}){St(e>=0,`Invalid IDs count: ${e}`);const i=new Set;for(;i.size<e;)i.add(mn(t||18,n||""));return[...i]}const In=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function wn(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)wn(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)wn(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(In.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${In.join(", ")}`);const n=e[t];if("object"!=typeof n&&"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof n}`)}}function vn(e,t,n){const i=atob(e),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return new File([s],t,{type:n||"application/octet-stream"})}const Sn="x-squid-traceid",Mn="x-squid-client-version",kn="x-squid-integration-access-tokens";function Tn(e){return JSON.stringify(e)}function _n(e){return e&&Object.keys(e).length?{[kn]:Tn(e)}:{}}function En(e){if(!e)return{headers:{},options:void 0};const{integrationAccessTokens:t,...n}=e;return{headers:_n(t),options:n}}function Dn(e,t){const{agentId:n,jobId:i}=t;return e.notifyWebSocketIsNeeded(),e.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&(void 0===n||e.agentId===n)),g(e=>!i||e.jobId===i),v(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 Cn{constructor(e,t,n,i,s,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=n,this.rpcManager=i,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();St(t,"Agent not found");const n={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",n)}async updatePii(e){const t=await this.get();St(t,"Agent not found");const n={onDetect:"off",...t.options?.pii,...e};await this.setAgentOptionInPath("pii",n)}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,n){return this.chatInternal(e,t,n).responseStream}async transcribeAndChat(e,t,n){const i=this.chatInternal(e,t,n),s=await Mt(i.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:i.responseStream,transcribedPrompt:s.transcribedPrompt}}async ask(e,t,n){const i=await this.askInternal(e,!1,t,n);return this.replaceFileTags(i.responseString,i.annotations)}async askWithResult(e,t,n){return this.askInternal(e,!1,t,n)}async askWithAnnotations(e,t,n){const i=await this.askInternal(e,!1,t,n);return{responseString:i.responseString,annotations:i.annotations,routing:i.routing,validation:i.validation}}async askAsync(e,t,n){const{headers:i,options:s}=En(n),r={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(s),jobId:t};await this.post("ai/chatbot/askAsync",r,[],"files",i)}observeStatusUpdates(e){return Dn(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,n){return await this.askInternal(e,!1,t,n)}async transcribeAndAskWithVoiceResponse(e,t,n){const i=await this.askInternal(e,!0,t,n),s=i.voiceResponse;return{responseString:i.responseString,transcribedPrompt:i.transcribedPrompt,voiceResponseFile:vn(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,n){const i=await this.askInternal(e,!0,t,n),s=i.voiceResponse;return{responseString:i.responseString,voiceResponseFile:vn(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,n){const i={agentId:this.agentId,request:e,memoryId:t,options:n};return await this.backendFunctionManager.executeFunction("buildAgent",i)}replaceFileTags(e,t={}){let n=e;for(const[e,i]of Object.entries(t)){let t="";const s=i.aiFileUrl.fileName?i.aiFileUrl.fileName:i.aiFileUrl.url;switch(i.aiFileUrl.type){case"image":t=`![${s}](${i.aiFileUrl.url})`;break;case"document":t=`[${s}](${i.aiFileUrl.url})`}const r=`\${id:${e}}`;n=n.replaceAll("`"+r+"`",t).replaceAll(r,t)}return n}async askInternal(e,t,n,i){if(n?.contextMetadataFilter&&wn(n.contextMetadataFilter),n?.contextMetadataFilterForKnowledgeBase)for(const e in n.contextMetadataFilterForKnowledgeBase)wn(n.contextMetadataFilterForKnowledgeBase[e]);i=i||pn();const{headers:s,options:r}=En(n);n=this.withMetricAnnotations({...On,...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:n,jobId:i},u=o?void 0:[e];return await this.post(a,c,u,"file",s),await this.jobClient.awaitJob(i)}chatInternal(e,t,n){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&wn(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)wn(t.contextMetadataFilterForKnowledgeBase[e]);const i=pn(),{headers:s,options:o}=En(t),a=void 0===(t=this.withMetricAnnotations({...On,...o||{}})).smoothTyping||t.smoothTyping;let c="";const l=new r,d=new r;this.ongoingChatSequences[i]=d;let p=-1;d.pipe(R(({tokenIndex:e})=>{void 0!==e&&e<p&&console.warn("Received token index out of order",e,p),void 0!==e&&(p=e)}),u(({value:e,complete:t,annotations:n})=>t?S({value:e,complete:t,annotations:n}):S(e).pipe((()=>{const e=globalThis.document,t="object"==typeof e&&null!==e&&!0===e.hidden;return a&&!t})()?h(0):R(),hn(e=>({value:e,complete:!1,annotations:void 0})))),A(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:n})=>{c+=e,t&&n&&(c=this.replaceFileTags(c,n)),l.next(c)},error:e=>{console.error(e)},complete:()=>{l.complete()}});const g="string"==typeof e;n=n||pn();const y={agentId:this.agentId,jobId:n,prompt:g?e:void 0,options:t,clientRequestId:i},m={responseStream:l.pipe(f(()=>{delete this.ongoingChatSequences[i]}),T())};let b;return b=g?this.post("ai/chatbot/chat",y,[],"files",s).catch(e=>{l.error(e),l.complete()}):this.post("ai/chatbot/transcribeAndChat",y,[e],"file",s).catch(e=>{throw l.error(e),l.complete(),e}),m.serverResponse=b.then(()=>this.jobClient.awaitJob(n)).catch(e=>{l.error(e),l.complete()}),m}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,n=[],i="files",s={}){const r={...s};return this.agentApiKey&&(r["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,n,i,r)}}const On={smoothTyping:!0,responseFormat:"text"};class qn{constructor(e,t,n,i,s=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=n,this.backendFunctionManager=i,this.getMetricAnnotations=s,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),hn(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new Cn(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:n,complete:i,tokenIndex:s,annotations:r}=e.payload;if(i&&!n.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(n.match(/\[.*?]\((.*?)\)/g))t.next({value:n,complete:i,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<n.length;e++)t.next({value:n[e],complete:i&&e===n.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const An="__squid_empty_chat_id";class Rn{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 n={input:e,options:t},i=await this.rpcManager.post("ai/audio/createSpeech",n);return vn(i.base64File,`audio.${i.extension}`,i.mimeType)}}class Nn{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 jn{constructor(e){this.rpcManager=e}async generate(e,t){const n={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",n)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function Fn(e){for(const t in e){const n=e[t];St("string"==typeof n||"number"==typeof n||"boolean"==typeof n||void 0===n,`Invalid metadata value for key ${t} - cannot be of type ${typeof n}`),St(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}const xn=new Set(["completed","failed","cancelled"]);class Bn{constructor(e,t,n,i,s){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=n,this.socketManager=i,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:n}=await this.rpcManager.post("ai/knowledge-base/setContextScopes",{knowledgeBaseId:this.knowledgeBaseId,contextId:e,scopes:t});return n}async setContextVersionStates(e){return(await this.rpcManager.post("ai/knowledge-base/setContextVersionStates",{knowledgeBaseId:this.knowledgeBaseId,items:e})).results}async upsertContext(e,t){const{failures:n,contextIds:i,graphIndexingSkippedContextIds:s,imageFailures:r}=await this.upsertContexts([e],t?[t]:void 0);if(n.length>0)return{failure:n[0]};const o=i?.[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,n){for(const t of e)t.metadata&&Fn(t.metadata);const i=pn();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),n?.onUploaded?.(),await this.jobClient.awaitJob(i)}async bulkUpsertContexts(e,t,n){return this.rpcManager.post("ai/knowledge-base/bulk/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contexts:e,speed:n?.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 i(t=>{const n=()=>{this.rpcManager.post("ai/knowledge-base/bulk/subscribeToJob",{jobId:e}).catch(e=>t.error(e))};t.add(this.socketManager.observeNotifications().pipe(g(e=>"bulkIngestionStatus"===e.type),g(t=>t.payload.jobId===e)).subscribe(e=>{t.next(e.payload),xn.has(e.payload.state)&&t.complete()})),t.add(this.clientIdService.observeClientId().pipe(p(),_(1)).subscribe(()=>n())),this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.awaitConnectionReady().then(n).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(e){return this.rpcManager.post("ai/knowledge-base/getGraphStatus",{...e,knowledgeBaseId:this.knowledgeBaseId})}async getFileStatus(e){return this.rpcManager.post("ai/knowledge-base/getFileStatus",{knowledgeBaseId:this.knowledgeBaseId,path:e})}async getFolderStatus(e,t){return this.rpcManager.post("ai/knowledge-base/getFolderStatus",{knowledgeBaseId:this.knowledgeBaseId,folderPath:e,fileLimit:t})}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 Pn{constructor(e,t,n,i){this.rpcManager=e,this.jobClient=t,this.socketManager=n,this.clientIdService=i}knowledgeBase(e){return new Bn(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 Un{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new Ln(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new Ln(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class Ln{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 Qn{constructor(e,t,n,i){this.sessionId=e,this.callId=t,this.peer=n,this.microphone=i,this.eventListeners=new Set,this.endListeners=new Set,this.ended=!1}static async start(e,t){const n=globalThis,i=n.RTCPeerConnection,s=n.navigator?.mediaDevices;if(!i||!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 i,u=r??n.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 Qn(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 n="string"==typeof t.transcript?t.transcript.trim():"";n&&("conversation.item.input_audio_transcription.completed"===t.type?e({role:"user",text:n,at:(new Date).toISOString()}):"response.output_audio_transcript.done"===t.type&&e({role:"agent",text:n,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 $n{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 Qn.start(this,e)}}class Gn{constructor(e,t,n,i,s,r=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=n,this.clientIdService=i,this.backendFunctionManager=s,this.getMetricAnnotations=r}agent(e=We,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 jn(this.rpcManager)}audio(){return new Rn(this.rpcManager)}voice(){return new $n(this.rpcManager)}matchMaking(){return new Un(this.rpcManager)}files(e){return new Nn(e,this.rpcManager)}executeAiQuery(e,t,n,i){const{accessToken:s,...r}=n??{},o={integrationId:e,prompt:t,options:r},a=_n(s?{[e]:s}:void 0);return this.rpcManager.post("ai/query/executeDataQuery",o,[],"files",a,i)}executeAiApiCall(e,t,n,i){const s={integrationId:e,prompt:t,options:n,sessionContext:i};return this.rpcManager.post("ai/query/executeApiQuery",s)}executeAiSpreadsheetQuery(e,t,n,i){const s={prompt:e,files:t,options:n,sessionContext:i};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 n={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",n)).settings}observeStatusUpdates(e){return Dn(this.socketManager,{jobId:e})}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new qn(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new Pn(this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)),this.aiKnowledgeBaseClient}}const Hn={headers:{},queryParams:{},pathParams:{}};class Kn{constructor(e){this.rpcManager=e}async get(e,t,n){return this.request(e,t,void 0,n,"get")}async post(e,t,n,i){return this.request(e,t,n,i,"post")}async delete(e,t,n,i){return this.request(e,t,n,i,"delete")}async patch(e,t,n,i){return this.request(e,t,n,i,"patch")}async put(e,t,n,i){return this.request(e,t,n,i,"put")}async request(e,t,n,i,s){const r={integrationId:e,endpointId:t,body:n,options:{...Hn,...this.convertOptionsToStrings(i||{})},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 Wn{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 Vn=/[.\[\]]/;function Jn(e,t){if(!e)return;const n=t.split(Vn);let i,s=e;for(;s&&n.length;){const e=n.shift();if(e){if("object"!=typeof s||!(e in s))return;i=s[e],s=i}}return i}function zn(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Yn(e,t,n,i="."){const s=t.split(i);let r=e;for(;s.length;){const e=Mt(s.shift());if(s.length){const t=r[e],n=zn(t)?ii(t)??{}:{};r[e]=n,r=n}else r[e]=n}}function Xn(e,t,n){if(e.has(t)){const i=e.get(t);e.delete(t),e.set(n,i)}}function Zn(e){return null==e}function ei(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const n=typeof e;if(n!==typeof t)return!1;if("object"!==n)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const n of i)if(!s.includes(n)||!ei(e[n],t[n]))return!1;return!0}function ti(e,t){const n=new Array(e.length);for(let i=0;i<e.length;i++)n[i]=ni(e[i],t);return n}function ni(e,t){const n=t?t(e):void 0;if(void 0!==n)return n;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return ti(e,t);if(e instanceof Map)return new Map(ti(Array.from(e),t));if(e instanceof Set)return new Set(ti(Array.from(e),t));if(ArrayBuffer.isView(e))return i=e,"undefined"!=typeof Buffer&&i instanceof Buffer?Buffer.from(i):new i.constructor(i.buffer.slice(),i.byteOffset,i.length);var i;const s={};for(const n in e)Object.hasOwnProperty.call(e,n)&&(s[n]=ni(e[n],t));return s}function ii(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 si(e,t){if(e===t||Zn(e)&&Zn(t))return 0;if(Zn(e))return-1;if(Zn(t))return 1;const n=typeof e,i=typeof t;return n!==i?n<i?-1:1:"number"==typeof e?(St("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(St("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(St("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(St("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function ri(e,t){return e.reduce((e,n)=>{const i=t(n);return e[i]?e[i].push(n):e[i]=[n],e},{})}function oi(e){if(Array.isArray(e))return e.map(e=>oi(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),n={};return t.sort().forEach(t=>{n[t]=oi(e[t])}),n}function ai(e){return ci(oi(e))}function ci(e){if(void 0===e)return null;const t=ni(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function ui(e){return ni(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,n=t.$date;return n&&1===Object.keys(t).length?new Date(n):void 0})}function li(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=ci(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let n="";for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return btoa(n)}}const di=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},hi=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(ci(e[n])!==ci(t[n]))return!1;return!0};class pi{constructor(e){this.options=e}get(e){const t=this.cachedEntry,n=this.options.argsComparator||di,i=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+i&&n(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function gi(e){const t=[],n=[];let i=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){n.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:i++};t.push(e)}else if(fi(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(n.push(s[t]),i++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:n}}function fi(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class yi{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...n){const{argsArray:i,fileArray:s}=gi(n),r="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(i);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,i));if(t)return t.promise}const u=this.createExecuteCallPromise(r,i,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:i,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,n,i,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:ci(t)},a=ui((await this.rpcManager.post(r,o,n.length>0?n:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return vn(e.base64,e.filename,e.mimetype)}return i&&i.set(t,a),a}}function mi(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 Ii{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 wi{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===bi().squidTenant,this.clientIdSubject=new t(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe(g(e=>e),v(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe(_(1),g(e=>!e),v(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=bi()[Si];return e?e():pn()}generateClientId(){const e=bi()[vi];if(e)return e();let t=`${this.isTenant?"tenant-":""}${pn()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const vi="SQUID_CLIENT_ID_GENERATOR",Si="SQUID_CLIENT_REQUEST_ID_GENERATOR",Mi="__squidId";function ki(e){return ui(e)}function Ti(...e){const[t,n,i]=e,s="object"==typeof t?t:{docId:t,collectionName:n,integrationId:i};return s.integrationId||(s.integrationId=void 0),ai(s)}function _i(e,t,n){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===n)return ei(e,t);if("!="===n)return!ei(e,t);switch(n){case"<":return!Zn(e)&&(!!Zn(t)||t<e);case"<=":return!!Zn(t)||!Zn(e)&&t<=e;case">":return!Zn(t)&&(!!Zn(e)||t>e);case">=":return!!Zn(e)||!Zn(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Ei(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Ei(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Ei(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Ei(t,e,!0));case"array_includes_some":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>Mt(n,"VALUE_CANNOT_BE_NULL").some(t=>ei(t,e)))}case"array_includes_all":{const n=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>Mt(n,"VALUE_CANNOT_BE_NULL").some(t=>ei(t,e)))}case"array_not_includes":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!Mt(n,"VALUE_CANNOT_BE_NULL").some(t=>ei(t,e)))}default:throw new Error(`Unsupported operator comparison: ${n}`)}}function Ei(e,t,n){n||(e=e.toLowerCase(),t=t.toLowerCase());const i=function(e){let t="";for(let n=0;n<e.length;++n)"\\"===e[n]?n+1<e.length&&["%","_"].includes(e[n+1])?(t+=e[n+1],n++):n+1<e.length&&"\\"===e[n+1]?(t+="\\\\",n++):t+="\\":"%"===e[n]?t+="[\\s\\S]*":"_"===e[n]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[n])&&(t+="\\"),t+=e[n]);return t}(t);return new RegExp(`^${i}$`).test(e)}function Di(e){for(let t=0;t<e.length;t++)if("\\"===e[t]){if(!["%","_","\\"].includes(e[t+1]))return!0;t++}return!1}function Ci(e,t){return`${e}_${t}`}function Oi(e){return"fieldName"in e}function qi(e){return"docIds"in e}function Ai(e,t,n){const i=e.docIds.some(e=>Object.entries(e).every(([e,i])=>_i(i,n(t,e)??null,"==")));switch(e.operator){case"==":case"in":return i;case"!=":case"not in":return!i}}function Ri(e,t,n,i){const s=e,r=i(t,ft);if("string"!=typeof r)return _i(s,r??null,n);let o;try{o=ui(r)}catch{return _i(s,r,n)}if(!o||"object"!=typeof o||Array.isArray(o))return _i(s,r,n);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:ai(e)}if("string"==typeof e)try{const t=ui(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 _i(t,e,n)}if(1===a.length){const e=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const n=Object.keys(e);if(1===n.length&&n[0]===t)return e[t]}if("string"==typeof e)try{const n=ui(e);if(n&&"object"==typeof n&&!Array.isArray(n)){const e=Object.keys(n);if(1===e.length&&e[0]===t)return n[t]}}catch{}return e}(s,a[0]);return _i(e,o[a[0]],n)}return"object"!=typeof s||null===s||Array.isArray(s)?_i(s,r,n):_i(ai(s),r,n)}class Ni{constructor(e,t,n,i,s){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=n,this.projectFields=i,this.identityReference=s,this.refId=pn()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this.identityReference?.squidDocId??this._squidDocId}get data(){return ni(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=Mt(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:n}=ki(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:n,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 Mt(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(v(e=>(Mt(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 n={};Object.entries(e).forEach(([e,t])=>{const i=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};n[e]=[i]});const i={type:"update",squidDocIdObj:ki(this.squidDocId),properties:n};return this.dataManager.applyOutgoingMutation(i,t)}async setInPath(e,t,n){return this.update({[e]:ni(t)},n)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,n){const i={type:"applyNumericFn",fn:"increment",value:t},s={type:"update",squidDocIdObj:ki(this.squidDocId),properties:{[e]:[i]}};return this.dataManager.applyOutgoingMutation(s,n)}decrementInPath(e,t,n){return this.incrementInPath(e,-t,n)}async upsert(e,t){const n=ki(this.squidDocId),i=n.integrationId;let s=ui(n.docId);if(s[Mi]&&(s={}),i===st&&s.__id)try{const e=ui(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:n,properties:{...e,__docId__:n.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:ki(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={},n=Mt(this.projectFields,"applyProjection called without projectFields"),{integrationId:i}=ki(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const s=i===st?"__id":"__docId__";if(s in e){const n=e[s];if("string"==typeof n&&n.startsWith("{"))try{const e=ui(n);if("object"==typeof e&&null!==e)for(const[n,i]of Object.entries(e))n in t||(t[n]=i)}catch{}}for(const i of n)if(i.includes(".")){const n=Jn(e,i);void 0!==n&&Yn(t,i,n)}else i in e&&(t[i]=e[i]);return t}hasSquidPlaceholderId(){const e=ui(this.squidDocId);if("object"==typeof e&&e.docId){const t=ui(e.docId);if("object"==typeof t&&Object.keys(t).includes(Mi))return!0}return!1}}class ji{constructor(e,n={}){this.internalStateObserver=new t(null),this.firstElement=null,this.isDestroyed=new t(!1),this.snapshotSubject=new r,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,St(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe(D()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...n},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(g(e=>null!==e),v(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(v(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||Zn(e)&&Zn(t))return 0;if(Zn(e))return-1;if(Zn(t))return 1;const n=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:i,asc:s}of n){const n=si(Jn(e,i),Jn(t,i));if(0!==n)return s?n:-n}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 n=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-n-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const n=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,i=Math.max(0,e.length-n-this.paginateOptions.pageSize);n!==e.length?this.internalStateObserver.next({numBefore:n,numAfter:i,data:e,extractedData:t}):this.prevInternal({numBefore:n,numAfter:i,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:Jn(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe(v(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:Jn(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await m(k(this.isDestroyed.pipe(g(Boolean),v(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),O(1))))}internalStateToState(e){const{data:t,numBefore:n,numAfter:i,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:i>0,hasPrev:n>0}}prevInternal(e){const{numBefore:t,numAfter:n,extractedData:i}=e;this.firstElement=null,this.lastElement=i[t-1],this.internalStateObserver.next(null),this.doNewQuery(i[i.length-n-1],!0)}}class Fi{constructor(e,t,n,i,s){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=n,this.documentIdentityService=i,this.mutationSender=s}getForDocument(e){const{collectionName:t,integrationId:n,docId:i}=ki(e),s=ui(i),r=this.get(t,n);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new Pi(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService,this.mutationSender)}}class xi{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(ft,e)}docIds(e){return this.in(ft,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,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"like_cs":"like",t)}notLike(e,t,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"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(Di(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class Bi{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return m(this.snapshots(!1).pipe(l([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(hn(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Bi(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 Bi(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new ji(this,e)}}class Pi extends xi{constructor(e,t,n,i,s,r,o,a){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.localQueryManager=i,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 li(this.build())}where(e,t,n){if(St(mt.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&e!==ft&&!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 i=Array.isArray(n)?[...n]:[n];"in"===t&&0===i.length&&(this.containsEmptyInCondition=!0);for(const n of i)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:n});return this}return this.query.conditions.push({fieldName:e,operator:t,value:n}),this}limit(e){return function(e){var t;St(function(e){return"number"==typeof e}(t=e),()=>Tt("Limit needs to be a number","Not a number",t)),-1!==e&&(St(e>0,"query limit has to be greater than 0"),St(Math.floor(e)===e,"query limit has to be an integer"),St(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const n=this.query.sortOrder.map(e=>e.fieldName);return St(ei(t.sort(),n.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 n={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 n,i,s,r;St((n=t,i=["fieldName","asc"],!Array.isArray(n)&&[...Object.keys(n)].every(e=>i.includes(e))),"Field sort should only contain a fieldName and asc"),St((s=t.asc,r="boolean",Array.isArray(s)?s.every(e=>typeof e===r):typeof s===r),"Asc needs to be boolean")}(n),St(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.projectFields&&e!==ft&&!this.query.projectFields.includes(e))throw new Error(`Cannot sort by field '${e}' that is not included in projectFields.`);return this.query.sortOrder.push(n),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!==ft&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(Oi(e)){if(e.fieldName!==ft&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else if(qi(e));else for(const n of e.fields)if(n.fieldName!==ft&&!t.includes(n.fieldName))throw new Error(`Cannot set projectFields without including filter field '${n.fieldName}'.`);const n=this.clone();return n.query.projectFields=[...e],n}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return m(this.snapshots(!1).pipe(l([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new t([]);const n=this.build(),i=n.projectFields;return this.querySubscriptionManager.processQuery(n,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(hn(e=>e.map(e=>{St(1===Object.keys(e).length);const t=e[this.collectionName],n=Ti(Mt(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(c(this.documentIdentityService.observeChanges().pipe(C(t=>(Object.entries(t).forEach(([t,n])=>{!function(e,t,n){const i=e[t];void 0!==i&&(e[n]=i,delete e[t])}(e||{},t,n)}),n)),E({}))),hn(([n])=>{let i=[];const s=[],r=[];if(e){for(const r of n){const n=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[n],t.delete(o);else if(e[n]){s.push(r);const i=e[n];delete e[n],t.delete(i)}else i.push(r)}for(const e of t)r.push(e)}else i=n;e={},t=new Set;for(const i of n){const n=i.dataRef;e[i.squidDocId]=n,t.add(n)}return new Ui(i,s,r)}))}async delete(){return this.validateQueryDeleteModifiers(),this.containsEmptyInCondition?{deletedCount:0}:(St(this.mutationSender,"Query delete is not available on this query builder."),this.mutationSender.deleteQuery(this.build()))}dereference(){return new Bi(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new Pi(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService,this.mutationSender);return e.query=ni(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!==ft&&!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 ji(this,e)}validateQueryDeleteModifiers(){St(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=ri(this.query.conditions.filter(Oi)||[],e=>e.fieldName);for(const n of Object.values(t)){const t=ri(n,e=>e.operator);for(const[n,i]of Object.entries(t)){if("=="===n||"!="===n){e.push(...i);continue}const t=[...i];t.sort((e,t)=>si(e.value,t.value)),">"===n||">="===n?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Oi(e)),...e]}}class Ui{constructor(e,t,n){this.inserts=e,this.updates=t,this.deletes=n}}class Li extends xi{constructor(e,t,n,i,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.documentReferenceFactory=i,this.queryBuilderFactory=s,this.rootAlias=r,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,n){return this.queryBuilder.where(e,t,n),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,n,i){const s=i?.leftAlias??this.latestAlias,r={...n,leftAlias:s,isInner:i?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new Li(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 m(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new t([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,ni(this.joins),ni(this.joinConditions),e,!1).pipe(hn(e=>e.map(e=>{const t={};for(const[n,i]of Object.entries(e)){const e=n===this.rootAlias?this.collectionName:this.joins[n].collectionName,s=n===this.rootAlias?this.integrationId:this.joins[n].integrationId,r=i?Ti(i.__docId__,e,s):void 0;t[n]=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 Gi(this)}dereference(){return new Qi(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Li(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,ni(this.leftToRight),ni(this.joins),ni(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 ji(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class Qi{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(hn(e=>e.map(e=>function(e,t){const n={},i=Object.keys(e);for(const s of i){const i=e[s];n[s]=t(i)}return n}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Qi(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 ji(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class $i{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(hn(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 $i(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 ji(this,e)}dereference(e,t){const n=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(n.length){const i={[t]:e[t].data};for(const t of n)i[t]=e[t].map(e=>this.dereference(e,t));return i}return e.data}}class Gi{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(hn(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new $i(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Gi(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 ji(this,e)}groupData(e,t){const n=ri(e,e=>e[t]?.squidDocId);return Object.values(n).filter(e=>void 0!==e[0][t]).map(e=>{const n=this.joinQueryBuilder.leftToRight[t],i=e[0][t];if(0===n.length)return i;const s={[t]:i};for(const t of n)s[t]=this.groupData(e,t);return s})}}class Hi{constructor(e,t,n,i,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=n,this.queryBuilderFactory=i,this.querySubscriptionManager=s,this.dataManager=r,this.refId=pn()}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!==st)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={[Mi]:pn()};else e=e&&"string"!=typeof e?{__id:ai(e)}:{__id:e||pn()};const t=Ti(ai(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 n of e)await this.doc(n.id).upsert(n.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const n of e)n instanceof Ni?await n.delete(t):await this.doc(n).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new Li(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new Ki(...e)}}class Ki{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 n=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==n.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<n.length;e++)if(t[e].fieldName!==n[e].fieldName||t[e].asc!==n[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return m(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 Ki(...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 ji(this,e)}or(e,...t){return a([...t]).pipe(v(t=>{const n=new Set,i=t.flat(),s=[];for(const e of i)n.has(this.extractData(e))||(n.add(this.extractData(e)),s.push(e));return s.sort((t,n)=>{for(const{fieldName:i,asc:s}of e){const e=Jn(this.extractData(t),i),r=Jn(this.extractData(n),i);if(!_i(e,r,"=="))return _i(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class Wi{constructor(e,t,n,i){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=n,this.dataManager=i,this.collections=new Map}get(e,t){let n=this.collections.get(t);n||(n=new Map,this.collections.set(t,n));let i=n.get(e);return i||(i=new Hi(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),n.set(e,i)),i}}class Vi{constructor(e,t,n){this.clientIdService=e,this.socketManager=t,this.runtimeOptions=n,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 Ji=x(150);const zi={"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 Zn(e)||Zn(t)?Zn(e)!==Zn(t):Zi(e,t)&&!ei(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=>ns(e,t)),">=:not in":(e,t)=>t.every(t=>ts(e,t)),"<:not in":(e,t)=>t.every(t=>Xi(e,t)),"<=:not in":(e,t)=>t.every(t=>Yi(e,t)),">:>":(e,t)=>ns(e,t),">=:>":(e,t)=>ts(e,t),"in:>":(e,t)=>e.every(e=>ts(e,t)),">:>=":(e,t)=>ns(e,t),">=:>=":(e,t)=>ns(e,t),"in:>=":(e,t)=>e.every(e=>ns(e,t)),"<:<":(e,t)=>Xi(e,t),"<=:<":(e,t)=>Yi(e,t),"in:<":(e,t)=>e.every(e=>Yi(e,t)),"<:<=":(e,t)=>Xi(e,t),"<=:<=":(e,t)=>Xi(e,t),"in:<=":(e,t)=>e.every(e=>Xi(e,t)),"like:like":(e,t)=>ss(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>ss(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>ss(e,t)&&cs(t),"like_cs:like_cs":(e,t)=>ss(e,t),"like:not like":(e,t)=>!os(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!os(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!os(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!os(e,t),"not like:not like":(e,t)=>ss(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>ss(t,e)&&cs(e),"not like:not like_cs":(e,t)=>ss(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>ss(t,e),"in:like":(e,t)=>e.every(e=>_i(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>_i(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>es(e)&&_i(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>es(e)&&_i(t,e,"not like_cs")),"like:in":(e,t)=>us(e)&&cs(e)&&t.includes(e),"like_cs:in":(e,t)=>us(e)&&t.includes(e),"not in:not like":(e,t)=>us(t)&&cs(t)&&e.includes(t),"not in:not like_cs":(e,t)=>us(t)&&e.includes(t),"like:not in":(e,t)=>t.every(t=>_i(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>_i(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>_i(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>_i(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 Yi(e,t){return Zn(e)?!Zn(t):!Zn(t)&&Zi(e,t)&&e<t}function Xi(e,t){return!!Zn(e)||!Zn(t)&&Zi(e,t)&&e<=t}function Zi(e,t){return typeof e==typeof t&&e instanceof Date==t instanceof Date}function es(e){return Zn(e)||"string"==typeof e}function ts(e,t){return Yi(t,e)}function ns(e,t){return Xi(t,e)}function is(e){const t=[];for(let n=0;n<e.length;n++){const i=e[n],s=e[n+1];"\\"!==i||"%"!==s&&"_"!==s?"\\"===i&&"\\"===s?(t.push(i),n++):t.push(i):(t.push(i+s),n++)}return t}function ss(e,t){return rs(is(e),is(t))}function rs(e,t,n=0,i=0){if(i>=t.length)return n>=e.length;if(n>=e.length)return ds(t.slice(i));const s=e[n],r=t[i];return"%"===s&&"%"===r?rs(e,t,n+1,i+1)||rs(e,t,n+1,i):"%"!==s&&("%"===r?rs(e,t,n,i+1)||rs(e,t,n+1,i):(s===r||"_"===r)&&rs(e,t,n+1,i+1))}function os(e,t){return as(is(e),is(t))}function as(e,t,n=0,i=0){if(n>=e.length&&i>=t.length)return!0;if(n>=e.length)return ds(t.slice(i));if(i>=t.length)return ds(e.slice(n));const s=e[n],r=t[i];return"%"===s&&"%"===r?as(e,t,n+1,i+1)||as(e,t,n,i+1)||as(e,t,n+1,i):"%"===s||"%"===r?as(e,t,n,i+1)||as(e,t,n+1,i):(s===r||"_"===s||"_"===r)&&as(e,t,n+1,i+1)}function cs(e){return e===e.toLowerCase()&&e===e.toUpperCase()}function us(e){return!/[%_\\]/.test(e)}function ls(e,t){return e.includes("like")&&"string"==typeof t&&Di(t)}function ds(e){return e.every(e=>"%"===e)}function hs(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const i of n){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ei(e[i],t[i]))return!1}return!0}function ps(e,t){return t.every(t=>{const n=Object.keys(t).sort();if(n.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(n[t]!==e[t])return!1;return!0})}class gs{constructor(e){this.query=e,this.query=e;const t=this.query.conditions.filter(Oi),n=this.query.conditions.filter(qi),i=n.flatMap(e=>function(e){if("=="!==e.operator&&"in"!==e.operator)return[];if(0===e.docIds.length)return[];const t=[],n=e.docIds[0];for(const i of Object.keys(n)){const s=n[i];e.docIds.every(e=>Object.prototype.hasOwnProperty.call(e,i)&&ei(e[i],s))&&t.push({fieldName:i,operator:"==",value:s})}return t}(e));this.exactSimpleConditions=this.parseConditions(t),this.exactDocIdConditions=n,this.subqueryConditions=this.parseConditions([...t,...i])}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)=>!ei(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,n){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:n})}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(qi))if(!this.childImpliesParentDocIdCondition(t))return!1;const t=e.conditions.filter(Oi),n=this.isSubqueryOfConditions(t),i=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return n&&i&&s&&r}childImpliesParentDocIdCondition(e){const t=e.docIds;if(0===t.length)return!1;const n="=="===e.operator||"in"===e.operator,i=Object.keys(t[0]).sort(),s=[];for(const e of this.query.conditions)qi(e)&&s.push(...e.docIds);if(!ps(i,t)||!ps(i,s))return!1;const r=this.buildChildEffectiveTupleSet();return n?void 0!==r.allowed&&r.allowed.every(e=>t.some(t=>hs(e,t))):void 0!==r.allowed?r.allowed.every(e=>!t.some(t=>hs(e,t))):t.every(e=>r.excluded.some(t=>hs(e,t)))}buildChildEffectiveTupleSet(){let e;const t=[];for(const n of this.query.conditions)if(qi(n))if("=="===n.operator||"in"===n.operator)e=void 0===e?[...n.docIds]:e.filter(e=>n.docIds.some(t=>hs(e,t)));else for(const e of n.docIds)t.some(t=>hs(t,e))||t.push(e);return void 0!==e&&t.length>0&&(e=e.filter(e=>!t.some(t=>hs(e,t)))),{allowed:e,excluded:t}}isProjectFieldsSubset(e,t){if(!t)return!0;if(!e)return!1;const n=new Set(t);return e.every(e=>n.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 n=t.fieldName,i=t.operator;if(n===ft){const n=t.value;if("in"===i||"not in"===i){const t=(Array.isArray(n)?n:[n]).some(t=>Ri(t,e,"==",Jn));if(!("in"===i?t:!t))return!1;continue}if(!Ri(n,e,i,Jn))return!1;continue}const s=Jn(e,n);if("in"===i){if(t.value.includes(s))continue;return!1}if("not in"!==i){if(!_i(t.value,s,i))return!1}else if(t.value.includes(s))return!1}for(const t of this.exactDocIdConditions)if(!Ai(t,e,Jn))return!1;return!0}evaluateSubset(e,t){const{operator:n,value:i}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=zi[`${n}:${s}`];return!!o&&!ls(n,i)&&!ls(s,r)&&o(i,r)}parseConditions(e){const t=[],n=new Map,i=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":i.set(e.fieldName,(i.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),n.forEach((e,n)=>{t.push({fieldName:n,operator:"in",value:e})}),i.forEach((e,n)=>{t.push({fieldName:n,operator:"not in",value:e})}),t}}function fs(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function ys(e,t){let n=e;for(const e of t.split(".")){if(!fs(n))return;n=n[e]}return n}function ms(e,t,n){const i=t.split(".");let s=e;for(const[e,r]of i.entries()){if(e===i.length-1)return void(s[r]=n);const o=s[r];if(null!=o&&!fs(o))throw new Error(`Cannot set path ${t}, ${r} is not an object`);const a=fs(o)?{...o}:{};s[r]=a,s=a}}function bs(e,t){const n=t.split(".");let i=e;for(const[e,t]of n.entries()){if(e===n.length-1)return void delete i[t];const s=i[t];if(!fs(s))return;const r={...s};i[t]=r,i=r}}function Is(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 n="string"==typeof e?e:null;switch(t.fn){case"trim":return null===n?null:n.trim();case"extendString":return null===n?t.value:n+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?ni(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function ws(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function vs(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(St("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const n=ni(e);t=ni(t);for(const[e]of ws(n)){const i=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&i>t.split(".").length)&&delete n.properties[e]}for(const[e,i]of ws(t))n.properties[e]=Ss([...n.properties[e]||[],...i]);return n}(e,t);const n=ni(e);for(const[e,i]of ws(t)){const t=i;for(const i of t){const t=n.properties,s=Is(ys(t,e),i);void 0===s?bs(t,e):ms(t,e,s)}}return n}function Ss(e){let t=0;for(;t+1<e.length;){const n=Ms(e[t],e[t+1]);n?e.splice(t,2,n):++t}return e}function Ms(e,t){if("removeProperty"===t.type||"update"===t.type)return t;if("applyNumericFn"===t.type){if(St("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type)return St("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 ks(e,t){if(!e)return;const n={...e},i=ws(t);for(const[e,t]of i){const i=t;for(const t of i){const i=Is(ys(n,e),t);void 0===i?bs(n,e):ms(n,e,i)}}return n}function Ts(e){const t={};for(const n of e){const e=`${n.squidDocIdObj.integrationId}/${n.squidDocIdObj.collectionName}/${n.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(n)}const n=[];for(const e in t){const i=t[e].reduce((e,t)=>Mt(vs(e,t),"Merge result cannot be null"));n.push(i)}return n}const _s="dataManager_runInTransaction";var Es;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Es||(Es={}));class Ds{constructor(e,n,i,s,o,a,c,u,l){this.documentStore=e,this.mutationSender=n,this.socketManager=i,this.querySubscriptionManager=s,this.queryBuilderFactory=o,this.lockManager=a,this.destructManager=c,this.documentIdentityService=u,this.querySender=l,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new r,this.outgoingMutationsEmpty=new t(!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),n=t&&!t.expireTimestamp?t.timestamp:void 0,i=this.docIdToLocalTimestamp.get(e);return!((!i||n)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&i===n)}async executeDetachedQuery(e){const t=this.currentTransactionId,n={query:e,clientRequestId:pn(),subscribe:!1},i=await this.querySender.sendQueryDirect(n);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(i.docs,e)}async reRunQueryThroughNormalPipeline(e){await m(this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)));const t={query:e,clientRequestId:pn(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}predictUpdate(e,t){try{return ks(e,t)}catch{return e}}applyPendingMutationsToQueryResult(e,t){const n=new gs(t),i=new Map;for(const n of e){const e=Ti(n.__docId__,t.collectionName,t.integrationId);i.set(e,n)}for(const[e,s]of this.pendingOutgoingMutations){const r=ki(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of s){const s=i.get(e);if("delete"===t.type)i.delete(e);else if("update"===t.type){if(s){const r=this.predictUpdate(s,t);r&&n.documentMatchesQuery(r)?i.set(e,r):i.delete(e)}}else if("insert"===t.type){const s={...t.properties,__docId__:r.docId};n.documentMatchesQuery(s)&&i.set(e,s)}}}const s=Array.from(i.values()),{sortOrder:r}=t;s.sort((e,t)=>{for(const{fieldName:n,asc:i}of r){const s=si(Jn(e,n),Jn(t,n));if(0!==s)return i?s:-s}return 0});const o=t.limit<0?2e3:t.limit;return s.slice(0,o)}async runInTransaction(e,t){if(t)return St(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(_s)?this.lockManager.lockSync(_s):await this.lockManager.lock(_s);let n=Cs;const i=()=>n!==Cs;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=pn();try{r=await e(this.currentTransactionId)}catch(e){n=e}finally{this.finishTransaction(i()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){n=i()?n:e}finally{try{this.lockManager.release(_s)}catch(e){n=i()?n:e}}i()&&s(n)})}async applyOutgoingMutation(e,t){const n=Ti(e.squidDocIdObj);this.knownDirtyDocs.add(n),t||this.lockManager.canGetLock(_s)||(await this.lockManager.lock(_s),this.lockManager.release(_s)),this.knownDirtyDocs.delete(n);const i=this.removeInternalProperties(e),s=this.pendingOutgoingMutations.get(n)?.slice(-1)[0],r=s&&!s.sentToServer?Mt(Ts([s.mutation,i])[0],"Failed to reduce mutations"):void 0;if("update"===e.type&&ks(this.documentStore.getDocumentOrUndefined(n),e),s&&r)s.mutation=r,this.outgoingMutationsEmpty.next(!1);else{const e={mutation:i,sentToServer:!1},t=this.pendingOutgoingMutations.get(n)||[];t.push(e),this.pendingOutgoingMutations.set(n,t),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(n),i="delete"===e.type?void 0:"update"===e.type?t&&this.predictUpdate(t,e):{...e.properties};this.updateDocumentFromSnapshot(n,i)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(n,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(n,i).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 St(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(_s);try{this.currentTransactionId=pn();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(_s)}}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(g(e=>"mutations"===e.type),hn(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t={},n=[];for(const i of e){if(!this.querySubscriptionManager.hasOngoingQuery(i.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(i.clientRequestId),s=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(i.clientRequestId);s&&r?n.push({squidDocId:i.squidDocId,item:{properties:i.doc,timestamp:i.mutationTimestamp,clientRequestId:i.clientRequestId,projectFields:e.projectFields}}):t[i.squidDocId]={properties:i.doc,timestamp:i.mutationTimestamp}}Object.keys(t).length>0&&this.applyIncomingUpdates(t),n.length>0&&this.runInTransactionSync(()=>{this.applyProjectedUpdates(n)})}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 n=[];for(const i of e.docs){const s=Ti(i.__docId__,t.collectionName,t.integrationId);n.push({squidDocId:s,item:{properties:i,timestamp:i.__ts__,clientRequestId:e.clientRequestId,projectFields:t.projectFields}})}this.runInTransactionSync(()=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId,e.docs),this.batchClientRequestIds.add(e.clientRequestId),this.applyProjectedUpdates(n)})}else{const n={};for(const i of e.docs){const e=Ti(i.__docId__,t.collectionName,t.integrationId);n[e]={properties:i,timestamp:i.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId,e.docs),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(n,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}}applyIncomingUpdates(e,t){let n=!1;const i=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?n=!0:o&&o.timestamp>r.timestamp?(r.properties&&this.documentStore.adoptMissingFields(t,r.properties),s.add(t)):(this.pendingIncomingUpdates.set(t,r),i.add(t))}return this.runInTransactionSync(()=>{for(const e of i)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),n}applyProjectedUpdates(e){for(const{squidDocId:t,item:n}of e){const e=Mt(n.clientRequestId,"clientRequestId required for projected updates"),i=this.pendingOutgoingMutations.get(t);if(i&&i.length)continue;const s=this.docIdToServerTimestamp.get(t);s&&s.timestamp>n.timestamp?(this.querySubscriptionManager.addDocToQuery(t,e),this.batchClientRequestIds.add(e)):(this.acknowledgeDocument(t,n.timestamp,!n.properties),this.docIdToLocalTimestamp.set(t,n.timestamp),n.properties?(this.documentStore.saveProjectedDocument(t,n.properties,n.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 n=this.pendingOutgoingMutations.get(e);n&&n.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 n=this.documentStore.getDocumentOrUndefined(e);return!(!n&&!t||n===t)&&((!n||!t||ai({...t,__ts__:void 0})!==ai(n))&&(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 Ji.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:n,idResolutionMap:i={},refreshList:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(i),s.forEach(e=>{this.refreshDocIdToTimestamp.set(i[e]||e,n)});for(const t of e){let e=this.removeOutgoingMutation(t);i[e]&&(e=i[e]),this.acknowledgeDocument(e,n),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=Ti(e.mutation.squidDocIdObj),n=Mt(this.pendingOutgoingMutations.get(t));return n.splice(n.indexOf(e),1),n.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}=ki(t);this.setExpiration(t,!0);try{const n=e.includes(Mi)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(Mt(n.length<=1,"Got more than one doc for the same id:"+t),!n.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,n]of this.refreshDocIdToTimestamp.entries()){const i=this.docIdToServerTimestamp.get(t)?.timestamp;i&&i>n||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 n=t[t.length-1];if(n&&!n.sentToServer){const t=n.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(n),n.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,n=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,n)}setExpiration(e,t){const n=this.docIdToServerTimestamp.get(e);n&&(n.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 n=Ti(t.mutation.squidDocIdObj),i=e[n];i&&(t.mutation.squidDocIdObj=ki(i))})}),Object.entries(e).forEach(([e,t])=>{Xn(this.pendingOutgoingMutations,e,t),Xn(this.docIdToLocalTimestamp,e,t),Xn(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 Cs=Symbol("undefined");class Os{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),hn(()=>{}))}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 qs{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(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)`),Ii.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 n=t?.acquisitionTimeoutMillis??2e3,i=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),St(await m(k(N(this.lockWaitForConnectionThreshold).pipe(hn(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const s=pn(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:n,maxHoldTimeMillis:i,clientRequestId:s}};this.socketManager.postMessage(r);const o=await m(k(N(n+4e3).pipe(O(1),hn(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:s}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===s)))),a=o.payload.lockId;St(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),St(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new As(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 As{constructor(e,t,n,i,r){this.lockId=e,this.resourceId=t,this.clientRequestId=n,this.ongoingLocks=i,this.socketManager=r,this.released=!1,this.onReleaseSubject=new s(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),n=await m(k(b(t.then(Rs,Rs)),this.socketManager.observeConnectionReady().pipe(g(e=>!e),hn(()=>!1))));if(this.onReleaseSubject.next(),!n)return t.catch(()=>{}),void this.onReleaseSubject.complete();try{await t}finally{this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}function Rs(){return!0}class Ns{constructor(e,n){this.documentStore=e,this.destructManager=n,this.changeNotifier=new t({}),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 js{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t,n,i=!1){if(n||i)return new Ni(e,Mt(this.dataManager,"dataManager not found"),t,n,i?this.create(e,t):void 0);let s=this.documents.get(e);if(s)return s;s=new Ni(e,Mt(this.dataManager,"dataManager not found"),t);const{integrationId:r,collectionName:o}=ki(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 n=this.getCollectionKey(e,t);return(this.documentsForCollection.get(n)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const n=ki(e),i=ki(t);Xn(this.documents,n.docId,i.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class Fs{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,n){const i=this.squidDocIdToDoc.get(e);if(i){const n=this.mergeDocuments(i,t),s=this.removeInternalProperties(n);this.squidDocIdToDoc.set(e,s)}else{const n=this.removeInternalProperties(t);this.squidDocIdToDoc.set(e,n)}if(n?.length){const t=this.squidDocIdToProjectedFields.get(e);if(void 0!==t)for(const e of n)t.add(e);else i||this.squidDocIdToProjectedFields.set(e,new Set(n))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const n=ni(e);for(const e of Object.keys(t)){const i=t[e],s=n[e];null===i||"object"!=typeof i||Array.isArray(i)||null===s||"object"!=typeof s||Array.isArray(s)?n[e]=i:n[e]=this.mergeDocuments(s,i)}return n}adoptMissingFields(e,t){const n=this.squidDocIdToDoc.get(e);if(!n)return;const i=Object.keys(t).filter(e=>"__ts__"!==e&&!(e in n));if(!i.length)return;const s=ni(n);for(const e of i)s[e]=t[e];this.squidDocIdToDoc.set(e,s);const r=this.squidDocIdToProjectedFields.get(e);if(r)for(const e of i)r.add(e)}deleteDocument(e){this.squidDocIdToDoc.delete(e),this.squidDocIdToProjectedFields.delete(e)}saveDocument(e,t){const n=this.squidDocIdToDoc.get(e);if(void 0===n&&!t)return;if(void 0!==n){if(t){const n=ni(t),i=this.removeInternalProperties(n);return this.squidDocIdToDoc.set(e,i),this.squidDocIdToProjectedFields.delete(e),i}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const i=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,i),this.squidDocIdToProjectedFields.delete(e),i}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 n=this.squidDocIdToProjectedFields.get(e);return void 0===n||!!t?.length&&t.every(e=>n.has(e))}group(e,t){return Object.values(ri(e,e=>ai(t.map(t=>Jn(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const n=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(wt),{sortOrder:i,limitBy:s}=t,r=n.sort((e,t)=>this.compareSquidDocs(e,t,i)),o=t.limit<0?2e3:t.limit;let a;if(s){const{limit:e,fields:t,reverseSort:n}=s,i=this.group(r,t);let c;c=n?i.map(t=>t.slice(-e)):i.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 n={};"__id"in e&&(n.__id=e.__id),"__docId__"in e&&(n.__docId__=e.__docId__);for(const i of t)if(i.includes(".")){const t=Jn(e,i);void 0!==t&&Yn(n,i,t)}else i in e&&(n[i]=e[i]);return n}migrateDocId(e,t){const n=this.getDocumentOrUndefined(e);if(!n)return;Xn(this.squidDocIdToDoc,e,t),Xn(this.squidDocIdToProjectedFields,e,t);const i=ki(t),s=ui(i.docId);this.saveDocument(t,{...n,...s,__docId__:i.docId})}countDocsUpTo(e,t,n){let i=0;for(const s of e){const e=this.squidDocIdToDoc.get(s);e&&this.compareSquidDocs(e,t,n)<=0&&i++}return i}findLastDoc(e,t){let n;for(const i of e)(!n||this.compareSquidDocs(i,n,t)>0)&&(n=i);return n}compareSquidDocs(e,t,n){for(const{fieldName:i,asc:s}of n){const n=si(Jn(e,i),Jn(t,i));if(0!==n)return s?n:-n}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class xs{constructor(e){this.rpcManager=e}async emit(e){const t={event:e};await this.rpcManager.post("events/emit",t)}}class Bs{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const n={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",n)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class Ps{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const n={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",n,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const n={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",n)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class Us{constructor(e,t,n,i,s){this.socketManager=e,this.rpcManager=t,this.clientIdService=n,this.isListening=!1,this.listeners={},this.ownedJobs=new Set,i.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(p(),_(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Ii.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(t=>{const n=this.listeners[e];n&&(n.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 s(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(n=>{t.error(n),delete this.listeners[e]}),m(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe(g(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,n=t.id,i=this.listeners[n];if(i){if("completed"===t.status)i.next(t.result);else if("failed"===t.status){const e=Object.assign(new Error(t.error||"Job failed"),{errorType:t.errorType});i.error(e)}else console.error("Unexpected job status:",t.status,"for jobId:",n);delete this.listeners[n]}}))}async resolveJob(e,t,n,i){try{await this.rpcManager.post("job/resolveJob",{jobId:e,status:t,result:n,error:i})}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=>Ii.debug("Job keep-alive failed:",e))},15e3))}stopKeepAlive(){void 0!==this.keepAliveHandle&&(clearInterval(this.keepAliveHandle),this.keepAliveHandle=void 0)}}class Ls{constructor(e,t,n){this.graphId=e,this.rpcManager=t,this.jobClient=n}async invoke(e={}){const t=pn();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,timeoutMs:e.timeoutMs,graphContext:e.context,jobId:t}),await this.jobClient.awaitJob(t)}async invokeAsync(e={}){const t=pn();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,timeoutMs:e.timeoutMs,graphContext:e.context,jobId:t}),t}async resume(e,t,n={}){const i=pn();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,timeoutMs:n.timeoutMs,graphContext:n.context,jobId:i}),await this.jobClient.awaitJob(i)}async resumeAsync(e,t,n={}){const i=pn();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,timeoutMs:n.timeoutMs,graphContext:n.context,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 Qs{constructor(e,t){this.rpcManager=e,this.jobClient=t}graph(e){return new Ls(e,this.rpcManager,this.jobClient)}}const $s="squid_mgmt_";function Gs(e="n_"){return`${e}${mn(10).toLowerCase()}`}const Hs=e=>e();class Ks extends Error{constructor(e,t,n,i,s){super(e),this.statusCode=t,this.url=n,this.headers=i,this.body=s}}const Ws="1.0.502";async function Vs(e){return Zs({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 Js(e){return Zs({...e,method:"GET",files:[],filesFieldName:""})}async function zs(e){return Zs({...e,method:"PUT"})}async function Ys(e){return Zs({...e,method:"PATCH"})}async function Xs(e){return Zs({...e,method:"DELETE",files:[],filesFieldName:""})}async function Zs(e){const t=await async function({headers:e,files:t,filesFieldName:n,message:i,url:s,extractErrorMessage:r,method:o,abortSignal:a}){const c=new Headers(e);c.append(Sn,Gs("c_")),c.append(Mn,Ws);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 i of t)e.append(n||"files",i,i.name);e.append("body",ci(i)),u.body=e}else void 0!==i&&(c.append("Content-Type","application/json"),u.body=ci(i));else"DELETE"===o&&void 0!==i&&(c.append("Content-Type","application/json"),u.body=ci(i));try{const e=await fetch(s,u),t={};if(e.headers.forEach((e,n)=>{t[n]=e}),!e.ok){const n=await e.text(),i=er(n);if(!r)throw new Ks(n,e.status,s,t,i);let o;try{o="string"==typeof i?i:i?.message||n}catch{}throw o||(o=e.statusText),new Ks(o,e.status,s,t,i)}const n=await e.text();return Ii.debug(`received response from url ${s}: ${JSON.stringify(n)}`),{body:n,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Ii.debug(`Unable to perform fetch request to url: ${s}`,e),e}}(e);return t.body=er(t.body),t}function er(e){if(e){try{return ui(e)}catch{}return e}}class tr{constructor(e){St(e.apiKey.startsWith($s),`Invalid management API key format. Key must start with '${$s}'`),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,n){const i=B(this.consoleRegion,"console",`openapi/iac/management/${t}`),s={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await Vs({url:i,headers:s,message:n,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await Ys({url:i,headers:s,message:n,extractErrorMessage:!0})).body:(await Xs({url:i,headers:s,message:n,extractErrorMessage:!0})).body}}class nr{constructor(e,t,n){this.rpcManager=e,this.lockManager=t,this.querySender=n}async sendMutations(e,t){const n=Ts(e),i=n.map(e=>`sendMutation_${Ti(e.squidDocIdObj)}`);await this.lockManager.lock(...i),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:n,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Ii.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(n,null,2)}),e}finally{this.lockManager.release(...i)}}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 Ii.debug("Error while deleting query results",{error:t,query:JSON.stringify(e,null,2)}),t}finally{this.lockManager.release(t)}}}class ir{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class sr{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"userNotification"===e.type),v(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 rr={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class or{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},n=Object.keys(t).filter(e=>!ar.test(e)||e.length>=cr);St(0===n.length,()=>`Tag name is not allowed: ${n.join(",")}`),this.isReporting=!0;const i={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},s=this.rpcManager.post("/observability/metrics",{metrics:[i]}).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={...rr,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const n=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:n,noDataBehavior:i}=e,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:i}){if("align-by-start-time"===i)return e;const s=t-e;let r=t-Math.floor(s/n)*n;return r>e&&(r-=n),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:i}){if("align-by-end-time"===i)return t-n;const s=t-e;let r=e+Math.floor(s/n)*n;return r>=t&&(r-=n),r}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const n=[];for(let t=0;t<e.groupByTags.length;t++){const i=e.groupByTags[t],s=a[i]?.[0]||"";n.push(s)}t.push({tagValues:n,points:[]})}else"return-result-group-with-default-values"===i&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[n,i]of Object.entries(a)){const s=e.groupByTags.indexOf(n);if(!(s<0))for(let e=0;e<t.length;e++){const n=t[e],r=new Set(i);for(let e=0;e<t.length;e++){const i=t[e];n.tagValues.every((e,t)=>t===s||e===i.tagValues[t])&&r.delete(i.tagValues[s])}if(0!==r.size)for(const e of r){const i={tagValues:[...n.tagValues],points:[]};i.tagValues[s]=e,t.push(i)}}}for(const i of t){if(0!==i.points.length){const e=i.points[0][0],t=i.points[i.points.length-1][0];St(e>=r,()=>`Invalid first point time: ${e}`),St(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+=n){const n=i.points[a];n?n[0]===e?(t.push(n),a++):(St(n[0]>e,()=>`Result point has invalid time: ${n[0]}`),t.push([e,...u])):t.push([e,...u])}i.points=t}}(t,n.resultGroups),n}}const ar=/^[a-zA-Z0-9_-]+$/,cr=1e3;async function ur(e,t,n=500,i){const s=Date.now(),r=e.paginate({pageSize:n,subscribe:!1});let o=0,a=0,c=await r.waitForData();for(i?.({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++,i?.({pageIndex:a,documentCount:c.data.length,totalLoaded:o+c.data.length})}return{count:o,time:Date.now()-s}}async function lr(e,t=500,n){const i=[],s=e.paginate({pageSize:t,subscribe:!1});let r=0,o=await s.waitForData();for(n?.({pageIndex:r,documentCount:o.data.length,totalLoaded:i.length+o.data.length});;){for(const e of o.data){const t=ki(e.squidDocId),n=ui(t.docId),s=t.integrationId===st?n.__id:n;i.push(s)}if(!o.hasNext)break;o=await s.next(),r++,n?.({pageIndex:r,documentCount:o.data.length,totalLoaded:i.length+o.data.length})}return i}function dr(e,t){switch(t.type){case"simple":return function(e,t){const{query:n,dereference:i}=t,{collectionName:s,integrationId:r}=n;let o=e.collection(s,r).query();return o=hr(o,n),i?o.dereference():o}(e,t);case"join":return function(e,t){const{root:n,joins:i,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=n.query;let u=e.collection(a,c).joinQuery(n.alias);return u=hr(u,n.query),Object.entries(i).map(([t,n])=>{const{collectionName:i,integrationId:r}=n,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(i,r).query();l=hr(l,n),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:n}=t,{collectionName:i,integrationId:s}=pr(n[0]),r=n.map(t=>dr(e,t));return e.collection(i,s).or(...r)}(e,t)}}function hr(e,t){const{conditions:n,limit:i,sortOrder:s}=t;for(const t of n){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:n,operator:i,value:s}=t;e.where(n,i,s)}e.limit(i);for(const{fieldName:t,asc:n}of s)e.sortBy(t,n);return e}function pr(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:n}=e.query;return{collectionName:t,integrationId:n}}case"join":{const{collectionName:t,integrationId:n}=e.root.query;return{collectionName:t,integrationId:n}}case"merged":return pr(e.queries[0])}}class gr{constructor(e,t,n){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=n}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:n}=e,i=new gs(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,n).filter(e=>i.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[Ti(e.__docId__,n,t)])}}function fr(e,t){return Qt(function(n,i){var s=0;n.subscribe(ln(i,function(n){return e.call(t,n,s++)&&i.next(n)}))})}class yr{constructor(e,n,i){this.rpcManager=e,this.destructManager=n,this.webSocketConnectionReady$=i,this.safeToSendQueriesToServer=new t(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new t(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new r,n=m(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.gateForCurrentBatch().subscribe(()=>{this.processQueryBatch()})},0),n)}gateForCurrentBatch(){return this.pendingQueryRequests.some(({queryRequest:e})=>e.subscribe)&&this.webSocketConnectionReady$?a([this.safeToSendQueriesToServer,this.webSocketConnectionReady$]).pipe(fr(([e,t])=>e&&t),O(1),hn(()=>!0)):this.safeToSendQueriesToServer.pipe(fr(Boolean),O(1))}async sendQueryDirect(e){const t=await this.rpcManager.post("query/batchQueries",[e]),n=t.errors[e.clientRequestId];if(n)throw n;return t.results[e.clientRequestId]}async waitForAllQueriesToFinish(){return m(this.inflightQueriesCount.pipe(fr(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()),n=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const n=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:i}of e){const e=t.clientRequestId,s=n.errors[e],r=n.results[e];s?i.error(s):i.next(r)}}catch(e){n.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var mr={d:(e,t)=>{for(var n in t)mr.o(t,n)&&!mr.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function br(e,t,...n){e||function(e,...t){const n=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof n)throw n;throw(e=>new Error(e))(n||"Assertion error",...t)}(t,...n)}function Ir(e,t){switch(t.type){case"set":return function(e,t,n){if(void 0===n)return wr(e,t);if(0===t.length)return br("object"==typeof n&&null!==n&&!Array.isArray(n),()=>`Root state must be a record. Trying to set '${n}', type: ${typeof n}`),n;function i(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 n=t[e];br(!Array.isArray(s)||i(n),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${n}'`),s=s[n],br(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 br(!Array.isArray(s)||i(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===n?e:vr(e,t,n)}(e,t.path,t.value);case"delete":return wr(e,t.path);case"batch":return t.actions.reduce((e,t)=>Ir(e,t),e)}}function wr(e,t){br(0!==t.length,"Can't delete an empty path");let n=e;for(let i=0;i<t.length-1;i++){const s=t[i];if(n=n[s],void 0===n)return e;br("object"==typeof n&&null!==n,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,i+1)}', type: ${null===n?"<null>":typeof n}`)}const i=t[t.length-1];return void 0===n[i]?e:vr(e,t,void 0)}function vr(e,t,n){function i(e,n){br(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[n]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];br(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===n?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return i(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===n?i(r,o):r[o]=n,s}function Sr(e,t){const n=[];if("set"===e.type||"delete"===e.type)n.push(e.path);else if("batch"===e.type)for(const t of e.actions)n.push(...Sr(t,"as-is"));return"unique-and-sorted"===t?Tr(n):n}function Mr(e,t){if(e.length<t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function kr(e){const t=[...e];return t.sort((e,t)=>{for(let n=0;n<e.length;n++){if(n===t.length)return 1;const i=e[n].localeCompare(t[n]);if(0!==i)return i}return e.length-t.length}),t}function Tr(e){const t=kr(e),n=t;for(let e=0;e<t.length-1;e++){const i=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];i.length===r.length&&Mr(i,r)&&(n[s]=void 0,e++)}}return n.filter(e=>void 0!==e)}const _r=(Er={Observable:()=>i,Subject:()=>r},Dr={},mr.d(Dr,Er),Dr);var Er,Dr;const Cr=(Or={filter:()=>fr,map:()=>hn},qr={},mr.d(qr,Or),qr);var Or,qr;class Ar{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 n=this._buildPath(e);if(void 0!==n.value)return n.value;const i=t(e);return this._setNodeValue(n,i,void 0===i),i}set(e,t){const n=void 0===t?this._findNode(e):this._buildPath(e);n&&this._setNodeValue(n,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 n=(void 0===t.value?0:1)+t.childrenWithValue;n>0&&this._updateChildrenWithValue(t,-n),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const n=this.getNode(e);return void 0===n?0:n.childrenWithValue+("node-and-children"===t&&void 0!==n.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const n=[];let i=this.root,s=t(i.value,n);if(s!==Ar.StopFillToken){this._setNodeValue(i,s,!1);for(let r=0;r<e.length;r++){const o=e[r];n.push(o);let a=i.children.get(o);if(s=t(null==a?void 0:a.value,n),s===Ar.StopFillToken)break;a||(a={children:new Map,parent:i,childrenWithValue:0},i.children.set(o,a)),this._setNodeValue(a,s,!1),i=a}this._runGc(i)}}visitDfs(e,t,n=[]){const i=this.getNode(n);void 0!==i&&this._visitDfs(e,i,t,[...n])}_visitDfs(e,t,n,i){if("pre-order"===e&&!1===n(t.value,i))return!1;for(const[s,r]of t.children){if(i.push(s),!this._visitDfs(e,r,n,i))return!1;i.pop()}return"in-order"!==e||!1!==n(t.value,i)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const n of e)if(t=t.children.get(n),!t)return;return t}_findNode(e){let t=this.root;for(let n=0;n<e.length&&t;n++)t=t.children.get(e[n]);return t}_buildPath(e){let t=this.root;for(let n=0;n<e.length;n++){const i=e[n];let s=t.children.get(i);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(i,s)),t=s}return t}_setNodeValue(e,t,n){if(e.value!==t){const n=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,n)}n&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let n=e.parent;n;n=n.parent)if(n.childrenWithValue+=t,n.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))}}Ar.StopFillToken=Symbol("Trie.StopFillToken");class Rr extends _r.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class Nr{constructor(e){this.rootState=e,this.observersTrie=new Ar,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,Cr.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,n){(null==n?void 0:n(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=Ir(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Sr(e,"unique-and-sorted"),n=this.selectChildPathsWithObservers(t),i=Tr([...t,...n]),s=new Ar;for(const e of i)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,n)=>{const i=this.observersTrie.get(n);if(i){const t=this.get(n),s=i.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,n):void 0;i.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],n){const i=0===t.length?void 0:new Ar;for(const e of t)null==i||i.set(e,!0);return new _r.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new Rr);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===n;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,Cr.filter)(({action:e})=>void 0===i||Sr(e,"as-is").some(e=>!i.get(e))),(0,Cr.map)(({action:t,value:n,oldValue:i})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const n=Sr(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=kr(e),n=t;for(let e=0;e<n.length-1;e++){const i=t[e];for(let s=e+1;s<t.length;s++)Mr(t[s],i)&&(n[s]=void 0,e++)}return n.filter(e=>void 0!==e)}(e.length>0?n.filter(t=>Mr(t,e)).map(t=>t.slice(e.length)):n)}return{value:n,oldValue:i,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.observed||this.observersTrie.delete(e)}})}_get(e,t){let n=e;for(let e=0;e<t.length&&void 0!==n;e++){const i=t[e];n=null==n?void 0:n[i]}return n}selectChildPathsWithObservers(e){const t=[];for(const n of e)this.observersTrie.count(n,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,n)=>{e&&t.push([...n])},n);return t}}function jr(e,t,n=(e,t)=>e>t?1:e<t?-1:0,i=0,s=e.length-1){if(s<i)return-1;const r=Math.trunc((i+s)/2);return 0===n(t,e[r])?r:n(t,e[r])>0?jr(e,t,n,r+1,s):jr(e,t,n,i,r-1)}function Fr(e,t,n=(e,t)=>e>t?1:e<t?-1:0){if(-1!==jr(e,t,n))return;let i;for(i=e.length-1;i>=0&&n(e[i],t)>0;i--)e[i+1]=e[i];e[i+1]=t}function xr(e,t,n=(e,t)=>e>t?1:e<t?-1:0){const i=jr(e,t,n);i>-1&&e.splice(i,1)}class Br{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,n,i,s,o,a,c){this.rpcManager=e,this.clientIdService=t,this.documentStore=n,this.destructManager=i,this.documentIdentityService=s,this.querySender=o,this.socketManager=a,this.lockManager=c,this.onOrphanDocuments=new r,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Ur,this.queryResultsSubject=new r,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 Mt(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e,t){const n=this.ongoingQueries.get(e);n?.gotInitialResponse&&this.removeClientRequestIdMapping(e),n&&(n.gotInitialResponse=!0,n.isInFlight=!1,t&&n.subscribe&&n.query.limit>0&&this.setLimitWindow(n,t))}findQueriesForDocument(e,t){const{collectionName:n,integrationId:i}=ki(t),s=this.queryMappingManager.getMapping(n,i);return s?function(e,t){const n=[...e.unconditional||[]],i=new Map;for(const[n,s]of Object.entries(e.conditional||{})){const e=ui(n);let r;if(Oi(e))if(e.fieldName===ft)r=Ri(e.value,t,e.operator,Jn);else{const n=Jn(t,e.fieldName)??null;r=_i(e.value,n,e.operator)}else r=qi(e)?Ai(e,t,Jn):Pr(e,t);if(r)for(const e of s)i.set(e,(i.get(e)||0)+1)}for(const[t,s]of i.entries())s>=e.queriesMetadata[t].condCount&&n.push(t);return n}(s,e):[]}setClientRequestIdsForLocalDoc(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set,i=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([...n,...i]);for(const t of[...n]){if(i.has(t))continue;n.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of i){let n=this.localDocumentToClientRequestIds.get(e);n||(n=new Set,this.localDocumentToClientRequestIds.set(e,n)),n.add(t);let i=this.clientRequestIdToLocalDocuments.get(t);i||(i=new Set,this.clientRequestIdToLocalDocuments.set(t,i)),i.add(e)}return[...s]}addDocToQuery(e,t){let n=this.localDocumentToClientRequestIds.get(e);n||(n=new Set,this.localDocumentToClientRequestIds.set(e,n)),n.add(t);let i=this.clientRequestIdToLocalDocuments.get(t);i||(i=new Set,this.clientRequestIdToLocalDocuments.set(t,i)),i.add(e)}removeDocFromQuery(e,t){const n=this.localDocumentToClientRequestIds.get(e);let i=!n;n&&(n.delete(t),n.size||(this.localDocumentToClientRequestIds.delete(e),i=!0));const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),i&&this.documentStore.deleteDocument(e)}errorOutAllQueries(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of n){const n=this.ongoingQueries.get(e);n&&(this.destructManager.isDestructing?n.dataSubject.complete():n.dataSubject.error(t),n.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const n of e){const e=this.ongoingQueries.get(n);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const i=this.clientRequestIdToLocalDocuments.get(n)||new Set,s=this.documentStore.sortAndLimitDocs(i,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(s,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=Mt(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case Es.UNKNOWN:e.limitUnderflowState=i.size===e.query.limit+100?Es.ENABLED:Es.DISABLED;break;case Es.DISABLED:break;case Es.ENABLED:{const{limitWindowEnd:t,query:n}=e;if((t?this.documentStore.countDocsUpTo(i,t,n.sortOrder):i.size)<n.limit+20){e.limitUnderflowState=Es.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}}e.dataSubject.next(s)}for(const e of t){const t=this.collectAllObservables(e);Mt(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new gs(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,n,i,r,o,c){r&&this.socketManager.notifyWebSocketIsNeeded();const u=Object.keys(n).length>0;return r||u||!this.detachedQueryExecutor||this.lockManager.canGetLock(_s)?d(()=>{const u=this.createOngoingQueryGraph(e,t,n,i,r,!0,{},c);o&&(u.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(u),u.allObservables=new s(1);const l=u.allObservables.pipe(C(e=>a(e).pipe(hn(e=>this.joinResults(e,i,u)))),fr(()=>this.allOngoingQueriesGotInitialResult(u)),E(void 0),M(),fr(([e,t])=>!ei(e,t)),hn(([,e])=>e),r?R():O(1),f(()=>{u.dataSubject.complete(),u.done=!0,this.completeAllSupportedQueries(u),u.allObservables?.complete()})),d=this.collectAllObservables(u);return u.allObservables.next(d),l}).pipe(T()):b(this.detachedQueryExecutor(e)).pipe(hn(e=>e.map(e=>{const n={[t]:e};return this.detachedRecords.add(n),n})))}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 gs(e.query);for(const n of this.ongoingQueries.values()){if(e===n)return;if(this.isValidParent(n)&&t.isSubqueryOfQuery(n.query))return n}}setLimitWindow(e,t){const{limit:n,sortOrder:i}=e.query,s=this.documentStore.findLastDoc(t,i),r=void 0!==s&&i.length>0&&i.every(({fieldName:e})=>void 0!==Jn(s,e));e.limitWindowEnd=r?s:void 0,e.limitUnderflowState=t.length===n+100?Es.ENABLED:Es.DISABLED}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const n=[];for(const i of t){const t=Mt(this.localDocumentToClientRequestIds.get(i));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(i),n.push(i))}n.length&&this.onOrphanDocuments.next(n)}registerQueryFinalizer(e){const t=e.clientRequestId,n=Ci(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(k(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(fr(e=>0===e)))),this.queryMappingManager.removeQuery(n),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const n={clientRequestId:t};this.rpcManager.post("query/unsubscribe",n).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t)}),fr(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,n,i,s,r,o,a={},c){if(a[n])return a[n];const u=o&&c?c:this.clientIdService.generateClientRequestId(),l=[],d={clientRequestId:u,activated:o,alias:n,query:e,subscribe:r,dataSubject:new t(null),supportedQueries:l,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t(0),queryRegistered:new t(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?Es.UNKNOWN:Es.DISABLED};this.registerQueryFinalizer(d),this.ongoingQueries.set(u,d),a[n]=d;for(const[e,t]of Object.entries(s)){const o=t.leftAlias;if(o!==n&&e!==n)continue;const c=o===n?e:o;if(o===n){const e=this.createOngoingQueryGraph(i[c],c,i,s,r,!1,a);e.joinCondition=t,l.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(i[c],c,i,s,r,!1,a)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const n=e.alias;t.push(e.dataSubject.pipe(fr(Boolean),hn(e=>({docs:e,alias:n}))));for(const n of e.supportedQueries)this.collectAllObservables(n,t);return t}joinResults(e,t,n){const i=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let s=i[n.alias].map(e=>({[n.alias]:e}));const r=this.getOngoingQueriesBfs(n),o=new Set;for(let e=1;e<r.length;e++){const n=r[e].alias;o.has(n)||(o.add(n),s=this.join(s,n,i[n],t[n]))}return s}join(e,t,n,i){if(!e.length)return e;const s=Object.keys(e[0]);if(!i||!s.includes(i.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(n||[]).forEach(e=>{const t=this.transformKey(e[i.right]);r.has(t)||r.set(t,[]),Mt(r.get(t)).push(e)}),e.flatMap(e=>{const n=r.get(this.transformKey(e[i.leftAlias]?.[i.left]))||[];return n.length?n.map(n=>({...e,[t]:n})):i.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],n=[e];for(;n.length;){const e=Mt(n.shift());e.isEmptyForJoin||(t.push(e),n.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,n){const i=Mt(n.joinCondition),s=n.query;if(n.activated){if(!n.canExpandForJoin)return!1;const r=Mt(n.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===n.alias),o=new Set(e.map(e=>e[i.left]??null));for(const e of r)e.query.conditions.filter(Oi).filter(e=>e.fieldName===i.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=ni(s);a.conditions=a.conditions.filter(e=>!Oi(e)||e.fieldName!==i.right),[...o].forEach(e=>{a.conditions.push({fieldName:i.right,operator:"==",value:e})});const c={...n,query:a,activated:!0,gotInitialResponse:!1,dataSubject:new t(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),Mt(n.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(n.activated=!0,s.conditions.filter(Oi).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(n),n.canExpandForJoin=!1,!0;const t=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return t.length?(s.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(n)):n.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=Mt(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(fr(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 n=e.query,i=e.clientRequestId,s=Ci(this.clientIdService.getClientId(),i);this.queryMappingManager.addQuery(n,s),this.ongoingQueries.set(i,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},i=new gs(e.query);e.limitWindowEnd=void 0,t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(fr(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",n).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(n=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,n),e.dataSubject.error(n)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const s=k(e.queryRegistered.pipe(fr(Boolean),h(2e3),O(1)),this.destructManager.observeIsDestructing().pipe(O(1)));t.dataSubject.pipe(A(()=>!e.done),q(s),fr(Boolean),R(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),hn(e=>e.filter(e=>i.documentMatchesQuery(e)))).subscribe({next:t=>{for(const n of t)this.setClientRequestIdsForLocalDoc(Ti(n.__docId__,e.query.collectionName,e.query.integrationId),n);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,n=t>0&&e.subscribe?t+100:t,i={query:{...e.query,limit:n},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(i).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()):(Ii.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 n of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{n.has(t)&&(n.delete(t),n.add(e[t]))});t.forEach(t=>{Xn(this.localDocumentToClientRequestIds,t,e[t])})}}function Pr(e,t){for(const n of e.fields){const e=Jn(t,n.fieldName)??null;if(_i(n.value,e,n.operator))return!0;if(_i(n.value,e,"!="))return!1}return!1}class Ur{constructor(){this.stateService=new Nr({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let n=0;const i=new Set;for(const s of e.conditions){if(Oi(s)&&["=="].includes(s.operator)){const e=li(s.fieldName);i.has(e)||(n++,i.add(e))}else n++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];Fr(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const n=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],i=[...this.stateService.get(n)||[]];Fr(i,t),this.stateService.set(n,i)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],n)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const n of t.conditions){const i=this.getConditionStatePath(t,n),s=[...this.stateService.get(i)||[]];xr(s,e),s.length?this.stateService.set(i,s):this.stateService.delete(i)}if(!t.conditions.length){const n=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],i=[...this.stateService.get(n)||[]];xr(i,e),this.stateService.set(n,i)}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",(n=t,ai(n))];var n}}class Lr{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 w(a(t).pipe(g(e=>!e.includes(!0)),O(1))),await this.lock(...e)}release(...e){for(const t of e){const e=Mt(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){St(this.canGetLock(...e),"Cannot acquire lock sync");for(const n of e)this.locks[n]=new t(!0)}}class Qr{constructor(e,t,n){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)}),n.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let n=this.queueManagers.get(e);n||(n=new Map,this.queueManagers.set(e,n));let i=n.get(t);return i||(i=new Gr(e,t,this.rpcManager,this.socketManager),n.set(t,i)),i}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const $r="subscriptionMutex";class Gr{constructor(e,t,n,i){this.integrationId=e,this.topicName=t,this.rpcManager=n,this.socketManager=i,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new Lr}async produce(e){await this.lockManager.lock($r);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release($r)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),d(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe(f(()=>{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($r);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 r}finally{this.lockManager.release($r)}}async performUnsubscribe(){await this.lockManager.lock($r);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release($r)}}}class Hr{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 m(I(10).pipe(g(()=>this.attemptConsume()),y()))}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 Kr{constructor(e,n,i,s,r,o){this.region=e,this.appId=n,this.authManager=r,this.clientIdService=o,this.staticHeaders={},this.onGoingRpcCounter=new t(0);for(const[e,t]of Object.entries(s))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 a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Hr(60*a,5),ai:new Hr(20*a,5),secret:new Hr(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:n}=await this.authManager.getAuthData();if(!t)return{};let i=`Bearer ${t}`;return n&&(i+=`; IntegrationId ${n}`),{Authorization:i}}async awaitAllSettled(){await m(this.onGoingRpcCounter.pipe(g(e=>0===e)))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,n=[],i="files",s={},r){return(await this.rawPost(e,t,n,i,!0,s,r)).body}async rawPost(e,t,n=[],i="files",s=!0,r={},o){return this.runRawRequest(e,r,async r=>{Ii.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const a=this.resolveUrl(e);return await Vs({url:a,headers:r,message:t,files:n,filesFieldName:i,extractErrorMessage:s,abortSignal:o})})}async get(e,t,n=!0){return(await this.rawGet(e,t,n)).body}async rawGet(e,t,n=!0){return this.runRawRequest(e,{},async i=>{let s=this.resolveUrl(e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,n])=>{e.append(t,String(n))}),s+=`?${e.toString()}`}return Ii.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await Js({url:s,headers:i,extractErrorMessage:n})})}async put(e,t,n=[],i="files"){return(await this.rawPut(e,t,n,i)).body}async rawPut(e,t,n=[],i="files",s=!0){return this.runRawRequest(e,{},async r=>{Ii.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const o=this.resolveUrl(e);return await zs({url:o,headers:r,message:t,files:n,filesFieldName:i,extractErrorMessage:s})})}async patch(e,t,n=[],i="files"){return(await this.rawPatch(e,t,n,i)).body}async rawPatch(e,t,n=[],i="files",s=!0){return this.runRawRequest(e,{},async r=>{Ii.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const o=this.resolveUrl(e);return await Ys({url:o,headers:r,message:t,files:n,filesFieldName:i,extractErrorMessage:s})})}async delete(e,t,n=!0){return(await this.rawDelete(e,t,n)).body}async rawDelete(e,t,n=!0){return this.runRawRequest(e,{},async i=>{Ii.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const s=this.resolveUrl(e);return await Xs({url:s,headers:i,message:t,extractErrorMessage:n})})}async runRawRequest(e,t,n){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const i=await this.getAuthHeaders(),s={...this.staticHeaders,...i,...t};return await n(s)}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")?e:B(this.region,this.appId,e)}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?Mt(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?Mt(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):Mt(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}function Wr(e){St(!e.isPassiveMode,"This operation is not available in passive mode. Use active mode for real-time features.")}class Vr{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 Jr(){}const zr="undefined"!=typeof process&&process.versions?.node?x(220):bi().WebSocket;class Yr{constructor(e,n,i,s=Hs,o,a,c){this.clientIdService=e,this.region=n,this.appId=i,this.messageNotificationWrapper=s,this.destructManager=o,this.authManager=a,this.runtimeOptions=c,this.webSocketObserver=new r,this.allMessagesObserver=new r,this.connectionReady=new t(!1),this.seenMessageIds=new Set,this.destructSubject=new r,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new t(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe(g(Boolean),O(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe(_(1),g(e=>!e),C(()=>k(N(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Ii.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Ii.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe(g(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe(g(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?Ii.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Ii.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Ii.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Ii.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(p())}async awaitConnectionReady(){Wr(this.runtimeOptions),await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){Wr(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&&(Ii.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 m(k(this.connectionReady.pipe(g(Boolean)),N(12e4).pipe(R(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))).pipe(q(this.destructSubject)))}catch(e){if(this.destructManager.isDestructing)return;throw e}const t=await this.authManager.getToken();if(this.connectionReady.value)try{St(this.socket,"Socket is undefined in sendMessageAsync");const n=ci({message:e,authToken:t});Ii.debug(this.clientIdService.getClientId(),"Sending message to socket: ",n),this.socket.send(n)}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(ci({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=B(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Ii.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const n=`${e}?clientId=${t}`;this.socket=function(e,t={}){let n,i=0,s=1;const r={connected:!1,closeCalled:!1,open(){n=new(zr?.WebSocket??zr)(e,t.protocols||[]),n.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.")}:Jr,n.onopen=function(e){r.connected=!0,(t.onopen||Jr)(e),i=0},n.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return Ii.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Jr)(e),void r.reconnect(e);(t.onclose||Jr)(e)},n.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||Jr)(e)}},reconnect(e){const n=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&i++<n?s=setTimeout(function(){(t.onreconnect||Jr)(e),Ii.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||Jr)(e)},json(e){n.send(JSON.stringify(e))},send(e){n.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,n.close(e,t)}catch(e){}}};return r.open(),r}(n,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Ii.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Ii.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Ii.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Ii.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Ii.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 Ii.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=ui(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Ii.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new r;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe(R(e=>t.push(e)),o(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await m(N(0)),this.connectionReady.next(!1),await m(N(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Xr(e){var t,n;n="Invalid application ID",St(function(e){return"string"==typeof e}(t=e),()=>Tt(n,"Not a string",t));const i=e.split("-");St(i.length<4,`Invalid application ID: ${e}`);const[s,r,o]=i;return{appId:s,environmentId:r??"prod",squidDeveloperId:o}}function Zr(e,t){return`${Xr(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function eo(e,t,n){return`${Zr(e,t)}${n?`-${n}`:""}`}function to(e){const t=Xr(e);return Zr(t.appId,t.environmentId)}class no{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,n){const i={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:n};await this.rpcManager.post("storage/uploadFile",i,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const n={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",n)}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 io{constructor(e,t,n,i,s){this.rpcManager=e,this.region=t,this.appId=n,this.apiKey=i,this.consoleRegion=s}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}async aiSearch(e,t,n){return await this.rpcManager.post("web/aiSearch",{query:e,allowedDomains:n},[],"files",{},t)}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e){St(this.apiKey,"API key is required to create a short URL");const t="string"==typeof e?{url:e}:e,n={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shorten",n,"create short URL","json")}async createShortUrls(e){St(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,n={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shortenMany",n,"create short URLs","json")}async deleteShortUrl(e){St(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){St(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,n,i){const s=P(this.region,this.consoleRegion,`openapi/sqd/${e}`),r=await fetch(s,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(t)});if("ignore"===i)return void St(r.ok,`Failed to ${n} (${r.status}): ${r.statusText}`);const o=await r.text();return St(r.ok,`Failed to ${n} (${r.status}): ${o}`),JSON.parse(o)}}class so{constructor(e,t,n){this.rpcManager=e,this.region=t,this.appId=n}async executeWebhook(e,t={}){const{headers:n={},queryParams:i={},body:s,files:r=[]}=t,o=await this.rpcManager.getAuthHeaders(),a={...this.rpcManager.getStaticHeaders(),...o,...n};let c=B(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(i&&Object.keys(i).length>0){const e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{e.append(t,String(n))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(Sn,Gs("c_")),u.append(Mn,Ws),r&&r.length>0){const e=new FormData;for(const t of r)e.append("file",t,t.name);s&&"object"==typeof s&&Object.entries(s).forEach(([t,n])=>{e.append(t,String(n))}),l=e}else u.append("Content-Type","application/json"),l=ci(s||{});const d=await fetch(c,{method:"POST",headers:u,body:l}),h={};if(d.headers.forEach((e,t)=>{h[t]=e}),!d.ok){const e=await d.text();let t;try{t=JSON.parse(e)}catch{t=e}const n="string"==typeof t?t:t?.message||d.statusText;throw new Ks(n,d.status,c,h,t)}const p=await d.text();let g;try{g=JSON.parse(p)}catch{g=p}return g}getWebhookUrl(e){return B(this.region,this.appId,e?`webhooks/${encodeURIComponent(e)}`:"webhooks")}}class ro{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Os,St(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,n=eo(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new wi(this.destructManager),Ii.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Wn(e.apiKey,e.authProvider),this.socketManager=new Yr(this.clientIdService,e.region,n,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new Kr(e.region,n,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new sr(this.socketManager,this.rpcManager),this.jobClient=new Us(this.socketManager,this.rpcManager,this.clientIdService,this.destructManager,this.runtimeOptions),this.langGraphClient=new Qs(this.rpcManager,this.jobClient),this.backendFunctionManager=new yi(this.rpcManager),this.aiClient=new Gn(this.socketManager,this.rpcManager,this.jobClient,this.clientIdService,this.backendFunctionManager,()=>this.metricAnnotations),this.apiClient=new Kn(this.rpcManager),this.eventsClient=new xs(this.rpcManager),this.documentStore=new Fs,this.lockManager=new Lr,this.distributedLockManager=new qs(this.socketManager,this.destructManager),this.documentIdentityService=new Ns(this.documentStore,this.destructManager),this.documentReferenceFactory=new js(this.documentIdentityService),this.querySender=new yr(this.rpcManager,this.destructManager,this.socketManager.observeConnectionReady()),this.observabilityClient=new or(this.rpcManager),this.schedulerClient=new Vr(this.rpcManager),this._appId=n,this.querySubscriptionManager=new Br(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new gr(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new nr(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Fi(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService,i),this.dataManager=new Ds(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new Wi(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new so(this.rpcManager,e.region,n),this.nativeQueryManager=new ir(this.rpcManager),this._connectionDetails=new Vi(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new Qr(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new Ut(this.rpcManager,this.options.region,to(n),this.options.consoleRegion,this.backendFunctionManager),this.webClient=new io(this.rpcManager,this.options.region,to(n),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=ai(e);let n=ro.squidInstancesMap[t];return n||(n=new ro(e),ro.squidInstancesMap[t]=n,n)}static getInstances(){return Object.values(ro.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=st){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,...n){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...n)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}getWebhookUrl(e){return this._validateNotDestructed(),this.webhookManager.getWebhookUrl(e)}executeNativeRelationalQuery(e,t,n={}){const i={type:"relational",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativePureQuery(e,t,n={}){const i={type:"pure",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativeMongoQuery(e,t,n){const i={type:"mongo",collectionName:t,aggregationPipeline:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativeElasticQuery(e,t,n,i="_search",s="GET"){const r={type:"elasticsearch",index:t,endpoint:i,method:s,body:n,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 no(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new Bs(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new Ps(this.rpcManager)}events(){return this._validateNotDestructed(),this.eventsClient}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,n){const i=await this.acquireLock(e,n);try{return await t(i)}finally{i.release()}}queue(e,t=rt){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(ro.squidInstancesMap).find(([,e])=>e===this);e&&delete ro.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,n)=>B(e,t,n),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,n)=>eo(e,t,n)}}_validateNotDestructed(){St(!this.destructManager.isDestructing,"The client was already destructed.")}}const oo=18,ao=100,co=50,uo=200,lo=500,ho=500,po=1e3,go=200,fo=20,yo=2e4;export{$ as AGENT_STATUS_TITLE_ACCESSING_KB,Q as AGENT_STATUS_TITLE_AGENT_RESPONSE,H as AGENT_STATUS_TITLE_AI_FUNCTION_RESULT,G as AGENT_STATUS_TITLE_CALLING_AI_FUNCTION,V as AGENT_STATUS_TITLE_GREPPING_KB,K as AGENT_STATUS_TITLE_INSPECTING_KB_METADATA,W as AGENT_STATUS_TITLE_QUERYING_KB_GRAPH,J as AGENT_STATUS_TITLE_QUERYING_SPREADSHEET,ze as AI_AGENTS_INTEGRATION_ID,ee as AI_AGENT_CONNECTION_EVENT_TYPE,_e as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,Te as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Y as AI_CHAT_MESSAGE_SOURCE,re as AI_CODE_INTERPRETER_PROVIDER_TYPES,fe as AI_EMBEDDINGS_MODEL_NAMES,ie as AI_FILE_PROVIDER_TYPES,ke as AI_IMAGE_MODEL_NAMES,Re as AI_KB_ACCESS_CONTROL_MODES,De as AI_MODEL_SOURCES,z as AI_PROVIDER_ERROR_TYPE,ne as AI_PROVIDER_TYPES,Qe as AI_VOICE_GREETING_MODES,Le as AI_VOICE_RELAY_PROVIDERS,$e as AI_VOICE_SESSION_EVENT_TYPE,mt as ALL_OPERATORS,ue as ANTHROPIC_CHAT_MODEL_NAMES,Ge as API_INJECTION_FIELD_TYPES,yt as ARRAY_OPERATORS,Ze as AUTH_INTEGRATION_TYPES,Ut as AdminClient,qn as AiAgentClient,Cn as AiAgentReference,Rn as AiAudioClient,Gn as AiClient,Nn as AiFilesClient,jn as AiImageClient,Pn as AiKnowledgeBaseClient,Bn as AiKnowledgeBaseReference,Un as AiMatchMakingClient,$n as AiVoiceClient,Qn as AiWebVoiceCall,Kn as ApiClient,Pt as ApiKeysSecretClient,Wn as AuthManager,ge as BEDROCK_EMBEDDING_MODEL_NAMES,We as BUILT_IN_AGENT_ID,st as BUILT_IN_DB_INTEGRATION_ID,rt as BUILT_IN_QUEUE_INTEGRATION_ID,ot as BUILT_IN_STORAGE_INTEGRATION_ID,xe as BULK_INGESTION_MAX_MULTIPART_FILE_BYTES,Ue as BULK_INGESTION_SPEEDS,yi as BackendFunctionManager,xi as BaseQueryBuilder,It as CLIENT_CONNECTION_STATES,vi as CLIENT_ID_GENERATOR_KEY,Si as CLIENT_REQUEST_ID_GENERATOR_KEY,Ve as CONNECTOR_IDS,Ui as Changes,wi as ClientIdService,Hi as CollectionReference,Wi as CollectionReferenceFactory,Vi as ConnectionDetails,U as ConnectorClient,Xe as DATA_INTEGRATION_TYPES,Z as DEFAULT_PII_CLASSIFIER_MODEL,X as DEFAULT_PII_ENTITY_TYPES,oo as DEFAULT_SHORT_ID_LENGTH,ft as DOC_ID_FIELD,Ds as DataManager,Qi as DereferencedJoin,Os as DestructManager,As as DistributedLockImpl,qs as DistributedLockManager,Ni as DocumentReference,js as DocumentReferenceFactory,Fs as DocumentStore,An as EMPTY_CHAT_ID,Ke as ENVIRONMENT_IDS,xs as EventsClient,Bs as ExternalAuthClient,Ps as ExtractionClient,ao as FETCH_BEYOND_LIMIT,je as FILE_NAME_METADATA_FIELD_NAME,Me as FLUX_MODEL_NAMES,Fe as FOLDER_PATH_METADATA_FIELD,Ne as FOLDER_PATH_METADATA_FIELD_NAME,qe as FUNCTION_AFFINITY_SCOPES,ae as GEMINI_CHAT_MODEL_NAMES,tt as GRAPHQL_INTEGRATION_TYPES,co as GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES,uo as GREP_KNOWLEDGE_BASE_MAX_MATCHES,lo as GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS,ho as GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS,ce as GROK_CHAT_MODEL_NAMES,Gi as GroupedJoin,nt as HTTP_INTEGRATION_TYPES,Je as HttpStatus,it as INTEGRATION_SCHEMA_TYPES,Ye as INTEGRATION_TYPES,xt as IntegrationClient,Us as JobClient,Li as JoinQueryBuilder,po as KNOWLEDGE_BASE_GRAPH_EXPLORE_MAX_NODES,go as KNOWLEDGE_BASE_GRAPH_SEARCH_MAX_LENGTH,Qs as LangGraphClient,Ls as LangGraphReference,pi as LastUsedValueExecuteFunctionCache,Es as LimitUnderflowState,gr as LocalQueryManager,Be as MAX_UPLOAD_FILE_BYTES,et as MCP_OAUTH_INTEGRATION_TYPES,ht as METRIC_DOMAIN,dt as METRIC_FUNCTIONS,pt as METRIC_INTERVAL_ALIGNMENT,gt as METRIC_NO_DATA_BEHAVIOR,tr as ManagementClient,Ln as MatchMaker,nr as MutationSender,Hs as NOOP_FN,ir as NativeQueryManager,sr as NotificationClient,we as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,ve as OPENAI_AUDIO_MODEL_NAMES,Ie as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,oe as OPENAI_CHAT_MODEL_NAMES,he as OPENAI_EMBEDDINGS_MODEL_NAMES,be as OPENAI_IMAGE_MODEL_NAMES,Ee as OPEN_AI_CREATE_SPEECH_FORMATS,or as ObservabilityClient,ji as Pagination,Pi as QueryBuilder,Fi as QueryBuilderFactory,yr as QuerySender,Br as QuerySubscriptionManager,Qr as QueueManagerFactory,Gr as QueueManagerImpl,Pe as RAG_TYPES,te as RERANK_PROVIDERS,_s as RUN_IN_TRANSACTION_MUTEX,Hr as RateLimiter,Kr as RpcManager,Et as SOURCE_CODE_ANALYZER_MODELS,_t as SOURCE_CODE_ANALYZE_FUNCTION_ID,Dt as SOURCE_CODE_CACHE_STRATEGIES,Ct as SOURCE_CODE_EXECUTION_MODES,qt as SOURCE_CODE_INTEGRATION_TYPES,fo as SOURCE_CODE_MAX_REPOSITORIES,yo as SOURCE_CODE_MAX_SUPPLEMENTAL_INSTRUCTIONS_LENGTH,Ot as SOURCE_CONTROL_PROVIDERS,ct as SQUID_BUILT_IN_INTEGRATION_IDS,lt as SQUID_METRIC_NAMES,bt as SQUID_REGIONS,Se as STABLE_DIFFUSION_MODEL_NAMES,Vr as SchedulerClient,Bt as SecretClient,Yr as SocketManager,ro as Squid,Ks as SquidClientError,no as StorageClient,Ae as VECTOR_DB_TYPES,le as VENDOR_AI_CHAT_MODEL_NAMES,pe as VOYAGE_EMBEDDING_MODEL_NAMES,io as WebClient,so as WebhookManager,Wr as assertNotPassiveMode,di as compareArgsByReference,hi as compareArgsBySerializedValue,dr as deserializeQuery,Ce as embeddingModelSelectionOf,fn as generateId,mn as generateShortId,bn as generateShortIds,pn as generateUUID,gn as generateUUIDPolyfill,P as getConsoleUrl,mi as getCustomizationFlag,ye as isAiEmbeddingsModelName,ut as isBuiltInIntegrationId,se as isFileCapableProviderType,at as isIntegrationDisabled,me as isIntegrationEmbeddingModelSpec,Oe as isIntegrationModelSpec,He as isPlaceholderParam,de as isVendorAiChatModelName,lr as loadQueryResultDocIds,Rt as normalizeBitbucketRepositorySelection,At as normalizeGitHubRepositorySelection,Dn as observeAiStatusUpdates,Xs as rawSquidHttpDelete,Js as rawSquidHttpGet,Ys as rawSquidHttpPatch,Vs as rawSquidHttpPost,zs as rawSquidHttpPut,gi as transformFileArgs,er as tryDeserializing,ur as visitQueryResults};
1
+ import*as e from"ws";import{BehaviorSubject as t,NEVER as n,Observable as s,ReplaySubject as i,Subject as r,auditTime as o,combineLatest as a,combineLatestWith as c,concatMap as u,defaultIfEmpty as l,defer as d,delay as h,distinctUntilChanged as p,filter as g,finalize as f,first as y,firstValueFrom as m,from as b,interval as I,lastValueFrom as w,map as v,of as S,pairwise as M,race as k,share as T,skip as _,startWith as E,switchAll as D,switchMap as C,take as O,takeUntil as q,takeWhile as A,tap as R,timer as j}from"rxjs";var N={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,i)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||s(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0});const r=n(642);t.default=r.PromisePool,i(n(273),t),i(n(642),t),i(n(837),t),i(n(426),t),i(n(858),t),i(n(172),t)},837(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class n 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=n},234(e,t,n){t.PromisePoolExecutor=void 0;const s=n(642),i=n(172),r=n(837),o=n(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 i.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 i.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw i.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw i.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw i.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw i.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw i.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()&&(this.meta.results=Array(e.length).fill(s.PromisePool.notRun)),this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=s.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 n=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(n)}).catch(async s=>{await this.handleErrorFor(s,e,t),this.removeActive(n)}).finally(()=>{this.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),this.runOnTaskFinishedHandlers(e)});this.tasks().push(n),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[n,s]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),n()]).finally(s)}createTaskTimeout(e){let t;return[async()=>new Promise((n,s)=>{t=setTimeout(()=>{s(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,n){if(this.shouldUseCorrespondingResults()&&(this.results()[n]=s.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 i.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(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,n){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const s=n(234);class i{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 i(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}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 s.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=i,i.notRun=Symbol("notRun"),i.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 n extends Error{}t.StopThePromisePoolError=n},172(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class n 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=n},220(t){t.exports=e}};const F={};function x(e){const t=F[e];if(void 0!==t)return t.exports;const n=F[e]={exports:{}};return N[e].call(n.exports,n,n.exports,x),n.exports}function B(e,t,n,s,i){let r="https",o=`${s||t}.${i||e}.${new URL("https://squid.cloud").host}`,a="";/^local/.test(e)&&(r="http",a="8000",/android$/.test(e)?o="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(o="localhost"));const c=r+"://"+o+(a?`:${a}`:""),u=n.replace(/^\/+/,"");return u?`${c}/${u}`:c}function P(e,t){const n=e.replace(/\/+$/,""),s=t.replace(/^\/+/,"");return s?`${n}/${s}`:n}function U(e,t,n=""){return B(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",n)}x.d=(e,t)=>{if(Array.isArray(t))for(var n=0;n<t.length;){var s=t[n++],i=t[n++];x.o(e,s)?0===i&&n++:0===i?Object.defineProperty(e,s,{enumerable:!0,value:t[n++]}):Object.defineProperty(e,s,{enumerable:!0,get:i})}else for(var s in t)x.o(t,s)&&!x.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},x.o=(e,t)=>Object.hasOwn(e,t);class L{constructor(e,t,n,s){this.rpcManager=e,this.iacBaseUrl=U(t,s,`openapi/iac/applications/${n}/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 Q={sharepoint:{functionName:"getSharePointPathStatus",buildArgs:(e,t)=>[{integrationId:e,path:t}]}},$="Agent Response",G="Accessing Knowledge Base",H="Calling AI Function",K="AI Function Result",W="Inspecting Knowledge Base Metadata",V="Querying Knowledge Base Graph",J="Searching Knowledge Base Text",z="Querying Spreadsheet",Y="AI_PROVIDER_ERROR",X=["user","ai"],Z=["email","phoneNumber","creditCard","ssn","iban","passport"],ee="gpt-6-luna",te="ai-agent-connection-event",ne=["cohere","voyage","none"],se=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","openai-compatible","grok","stability","voyage","mistral","textract","azure_document_intelligence","vertex","external"],ie=["openai","gemini","anthropic","grok"];function re(e){return ie.includes(e)}const oe=["openai","anthropic","gemini"],ae=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-luna","gpt-6.1-sol"],ce=["gemini-4-argon","gemini-3.8-flash","gemini-3.5-flash-lite"],ue=["grok-4.6","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],le=["claude-fable-5","claude-fable-5-1","claude-haiku-5-5","claude-opus-5-5","claude-sonnet-5-5"],de=[...ae,...le,...ce,...ue];function he(e){return de.includes(e)}const pe=["text-embedding-3-small"],ge=["voyage-3-large","voyage-4-large","voyage-4"],fe=["titan-embed-text-v2"],ye=[...pe,...ge,...fe];function me(e){return ye.includes(e)}function be(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const Ie=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],we=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],ve=["tts-1","tts-1-hd","gpt-4o-mini-tts"],Se=[...we,...ve],Me=["stable-diffusion-core"],ke=["flux-pro-1.1","flux-kontext-pro"],Te=[...Ie,...Me,...ke],_e=[...we],Ee=[...ve],De=["mp3","opus","aac","flac","wav","pcm"],Ce=["vendor","connector","custom"];function Oe(e){return void 0!==e.integrationId&&void 0!==e.dimensions?{integrationId:e.integrationId,model:e.modelId,dimensions:e.dimensions}:e.modelId}function qe(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const Ae=["pod","worker"],Re=["postgres","mongoAtlas"],je=["none","enforced"],Ne="folderPath",Fe="filename",xe={name:Ne,dataType:"string",required:!1,llmExtraction:!1},Be=104857600,Pe=524288e3,Ue=["contextual","basic"],Le=["economy","auto","fast"],Qe=["twilio","openai"],$e=["phrase","agent"],Ge="ai-voice-session-event",He=["secret","regular"];function Ke(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const We=["dev","prod"],Ve="built_in_agent",Je=["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"],ze={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",Xe=["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","bedrock_embedding","sharepoint","vertex"],Ze=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","snowflake","elasticsearch","legend"],et=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id","azure-entra-id"],tt=["auth0","azure-entra-id","azure-entra-external-id"],nt=["graphql"],st=["api"],it=["data","api","graphql"],rt="built_in_db",ot="built_in_queue",at="built_in_storage";function ct(e){return!1===e.enabled}const ut=[rt,ot,at];function lt(e){return ut.includes(e)}const dt=["squid_functionExecution_count","squid_functionExecution_time"],ht=["sum","max","min","average","median","p95","p99","count"],pt=["user","squid"],gt=["align-by-start-time","align-by-end-time"],ft=["return-no-result-groups","return-result-group-with-default-values"],yt="__docId__",mt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],bt=[...mt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],It=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],wt=["CONNECTED","DISCONNECTED","REMOVED"];function vt(e){return null!=e}let St=e=>new Error(e);function Mt(e,t,...n){e||function(e,...t){const n=Tt(e);if("object"==typeof n)throw n;throw St(n||"Assertion error",...t)}(t,...n)}function kt(e,t,...n){return Mt(e,t,...n),e}function Tt(e){return void 0===e?"":"string"==typeof e?e:e()}function _t(e,t,n){const s=Tt(e);if("object"==typeof s)throw s;return`${s?`${s}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(n)}`}const Et="analyzeCode",Dt=["claude-code","codex"],Ct=["reuse","recreate"],Ot=["read-only","write"],qt=["github","bitbucket"],At=["github","bitbucket"];function Rt(e){const t=function(e){const t=new Set,n=new Set;for(const s of e){Mt(Number.isSafeInteger(s.id)&&s.id>0,"GITHUB_REPOSITORY_ID_INVALID"),Mt(!t.has(s.id),"GITHUB_REPOSITORY_IDS_MUST_BE_UNIQUE"),t.add(s.id),Mt(Nt(s.fullName),"GITHUB_REPOSITORY_NAME_INVALID");const e=s.fullName.toLowerCase();Mt(!n.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),n.add(e),Mt(s.defaultBranch.trim(),"GITHUB_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),Ft(s.cloneUrl,s.fullName,!0),Ft(s.htmlUrl,s.fullName,!1)}return e}(e.repositories??[]),n=0===t.length?e.repository:void 0,s=t.map(e=>e.fullName);Mt(t.length>0||n,"GITHUB_REPOSITORIES_REQUIRED"),Mt(t.length<=20,"GITHUB_REPOSITORY_LIMIT_EXCEEDED");const i=e.defaultRepository??s[0]??n;return Mt(i,"GITHUB_DEFAULT_REPOSITORY_REQUIRED"),Mt(s.some(e=>e.toLowerCase()===i.toLowerCase())||n?.toLowerCase()===i.toLowerCase(),"GITHUB_DEFAULT_REPOSITORY_NOT_ALLOWED"),{...n?{legacyRepository:n}:{},repositories:t,defaultRepository:i}}function jt(e){const t=e.workspace;Mt(t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),"BITBUCKET_WORKSPACE_INVALID");const n=e.repositories;Mt(n.length>0,"BITBUCKET_REPOSITORIES_REQUIRED"),Mt(n.length<=20,"BITBUCKET_REPOSITORY_LIMIT_EXCEEDED");const s=new Set,i=new Set;for(const e of n){const n=e.uuid.trim();Mt(n===e.uuid&&n.length>0,"BITBUCKET_REPOSITORY_ID_INVALID");const r=n.toLowerCase();Mt(!s.has(r),"BITBUCKET_REPOSITORY_IDS_MUST_BE_UNIQUE"),s.add(r);const o=`${t}/`;Mt(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();Mt(!i.has(a),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),i.add(a),Mt(e.defaultBranch.trim(),"BITBUCKET_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),xt(e.cloneUrl,e.fullName,!0),xt(e.webUrl,e.fullName,!1)}const r=e.defaultRepository;return Mt(r&&n.some(e=>e.fullName.toLowerCase()===r.toLowerCase()),"BITBUCKET_DEFAULT_REPOSITORY_NOT_ALLOWED"),{repositories:n,defaultRepository:r}}function Nt(e){return/^[^/\s]+\/[^/\s]+$/.test(e)}function Ft(e,t,n){let s;try{s=new URL(e)}catch{throw new Error("GITHUB_REPOSITORY_URL_INVALID")}const i=`/${t}${n?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?github\.com:\d+(?:\/|$)/i.test(e);Mt(!("https:"!==s.protocol||"github.com"!==s.hostname||r||s.username||s.password||s.search||s.hash||s.pathname!==i),"GITHUB_REPOSITORY_URL_INVALID")}function xt(e,t,n){let s;try{s=new URL(e)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const i=`/${t}${n?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(e);Mt(!("https:"!==s.protocol||"bitbucket.org"!==s.hostname||r||s.username||s.password||s.search||s.hash||s.pathname!==i),"BITBUCKET_REPOSITORY_URL_INVALID")}class Bt{constructor(e,t,n,s,i){this.rpcManager=e,this.backendFunctionManager=i,this.iacBaseUrl=U(t,s,`openapi/iac/applications/${n}/integrations`)}async list(e,t){return(await this.rpcManager.get(this.iacBaseUrl)).filter(n=>(!e||n.type===e)&&(t?.includeDisabled||!ct(n)))}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getPathStatus(e,t){const n=await this.get(e);if(!n)throw new Error(`Integration not found: ${e}`);return async function(e,t,n,s){const i=Q[t];if(!i)return{supported:!1};const r=await e.executeFunction(i.functionName,...i.buildArgs(n,s));return{supported:!0,knowledgeBaseId:r.knowledgeBaseId,entries:r.entries,truncated:r.truncated}}(this.backendFunctionManager,n.type,e,t)}async enable(e){await this.setEnabled(e,!0)}async disable(e){await this.setEnabled(e,!1)}async setEnabled(e,t){const n=await this.get(e);if(!n)throw new Error(`Integration not found: ${e}`);await this.upsertIntegration({...n,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 startRelationshipInference(e,t){const{jobId:n}=await this.rpcManager.post(`${this.iacBaseUrl}/${e}/infer-relationships`,t??{});return n}async getRelationshipInference(e){const{run:t}=await this.rpcManager.get(`${this.iacBaseUrl}/${e}/infer-relationships`);return t}async cancelRelationshipInference(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}/infer-relationships`)}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 Pt{constructor(e){this.rpcManager=e}get apiKeys(){return new Ut(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 n={keys:[e],force:t};return this.rpcManager.post("secret/delete",n)}async deleteMany(e,t=!1){if(0===e.length)return;const n={keys:e,force:t};return this.rpcManager.post("secret/delete",n)}}class Ut{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 Lt{constructor(e,t,n,s,i){this.rpcManager=e,this.region=t,this.appId=n,this.consoleRegion=s,this.backendFunctionManager=i,this.integrationClient=new Bt(this.rpcManager,this.region,this.appId,this.consoleRegion,this.backendFunctionManager),this.connectorClient=new L(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new Pt(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}function Qt(e){return"function"==typeof e}function $t(e){return function(t){if(function(e){return Qt(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 Gt=function(e,t){return Gt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Gt(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 n(){this.constructor=e}Gt(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function Kt(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],s=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Wt(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var s,i,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return o}function Vt(e,t,n){if(n||2===arguments.length)for(var s,i=0,r=t.length;i<r;i++)!s&&i in t||(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}Object.create,Object.create;var Jt,zt=((Jt=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),Jt.prototype.constructor=Jt,Jt);function Yt(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Xt=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,n,s,i;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=Kt(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(Qt(c))try{c()}catch(e){i=e instanceof zt?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=Kt(u),d=l.next();!d.done;d=l.next()){var h=d.value;try{Zt(h)}catch(e){i=null!=i?i:[],e instanceof zt?i=Vt(Vt([],Wt(i)),Wt(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(s=l.return)&&s.call(l)}finally{if(n)throw n.error}}}if(i)throw new zt(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Zt(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).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)&&Yt(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&Yt(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function Zt(e){Qt(e)?e():e.unsubscribe()}Xt.EMPTY;var en={setTimeout:function(e,t){for(var n=[],s=2;s<arguments.length;s++)n[s-2]=arguments[s];var i=en.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,Vt([e,t],Wt(n))):setTimeout.apply(void 0,Vt([e,t],Wt(n)))},clearTimeout:function(e){var t=en.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function tn(){}var nn=sn("C",void 0,void 0);function sn(e,t,n){return{kind:e,value:t,error:n}}var rn=function(e){function t(t){var n,s=e.call(this)||this;return s.isStopped=!1,t?(s.destination=t,((n=t)instanceof Xt||n&&"closed"in n&&Qt(n.remove)&&Qt(n.add)&&Qt(n.unsubscribe))&&t.add(s)):s.destination=ln,s}return Ht(t,e),t.create=function(e,t,n){return new an(e,t,n)},t.prototype.next=function(e){this.isStopped?un(function(e){return sn("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?un(sn("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?un(nn,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}(Xt);Function.prototype.bind;var on=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){cn(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){cn(e)}else cn(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){cn(e)}},e}(),an=function(e){function t(t,n,s){var i,r=e.call(this)||this;return i=Qt(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=s?s:void 0}:t,r.destination=new on(i),r}return Ht(t,e),t}(rn);function cn(e){!function(e){en.setTimeout(function(){throw e})}(e)}function un(e,t){var n=null;n&&en.setTimeout(function(){return n(e,t)})}var ln={closed:!0,next:tn,error:function(e){throw e},complete:tn};function dn(e,t,n,s,i){return new hn(e,t,n,s,i)}var hn=function(e){function t(t,n,s,i,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=s?function(){try{s()}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 n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(rn);function pn(e,t){return $t(function(n,s){var i=0;n.subscribe(dn(s,function(n){s.next(e.call(t,n,i++))}))})}function gn(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():fn()}function fn(){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 yn(){return gn()}function mn(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function bn(e=18,t="",n=""){Mt(t.length<e,"ID prefix is too long"),Mt(!t||!n||n.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let s="";for(let t=0;t<e;t++)s+=mn();if(t.length>0&&(s=t+s.substring(t.length)),n)for(;s.charAt(t.length)===n[t.length];)s=s.substring(0,t.length)+mn()+s.substring(t.length+1);return s}function In({count:e,length:t,prefix:n}){Mt(e>=0,`Invalid IDs count: ${e}`);const s=new Set;for(;s.size<e;)s.add(bn(t||18,n||""));return[...s]}const wn=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function vn(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)vn(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)vn(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(wn.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${wn.join(", ")}`);const n=e[t];if("object"!=typeof n&&"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof n}`)}}function Sn(e,t,n){const s=atob(e),i=new Uint8Array(s.length);for(let e=0;e<s.length;e++)i[e]=s.charCodeAt(e);return new File([i],t,{type:n||"application/octet-stream"})}const Mn="x-squid-traceid",kn="x-squid-appid",Tn="x-squid-client-version",_n="x-squid-integration-access-tokens";class En extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.details=n}}function Dn(e){return JSON.stringify(e)}function Cn(e){return e&&Object.keys(e).length?{[_n]:Dn(e)}:{}}function On(e){if(!e)return{headers:{},options:void 0};const{integrationAccessTokens:t,...n}=e;return{headers:Cn(t),options:n}}function qn(e,t){const{agentId:n,jobId:s}=t;return e.notifyWebSocketIsNeeded(),e.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&(void 0===n||e.agentId===n)),g(e=>!s||e.jobId===s),v(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})))}class An{constructor(e,t,n,s,i,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=n,this.rpcManager=s,this.socketManager=i,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();Mt(t,"Agent not found");const n={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",n)}async updatePii(e){const t=await this.get();Mt(t,"Agent not found");const n={onDetect:"off",...t.options?.pii,...e};await this.setAgentOptionInPath("pii",n)}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,n){return this.chatInternal(e,t,n).responseStream}async transcribeAndChat(e,t,n){const s=this.chatInternal(e,t,n),i=await kt(s.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:s.responseStream,transcribedPrompt:i.transcribedPrompt}}async ask(e,t,n){const s=await this.askInternal(e,!1,t,n);return this.replaceFileTags(s.responseString,s.annotations)}async askWithResult(e,t,n){return this.askInternal(e,!1,t,n)}async askWithAnnotations(e,t,n){const s=await this.askInternal(e,!1,t,n);return{responseString:s.responseString,annotations:s.annotations,routing:s.routing,validation:s.validation}}async askAsync(e,t,n){const{headers:s,options:i}=On(n),[r,o]=jn(i),a={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(o),jobId:t,session:r};await this.post("ai/chatbot/askAsync",a,[],"files",s)}observeStatusUpdates(e){return qn(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,n){return await this.askInternal(e,!1,t,n)}async transcribeAndAskWithVoiceResponse(e,t,n){const s=await this.askInternal(e,!0,t,n),i=s.voiceResponse;return{responseString:s.responseString,transcribedPrompt:s.transcribedPrompt,voiceResponseFile:Sn(i.base64File,`voice.${i.extension}`,i.mimeType)}}async askWithVoiceResponse(e,t,n){const s=await this.askInternal(e,!0,t,n),i=s.voiceResponse;return{responseString:s.responseString,voiceResponseFile:Sn(i.base64File,`voice.${i.extension}`,i.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,n){const s={agentId:this.agentId,request:e,memoryId:t,options:n};return await this.backendFunctionManager.executeFunction("buildAgent",s)}replaceFileTags(e,t={}){let n=e;for(const[e,s]of Object.entries(t)){let t="";const i=s.aiFileUrl.fileName?s.aiFileUrl.fileName:s.aiFileUrl.url;switch(s.aiFileUrl.type){case"image":t=`![${i}](${s.aiFileUrl.url})`;break;case"document":t=`[${i}](${s.aiFileUrl.url})`}const r=`\${id:${e}}`;n=n.replaceAll("`"+r+"`",t).replaceAll(r,t)}return n}async askInternal(e,t,n,s){if(n?.contextMetadataFilter&&vn(n.contextMetadataFilter),n?.contextMetadataFilterForKnowledgeBase)for(const e in n.contextMetadataFilterForKnowledgeBase)vn(n.contextMetadataFilterForKnowledgeBase[e]);s=s||gn();const{headers:i,options:r}=On(n),[o,a]=jn(r);n=this.withMetricAnnotations({...Rn,...a||{}});const c="string"==typeof e;let u="ai/chatbot/";u+=c||t?!c&&t?"transcribeAndAskWithVoiceResponse":c&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const l={agentId:this.agentId,prompt:c?e:void 0,options:n,jobId:s,session:o},d=c?void 0:[e];return await this.post(u,l,d,"file",i),await this.jobClient.awaitJob(s)}chatInternal(e,t,n){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&vn(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)vn(t.contextMetadataFilterForKnowledgeBase[e]);const s=gn(),{headers:i,options:o}=On(t),[a,c]=jn(o),l=void 0===(t=this.withMetricAnnotations({...Rn,...c||{}})).smoothTyping||t.smoothTyping;let d="";const p=new r,g=new r;this.ongoingChatSequences[s]=g;let y=-1;g.pipe(R(({tokenIndex:e})=>{void 0!==e&&e<y&&console.warn("Received token index out of order",e,y),void 0!==e&&(y=e)}),u(({value:e,complete:t,annotations:n})=>t?S({value:e,complete:t,annotations:n}):S(e).pipe((()=>{const e=globalThis.document,t="object"==typeof e&&null!==e&&!0===e.hidden;return l&&!t})()?h(0):R(),pn(e=>({value:e,complete:!1,annotations:void 0})))),A(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:n})=>{d+=e,t&&n&&(d=this.replaceFileTags(d,n)),p.next(d)},error:e=>{console.error(e)},complete:()=>{p.complete()}});const m="string"==typeof e;n=n||gn();const b={agentId:this.agentId,jobId:n,prompt:m?e:void 0,options:t,clientRequestId:s,session:a},I={responseStream:p.pipe(f(()=>{delete this.ongoingChatSequences[s]}),T())};let w;return w=m?this.post("ai/chatbot/chat",b,[],"files",i).catch(e=>{p.error(e),p.complete()}):this.post("ai/chatbot/transcribeAndChat",b,[e],"file",i).catch(e=>{throw p.error(e),p.complete(),e}),I.serverResponse=w.then(()=>this.jobClient.awaitJob(n)).catch(e=>{p.error(e),p.complete()}),I}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,n=[],s="files",i={}){const r={...i};return this.agentApiKey&&(r["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,n,s,r)}}const Rn={smoothTyping:!0,responseFormat:"text"};function jn(e){const{session:t,...n}=e??{};return[t,e&&n]}class Nn{constructor(e,t,n,s,i=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=n,this.backendFunctionManager=s,this.getMetricAnnotations=i,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),pn(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new An(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:n,complete:s,tokenIndex:i,annotations:r}=e.payload;if(s&&!n.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(n.match(/\[.*?]\((.*?)\)/g))t.next({value:n,complete:s,tokenIndex:void 0===i?void 0:i,annotations:r});else for(let e=0;e<n.length;e++)t.next({value:n[e],complete:s&&e===n.length-1,tokenIndex:void 0===i?void 0:i,annotations:r})}}const Fn="__squid_empty_chat_id";class xn{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 n={input:e,options:t},s=await this.rpcManager.post("ai/audio/createSpeech",n);return Sn(s.base64File,`audio.${s.extension}`,s.mimeType)}}class Bn{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 Pn{constructor(e){this.rpcManager=e}async generate(e,t){const n={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",n)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function Un(e){for(const t in e){const n=e[t];Mt("string"==typeof n||"number"==typeof n||"boolean"==typeof n||void 0===n,`Invalid metadata value for key ${t} - cannot be of type ${typeof n}`),Mt(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}const Ln=new Set(["completed","failed","cancelled"]);class Qn{constructor(e,t,n,s,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=n,this.socketManager=s,this.clientIdService=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async 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:n}=await this.rpcManager.post("ai/knowledge-base/setContextScopes",{knowledgeBaseId:this.knowledgeBaseId,contextId:e,scopes:t});return n}async setContextVersionStates(e){return(await this.rpcManager.post("ai/knowledge-base/setContextVersionStates",{knowledgeBaseId:this.knowledgeBaseId,items:e})).results}async upsertContext(e,t){const{failures:n,contextIds:s,graphIndexingSkippedContextIds:i,imageFailures:r}=await this.upsertContexts([e],t?[t]:void 0);if(n.length>0)return{failure:n[0]};const o=s?.[0],a=void 0!==o&&(i?.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,n){for(const t of e)t.metadata&&Un(t.metadata);const s=gn();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:s},t),n?.onUploaded?.(),await this.jobClient.awaitJob(s)}async bulkUpsertContexts(e,t,n){return this.rpcManager.post("ai/knowledge-base/bulk/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contexts:e,speed:n?.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 s(t=>{const n=()=>{this.rpcManager.post("ai/knowledge-base/bulk/subscribeToJob",{jobId:e}).catch(e=>t.error(e))};t.add(this.socketManager.observeNotifications().pipe(g(e=>"bulkIngestionStatus"===e.type),g(t=>t.payload.jobId===e)).subscribe(e=>{t.next(e.payload),Ln.has(e.payload.state)&&t.complete()})),t.add(this.clientIdService.observeClientId().pipe(p(),_(1)).subscribe(()=>n())),this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.awaitConnectionReady().then(n).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(e){return this.rpcManager.post("ai/knowledge-base/getGraphStatus",{...e,knowledgeBaseId:this.knowledgeBaseId})}async getFileStatus(e){return this.rpcManager.post("ai/knowledge-base/getFileStatus",{knowledgeBaseId:this.knowledgeBaseId,path:e})}async getFolderStatus(e,t){return this.rpcManager.post("ai/knowledge-base/getFolderStatus",{knowledgeBaseId:this.knowledgeBaseId,folderPath:e,fileLimit:t})}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 $n{constructor(e,t,n,s){this.rpcManager=e,this.jobClient=t,this.socketManager=n,this.clientIdService=s}knowledgeBase(e){return new Qn(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 Gn{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new Hn(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new Hn(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class Hn{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 Kn{constructor(e,t,n,s){this.sessionId=e,this.callId=t,this.peer=n,this.microphone=s,this.eventListeners=new Set,this.endListeners=new Set,this.ended=!1}static async start(e,t){const n=globalThis,s=n.RTCPeerConnection,i=n.navigator?.mediaDevices;if(!s||!i)throw new Error("A web voice call needs a browser with WebRTC support");const{sink:r,...o}=t,a=await i.getUserMedia({audio:!0}),c=new s,u=r??n.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 Kn(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 n="string"==typeof t.transcript?t.transcript.trim():"";n&&("conversation.item.input_audio_transcription.completed"===t.type?e({role:"user",text:n,at:(new Date).toISOString()}):"response.output_audio_transcript.done"===t.type&&e({role:"agent",text:n,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 Wn{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 Kn.start(this,e)}}class Vn{constructor(e,t,n,s,i,r=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=n,this.clientIdService=s,this.backendFunctionManager=i,this.getMetricAnnotations=r}agent(e=Ve,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 Pn(this.rpcManager)}audio(){return new xn(this.rpcManager)}voice(){return new Wn(this.rpcManager)}matchMaking(){return new Gn(this.rpcManager)}files(e){return new Bn(e,this.rpcManager)}executeAiQuery(e,t,n,s){const{accessToken:i,...r}=n??{},o={integrationId:e,prompt:t,options:r},a=Cn(i?{[e]:i}:void 0);return this.rpcManager.post("ai/query/executeDataQuery",o,[],"files",a,s)}executeAiApiCall(e,t,n,s){const i={integrationId:e,prompt:t,options:n,sessionContext:s};return this.rpcManager.post("ai/query/executeApiQuery",i)}executeAiSpreadsheetQuery(e,t,n,s){const i={prompt:e,files:t,options:n,sessionContext:s};return this.rpcManager.post("ai/query/executeSpreadsheetQuery",i)}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 n={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",n)).settings}observeStatusUpdates(e){return qn(this.socketManager,{jobId:e})}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Nn(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new $n(this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)),this.aiKnowledgeBaseClient}}const Jn={headers:{},queryParams:{},pathParams:{}};class zn{constructor(e){this.rpcManager=e}async get(e,t,n){return this.request(e,t,void 0,n,"get")}async post(e,t,n,s){return this.request(e,t,n,s,"post")}async delete(e,t,n,s){return this.request(e,t,n,s,"delete")}async patch(e,t,n,s){return this.request(e,t,n,s,"patch")}async put(e,t,n,s){return this.request(e,t,n,s,"put")}async request(e,t,n,s,i){const r={integrationId:e,endpointId:t,body:n,options:{...Jn,...this.convertOptionsToStrings(s||{})},overrideMethod:i};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 Yn{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 Xn=/[.\[\]]/;function Zn(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function es(e,t,n){"__proto__"===t?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function ts(e,t){if(!e)return;const n=t.split(Xn);let s,i=e;for(;i&&n.length;){const e=n.shift();if(e){if("object"!=typeof i||!Object.hasOwn(i,e))return;s=i[e],i=s}}return s}function ns(e,t,n,s="."){const i=t.split(s);let r=e;for(;i.length;){const e=kt(i.shift());if(i.length){const t=Zn(r,e),n=us(t)?cs(t)??{}:{};es(r,e,n),r=n}else es(r,e,n)}}function ss(e,t,n){if(e.has(t)){const s=e.get(t);e.delete(t),e.set(n,s)}}function is(e){return null==e}function rs(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const n=typeof e;if(n!==typeof t)return!1;if("object"!==n)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(const n of s)if(!i.includes(n)||!rs(e[n],t[n]))return!1;return!0}function os(e,t){const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=as(e[s],t);return n}function as(e,t){const n=t?t(e):void 0;if(void 0!==n)return n;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return os(e,t);if(e instanceof Map)return new Map(os(Array.from(e),t));if(e instanceof Set)return new Set(os(Array.from(e),t));if(ArrayBuffer.isView(e))return s=e,"undefined"!=typeof Buffer&&s instanceof Buffer?Buffer.from(s):new s.constructor(s.buffer.slice(),s.byteOffset,s.length);var s;const i={};for(const n in e)Object.hasOwnProperty.call(e,n)&&es(i,n,as(e[n],t));return i}function cs(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 us(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ls(e,t){if(e===t||is(e)&&is(t))return 0;if(is(e))return-1;if(is(t))return 1;const n=typeof e,s=typeof t;return n!==s?n<s?-1:1:"number"==typeof e?(Mt("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(Mt("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(Mt("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(Mt("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function ds(e,t){return e.reduce((e,n)=>{const s=t(n),i=Zn(e,s);return i?i.push(n):es(e,s,[n]),e},{})}function hs(e,t=!1){if(Array.isArray(e))return e.map(e=>hs(e,t));if("object"!=typeof e||null===e||e instanceof Date)return e;const n=Object.keys(e).filter(e=>t||"__proto__"!==e),s={};return n.sort().forEach(n=>{es(s,n,hs(e[n],t))}),s}function ps(e){return fs(hs(e))}function gs(e){return fs(hs(e,!0))}function fs(e){if(void 0===e)return null;const t=as(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function ys(e){return as(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,n=t.$date;return n&&1===Object.keys(t).length?new Date(n):void 0})}function ms(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=fs(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let n="";for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return btoa(n)}}const bs=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Is=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(fs(e[n])!==fs(t[n]))return!1;return!0};class ws{constructor(e){this.options=e}get(e){const t=this.cachedEntry,n=this.options.argsComparator||bs,s=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+s&&n(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function vs(e){const t=[],n=[];let s=0;for(const i of e)if("undefined"!=typeof File)if(i instanceof File){n.push(i);const e={type:"file",__squid_placeholder__:!0,fileIndex:s++};t.push(e)}else if(Ss(i)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:i.map((e,t)=>(n.push(i[t]),s++))};t.push(e)}else t.push(i);else t.push(i);return{argsArray:t,fileArray:n}}function Ss(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class Ms{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...n){const{argsArray:s,fileArray:i}=vs(n),r="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(s);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?bs:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,s));if(t)return t.promise}const u=this.createExecuteCallPromise(r,s,i,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:s,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,n,s,i={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:fs(t)},a=ys((await this.rpcManager.post(r,o,n.length>0?n:[],"files",i)).payload);if(a?.__isSquidBase64File__){const e=a;return Sn(e.base64,e.filename,e.mimetype)}return s&&s.set(t,a),a}}function ks(e){if("undefined"!=typeof globalThis)return globalThis[e]}function Ts(){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===Ts()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){Ts().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 _s{static debug(...e){(function(){const e=Ts();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=Ts();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Es{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===Ts().squidTenant,this.clientIdSubject=new t(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe(g(e=>e),v(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe(_(1),g(e=>!e),v(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=Ts()[Cs];return e?e():gn()}generateClientId(){const e=Ts()[Ds];if(e)return e();let t=`${this.isTenant?"tenant-":""}${gn()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Ds="SQUID_CLIENT_ID_GENERATOR",Cs="SQUID_CLIENT_REQUEST_ID_GENERATOR",Os="__squidId";function qs(e){return ys(e)}function As(...e){const[t,n,s]=e,i="object"==typeof t?t:{docId:t,collectionName:n,integrationId:s};return i.integrationId||(i.integrationId=void 0),ps(i)}function Rs(e,t,n){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===n)return rs(e,t);if("!="===n)return!rs(e,t);switch(n){case"<":return!is(e)&&(!!is(t)||t<e);case"<=":return!!is(t)||!is(e)&&t<=e;case">":return!is(t)&&(!!is(e)||t>e);case">=":return!!is(e)||!is(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&js(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&js(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&js(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&js(t,e,!0));case"array_includes_some":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>kt(n,"VALUE_CANNOT_BE_NULL").some(t=>rs(t,e)))}case"array_includes_all":{const n=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>kt(n,"VALUE_CANNOT_BE_NULL").some(t=>rs(t,e)))}case"array_not_includes":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!kt(n,"VALUE_CANNOT_BE_NULL").some(t=>rs(t,e)))}default:throw new Error(`Unsupported operator comparison: ${n}`)}}function js(e,t,n){n||(e=e.toLowerCase(),t=t.toLowerCase());const s=function(e){let t="";for(let n=0;n<e.length;++n)"\\"===e[n]?n+1<e.length&&["%","_"].includes(e[n+1])?(t+=e[n+1],n++):n+1<e.length&&"\\"===e[n+1]?(t+="\\\\",n++):t+="\\":"%"===e[n]?t+="[\\s\\S]*":"_"===e[n]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[n])&&(t+="\\"),t+=e[n]);return t}(t);return new RegExp(`^${s}$`).test(e)}function Ns(e){for(let t=0;t<e.length;t++)if("\\"===e[t]){if(!["%","_","\\"].includes(e[t+1]))return!0;t++}return!1}function Fs(e,t){return`${e}_${t}`}function xs(e){return"fieldName"in e}function Bs(e){return"docIds"in e}function Ps(e,t,n){const s=e.docIds.some(e=>Object.entries(e).every(([e,s])=>Rs(s,n(t,e)??null,"==")));switch(e.operator){case"==":case"in":return s;case"!=":case"not in":return!s}}function Us(e,t,n,s){const i=e,r=s(t,yt);if("string"!=typeof r)return Rs(i,r??null,n);let o;try{o=ys(r)}catch{return Rs(i,r,n)}if(!o||"object"!=typeof o||Array.isArray(o))return Rs(i,r,n);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:ps(e)}if("string"==typeof e)try{const t=ys(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}(i);return Rs(t,e,n)}if(1===a.length){const e=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const n=Object.keys(e);if(1===n.length&&n[0]===t)return e[t]}if("string"==typeof e)try{const n=ys(e);if(n&&"object"==typeof n&&!Array.isArray(n)){const e=Object.keys(n);if(1===e.length&&e[0]===t)return n[t]}}catch{}return e}(i,a[0]);return Rs(e,o[a[0]],n)}return"object"!=typeof i||null===i||Array.isArray(i)?Rs(i,r,n):Rs(ps(i),r,n)}function Ls(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Qs(e){!function(e,t){if(!e)throw new En(t,ze.BAD_REQUEST)}(!e.split(".").includes("__proto__"),`A field path cannot name __proto__: ${e}`)}function $s(e,t){Qs(t);let n=e;for(const e of t.split(".")){if(!Ls(n))return;n=Zn(n,e)}return n}function Gs(e,t,n){Qs(t);const s=t.split(".");let i=e;for(const[e,r]of s.entries()){if(e===s.length-1)return void(i[r]=n);const o=Zn(i,r);if(null!=o&&!Ls(o))throw new Error(`Cannot set path ${t}, ${r} is not an object`);const a=Ls(o)?{...o}:{};i[r]=a,i=a}}function Hs(e,t){Qs(t);const n=t.split(".");let s=e;for(const[e,t]of n.entries()){if(e===n.length-1)return void delete s[t];const i=Zn(s,t);if(!Ls(i))return;const r={...i};s[t]=r,s=r}}function Ks(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 n="string"==typeof e?e:null;switch(t.fn){case"trim":return null===n?null:n.trim();case"extendString":return null===n?t.value:n+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?as(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Ws(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function Vs(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(Mt("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){Object.keys(t.properties).forEach(Qs);const n=as(e);t=as(t);for(const[e]of Ws(n)){const s=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&s>t.split(".").length)&&delete n.properties[e]}for(const[e,s]of Ws(t)){const t=Zn(n.properties,e)??[];n.properties[e]=Js([...t,...s])}return n}(e,t);const n=as(e);for(const[e,s]of Ws(t)){const t=s;for(const s of t){const t=n.properties,i=Ks($s(t,e),s);void 0===i?Hs(t,e):Gs(t,e,i)}}return n}function Js(e){let t=0;for(;t+1<e.length;){const n=zs(e[t],e[t+1]);n?e.splice(t,2,n):++t}return e}function zs(e,t){if("removeProperty"===t.type||"update"===t.type)return t;if("applyNumericFn"===t.type){if(Mt("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type)return Mt("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 Ys(e,t){if(!e)return;const n={...e},s=Ws(t);for(const[e,t]of s){const s=t;for(const t of s){const s=Ks($s(n,e),t);void 0===s?Hs(n,e):Gs(n,e,s)}}return n}function Xs(e){const t={};for(const n of e){const e=`${n.squidDocIdObj.integrationId}/${n.squidDocIdObj.collectionName}/${n.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(n)}const n=[];for(const e in t){const s=t[e].reduce((e,t)=>kt(Vs(e,t),"Merge result cannot be null"));n.push(s)}return n}class Zs{constructor(e,t,n,s,i){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=n,this.projectFields=s,this.identityReference=i,this.refId=gn()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this.identityReference?.squidDocId??this._squidDocId}get data(){return as(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=kt(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:n}=qs(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:n,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 kt(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(v(e=>(kt(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 n={};Object.entries(e).forEach(([e,t])=>{Qs(e);const s=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};n[e]=[s]});const s={type:"update",squidDocIdObj:qs(this.squidDocId),properties:n};return this.dataManager.applyOutgoingMutation(s,t)}async setInPath(e,t,n){return this.update({[e]:as(t)},n)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,n){const s={type:"applyNumericFn",fn:"increment",value:t},i={type:"update",squidDocIdObj:qs(this.squidDocId),properties:{[e]:[s]}};return this.dataManager.applyOutgoingMutation(i,n)}decrementInPath(e,t,n){return this.incrementInPath(e,-t,n)}async upsert(e,t){const n=qs(this.squidDocId),s=n.integrationId;let i=ys(n.docId);if(i[Os]&&(i={}),s===rt&&i.__id)try{const e=ys(i.__id);i={...i,...e}}catch{}const r={type:"insert",squidDocIdObj:n,properties:{...e,__docId__:n.docId,...i}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:qs(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={},n=kt(this.projectFields,"applyProjection called without projectFields"),{integrationId:s}=qs(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const i=s===rt?"__id":"__docId__";if(i in e){const n=e[i];if("string"==typeof n&&n.startsWith("{"))try{const e=ys(n);if("object"==typeof e&&null!==e)for(const[n,s]of Object.entries(e))n in t||(t[n]=s)}catch{}}for(const s of n)if(s.includes(".")){const n=ts(e,s);void 0!==n&&ns(t,s,n)}else Object.hasOwn(e,s)&&es(t,s,e[s]);return t}hasSquidPlaceholderId(){const e=ys(this.squidDocId);if("object"==typeof e&&e.docId){const t=ys(e.docId);if("object"==typeof t&&Object.keys(t).includes(Os))return!0}return!1}}class ei{constructor(e,n={}){this.internalStateObserver=new t(null),this.firstElement=null,this.isDestroyed=new t(!1),this.snapshotSubject=new r,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,Mt(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe(D()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...n},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(g(e=>null!==e),v(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(v(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||is(e)&&is(t))return 0;if(is(e))return-1;if(is(t))return 1;const n=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:s,asc:i}of n){const n=ls(ts(e,s),ts(t,s));if(0!==n)return i?n:-n}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 n=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-n-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const n=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,s=Math.max(0,e.length-n-this.paginateOptions.pageSize);n!==e.length?this.internalStateObserver.next({numBefore:n,numAfter:s,data:e,extractedData:t}):this.prevInternal({numBefore:n,numAfter:s,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:ts(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe(v(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:ts(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await m(k(this.isDestroyed.pipe(g(Boolean),v(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),O(1))))}internalStateToState(e){const{data:t,numBefore:n,numAfter:s,extractedData:i}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(i[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:s>0,hasPrev:n>0}}prevInternal(e){const{numBefore:t,numAfter:n,extractedData:s}=e;this.firstElement=null,this.lastElement=s[t-1],this.internalStateObserver.next(null),this.doNewQuery(s[s.length-n-1],!0)}}class ti{constructor(e,t,n,s,i){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=n,this.documentIdentityService=s,this.mutationSender=i}getForDocument(e){const{collectionName:t,integrationId:n,docId:s}=qs(e),i=ys(s),r=this.get(t,n);for(const[e,t]of Object.entries(i))r.where(e,"==",t);return r}get(e,t){return new ii(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService,this.mutationSender)}}class ni{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(yt,e)}docIds(e){return this.in(yt,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,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"like_cs":"like",t)}notLike(e,t,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"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(Ns(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class si{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return m(this.snapshots(!1).pipe(l([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(pn(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new si(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 si(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new ei(this,e)}}class ii extends ni{constructor(e,t,n,s,i,r,o,a){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.localQueryManager=s,this.documentReferenceFactory=i,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 ms(this.build())}where(e,t,n){if(Mt(bt.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&e!==yt&&!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 s=Array.isArray(n)?[...n]:[n];"in"===t&&0===s.length&&(this.containsEmptyInCondition=!0);for(const n of s)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:n});return this}return this.query.conditions.push({fieldName:e,operator:t,value:n}),this}limit(e){return function(e){var t;Mt(function(e){return"number"==typeof e}(t=e),()=>_t("Limit needs to be a number","Not a number",t)),-1!==e&&(Mt(e>0,"query limit has to be greater than 0"),Mt(Math.floor(e)===e,"query limit has to be an integer"),Mt(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const n=this.query.sortOrder.map(e=>e.fieldName);return Mt(rs(t.sort(),n.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 n={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 n,s,i,r;Mt((n=t,s=["fieldName","asc"],!Array.isArray(n)&&[...Object.keys(n)].every(e=>s.includes(e))),"Field sort should only contain a fieldName and asc"),Mt((i=t.asc,r="boolean",Array.isArray(i)?i.every(e=>typeof e===r):typeof i===r),"Asc needs to be boolean")}(n),Mt(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.projectFields&&e!==yt&&!this.query.projectFields.includes(e))throw new Error(`Cannot sort by field '${e}' that is not included in projectFields.`);return this.query.sortOrder.push(n),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!==yt&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(xs(e)){if(e.fieldName!==yt&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else if(Bs(e));else for(const n of e.fields)if(n.fieldName!==yt&&!t.includes(n.fieldName))throw new Error(`Cannot set projectFields without including filter field '${n.fieldName}'.`);const n=this.clone();return n.query.projectFields=[...e],n}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return m(this.snapshots(!1).pipe(l([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new t([]);const n=this.build(),s=n.projectFields;return this.querySubscriptionManager.processQuery(n,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(pn(e=>e.map(e=>{Mt(1===Object.keys(e).length);const t=e[this.collectionName],n=As(kt(t).__docId__,this.collectionName,this.integrationId),i=this.querySubscriptionManager.detachedRecords.delete(e),r=this.documentReferenceFactory.create(n,this.queryBuilderFactory,s,i);return i&&r.setInMemoryData(t),r})))}changes(){let e,t=new Set;return this.snapshots().pipe(c(this.documentIdentityService.observeChanges().pipe(C(t=>(Object.entries(t).forEach(([t,n])=>{!function(e,t,n){const s=Zn(e,t);void 0!==s&&(es(e,n,s),delete e[t])}(e||{},t,n)}),n)),E({}))),pn(([n])=>{let s=[];const i=[],r=[];if(e){for(const r of n){const n=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[n],t.delete(o);else if(e[n]){i.push(r);const s=e[n];delete e[n],t.delete(s)}else s.push(r)}for(const e of t)r.push(e)}else s=n;e={},t=new Set;for(const s of n){const n=s.dataRef;e[s.squidDocId]=n,t.add(n)}return new ri(s,i,r)}))}async delete(){return this.validateQueryDeleteModifiers(),this.containsEmptyInCondition?{deletedCount:0}:(Mt(this.mutationSender,"Query delete is not available on this query builder."),this.mutationSender.deleteQuery(this.build()))}dereference(){return new si(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new ii(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService,this.mutationSender);return e.query=as(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!==yt&&!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 ei(this,e)}validateQueryDeleteModifiers(){Mt(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=ds(this.query.conditions.filter(xs)||[],e=>e.fieldName);for(const n of Object.values(t)){const t=ds(n,e=>e.operator);for(const[n,s]of Object.entries(t)){if("=="===n||"!="===n){e.push(...s);continue}const t=[...s];t.sort((e,t)=>ls(e.value,t.value)),">"===n||">="===n?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!xs(e)),...e]}}class ri{constructor(e,t,n){this.inserts=e,this.updates=t,this.deletes=n}}class oi extends ni{constructor(e,t,n,s,i,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.documentReferenceFactory=s,this.queryBuilderFactory=i,this.rootAlias=r,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,n){return this.queryBuilder.where(e,t,n),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,n,s){const i=s?.leftAlias??this.latestAlias,r={...n,leftAlias:i,isInner:s?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[i].push(t),new oi(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 m(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new t([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,as(this.joins),as(this.joinConditions),e,!1).pipe(pn(e=>e.map(e=>{const t={};for(const[n,s]of Object.entries(e)){const e=n===this.rootAlias?this.collectionName:this.joins[n].collectionName,i=n===this.rootAlias?this.integrationId:this.joins[n].integrationId,r=s?As(s.__docId__,e,i):void 0;t[n]=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 ui(this)}dereference(){return new ai(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new oi(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,as(this.leftToRight),as(this.joins),as(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 ei(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class ai{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(pn(e=>e.map(e=>function(e,t){const n={},s=Object.keys(e);for(const i of s)es(n,i,t(e[i]));return n}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ai(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 ei(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class ci{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(pn(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 ci(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 ei(this,e)}dereference(e,t){const n=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(n.length){const s={[t]:e[t].data};for(const t of n)s[t]=e[t].map(e=>this.dereference(e,t));return s}return e.data}}class ui{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(pn(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new ci(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ui(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 ei(this,e)}groupData(e,t){const n=ds(e,e=>e[t]?.squidDocId);return Object.values(n).filter(e=>void 0!==e[0][t]).map(e=>{const n=this.joinQueryBuilder.leftToRight[t],s=e[0][t];if(0===n.length)return s;const i={[t]:s};for(const t of n)i[t]=this.groupData(e,t);return i})}}class li{constructor(e,t,n,s,i,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=n,this.queryBuilderFactory=s,this.querySubscriptionManager=i,this.dataManager=r,this.refId=gn()}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!==rt)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={[Os]:gn()};else e=e&&"string"!=typeof e?{__id:ps(e)}:{__id:e||gn()};const t=As(ps(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 n of e)await this.doc(n.id).upsert(n.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const n of e)n instanceof Zs?await n.delete(t):await this.doc(n).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new oi(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new di(...e)}}class di{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 n=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==n.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<n.length;e++)if(t[e].fieldName!==n[e].fieldName||t[e].asc!==n[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return m(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 di(...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 ei(this,e)}or(e,...t){return a([...t]).pipe(v(t=>{const n=new Set,s=t.flat(),i=[];for(const e of s)n.has(this.extractData(e))||(n.add(this.extractData(e)),i.push(e));return i.sort((t,n)=>{for(const{fieldName:s,asc:i}of e){const e=ts(this.extractData(t),s),r=ts(this.extractData(n),s);if(!Rs(e,r,"=="))return Rs(r,e,"<")?i?-1:1:i?1:-1}return 0}).slice(0,this.getLimit())}))}}class hi{constructor(e,t,n,s){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=n,this.dataManager=s,this.collections=new Map}get(e,t){let n=this.collections.get(t);n||(n=new Map,this.collections.set(t,n));let s=n.get(e);return s||(s=new li(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),n.set(e,s)),s}}class pi{constructor(e,t,n){this.clientIdService=e,this.socketManager=t,this.runtimeOptions=n,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 gi=x(150);const fi={"in:in":(e,t)=>e.every(e=>t.includes(e)),"not in:not in":(e,t)=>t.every(t=>e.includes(t)),">:>":(e,t)=>wi(e,t),">=:>":(e,t)=>Ii(e,t),"in:>":(e,t)=>e.every(e=>Ii(e,t)),">:>=":(e,t)=>wi(e,t),">=:>=":(e,t)=>wi(e,t),"in:>=":(e,t)=>e.every(e=>wi(e,t)),"<:<":(e,t)=>mi(e,t),"<=:<":(e,t)=>yi(e,t),"in:<":(e,t)=>e.every(e=>yi(e,t)),"<:<=":(e,t)=>mi(e,t),"<=:<=":(e,t)=>mi(e,t),"in:<=":(e,t)=>e.every(e=>mi(e,t)),"like:like":(e,t)=>Si(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Si(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Si(e,t)&&ki(t),"like_cs:like_cs":(e,t)=>Si(e,t),"not like:not like":(e,t)=>Si(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Si(t,e)&&ki(e),"not like:not like_cs":(e,t)=>Si(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Si(t,e),"in:like":(e,t)=>e.every(e=>Rs(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Rs(t,e,"like_cs")),"like:in":(e,t)=>Ti(e)&&ki(e)&&t.includes(e),"like_cs:in":(e,t)=>Ti(e)&&t.includes(e),"not in:not like":(e,t)=>Ti(t)&&ki(t)&&e.includes(t),"not in:not like_cs":(e,t)=>Ti(t)&&e.includes(t),"not like:not in":(e,t)=>t.every(t=>Rs(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Rs(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.length>0&&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)=>t.length>0&&e.every(e=>t.every(t=>e===t))};function yi(e,t){return is(e)?!is(t):!is(t)&&bi(e,t)&&e<t}function mi(e,t){return!!is(e)||!is(t)&&bi(e,t)&&e<=t}function bi(e,t){return typeof e==typeof t&&("object"!=typeof e||e instanceof Date&&t instanceof Date)}function Ii(e,t){return yi(t,e)}function wi(e,t){return mi(t,e)}function vi(e){const t=[];for(let n=0;n<e.length;n++){const s=e[n],i=e[n+1];"\\"!==s||"%"!==i&&"_"!==i?"\\"===s&&"\\"===i?(t.push(s),n++):t.push(s):(t.push(s+i),n++)}return t}function Si(e,t){return Mi(vi(e),vi(t))}function Mi(e,t,n=0,s=0){if(s>=t.length)return n>=e.length;if(n>=e.length)return t.slice(s).every(e=>"%"===e);const i=e[n],r=t[s];return"%"===i&&"%"===r?Mi(e,t,n+1,s+1)||Mi(e,t,n+1,s):"%"!==i&&("%"===r?Mi(e,t,n,s+1)||Mi(e,t,n+1,s):(i===r||"_"===r)&&Mi(e,t,n+1,s+1))}function ki(e){return e===e.toLowerCase()&&e===e.toUpperCase()}function Ti(e){return!/[%_\\]/.test(e)}function _i(e,t){return e.includes("like")&&"string"==typeof t&&Ns(t)}function Ei(e,t){const n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return!1;for(const s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!rs(e[s],t[s]))return!1}return!0}function Di(e,t){return t.every(t=>{const n=Object.keys(t).sort();if(n.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(n[t]!==e[t])return!1;return!0})}class Ci{constructor(e){this.query=e,this.query=e;const t=this.query.conditions.filter(xs),n=this.query.conditions.filter(Bs),s=n.flatMap(e=>function(e){if("=="!==e.operator&&"in"!==e.operator)return[];if(0===e.docIds.length)return[];const t=[],n=e.docIds[0];for(const s of Object.keys(n)){const i=n[s];e.docIds.every(e=>Object.prototype.hasOwnProperty.call(e,s)&&rs(e[s],i))&&t.push({fieldName:s,operator:"==",value:i})}return t}(e));this.exactSimpleConditions=this.parseConditions(t),this.exactDocIdConditions=n,this.subqueryConditions=this.parseConditions([...t,...s])}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)=>!rs(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,n){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:n})}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(Bs))if(!this.childImpliesParentDocIdCondition(t))return!1;const t=e.conditions.filter(xs),n=this.isSubqueryOfConditions(t),s=this.sortedBy(e.sortOrder),i=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return n&&s&&i&&r}childImpliesParentDocIdCondition(e){const t=e.docIds;if(0===t.length)return!1;const n="=="===e.operator||"in"===e.operator,s=Object.keys(t[0]).sort(),i=[];for(const e of this.query.conditions)Bs(e)&&i.push(...e.docIds);if(!Di(s,t)||!Di(s,i))return!1;const r=this.buildChildEffectiveTupleSet();return n?void 0!==r.allowed&&r.allowed.every(e=>t.some(t=>Ei(e,t))):void 0!==r.allowed?r.allowed.every(e=>!t.some(t=>Ei(e,t))):t.every(e=>r.excluded.some(t=>Ei(e,t)))}buildChildEffectiveTupleSet(){let e;const t=[];for(const n of this.query.conditions)if(Bs(n))if("=="===n.operator||"in"===n.operator)e=void 0===e?[...n.docIds]:e.filter(e=>n.docIds.some(t=>Ei(e,t)));else for(const e of n.docIds)t.some(t=>Ei(t,e))||t.push(e);return void 0!==e&&t.length>0&&(e=e.filter(e=>!t.some(t=>Ei(e,t)))),{allowed:e,excluded:t}}isProjectFieldsSubset(e,t){if(!t)return!0;if(!e)return!1;const n=new Set(t);return e.every(e=>n.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 n=t.fieldName,s=t.operator;if(n===yt){const n=t.value;if("in"===s||"not in"===s){const t=(Array.isArray(n)?n:[n]).some(t=>Us(t,e,"==",ts));if(!("in"===s?t:!t))return!1;continue}if(!Us(n,e,s,ts))return!1;continue}const i=ts(e,n);if("in"===s){if(t.value.includes(i))continue;return!1}if("not in"!==s){if(!Rs(t.value,i,s))return!1}else if(t.value.includes(i))return!1}for(const t of this.exactDocIdConditions)if(!Ps(t,e,ts))return!1;return!0}evaluateSubset(e,t){const{operator:n,value:s}=e,{operator:i,value:r}=this.parseConditions([t])[0],o=fi[`${n}:${i}`];return!!o&&(">"===i&&is(r)?">"===n&&is(s):!_i(n,s)&&!_i(i,r)&&o(s,r))}parseConditions(e){const t=[],n=new Map,s=new Map;return e.forEach(e=>{switch(e.operator){case"==":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat([e.value]));break;case"in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;case"!=":s.set(e.fieldName,(s.get(e.fieldName)||[]).concat([e.value]));break;case"not in":s.set(e.fieldName,(s.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),n.forEach((e,n)=>{t.push({fieldName:n,operator:"in",value:e})}),s.forEach((e,n)=>{t.push({fieldName:n,operator:"not in",value:e})}),t}}const Oi="dataManager_runInTransaction";var qi;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(qi||(qi={}));class Ai{constructor(e,n,s,i,o,a,c,u,l){this.documentStore=e,this.mutationSender=n,this.socketManager=s,this.querySubscriptionManager=i,this.queryBuilderFactory=o,this.lockManager=a,this.destructManager=c,this.documentIdentityService=u,this.querySender=l,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new r,this.outgoingMutationsEmpty=new t(!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),n=t&&!t.expireTimestamp?t.timestamp:void 0,s=this.docIdToLocalTimestamp.get(e);return!((!s||n)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&s===n)}async executeDetachedQuery(e){const t=this.currentTransactionId,n={query:e,clientRequestId:gn(),subscribe:!1},s=await this.querySender.sendQueryDirect(n);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(s.docs,e)}async reRunQueryThroughNormalPipeline(e){await m(this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)));const t={query:e,clientRequestId:gn(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}predictUpdate(e,t){try{return Ys(e,t)}catch{return e}}applyPendingMutationsToQueryResult(e,t){const n=new Ci(t),s=new Map;for(const n of e){const e=As(n.__docId__,t.collectionName,t.integrationId);s.set(e,n)}for(const[e,i]of this.pendingOutgoingMutations){const r=qs(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of i){const i=s.get(e);if("delete"===t.type)s.delete(e);else if("update"===t.type){if(i){const r=this.predictUpdate(i,t);r&&n.documentMatchesQuery(r)?s.set(e,r):s.delete(e)}}else if("insert"===t.type){const i={...t.properties,__docId__:r.docId};n.documentMatchesQuery(i)&&s.set(e,i)}}}const i=Array.from(s.values()),{sortOrder:r}=t;i.sort((e,t)=>{for(const{fieldName:n,asc:s}of r){const i=ls(ts(e,n),ts(t,n));if(0!==i)return s?i:-i}return 0});const o=t.limit<0?2e3:t.limit;return i.slice(0,o)}async runInTransaction(e,t){if(t)return Mt(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(Oi)?this.lockManager.lockSync(Oi):await this.lockManager.lock(Oi);let n=Ri;const s=()=>n!==Ri;return new Promise(async(t,i)=>{try{let r;this.currentTransactionId=gn();try{r=await e(this.currentTransactionId)}catch(e){n=e}finally{this.finishTransaction(s()?void 0:{resolve:()=>t(r),reject:i})}}catch(e){n=s()?n:e}finally{try{this.lockManager.release(Oi)}catch(e){n=s()?n:e}}s()&&i(n)})}async applyOutgoingMutation(e,t){const n=As(e.squidDocIdObj);this.knownDirtyDocs.add(n),t||this.lockManager.canGetLock(Oi)||(await this.lockManager.lock(Oi),this.lockManager.release(Oi)),this.knownDirtyDocs.delete(n);const s=this.removeInternalProperties(e),i=this.pendingOutgoingMutations.get(n)?.slice(-1)[0],r=i&&!i.sentToServer?kt(Xs([i.mutation,s])[0],"Failed to reduce mutations"):void 0;if("update"===e.type&&Ys(this.documentStore.getDocumentOrUndefined(n),e),i&&r)i.mutation=r,this.outgoingMutationsEmpty.next(!1);else{const e={mutation:s,sentToServer:!1},t=this.pendingOutgoingMutations.get(n)||[];t.push(e),this.pendingOutgoingMutations.set(n,t),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(n),s="delete"===e.type?void 0:"update"===e.type?t&&this.predictUpdate(t,e):{...e.properties};this.updateDocumentFromSnapshot(n,s)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(n,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(n,s).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 Mt(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(Oi);try{this.currentTransactionId=gn();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(Oi)}}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(g(e=>"mutations"===e.type),pn(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t={},n=[];for(const s of e){if(!this.querySubscriptionManager.hasOngoingQuery(s.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(s.clientRequestId),i=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(s.clientRequestId);i&&r?n.push({squidDocId:s.squidDocId,item:{properties:s.doc,timestamp:s.mutationTimestamp,clientRequestId:s.clientRequestId,projectFields:e.projectFields}}):t[s.squidDocId]={properties:s.doc,timestamp:s.mutationTimestamp}}Object.keys(t).length>0&&this.applyIncomingUpdates(t),n.length>0&&this.runInTransactionSync(()=>{this.applyProjectedUpdates(n)})}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 n=[];for(const s of e.docs){const i=As(s.__docId__,t.collectionName,t.integrationId);n.push({squidDocId:i,item:{properties:s,timestamp:s.__ts__,clientRequestId:e.clientRequestId,projectFields:t.projectFields}})}this.runInTransactionSync(()=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId,e.docs),this.batchClientRequestIds.add(e.clientRequestId),this.applyProjectedUpdates(n)})}else{const n={};for(const s of e.docs){const e=As(s.__docId__,t.collectionName,t.integrationId);n[e]={properties:s,timestamp:s.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId,e.docs),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(n,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}}applyIncomingUpdates(e,t){let n=!1;const s=new Set,i=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?n=!0:o&&o.timestamp>r.timestamp?(r.properties&&this.documentStore.adoptMissingFields(t,r.properties),i.add(t)):(this.pendingIncomingUpdates.set(t,r),s.add(t))}return this.runInTransactionSync(()=>{for(const e of s)this.maybeApplyIncomingUpdate(e);for(const e of i)this.refreshQueryMapping(e)},t),n}applyProjectedUpdates(e){for(const{squidDocId:t,item:n}of e){const e=kt(n.clientRequestId,"clientRequestId required for projected updates"),s=this.pendingOutgoingMutations.get(t);if(s&&s.length)continue;const i=this.docIdToServerTimestamp.get(t);i&&i.timestamp>n.timestamp?(this.querySubscriptionManager.addDocToQuery(t,e),this.batchClientRequestIds.add(e)):(this.acknowledgeDocument(t,n.timestamp,!n.properties),this.docIdToLocalTimestamp.set(t,n.timestamp),n.properties?(this.documentStore.saveProjectedDocument(t,n.properties,n.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 n=this.pendingOutgoingMutations.get(e);n&&n.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 n=this.documentStore.getDocumentOrUndefined(e);return!(!n&&!t||n===t||n&&t&&((s={...t,__ts__:void 0})===(i=n)||s&&i&&gs(s)===gs(i))||(this.documentStore.saveDocument(e,t),0));var s,i}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 gi.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:n,idResolutionMap:s={},refreshList:i=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(s),i.forEach(e=>{this.refreshDocIdToTimestamp.set(s[e]||e,n)});for(const t of e){let e=this.removeOutgoingMutation(t);s[e]&&(e=s[e]),this.acknowledgeDocument(e,n),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=As(e.mutation.squidDocIdObj),n=kt(this.pendingOutgoingMutations.get(t));return n.splice(n.indexOf(e),1),n.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}=qs(t);this.setExpiration(t,!0);try{const n=e.includes(Os)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(kt(n.length<=1,"Got more than one doc for the same id:"+t),!n.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,n]of this.refreshDocIdToTimestamp.entries()){const s=this.docIdToServerTimestamp.get(t)?.timestamp;s&&s>n||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 n=t[t.length-1];if(n&&!n.sentToServer){const t=n.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(n),n.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,n=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,n)}setExpiration(e,t){const n=this.docIdToServerTimestamp.get(e);n&&(n.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 n=As(t.mutation.squidDocIdObj),s=e[n];s&&(t.mutation.squidDocIdObj=qs(s))})}),Object.entries(e).forEach(([e,t])=>{ss(this.pendingOutgoingMutations,e,t),ss(this.docIdToLocalTimestamp,e,t),ss(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 Ri=Symbol("undefined");class ji{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),pn(()=>{}))}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 Ni{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(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)`),_s.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 n=t?.acquisitionTimeoutMillis??2e3,s=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),Mt(await m(k(j(this.lockWaitForConnectionThreshold).pipe(pn(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const i=gn(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:n,maxHoldTimeMillis:s,clientRequestId:i}};this.socketManager.postMessage(r);const o=await m(k(j(n+4e3).pipe(O(1),pn(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:i}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===i)))),a=o.payload.lockId;Mt(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),Mt(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new Fi(a,e,i,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 Fi{constructor(e,t,n,s,r){this.lockId=e,this.resourceId=t,this.clientRequestId=n,this.ongoingLocks=s,this.socketManager=r,this.released=!1,this.onReleaseSubject=new i(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),n=await m(k(b(t.then(xi,xi)),this.socketManager.observeConnectionReady().pipe(g(e=>!e),pn(()=>!1))));if(this.onReleaseSubject.next(),!n)return t.catch(()=>{}),void this.onReleaseSubject.complete();try{await t}finally{this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}function xi(){return!0}class Bi{constructor(e,n){this.documentStore=e,this.destructManager=n,this.changeNotifier=new t({}),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 Pi{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t,n,s=!1){if(n||s)return new Zs(e,kt(this.dataManager,"dataManager not found"),t,n,s?this.create(e,t):void 0);let i=this.documents.get(e);if(i)return i;i=new Zs(e,kt(this.dataManager,"dataManager not found"),t);const{integrationId:r,collectionName:o}=qs(e);this.documents.set(e,i);const a=this.getCollectionKey(r,o),c=this.documentsForCollection.get(a)||[];return this.documentsForCollection.set(a,c.concat(i)),i}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const n=this.getCollectionKey(e,t);return(this.documentsForCollection.get(n)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const n=qs(e),s=qs(t);ss(this.documents,n.docId,s.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class Ui{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,n){const s=this.squidDocIdToDoc.get(e);if(s){const n=this.mergeDocuments(s,t),i=this.removeInternalProperties(n);this.squidDocIdToDoc.set(e,i)}else{const n=this.removeInternalProperties(t);this.squidDocIdToDoc.set(e,n)}if(n?.length){const t=this.squidDocIdToProjectedFields.get(e);if(void 0!==t)for(const e of n)t.add(e);else s||this.squidDocIdToProjectedFields.set(e,new Set(n))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const n=as(e);for(const e of Object.keys(t)){const s=t[e],i=n[e];null===s||"object"!=typeof s||Array.isArray(s)||null===i||"object"!=typeof i||Array.isArray(i)?n[e]=s:n[e]=this.mergeDocuments(i,s)}return n}adoptMissingFields(e,t){const n=this.squidDocIdToDoc.get(e);if(!n)return;const s=Object.keys(t).filter(e=>"__ts__"!==e&&!(e in n));if(!s.length)return;const i=as(n);for(const e of s)i[e]=t[e];this.squidDocIdToDoc.set(e,i);const r=this.squidDocIdToProjectedFields.get(e);if(r)for(const e of s)r.add(e)}deleteDocument(e){this.squidDocIdToDoc.delete(e),this.squidDocIdToProjectedFields.delete(e)}saveDocument(e,t){const n=this.squidDocIdToDoc.get(e);if(void 0===n&&!t)return;if(void 0!==n){if(t){const n=as(t),s=this.removeInternalProperties(n);return this.squidDocIdToDoc.set(e,s),this.squidDocIdToProjectedFields.delete(e),s}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const s=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,s),this.squidDocIdToProjectedFields.delete(e),s}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 n=this.squidDocIdToProjectedFields.get(e);return void 0===n||!!t?.length&&t.every(e=>n.has(e))}group(e,t){return Object.values(ds(e,e=>ps(t.map(t=>ts(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const n=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(vt),{sortOrder:s,limitBy:i}=t,r=n.sort((e,t)=>this.compareSquidDocs(e,t,s)),o=t.limit<0?2e3:t.limit;let a;if(i){const{limit:e,fields:t,reverseSort:n}=i,s=this.group(r,t);let c;c=n?s.map(t=>t.slice(-e)):s.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 n={};"__id"in e&&(n.__id=e.__id),"__docId__"in e&&(n.__docId__=e.__docId__);for(const s of t)if(s.includes(".")){const t=ts(e,s);void 0!==t&&ns(n,s,t)}else Object.hasOwn(e,s)&&es(n,s,e[s]);return n}migrateDocId(e,t){const n=this.getDocumentOrUndefined(e);if(!n)return;ss(this.squidDocIdToDoc,e,t),ss(this.squidDocIdToProjectedFields,e,t);const s=qs(t),i=ys(s.docId);this.saveDocument(t,{...n,...i,__docId__:s.docId})}countDocsUpTo(e,t,n){let s=0;for(const i of e){const e=this.squidDocIdToDoc.get(i);e&&this.compareSquidDocs(e,t,n)<=0&&s++}return s}findLastDoc(e,t){let n;for(const s of e)(!n||this.compareSquidDocs(s,n,t)>0)&&(n=s);return n}compareSquidDocs(e,t,n){for(const{fieldName:s,asc:i}of n){const n=ls(ts(e,s),ts(t,s));if(0!==n)return i?n:-n}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class Li{constructor(e){this.rpcManager=e}async emit(e){const t={event:e};await this.rpcManager.post("events/emit",t)}}class Qi{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const n={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",n)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class $i{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const n={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",n,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const n={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",n)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class Gi{constructor(e,t,n,s,i){this.socketManager=e,this.rpcManager=t,this.clientIdService=n,this.isListening=!1,this.listeners={},this.ownedJobs=new Set,s.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(()=>{})))}),i.isPassiveMode||this.clientIdService.observeClientId().pipe(p(),_(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))_s.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(t=>{const n=this.listeners[e];n&&(n.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 i(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(n=>{t.error(n),delete this.listeners[e]}),m(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe(g(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,n=t.id,s=this.listeners[n];if(s){if("completed"===t.status)s.next(t.result);else if("failed"===t.status){const e=Object.assign(new Error(t.error||"Job failed"),{errorType:t.errorType});s.error(e)}else console.error("Unexpected job status:",t.status,"for jobId:",n);delete this.listeners[n]}}))}async resolveJob(e,t,n,s){try{await this.rpcManager.post("job/resolveJob",{jobId:e,status:t,result:n,error:s})}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=>_s.debug("Job keep-alive failed:",e))},15e3))}stopKeepAlive(){void 0!==this.keepAliveHandle&&(clearInterval(this.keepAliveHandle),this.keepAliveHandle=void 0)}}class Hi{constructor(e,t,n,s){this.graphId=e,this.rpcManager=t,this.jobClient=n,this.socketManager=s}async invoke(e={}){const t=gn();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,timeoutMs:e.timeoutMs,graphContext:e.context,session:e.session,jobId:t}),await this.jobClient.awaitJob(t)}async invokeAsync(e={}){const t=gn();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,timeoutMs:e.timeoutMs,graphContext:e.context,session:e.session,jobId:t}),t}async resume(e,t,n={}){const s=gn();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,timeoutMs:n.timeoutMs,graphContext:n.context,session:n.session,jobId:s}),await this.jobClient.awaitJob(s)}async resumeAsync(e,t,n={}){const s=gn();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,timeoutMs:n.timeoutMs,graphContext:n.context,session:n.session,jobId:s}),s}stream(e={}){return this.streamRun("langgraph/invoke",e.tokenTags,{graphId:this.graphId,threadId:e.threadId,input:e.input,timeoutMs:e.timeoutMs,graphContext:e.context,session:e.session})}resumeStream(e,t,n={}){return this.streamRun("langgraph/resume",n.tokenTags,{graphId:this.graphId,threadId:e,resumePayload:t,timeoutMs:n.timeoutMs,graphContext:n.context,session:n.session})}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})}streamRun(e,t,n){return this.socketManager.notifyWebSocketIsNeeded(),new s(s=>{const i=gn(),r=gn();let o,a,c=!1,u=!1;const l=()=>{o&&!s.closed&&(clearTimeout(a),s.next({type:"result",result:o,...u||!c?{incomplete:!0}:{}}),s.complete())},d=this.socketManager.observeNotifications().pipe(g(e=>"langGraphStream"===e.type&&e.clientRequestId===i)).subscribe(({payload:e})=>{for(const t of e.events)s.next(t);e.final&&(c=!0,e.incomplete&&(u=!0),l())});return(async()=>{await this.socketManager.awaitConnectionReady(),await this.rpcManager.post(e,{...n,jobId:r,stream:{clientRequestId:i,tokenTags:t}}),o=await this.jobClient.awaitJob(r),c?l():a=setTimeout(l,5e3)})().catch(e=>s.error(e)),()=>{d.unsubscribe(),clearTimeout(a)}})}}class Ki{constructor(e,t,n){this.rpcManager=e,this.jobClient=t,this.socketManager=n}graph(e){return new Hi(e,this.rpcManager,this.jobClient,this.socketManager)}}const Wi="squid_mgmt_";function Vi(e="n_"){return`${e}${bn(10).toLowerCase()}`}const Ji=e=>e();class zi extends Error{constructor(e,t,n,s,i){super(e),this.statusCode=t,this.url=n,this.headers=s,this.body=i}}const Yi="1.0.504";async function Xi(e){return sr({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 Zi(e){return sr({...e,method:"GET",files:[],filesFieldName:""})}async function er(e){return sr({...e,method:"PUT"})}async function tr(e){return sr({...e,method:"PATCH"})}async function nr(e){return sr({...e,method:"DELETE",files:[],filesFieldName:""})}async function sr(e){const t=await async function({headers:e,files:t,filesFieldName:n,message:s,url:i,extractErrorMessage:r,method:o,abortSignal:a}){const c=new Headers(e);c.append(Mn,Vi("c_")),c.append(Tn,Yi);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 s of t)e.append(n||"files",s,s.name);e.append("body",fs(s)),u.body=e}else void 0!==s&&(c.append("Content-Type","application/json"),u.body=fs(s));else"DELETE"===o&&void 0!==s&&(c.append("Content-Type","application/json"),u.body=fs(s));try{const e=await fetch(i,u),t={};if(e.headers.forEach((e,n)=>{t[n]=e}),!e.ok){const n=await e.text(),s=ir(n);if(!r)throw new zi(n,e.status,i,t,s);let o;try{o="string"==typeof s?s:s?.message||n}catch{}throw o||(o=e.statusText),new zi(o,e.status,i,t,s)}const n=await e.text();return _s.debug(`received response from url ${i}: ${JSON.stringify(n)}`),{body:n,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw _s.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=ir(t.body),t}function ir(e){if(e){try{return ys(e)}catch{}return e}}class rr{constructor(e){Mt(e.apiKey.startsWith(Wi),`Invalid management API key format. Key must start with '${Wi}'`),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,n){const s=B(this.consoleRegion,"console",`openapi/iac/management/${t}`),i={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await Xi({url:s,headers:i,message:n,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await tr({url:s,headers:i,message:n,extractErrorMessage:!0})).body:(await nr({url:s,headers:i,message:n,extractErrorMessage:!0})).body}}class or{constructor(e,t,n){this.rpcManager=e,this.lockManager=t,this.querySender=n}async sendMutations(e,t){const n=Xs(e),s=n.map(e=>`sendMutation_${As(e.squidDocIdObj)}`);await this.lockManager.lock(...s),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:n,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw _s.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(n,null,2)}),e}finally{this.lockManager.release(...s)}}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 _s.debug("Error while deleting query results",{error:t,query:JSON.stringify(e,null,2)}),t}finally{this.lockManager.release(t)}}}class ar{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class cr{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"userNotification"===e.type),v(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 ur={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class lr{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},n=Object.keys(t).filter(e=>!dr.test(e)||e.length>=hr);Mt(0===n.length,()=>`Tag name is not allowed: ${n.join(",")}`),this.isReporting=!0;const s={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},i=this.rpcManager.post("/observability/metrics",{metrics:[s]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==i),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(i)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...ur,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const n=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:n,noDataBehavior:s}=e,i=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:s}){if("align-by-start-time"===s)return e;const i=t-e;let r=t-Math.floor(i/n)*n;return r>e&&(r-=n),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:s}){if("align-by-end-time"===s)return t-n;const i=t-e;let r=e+Math.floor(i/n)*n;return r>=t&&(r-=n),r}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const n=[];for(let t=0;t<e.groupByTags.length;t++){const s=e.groupByTags[t],i=a[s]?.[0]||"";n.push(i)}t.push({tagValues:n,points:[]})}else"return-result-group-with-default-values"===s&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[n,s]of Object.entries(a)){const i=e.groupByTags.indexOf(n);if(!(i<0))for(let e=0;e<t.length;e++){const n=t[e],r=new Set(s);for(let e=0;e<t.length;e++){const s=t[e];n.tagValues.every((e,t)=>t===i||e===s.tagValues[t])&&r.delete(s.tagValues[i])}if(0!==r.size)for(const e of r){const s={tagValues:[...n.tagValues],points:[]};s.tagValues[i]=e,t.push(s)}}}for(const s of t){if(0!==s.points.length){const e=s.points[0][0],t=s.points[s.points.length-1][0];Mt(e>=r,()=>`Invalid first point time: ${e}`),Mt(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:i,u=Array.isArray(e.fn)?e.fn.map(c):[i];for(let e=r;e<=o;e+=n){const n=s.points[a];n?n[0]===e?(t.push(n),a++):(Mt(n[0]>e,()=>`Result point has invalid time: ${n[0]}`),t.push([e,...u])):t.push([e,...u])}s.points=t}}(t,n.resultGroups),n}}const dr=/^[a-zA-Z0-9_-]+$/,hr=1e3;async function pr(e,t,n=500,s){const i=Date.now(),r=e.paginate({pageSize:n,subscribe:!1});let o=0,a=0,c=await r.waitForData();for(s?.({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++,s?.({pageIndex:a,documentCount:c.data.length,totalLoaded:o+c.data.length})}return{count:o,time:Date.now()-i}}async function gr(e,t=500,n){const s=[],i=e.paginate({pageSize:t,subscribe:!1});let r=0,o=await i.waitForData();for(n?.({pageIndex:r,documentCount:o.data.length,totalLoaded:s.length+o.data.length});;){for(const e of o.data){const t=qs(e.squidDocId),n=ys(t.docId),i=t.integrationId===rt?n.__id:n;s.push(i)}if(!o.hasNext)break;o=await i.next(),r++,n?.({pageIndex:r,documentCount:o.data.length,totalLoaded:s.length+o.data.length})}return s}function fr(e,t){switch(t.type){case"simple":return function(e,t){const{query:n,dereference:s}=t,{collectionName:i,integrationId:r}=n;let o=e.collection(i,r).query();return o=yr(o,n),s?o.dereference():o}(e,t);case"join":return function(e,t){const{root:n,joins:s,joinConditions:i,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=n.query;let u=e.collection(a,c).joinQuery(n.alias);return u=yr(u,n.query),Object.entries(s).map(([t,n])=>{const{collectionName:s,integrationId:r}=n,{left:o,right:a,leftAlias:c}=i[t];let l=e.collection(s,r).query();l=yr(l,n),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:n}=t,{collectionName:s,integrationId:i}=mr(n[0]),r=n.map(t=>fr(e,t));return e.collection(s,i).or(...r)}(e,t)}}function yr(e,t){const{conditions:n,limit:s,sortOrder:i}=t;for(const t of n){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:n,operator:s,value:i}=t;e.where(n,s,i)}e.limit(s);for(const{fieldName:t,asc:n}of i)e.sortBy(t,n);return e}function mr(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:n}=e.query;return{collectionName:t,integrationId:n}}case"join":{const{collectionName:t,integrationId:n}=e.root.query;return{collectionName:t,integrationId:n}}case"merged":return mr(e.queries[0])}}class br{constructor(e,t,n){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=n}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:n}=e,s=new Ci(e),i=this.documentReferenceFactory.getDocumentsForCollection(t,n).filter(e=>s.documentMatchesQuery(e.data)),r={};return i.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[As(e.__docId__,n,t)])}}function Ir(e,t){return $t(function(n,s){var i=0;n.subscribe(dn(s,function(n){return e.call(t,n,i++)&&s.next(n)}))})}class wr{constructor(e,n,s){this.rpcManager=e,this.destructManager=n,this.webSocketConnectionReady$=s,this.safeToSendQueriesToServer=new t(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new t(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new r,n=m(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.gateForCurrentBatch().subscribe(()=>{this.processQueryBatch()})},0),n)}gateForCurrentBatch(){return this.pendingQueryRequests.some(({queryRequest:e})=>e.subscribe)&&this.webSocketConnectionReady$?a([this.safeToSendQueriesToServer,this.webSocketConnectionReady$]).pipe(Ir(([e,t])=>e&&t),O(1),pn(()=>!0)):this.safeToSendQueriesToServer.pipe(Ir(Boolean),O(1))}async sendQueryDirect(e){const t=await this.rpcManager.post("query/batchQueries",[e]),n=t.errors[e.clientRequestId];if(n)throw n;return t.results[e.clientRequestId]}async waitForAllQueriesToFinish(){return m(this.inflightQueriesCount.pipe(Ir(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()),n=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const n=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:s}of e){const e=t.clientRequestId,i=n.errors[e],r=n.results[e];i?s.error(i):s.next(r)}}catch(e){n.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var vr={d:(e,t)=>{for(var n in t)vr.o(t,n)&&!vr.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Sr(e,t,...n){e||function(e,...t){const n=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof n)throw n;throw(e=>new Error(e))(n||"Assertion error",...t)}(t,...n)}function Mr(e,t){switch(t.type){case"set":return function(e,t,n){if(void 0===n)return kr(e,t);if(0===t.length)return Sr("object"==typeof n&&null!==n&&!Array.isArray(n),()=>`Root state must be a record. Trying to set '${n}', type: ${typeof n}`),n;function s(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let i=e;for(let e=0;e<t.length-1&&void 0!==i;e++){const n=t[e];Sr(!Array.isArray(i)||s(n),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${n}'`),i=i[n],Sr(void 0===i||"object"==typeof i&&null!==i,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===i?"<null>":typeof i}'`)}const r=t[t.length-1];return Sr(!Array.isArray(i)||s(r),()=>`Invalid array index Path: '${t}`),(null==i?void 0:i[r])===n?e:Tr(e,t,n)}(e,t.path,t.value);case"delete":return kr(e,t.path);case"batch":return t.actions.reduce((e,t)=>Mr(e,t),e)}}function kr(e,t){Sr(0!==t.length,"Can't delete an empty path");let n=e;for(let s=0;s<t.length-1;s++){const i=t[s];if(n=n[i],void 0===n)return e;Sr("object"==typeof n&&null!==n,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,s+1)}', type: ${null===n?"<null>":typeof n}`)}const s=t[t.length-1];return void 0===n[s]?e:Tr(e,t,void 0)}function Tr(e,t,n){function s(e,n){Sr(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[n]}const i=Object.assign({},e);let r=i;for(let e=0;e<t.length-1;e++){const i=t[e],o=r[i];Sr(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===n?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return s(r,i),r;r[i]=a,r=a}const o=t[t.length-1];return void 0===n?s(r,o):r[o]=n,i}function _r(e,t){const n=[];if("set"===e.type||"delete"===e.type)n.push(e.path);else if("batch"===e.type)for(const t of e.actions)n.push(..._r(t,"as-is"));return"unique-and-sorted"===t?Cr(n):n}function Er(e,t){if(e.length<t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Dr(e){const t=[...e];return t.sort((e,t)=>{for(let n=0;n<e.length;n++){if(n===t.length)return 1;const s=e[n].localeCompare(t[n]);if(0!==s)return s}return e.length-t.length}),t}function Cr(e){const t=Dr(e),n=t;for(let e=0;e<t.length-1;e++){const s=t[e];for(let i=e+1;i<t.length;i++){const r=t[i];s.length===r.length&&Er(s,r)&&(n[i]=void 0,e++)}}return n.filter(e=>void 0!==e)}const Or=(qr={Observable:()=>s,Subject:()=>r},Ar={},vr.d(Ar,qr),Ar);var qr,Ar;const Rr=(jr={filter:()=>Ir,map:()=>pn},Nr={},vr.d(Nr,jr),Nr);var jr,Nr;class Fr{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 n=this._buildPath(e);if(void 0!==n.value)return n.value;const s=t(e);return this._setNodeValue(n,s,void 0===s),s}set(e,t){const n=void 0===t?this._findNode(e):this._buildPath(e);n&&this._setNodeValue(n,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 n=(void 0===t.value?0:1)+t.childrenWithValue;n>0&&this._updateChildrenWithValue(t,-n),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const n=this.getNode(e);return void 0===n?0:n.childrenWithValue+("node-and-children"===t&&void 0!==n.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const n=[];let s=this.root,i=t(s.value,n);if(i!==Fr.StopFillToken){this._setNodeValue(s,i,!1);for(let r=0;r<e.length;r++){const o=e[r];n.push(o);let a=s.children.get(o);if(i=t(null==a?void 0:a.value,n),i===Fr.StopFillToken)break;a||(a={children:new Map,parent:s,childrenWithValue:0},s.children.set(o,a)),this._setNodeValue(a,i,!1),s=a}this._runGc(s)}}visitDfs(e,t,n=[]){const s=this.getNode(n);void 0!==s&&this._visitDfs(e,s,t,[...n])}_visitDfs(e,t,n,s){if("pre-order"===e&&!1===n(t.value,s))return!1;for(const[i,r]of t.children){if(s.push(i),!this._visitDfs(e,r,n,s))return!1;s.pop()}return"in-order"!==e||!1!==n(t.value,s)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const n of e)if(t=t.children.get(n),!t)return;return t}_findNode(e){let t=this.root;for(let n=0;n<e.length&&t;n++)t=t.children.get(e[n]);return t}_buildPath(e){let t=this.root;for(let n=0;n<e.length;n++){const s=e[n];let i=t.children.get(s);i||(i={children:new Map,parent:t,childrenWithValue:0},t.children.set(s,i)),t=i}return t}_setNodeValue(e,t,n){if(e.value!==t){const n=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,n)}n&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let n=e.parent;n;n=n.parent)if(n.childrenWithValue+=t,n.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))}}Fr.StopFillToken=Symbol("Trie.StopFillToken");class xr extends Or.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class Br{constructor(e){this.rootState=e,this.observersTrie=new Fr,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,Rr.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,n){(null==n?void 0:n(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=Mr(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=_r(e,"unique-and-sorted"),n=this.selectChildPathsWithObservers(t),s=Cr([...t,...n]),i=new Fr;for(const e of s)i.fillPath(e,()=>!0);i.visitDfs("pre-order",(t,n)=>{const s=this.observersTrie.get(n);if(s){const t=this.get(n),i=s.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,n):void 0;s.next({action:e,value:t,oldValue:i})}})}_observeChanges(e,t=[],n){const s=0===t.length?void 0:new Fr;for(const e of t)null==s||s.set(e,!0);return new Or.Observable(t=>{const i=this.observersTrie.getOrSet(e,()=>new xr);i.isAllDetailsMode=i.isAllDetailsMode||"all-details"===n;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=i.pipe((0,Rr.filter)(({action:e})=>void 0===s||_r(e,"as-is").some(e=>!s.get(e))),(0,Rr.map)(({action:t,value:n,oldValue:s})=>{let r=this.stubForUnusedPaths;if(i.isAllDetailsMode){const n=_r(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=Dr(e),n=t;for(let e=0;e<n.length-1;e++){const s=t[e];for(let i=e+1;i<t.length;i++)Er(t[i],s)&&(n[i]=void 0,e++)}return n.filter(e=>void 0!==e)}(e.length>0?n.filter(t=>Er(t,e)).map(t=>t.slice(e.length)):n)}return{value:n,oldValue:s,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),i.observed||this.observersTrie.delete(e)}})}_get(e,t){let n=e;for(let e=0;e<t.length&&void 0!==n;e++){const s=t[e];n=null==n?void 0:n[s]}return n}selectChildPathsWithObservers(e){const t=[];for(const n of e)this.observersTrie.count(n,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,n)=>{e&&t.push([...n])},n);return t}}function Pr(e,t,n=(e,t)=>e>t?1:e<t?-1:0,s=0,i=e.length-1){if(i<s)return-1;const r=Math.trunc((s+i)/2);return 0===n(t,e[r])?r:n(t,e[r])>0?Pr(e,t,n,r+1,i):Pr(e,t,n,s,r-1)}function Ur(e,t,n=(e,t)=>e>t?1:e<t?-1:0){if(-1!==Pr(e,t,n))return;let s;for(s=e.length-1;s>=0&&n(e[s],t)>0;s--)e[s+1]=e[s];e[s+1]=t}function Lr(e,t,n=(e,t)=>e>t?1:e<t?-1:0){const s=Pr(e,t,n);s>-1&&e.splice(s,1)}class Qr{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,n,s,i,o,a,c){this.rpcManager=e,this.clientIdService=t,this.documentStore=n,this.destructManager=s,this.documentIdentityService=i,this.querySender=o,this.socketManager=a,this.lockManager=c,this.onOrphanDocuments=new r,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Gr,this.queryResultsSubject=new r,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 kt(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e,t){const n=this.ongoingQueries.get(e);n?.gotInitialResponse&&this.removeClientRequestIdMapping(e),n&&(n.gotInitialResponse=!0,n.isInFlight=!1,t&&n.subscribe&&n.query.limit>0&&this.setLimitWindow(n,t))}findQueriesForDocument(e,t){const{collectionName:n,integrationId:s}=qs(t),i=this.queryMappingManager.getMapping(n,s);return i?function(e,t){const n=[...e.unconditional||[]],s=new Map;for(const[n,i]of Object.entries(e.conditional||{})){const e=ys(n);let r;if(xs(e))if(e.fieldName===yt)r=Us(e.value,t,e.operator,ts);else{const n=ts(t,e.fieldName)??null;r=Rs(e.value,n,e.operator)}else r=Bs(e)?Ps(e,t,ts):$r(e,t);if(r)for(const e of i)s.set(e,(s.get(e)||0)+1)}for(const[t,i]of s.entries())i>=e.queriesMetadata[t].condCount&&n.push(t);return n}(i,e):[]}setClientRequestIdsForLocalDoc(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set,s=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),i=new Set([...n,...s]);for(const t of[...n]){if(s.has(t))continue;n.delete(t);const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),n.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of s){let n=this.localDocumentToClientRequestIds.get(e);n||(n=new Set,this.localDocumentToClientRequestIds.set(e,n)),n.add(t);let s=this.clientRequestIdToLocalDocuments.get(t);s||(s=new Set,this.clientRequestIdToLocalDocuments.set(t,s)),s.add(e)}return[...i]}addDocToQuery(e,t){let n=this.localDocumentToClientRequestIds.get(e);n||(n=new Set,this.localDocumentToClientRequestIds.set(e,n)),n.add(t);let s=this.clientRequestIdToLocalDocuments.get(t);s||(s=new Set,this.clientRequestIdToLocalDocuments.set(t,s)),s.add(e)}removeDocFromQuery(e,t){const n=this.localDocumentToClientRequestIds.get(e);let s=!n;n&&(n.delete(t),n.size||(this.localDocumentToClientRequestIds.delete(e),s=!0));const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),s&&this.documentStore.deleteDocument(e)}errorOutAllQueries(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of n){const n=this.ongoingQueries.get(e);n&&(this.destructManager.isDestructing?n.dataSubject.complete():n.dataSubject.error(t),n.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const n of e){const e=this.ongoingQueries.get(n);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const s=this.clientRequestIdToLocalDocuments.get(n)||new Set,i=this.documentStore.sortAndLimitDocs(s,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(i,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=kt(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case qi.UNKNOWN:e.limitUnderflowState=s.size===e.query.limit+100?qi.ENABLED:qi.DISABLED;break;case qi.DISABLED:break;case qi.ENABLED:{const{limitWindowEnd:t,query:n}=e;if((t?this.documentStore.countDocsUpTo(s,t,n.sortOrder):s.size)<n.limit+20){e.limitUnderflowState=qi.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);kt(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new Ci(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,n,s,r,o,c){r&&this.socketManager.notifyWebSocketIsNeeded();const u=Object.keys(n).length>0;return r||u||!this.detachedQueryExecutor||this.lockManager.canGetLock(Oi)?d(()=>{const u=this.createOngoingQueryGraph(e,t,n,s,r,!0,{},c);o&&(u.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(u),u.allObservables=new i(1);const l=u.allObservables.pipe(C(e=>a(e).pipe(pn(e=>this.joinResults(e,s,u)))),Ir(()=>this.allOngoingQueriesGotInitialResult(u)),E(void 0),M(),Ir(([e,t])=>!rs(e,t)),pn(([,e])=>e),r?R():O(1),f(()=>{u.dataSubject.complete(),u.done=!0,this.completeAllSupportedQueries(u),u.allObservables?.complete()})),d=this.collectAllObservables(u);return u.allObservables.next(d),l}).pipe(T()):b(this.detachedQueryExecutor(e)).pipe(pn(e=>e.map(e=>{const n={[t]:e};return this.detachedRecords.add(n),n})))}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 Ci(e.query);for(const n of this.ongoingQueries.values()){if(e===n)return;if(this.isValidParent(n)&&t.isSubqueryOfQuery(n.query))return n}}setLimitWindow(e,t){const{limit:n,sortOrder:s}=e.query,i=this.documentStore.findLastDoc(t,s),r=void 0!==i&&s.length>0&&s.every(({fieldName:e})=>void 0!==ts(i,e));e.limitWindowEnd=r?i:void 0,e.limitUnderflowState=t.length===n+100?qi.ENABLED:qi.DISABLED}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const n=[];for(const s of t){const t=kt(this.localDocumentToClientRequestIds.get(s));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(s),n.push(s))}n.length&&this.onOrphanDocuments.next(n)}registerQueryFinalizer(e){const t=e.clientRequestId,n=Fs(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(k(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Ir(e=>0===e)))),this.queryMappingManager.removeQuery(n),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const n={clientRequestId:t};this.rpcManager.post("query/unsubscribe",n).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t)}),Ir(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,n,s,i,r,o,a={},c){if(a[n])return a[n];const u=o&&c?c:this.clientIdService.generateClientRequestId(),l=[],d={clientRequestId:u,activated:o,alias:n,query:e,subscribe:r,dataSubject:new t(null),supportedQueries:l,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t(0),queryRegistered:new t(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?qi.UNKNOWN:qi.DISABLED};this.registerQueryFinalizer(d),this.ongoingQueries.set(u,d),a[n]=d;for(const[e,t]of Object.entries(i)){const o=t.leftAlias;if(o!==n&&e!==n)continue;const c=o===n?e:o;if(o===n){const e=this.createOngoingQueryGraph(s[c],c,s,i,r,!1,a);e.joinCondition=t,l.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(s[c],c,s,i,r,!1,a)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const n=e.alias;t.push(e.dataSubject.pipe(Ir(Boolean),pn(e=>({docs:e,alias:n}))));for(const n of e.supportedQueries)this.collectAllObservables(n,t);return t}joinResults(e,t,n){const s=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let i=s[n.alias].map(e=>({[n.alias]:e}));const r=this.getOngoingQueriesBfs(n),o=new Set;for(let e=1;e<r.length;e++){const n=r[e].alias;o.has(n)||(o.add(n),i=this.join(i,n,s[n],t[n]))}return i}join(e,t,n,s){if(!e.length)return e;const i=Object.keys(e[0]);if(!s||!i.includes(s.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(n||[]).forEach(e=>{const t=this.transformKey(e[s.right]);r.has(t)||r.set(t,[]),kt(r.get(t)).push(e)}),e.flatMap(e=>{const n=r.get(this.transformKey(e[s.leftAlias]?.[s.left]))||[];return n.length?n.map(n=>({...e,[t]:n})):s.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],n=[e];for(;n.length;){const e=kt(n.shift());e.isEmptyForJoin||(t.push(e),n.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,n){const s=kt(n.joinCondition),i=n.query;if(n.activated){if(!n.canExpandForJoin)return!1;const r=kt(n.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===n.alias),o=new Set(e.map(e=>e[s.left]??null));for(const e of r)e.query.conditions.filter(xs).filter(e=>e.fieldName===s.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=as(i);a.conditions=a.conditions.filter(e=>!xs(e)||e.fieldName!==s.right),[...o].forEach(e=>{a.conditions.push({fieldName:s.right,operator:"==",value:e})});const c={...n,query:a,activated:!0,gotInitialResponse:!1,dataSubject:new t(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),kt(n.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(n.activated=!0,i.conditions.filter(xs).filter(e=>e.fieldName===s.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(n),n.canExpandForJoin=!1,!0;const t=e.map(e=>e[s.left]??null).map(e=>({fieldName:s.right,operator:"==",value:e}));return t.length?(i.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(n)):n.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=kt(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(Ir(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 n=e.query,s=e.clientRequestId,i=Fs(this.clientIdService.getClientId(),s);this.queryMappingManager.addQuery(n,i),this.ongoingQueries.set(s,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},s=new Ci(e.query);e.limitWindowEnd=void 0,t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(Ir(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",n).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(n=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,n),e.dataSubject.error(n)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const i=k(e.queryRegistered.pipe(Ir(Boolean),h(2e3),O(1)),this.destructManager.observeIsDestructing().pipe(O(1)));t.dataSubject.pipe(A(()=>!e.done),q(i),Ir(Boolean),R(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),pn(e=>e.filter(e=>s.documentMatchesQuery(e)))).subscribe({next:t=>{for(const n of t)this.setClientRequestIdsForLocalDoc(As(n.__docId__,e.query.collectionName,e.query.integrationId),n);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,n=t>0&&e.subscribe?t+100:t,s={query:{...e.query,limit:n},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(s).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()):(_s.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 n of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{n.has(t)&&(n.delete(t),n.add(e[t]))});t.forEach(t=>{ss(this.localDocumentToClientRequestIds,t,e[t])})}}function $r(e,t){for(const n of e.fields){const e=ts(t,n.fieldName)??null;if(Rs(n.value,e,n.operator))return!0;if(Rs(n.value,e,"!="))return!1}return!1}class Gr{constructor(){this.stateService=new Br({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let n=0;const s=new Set;for(const i of e.conditions){if(xs(i)&&["=="].includes(i.operator)){const e=ms(i.fieldName);s.has(e)||(n++,s.add(e))}else n++;const r=this.getConditionStatePath(e,i),o=[...this.stateService.get(r)||[]];Ur(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const n=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],s=[...this.stateService.get(n)||[]];Ur(s,t),this.stateService.set(n,s)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],n)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const n of t.conditions){const s=this.getConditionStatePath(t,n),i=[...this.stateService.get(s)||[]];Lr(i,e),i.length?this.stateService.set(s,i):this.stateService.delete(s)}if(!t.conditions.length){const n=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],s=[...this.stateService.get(n)||[]];Lr(s,e),this.stateService.set(n,s)}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",(n=t,ps(n))];var n}}class Hr{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 w(a(t).pipe(g(e=>!e.includes(!0)),O(1))),await this.lock(...e)}release(...e){for(const t of e){const e=kt(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){Mt(this.canGetLock(...e),"Cannot acquire lock sync");for(const n of e)this.locks[n]=new t(!0)}}class Kr{constructor(e,t,n){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)}),n.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let n=this.queueManagers.get(e);n||(n=new Map,this.queueManagers.set(e,n));let s=n.get(t);return s||(s=new Vr(e,t,this.rpcManager,this.socketManager),n.set(t,s)),s}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const Wr="subscriptionMutex";class Vr{constructor(e,t,n,s){this.integrationId=e,this.topicName=t,this.rpcManager=n,this.socketManager=s,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new Hr}async produce(e){await this.lockManager.lock(Wr);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(Wr)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),d(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe(f(()=>{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(Wr);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 r}finally{this.lockManager.release(Wr)}}async performUnsubscribe(){await this.lockManager.lock(Wr);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(Wr)}}}class Jr{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 m(I(10).pipe(g(()=>this.attemptConsume()),y()))}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 zr{constructor(e,n,s,i,r,o,a){this.region=e,this.appId=n,this.authManager=r,this.clientIdService=o,this.baseUrl=a,this.staticHeaders={},this.onGoingRpcCounter=new t(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe(e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")}),s.onDestruct(async()=>{await this.awaitAllSettled()});const c=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Jr(60*c,5),ai:new Jr(20*c,5),secret:new Jr(20*c,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:n}=await this.authManager.getAuthData();if(!t)return{};let s=`Bearer ${t}`;return n&&(s+=`; IntegrationId ${n}`),{Authorization:s}}async awaitAllSettled(){await m(this.onGoingRpcCounter.pipe(g(e=>0===e)))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(e=""){return{...!this.baseUrl||e.startsWith("http://")||e.startsWith("https://")?{}:{[kn]:this.appId},...this.staticHeaders}}async post(e,t,n=[],s="files",i={},r){return(await this.rawPost(e,t,n,s,!0,i,r)).body}async rawPost(e,t,n=[],s="files",i=!0,r={},o){return this.runRawRequest(e,r,async r=>{_s.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const a=this.resolveUrl(e);return await Xi({url:a,headers:r,message:t,files:n,filesFieldName:s,extractErrorMessage:i,abortSignal:o})})}async get(e,t,n=!0){return(await this.rawGet(e,t,n)).body}async rawGet(e,t,n=!0){return this.runRawRequest(e,{},async s=>{let i=this.resolveUrl(e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,n])=>{e.append(t,String(n))}),i+=`?${e.toString()}`}return _s.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await Zi({url:i,headers:s,extractErrorMessage:n})})}async put(e,t,n=[],s="files"){return(await this.rawPut(e,t,n,s)).body}async rawPut(e,t,n=[],s="files",i=!0){return this.runRawRequest(e,{},async r=>{_s.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const o=this.resolveUrl(e);return await er({url:o,headers:r,message:t,files:n,filesFieldName:s,extractErrorMessage:i})})}async patch(e,t,n=[],s="files"){return(await this.rawPatch(e,t,n,s)).body}async rawPatch(e,t,n=[],s="files",i=!0){return this.runRawRequest(e,{},async r=>{_s.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const o=this.resolveUrl(e);return await tr({url:o,headers:r,message:t,files:n,filesFieldName:s,extractErrorMessage:i})})}async delete(e,t,n=!0){return(await this.rawDelete(e,t,n)).body}async rawDelete(e,t,n=!0){return this.runRawRequest(e,{},async s=>{_s.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const i=this.resolveUrl(e);return await nr({url:i,headers:s,message:t,extractErrorMessage:n})})}async runRawRequest(e,t,n){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const s=await this.getAuthHeaders(),i={...this.getStaticHeaders(e),...s,...t};return await n(i)}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")?e:this.baseUrl?P(this.baseUrl,e):B(this.region,this.appId,e)}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?kt(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?kt(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):kt(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}function Yr(e){Mt(!e.isPassiveMode,"This operation is not available in passive mode. Use active mode for real-time features.")}class Xr{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}]}}class Zr{constructor(e){this.rpcManager=e}async upsert(e){return await this.rpcManager.post("sessions/upsert",e)}async get(e){const{session:t}=await this.rpcManager.post("sessions/get",{id:e});return t}async delete(e){await this.rpcManager.post("sessions/delete",{id:e})}async list(e={}){return await this.rpcManager.post("sessions/list",e)}}function eo(){}const to="undefined"!=typeof process&&process.versions?.node?x(220):Ts().WebSocket;class no{constructor(e,n,s,i=Ji,o,a,c,u){this.clientIdService=e,this.region=n,this.appId=s,this.messageNotificationWrapper=i,this.destructManager=o,this.authManager=a,this.runtimeOptions=c,this.baseUrl=u,this.webSocketObserver=new r,this.allMessagesObserver=new r,this.connectionReady=new t(!1),this.seenMessageIds=new Set,this.destructSubject=new r,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new t(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe(g(Boolean),O(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe(_(1),g(e=>!e),C(()=>k(j(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?_s.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(_s.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe(g(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe(g(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?_s.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?_s.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(_s.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),_s.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(p())}async awaitConnectionReady(){Yr(this.runtimeOptions),await m(this.observeConnectionReady().pipe(g(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&&(_s.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 m(k(this.connectionReady.pipe(g(Boolean)),j(12e4).pipe(R(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))).pipe(q(this.destructSubject)))}catch(e){if(this.destructManager.isDestructing)return;throw e}const t=await this.authManager.getToken();if(this.connectionReady.value)try{Mt(this.socket,"Socket is undefined in sendMessageAsync");const n=fs({message:e,authToken:t});_s.debug(this.clientIdService.getClientId(),"Sending message to socket: ",n),this.socket.send(n)}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(fs({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=(this.baseUrl?P(this.baseUrl,"ws/general"):B(this.region,this.appId,"ws/general")).replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();_s.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const n=this.baseUrl?`&appId=${encodeURIComponent(this.appId)}`:"",s=`${e}?clientId=${t}${n}`;this.socket=function(e,t={}){let n,s=0,i=1;const r={connected:!1,closeCalled:!1,open(){n=new(to?.WebSocket??to)(e,t.protocols||[]),n.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.")}:eo,n.onopen=function(e){r.connected=!0,(t.onopen||eo)(e),s=0},n.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return _s.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||eo)(e),void r.reconnect(e);(t.onclose||eo)(e)},n.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||eo)(e)}},reconnect(e){const n=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&s++<n?i=setTimeout(function(){(t.onreconnect||eo)(e),_s.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||eo)(e)},json(e){n.send(JSON.stringify(e))},send(e){n.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(i),i=void 0,n.close(e,t)}catch(e){}}};return r.open(),r}(s,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{_s.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{_s.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):_s.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{_s.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):_s.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 _s.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=ys(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),_s.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new r;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe(R(e=>t.push(e)),o(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await m(j(0)),this.connectionReady.next(!1),await m(j(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function so(e){var t,n;n="Invalid application ID",Mt(function(e){return"string"==typeof e}(t=e),()=>_t(n,"Not a string",t));const s=e.split("-");Mt(s.length<4,`Invalid application ID: ${e}`);const[i,r,o]=s;return{appId:i,environmentId:r??"prod",squidDeveloperId:o}}function io(e,t){return`${so(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function ro(e,t,n){return`${io(e,t)}${n?`-${n}`:""}`}function oo(e){const t=so(e);return io(t.appId,t.environmentId)}class ao{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,n){const s={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:n};await this.rpcManager.post("storage/uploadFile",s,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const n={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",n)}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 co{constructor(e,t,n,s,i){this.rpcManager=e,this.region=t,this.appId=n,this.apiKey=s,this.consoleRegion=i}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}async aiSearch(e,t,n){return await this.rpcManager.post("web/aiSearch",{query:e,allowedDomains:n},[],"files",{},t)}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e){Mt(this.apiKey,"API key is required to create a short URL");const t="string"==typeof e?{url:e}:e,n={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shorten",n,"create short URL","json")}async createShortUrls(e){Mt(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,n={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shortenMany",n,"create short URLs","json")}async deleteShortUrl(e){Mt(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){Mt(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,n,s){const i=U(this.region,this.consoleRegion,`openapi/sqd/${e}`),r=await fetch(i,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(t)});if("ignore"===s)return void Mt(r.ok,`Failed to ${n} (${r.status}): ${r.statusText}`);const o=await r.text();return Mt(r.ok,`Failed to ${n} (${r.status}): ${o}`),JSON.parse(o)}}class uo{constructor(e,t,n){this.rpcManager=e,this.region=t,this.appId=n}async executeWebhook(e,t={}){const{headers:n={},queryParams:s={},body:i,files:r=[]}=t,o=await this.rpcManager.getAuthHeaders(),a={...this.rpcManager.getStaticHeaders(),...o,...n};let c=this.rpcManager.resolveUrl(`webhooks/${encodeURIComponent(e)}`);if(s&&Object.keys(s).length>0){const e=new URLSearchParams;Object.entries(s).forEach(([t,n])=>{e.append(t,String(n))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(Mn,Vi("c_")),u.append(Tn,Yi),r&&r.length>0){const e=new FormData;for(const t of r)e.append("file",t,t.name);i&&"object"==typeof i&&Object.entries(i).forEach(([t,n])=>{e.append(t,String(n))}),l=e}else u.append("Content-Type","application/json"),l=fs(i||{});const d=await fetch(c,{method:"POST",headers:u,body:l}),h={};if(d.headers.forEach((e,t)=>{h[t]=e}),!d.ok){const e=await d.text();let t;try{t=JSON.parse(e)}catch{t=e}const n="string"==typeof t?t:t?.message||d.statusText;throw new zi(n,d.status,c,h,t)}const p=await d.text();let g;try{g=JSON.parse(p)}catch{g=p}return g}getWebhookUrl(e){return B(this.region,this.appId,e?`webhooks/${encodeURIComponent(e)}`:"webhooks")}}class lo{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new ji,Mt(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,n=ro(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Es(this.destructManager),_s.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Yn(e.apiKey,e.authProvider),this.socketManager=new no(this.clientIdService,e.region,n,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions,e.baseUrl),this.rpcManager=new zr(e.region,n,this.destructManager,{},this.authManager,this.clientIdService,e.baseUrl),this.notificationClient=new cr(this.socketManager,this.rpcManager),this.jobClient=new Gi(this.socketManager,this.rpcManager,this.clientIdService,this.destructManager,this.runtimeOptions),this.langGraphClient=new Ki(this.rpcManager,this.jobClient,this.socketManager),this.sessionClient=new Zr(this.rpcManager),this.backendFunctionManager=new Ms(this.rpcManager),this.aiClient=new Vn(this.socketManager,this.rpcManager,this.jobClient,this.clientIdService,this.backendFunctionManager,()=>this.metricAnnotations),this.apiClient=new zn(this.rpcManager),this.eventsClient=new Li(this.rpcManager),this.documentStore=new Ui,this.lockManager=new Hr,this.distributedLockManager=new Ni(this.socketManager,this.destructManager),this.documentIdentityService=new Bi(this.documentStore,this.destructManager),this.documentReferenceFactory=new Pi(this.documentIdentityService),this.querySender=new wr(this.rpcManager,this.destructManager,this.socketManager.observeConnectionReady()),this.observabilityClient=new lr(this.rpcManager),this.schedulerClient=new Xr(this.rpcManager),this._appId=n,this.querySubscriptionManager=new Qr(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new br(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const s=new or(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new ti(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService,s),this.dataManager=new Ai(this.documentStore,s,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new hi(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new uo(this.rpcManager,e.region,n),this.nativeQueryManager=new ar(this.rpcManager),this._connectionDetails=new pi(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new Kr(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new Lt(this.rpcManager,this.options.region,oo(n),this.options.consoleRegion,this.backendFunctionManager),this.webClient=new co(this.rpcManager,this.options.region,oo(n),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=ps(e);let n=lo.squidInstancesMap[t];return n||(n=new lo(e),lo.squidInstancesMap[t]=n,n)}static getInstances(){return Object.values(lo.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=rt){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,...n){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...n)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}getWebhookUrl(e){return this._validateNotDestructed(),this.webhookManager.getWebhookUrl(e)}executeNativeRelationalQuery(e,t,n={}){const s={type:"relational",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativePureQuery(e,t,n={}){const s={type:"pure",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativeMongoQuery(e,t,n){const s={type:"mongo",collectionName:t,aggregationPipeline:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativeElasticQuery(e,t,n,s="_search",i="GET"){const r={type:"elasticsearch",index:t,endpoint:s,method:i,body:n,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)}sessions(){return this._validateNotDestructed(),this.sessionClient}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 ao(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new Qi(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new $i(this.rpcManager)}events(){return this._validateNotDestructed(),this.eventsClient}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,n){const s=await this.acquireLock(e,n);try{return await t(s)}finally{s.release()}}queue(e,t=ot){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(lo.squidInstancesMap).find(([,e])=>e===this);e&&delete lo.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,n)=>B(e,t,n),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,n)=>ro(e,t,n)}}_validateNotDestructed(){Mt(!this.destructManager.isDestructing,"The client was already destructed.")}}const ho=18,po=100,go=50,fo=200,yo=500,mo=500,bo=1e3,Io=200,wo=20,vo=2e4;export{G as AGENT_STATUS_TITLE_ACCESSING_KB,$ as AGENT_STATUS_TITLE_AGENT_RESPONSE,K as AGENT_STATUS_TITLE_AI_FUNCTION_RESULT,H as AGENT_STATUS_TITLE_CALLING_AI_FUNCTION,J as AGENT_STATUS_TITLE_GREPPING_KB,W as AGENT_STATUS_TITLE_INSPECTING_KB_METADATA,V as AGENT_STATUS_TITLE_QUERYING_KB_GRAPH,z as AGENT_STATUS_TITLE_QUERYING_SPREADSHEET,Ye as AI_AGENTS_INTEGRATION_ID,te as AI_AGENT_CONNECTION_EVENT_TYPE,Ee as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,_e as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,X as AI_CHAT_MESSAGE_SOURCE,oe as AI_CODE_INTERPRETER_PROVIDER_TYPES,ye as AI_EMBEDDINGS_MODEL_NAMES,ie as AI_FILE_PROVIDER_TYPES,Te as AI_IMAGE_MODEL_NAMES,je as AI_KB_ACCESS_CONTROL_MODES,Ce as AI_MODEL_SOURCES,Y as AI_PROVIDER_ERROR_TYPE,se as AI_PROVIDER_TYPES,$e as AI_VOICE_GREETING_MODES,Qe as AI_VOICE_RELAY_PROVIDERS,Ge as AI_VOICE_SESSION_EVENT_TYPE,bt as ALL_OPERATORS,le as ANTHROPIC_CHAT_MODEL_NAMES,He as API_INJECTION_FIELD_TYPES,mt as ARRAY_OPERATORS,et as AUTH_INTEGRATION_TYPES,Lt as AdminClient,Nn as AiAgentClient,An as AiAgentReference,xn as AiAudioClient,Vn as AiClient,Bn as AiFilesClient,Pn as AiImageClient,$n as AiKnowledgeBaseClient,Qn as AiKnowledgeBaseReference,Gn as AiMatchMakingClient,Wn as AiVoiceClient,Kn as AiWebVoiceCall,zn as ApiClient,Ut as ApiKeysSecretClient,Yn as AuthManager,fe as BEDROCK_EMBEDDING_MODEL_NAMES,Ve as BUILT_IN_AGENT_ID,rt as BUILT_IN_DB_INTEGRATION_ID,ot as BUILT_IN_QUEUE_INTEGRATION_ID,at as BUILT_IN_STORAGE_INTEGRATION_ID,Be as BULK_INGESTION_MAX_MULTIPART_FILE_BYTES,Le as BULK_INGESTION_SPEEDS,Ms as BackendFunctionManager,ni as BaseQueryBuilder,wt as CLIENT_CONNECTION_STATES,Ds as CLIENT_ID_GENERATOR_KEY,Cs as CLIENT_REQUEST_ID_GENERATOR_KEY,Je as CONNECTOR_IDS,ri as Changes,Es as ClientIdService,li as CollectionReference,hi as CollectionReferenceFactory,pi as ConnectionDetails,L as ConnectorClient,Ze as DATA_INTEGRATION_TYPES,ee as DEFAULT_PII_CLASSIFIER_MODEL,Z as DEFAULT_PII_ENTITY_TYPES,ho as DEFAULT_SHORT_ID_LENGTH,yt as DOC_ID_FIELD,Ai as DataManager,ai as DereferencedJoin,ji as DestructManager,Fi as DistributedLockImpl,Ni as DistributedLockManager,Zs as DocumentReference,Pi as DocumentReferenceFactory,Ui as DocumentStore,Fn as EMPTY_CHAT_ID,We as ENVIRONMENT_IDS,Li as EventsClient,Qi as ExternalAuthClient,$i as ExtractionClient,po as FETCH_BEYOND_LIMIT,Fe as FILE_NAME_METADATA_FIELD_NAME,ke as FLUX_MODEL_NAMES,xe as FOLDER_PATH_METADATA_FIELD,Ne as FOLDER_PATH_METADATA_FIELD_NAME,Ae as FUNCTION_AFFINITY_SCOPES,ce as GEMINI_CHAT_MODEL_NAMES,nt as GRAPHQL_INTEGRATION_TYPES,go as GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES,fo as GREP_KNOWLEDGE_BASE_MAX_MATCHES,yo as GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS,mo as GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS,ue as GROK_CHAT_MODEL_NAMES,ui as GroupedJoin,st as HTTP_INTEGRATION_TYPES,ze as HttpStatus,it as INTEGRATION_SCHEMA_TYPES,Xe as INTEGRATION_TYPES,Bt as IntegrationClient,Gi as JobClient,oi as JoinQueryBuilder,bo as KNOWLEDGE_BASE_GRAPH_EXPLORE_MAX_NODES,Io as KNOWLEDGE_BASE_GRAPH_SEARCH_MAX_LENGTH,Ki as LangGraphClient,Hi as LangGraphReference,ws as LastUsedValueExecuteFunctionCache,qi as LimitUnderflowState,br as LocalQueryManager,Pe as MAX_UPLOAD_FILE_BYTES,tt as MCP_OAUTH_INTEGRATION_TYPES,pt as METRIC_DOMAIN,ht as METRIC_FUNCTIONS,gt as METRIC_INTERVAL_ALIGNMENT,ft as METRIC_NO_DATA_BEHAVIOR,rr as ManagementClient,Hn as MatchMaker,or as MutationSender,Ji as NOOP_FN,ar as NativeQueryManager,cr as NotificationClient,ve as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,Se as OPENAI_AUDIO_MODEL_NAMES,we as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,ae as OPENAI_CHAT_MODEL_NAMES,pe as OPENAI_EMBEDDINGS_MODEL_NAMES,Ie as OPENAI_IMAGE_MODEL_NAMES,De as OPEN_AI_CREATE_SPEECH_FORMATS,lr as ObservabilityClient,ei as Pagination,ii as QueryBuilder,ti as QueryBuilderFactory,wr as QuerySender,Qr as QuerySubscriptionManager,Kr as QueueManagerFactory,Vr as QueueManagerImpl,Ue as RAG_TYPES,ne as RERANK_PROVIDERS,Oi as RUN_IN_TRANSACTION_MUTEX,Jr as RateLimiter,zr as RpcManager,Dt as SOURCE_CODE_ANALYZER_MODELS,Et as SOURCE_CODE_ANALYZE_FUNCTION_ID,Ct as SOURCE_CODE_CACHE_STRATEGIES,Ot as SOURCE_CODE_EXECUTION_MODES,At as SOURCE_CODE_INTEGRATION_TYPES,wo as SOURCE_CODE_MAX_REPOSITORIES,vo as SOURCE_CODE_MAX_SUPPLEMENTAL_INSTRUCTIONS_LENGTH,qt as SOURCE_CONTROL_PROVIDERS,ut as SQUID_BUILT_IN_INTEGRATION_IDS,dt as SQUID_METRIC_NAMES,It as SQUID_REGIONS,Me as STABLE_DIFFUSION_MODEL_NAMES,Xr as SchedulerClient,Pt as SecretClient,Zr as SessionClient,no as SocketManager,lo as Squid,zi as SquidClientError,ao as StorageClient,Re as VECTOR_DB_TYPES,de as VENDOR_AI_CHAT_MODEL_NAMES,ge as VOYAGE_EMBEDDING_MODEL_NAMES,co as WebClient,uo as WebhookManager,Yr as assertNotPassiveMode,bs as compareArgsByReference,Is as compareArgsBySerializedValue,fr as deserializeQuery,Oe as embeddingModelSelectionOf,yn as generateId,bn as generateShortId,In as generateShortIds,gn as generateUUID,fn as generateUUIDPolyfill,U as getConsoleUrl,ks as getCustomizationFlag,me as isAiEmbeddingsModelName,lt as isBuiltInIntegrationId,re as isFileCapableProviderType,ct as isIntegrationDisabled,be as isIntegrationEmbeddingModelSpec,qe as isIntegrationModelSpec,Ke as isPlaceholderParam,he as isVendorAiChatModelName,gr as loadQueryResultDocIds,jt as normalizeBitbucketRepositorySelection,Rt as normalizeGitHubRepositorySelection,qn as observeAiStatusUpdates,nr as rawSquidHttpDelete,Zi as rawSquidHttpGet,tr as rawSquidHttpPatch,Xi as rawSquidHttpPost,er as rawSquidHttpPut,vs as transformFileArgs,ir as tryDeserializing,pr as visitQueryResults};