@coalescesoftware/coa 7.40.0-alpha.16af1ae6d5b0 → 7.40.0-alpha.7d6bba96702c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/coa.js +20 -20
- package/heartbeat-worker.js +1 -1
- package/package.json +1 -1
- package/test-heartbeat-worker.js +1 -1
- package/web-ui/index.html +1 -1
- package/web-ui/static/js/{Auth0ActivationForm-Dl1tzNaR.js → Auth0ActivationForm-JUC5t0H_.js} +2 -2
- package/web-ui/static/js/{UserActivationForm-3YUqp8YV.js → UserActivationForm-CNP1My-Z.js} +2 -2
- package/web-ui/static/js/{__vite-browser-external-DNxhgrJr.js → __vite-browser-external-EJj5v7lq.js} +2 -2
- package/web-ui/static/js/{browser-D7hy1ocE.js → browser-F4vsSwXw.js} +2 -2
- package/web-ui/static/js/{index-BFG7PLIH.js → index-DPMweBOO.js} +4 -4
- package/web-ui/static/js/{path-browserify-BdaxZUwW.js → path-browserify-C-MhbP2k.js} +2 -2
- package/web-ui/static/js/{worker.browser-WOfE1dxT.js → worker.browser-B9YS002n.js} +8 -8
- package/worker.node.js +1 -1
package/coa.js
CHANGED
|
@@ -980,7 +980,7 @@ To learn more about authentication and Google APIs, visit:
|
|
|
980
980
|
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
981
981
|
To learn more about Universe Domain retrieval, visit:
|
|
982
982
|
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var A7s=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(t={}){if(this._cachedProjectId=t.projectId||null,this.cachedCredential=t.authClient||null,this.keyFilename=t.keyFilename||t.keyFile,this.scopes=t.scopes,this.clientOptions=t.clientOptions||{},this.jsonContent=t.credentials||null,this.apiKey=t.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(WW.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);t.universeDomain&&(this.clientOptions.universeDomain=t.universeDomain)}setGapicJWTValues(t){t.defaultServicePath=this.defaultServicePath,t.useJWTAccessWithScope=this.useJWTAccessWithScope,t.defaultScopes=this.defaultScopes}getProjectId(t){if(t)this.getProjectIdAsync().then(n=>t(null,n),t);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(t){if(t instanceof Error&&t.message===WW.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw t}}async findAndCacheProjectId(){let t=null;if(t||=await this.getProductionProjectId(),t||=await this.getFileProjectId(),t||=await this.getDefaultServiceProjectId(),t||=await this.getGCEProjectId(),t||=await this.getExternalAccountClientProjectId(),t)return this._cachedProjectId=t,t;throw new Error(WW.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let t;try{t=await zQt.universe("universe-domain"),t||=g7s.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)t=g7s.DEFAULT_UNIVERSE;else throw n}return t}async getUniverseDomain(){let t=(0,IHp.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{t??=(await this.getClient()).universeDomain}catch{t??=g7s.DEFAULT_UNIVERSE}return t}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(t={},n){let i;if(typeof t=="function"?n=t:i=t,n)this.getApplicationDefaultAsync(i).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(i)}async getApplicationDefaultAsync(t={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(t),n)return n instanceof Ght.JWT?n.scopes=this.scopes:n instanceof QQt.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(t),n)return n instanceof Ght.JWT?n.scopes=this.scopes:n instanceof QQt.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return t.scopes=this.getAnyScopes(),await this.#t(new obm.Compute(t));throw new Error(WW.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(t,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let i=await this.getProjectIdOptional();return n&&(t.quotaProjectId=n),this.cachedCredential=t,{credential:t,projectId:i}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=zQt.getGCPResidency()||await zQt.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(t){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(n,t)}catch(i){throw i instanceof Error&&(i.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${i.message}`),i}}async _tryGetApplicationCredentialsFromWellKnownFile(t){let n=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=h7s.join(o,".config"))}return n&&(n=h7s.join(n,"gcloud","application_default_credentials.json"),UQt.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,t):null}async _getApplicationCredentialsFromFilePath(t,n={}){if(!t||t.length===0)throw new Error("The file path is invalid.");try{if(t=UQt.realpathSync(t),!UQt.lstatSync(t).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${t} does not exist, or it is not a file. ${o.message}`),o}let i=UQt.createReadStream(t);return this.fromStream(i,n)}fromImpersonatedJSON(t){if(!t)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(t.type!==Hht.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Hht.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!t.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!t.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(t.source_credentials);if(t.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${t.service_account_impersonation_url}`);let i=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(t.service_account_impersonation_url)?.groups?.target;if(!i)throw new RangeError(`Cannot extract target principal from ${t.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new Hht.Impersonated({...t,sourceClient:n,targetPrincipal:i,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(t,n={}){let i,o=(0,IHp.originalOrCamelOptions)(n).get("universe_domain");return t.type===THp.USER_REFRESH_ACCOUNT_TYPE?(i=new THp.UserRefreshClient(n),i.fromJSON(t)):t.type===Hht.IMPERSONATED_ACCOUNT_TYPE?i=this.fromImpersonatedJSON(t):t.type===QQt.EXTERNAL_ACCOUNT_TYPE?(i=ubm.ExternalAccountClient.fromJSON({...t,...n}),i.scopes=this.getAnyScopes()):t.type===_Hp.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?i=new _Hp.ExternalAccountAuthorizedUserClient({...t,...n}):(n.scopes=this.scopes,i=new Ght.JWT(n),this.setGapicJWTValues(i),i.fromJSON(t)),o&&(i.universeDomain=o),i}_cacheClientFromJSON(t,n){let i=this.fromJSON(t,n);return this.jsonContent=t,this.cachedCredential=i,i}fromStream(t,n={},i){let o={};if(typeof n=="function"?i=n:o=n,i)this.fromStreamAsync(t,o).then(s=>i(null,s),i);else return this.fromStreamAsync(t,o)}fromStreamAsync(t,n){return new Promise((i,o)=>{if(!t)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];t.setEncoding("utf8").on("error",o).on("data",a=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),u=this._cacheClientFromJSON(a,n);return i(u)}catch(a){if(!this.keyFilename)throw a;let u=new Ght.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),i(u)}}catch(a){return o(a)}})})}fromAPIKey(t,n={}){return new Ght.JWT({...n,apiKey:t})}_isWindows(){let t=nbm.platform();return!!(t&&t.length>=3&&t.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(t=>{(0,tbm.exec)("gcloud config config-helper --format json",(n,i)=>{if(!n&&i)try{let o=JSON.parse(i).configuration.properties.core.project;t(o);return}catch{}t(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let t=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return t?t.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==QQt.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await zQt.project("project-id")}catch{return null}}getCredentials(t){if(t)this.getCredentialsAsync().then(n=>t(null,n),t);else return this.getCredentialsAsync()}async getCredentialsAsync(){let t=await this.getClient();if(t instanceof Hht.Impersonated)return{client_email:t.getTargetPrincipal()};if(t instanceof QQt.BaseExternalAccountClient){let n=t.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:t.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,i]=await Promise.all([zQt.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:i}}throw new Error(WW.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let t=h7s.resolve(this.keyFilename),n=UQt.createReadStream(t);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let t=await this.fromAPIKey(this.apiKey,this.clientOptions);t.scopes=this.scopes;let{credential:n}=await this.#t(t);return n}else{let{credential:t}=await this.getApplicationDefaultAsync(this.clientOptions);return t}}async getIdTokenClient(t){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new sbm.IdTokenClient({targetAudience:t,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(t){return(await this.getClient()).getRequestHeaders(t)}async authorizeRequest(t={}){let n=t.url,o=await(await this.getClient()).getRequestHeaders(n);return t.headers=rbm.Gaxios.mergeHeaders(t.headers,o),t}async fetch(...t){return(await this.getClient()).fetch(...t)}async request(t){return(await this.getClient()).request(t)}getEnv(){return(0,abm.getEnv)()}async sign(t,n){let i=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,i instanceof Hht.Impersonated)return(await i.sign(t)).signedBlob;let s=(0,ibm.createCrypto)();if(i instanceof Ght.JWT&&i.key)return await s.sign(i.key,t);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,t,n)}async signBlob(t,n,i,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:t.encodeBase64StringUtf8(i)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};WW.GoogleAuth=A7s});var OHp=m(Hrn=>{"use strict";Object.defineProperty(Hrn,"__esModule",{value:!0});Hrn.IAMAuth=void 0;var m7s=class{selector;token;constructor(t,n){this.selector=t,this.token=n,this.selector=t,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Hrn.IAMAuth=m7s});var wHp=m(Pne=>{"use strict";Object.defineProperty(Pne,"__esModule",{value:!0});Pne.DownscopedClient=Pne.EXPIRATION_TIME_OFFSET=Pne.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var cbm=ZO(),lbm=require("stream"),y7s=E9(),pbm=_rn(),dbm="urn:ietf:params:oauth:grant-type:token-exchange",fbm="urn:ietf:params:oauth:token-type:access_token",hbm="urn:ietf:params:oauth:token-type:access_token";Pne.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Pne.EXPIRATION_TIME_OFFSET=300*1e3;var b7s=class extends y7s.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(t,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(t instanceof y7s.AuthClient?{}:t),t instanceof y7s.AuthClient?(this.authClient=t,this.credentialAccessBoundary=n):(this.authClient=t.authClient,this.credentialAccessBoundary=t.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Pne.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Pne.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let i of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(i.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new pbm.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(t){if(!t.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(t),this.cachedDownscopedAccessToken=t}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let t=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${t.token}`});return this.addSharedMetadataHeaders(n)}request(t,n){if(n)this.requestAsync(t).then(i=>n(null,i),i=>n(i,i.response));else return this.requestAsync(t)}async requestAsync(t,n=!1){let i;try{let o=await this.getRequestHeaders();t.headers=cbm.Gaxios.mergeHeaders(t.headers),this.addUserProjectAndAuthHeaders(t.headers,o),i=await this.transporter.request(t)}catch(o){let s=o.response;if(s){let a=s.status,u=s.config.data instanceof lbm.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(t,!0)}throw o}return i}async refreshAccessTokenAsync(){let t=(await this.authClient.getAccessToken()).token,n={grantType:dbm,requestedTokenType:fbm,subjectToken:t,subjectTokenType:hbm},i=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=i.expires_in?new Date().getTime()+i.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:i.access_token,expiry_date:s,res:i.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(t){let n=new Date().getTime();return t.expiry_date?n>=t.expiry_date-this.eagerRefreshThresholdMillis:!1}};Pne.DownscopedClient=b7s});var MHp=m(Vrn=>{"use strict";Object.defineProperty(Vrn,"__esModule",{value:!0});Vrn.PassThroughClient=void 0;var gbm=E9(),E7s=class extends gbm.AuthClient{async request(t){return this.transporter.request(t)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Vrn.PassThroughClient=E7s});var DHp=m(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});uu.GoogleAuth=uu.auth=uu.PassThroughClient=uu.ExecutableError=uu.PluggableAuthClient=uu.DownscopedClient=uu.BaseExternalAccountClient=uu.ExternalAccountClient=uu.IdentityPoolClient=uu.AwsRequestSigner=uu.AwsClient=uu.UserRefreshClient=uu.LoginTicket=uu.ClientAuthentication=uu.OAuth2Client=uu.CodeChallengeMethod=uu.Impersonated=uu.JWT=uu.JWTAccess=uu.IdTokenClient=uu.IAMAuth=uu.GCPEnv=uu.Compute=uu.DEFAULT_UNIVERSE=uu.AuthClient=uu.gaxios=uu.gcpMetadata=void 0;var xHp=RHp();Object.defineProperty(uu,"GoogleAuth",{enumerable:!0,get:function(){return xHp.GoogleAuth}});uu.gcpMetadata=wQt();uu.gaxios=ZO();var PHp=E9();Object.defineProperty(uu,"AuthClient",{enumerable:!0,get:function(){return PHp.AuthClient}});Object.defineProperty(uu,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return PHp.DEFAULT_UNIVERSE}});var Abm=m9s();Object.defineProperty(uu,"Compute",{enumerable:!0,get:function(){return Abm.Compute}});var mbm=E9s();Object.defineProperty(uu,"GCPEnv",{enumerable:!0,get:function(){return mbm.GCPEnv}});var ybm=OHp();Object.defineProperty(uu,"IAMAuth",{enumerable:!0,get:function(){return ybm.IAMAuth}});var bbm=b9s();Object.defineProperty(uu,"IdTokenClient",{enumerable:!0,get:function(){return bbm.IdTokenClient}});var Ebm=O9s();Object.defineProperty(uu,"JWTAccess",{enumerable:!0,get:function(){return Ebm.JWTAccess}});var Cbm=M9s();Object.defineProperty(uu,"JWT",{enumerable:!0,get:function(){return Cbm.JWT}});var Sbm=D9s();Object.defineProperty(uu,"Impersonated",{enumerable:!0,get:function(){return Sbm.Impersonated}});var C7s=_9e();Object.defineProperty(uu,"CodeChallengeMethod",{enumerable:!0,get:function(){return C7s.CodeChallengeMethod}});Object.defineProperty(uu,"OAuth2Client",{enumerable:!0,get:function(){return C7s.OAuth2Client}});Object.defineProperty(uu,"ClientAuthentication",{enumerable:!0,get:function(){return C7s.ClientAuthentication}});var vbm=f9s();Object.defineProperty(uu,"LoginTicket",{enumerable:!0,get:function(){return vbm.LoginTicket}});var Tbm=P9s();Object.defineProperty(uu,"UserRefreshClient",{enumerable:!0,get:function(){return Tbm.UserRefreshClient}});var _bm=Z9s();Object.defineProperty(uu,"AwsClient",{enumerable:!0,get:function(){return _bm.AwsClient}});var Ibm=J9s();Object.defineProperty(uu,"AwsRequestSigner",{enumerable:!0,get:function(){return Ibm.AwsRequestSigner}});var Rbm=K9s();Object.defineProperty(uu,"IdentityPoolClient",{enumerable:!0,get:function(){return Rbm.IdentityPoolClient}});var Obm=p7s();Object.defineProperty(uu,"ExternalAccountClient",{enumerable:!0,get:function(){return Obm.ExternalAccountClient}});var wbm=hRe();Object.defineProperty(uu,"BaseExternalAccountClient",{enumerable:!0,get:function(){return wbm.BaseExternalAccountClient}});var Mbm=wHp();Object.defineProperty(uu,"DownscopedClient",{enumerable:!0,get:function(){return Mbm.DownscopedClient}});var NHp=c7s();Object.defineProperty(uu,"PluggableAuthClient",{enumerable:!0,get:function(){return NHp.PluggableAuthClient}});Object.defineProperty(uu,"ExecutableError",{enumerable:!0,get:function(){return NHp.ExecutableError}});var xbm=MHp();Object.defineProperty(uu,"PassThroughClient",{enumerable:!0,get:function(){return xbm.PassThroughClient}});var Pbm=new xHp.GoogleAuth;uu.auth=Pbm});var BHp=m(gfe=>{"use strict";var Nbm=gfe&&gfe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(gfe,"__esModule",{value:!0});gfe.SNOWFLAKE_AUDIENCE=void 0;gfe.getGcpAttestationToken=Lbm;var Dbm=DHp(),Bbm=Nbm(yd());gfe.SNOWFLAKE_AUDIENCE="snowflakecomputing.com";async function Lbm(){let r=new Dbm.GoogleAuth;return(0,Bbm.default)().debug("Getting GCP auth token"),await(await r.getIdTokenClient(gfe.SNOWFLAKE_AUDIENCE)).idTokenProvider.fetchIdToken(gfe.SNOWFLAKE_AUDIENCE)}});var kHp=m(GQt=>{"use strict";var LHp=GQt&&GQt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(GQt,"__esModule",{value:!0});var kbm=vqp(),jQt=Tqp(),Wrn=oA(),qbm=LHp(yd()),Fbm=sjp(),Ubm=BHp(),zbm=LHp(PW()),S7s=class{connectionConfig;tokenProvider;token;constructor(t){this.connectionConfig=t}updateBody(t){t.data.AUTHENTICATOR=zbm.default.WORKLOAD_IDENTITY,t.data.PROVIDER=this.tokenProvider,t.data.TOKEN=this.token}async authenticate(){let t=this.connectionConfig.workloadIdentityProvider,n;if(t===jQt.WorkloadIdentityProvider.AWS)n=await(0,kbm.getAwsAttestationToken)();else if(t===jQt.WorkloadIdentityProvider.AZURE)n=await(0,Fbm.getAzureAttestationToken)(this.connectionConfig.workloadIdentityAzureEntraIdResource);else if(t===jQt.WorkloadIdentityProvider.GCP)n=await(0,Ubm.getGcpAttestationToken)();else if(t===jQt.WorkloadIdentityProvider.OIDC)if(this.connectionConfig.token)n=this.connectionConfig.token;else throw(0,Wrn.createInvalidParameterError)(Wrn.ErrorCode.ERR_CONN_CREATE_INVALID_WORKLOAD_IDENTITY_PARAMETERS,"workloadIdentityProvider: OIDC requires token in connection options");else throw(0,Wrn.createInvalidParameterError)(Wrn.ErrorCode.ERR_CONN_CREATE_INVALID_WORKLOAD_IDENTITY_PARAMETERS,`workloadIdentityProvider must be one of: ${Object.values(jQt.WorkloadIdentityProvider).join(", ")}`);(0,qbm.default)().debug(`AuthWorkloadIdentity using provider=${t}`),this.tokenProvider=t,this.token=n}};GQt.default=S7s});var qHp=m(Vht=>{"use strict";var Qbm=Vht&&Vht.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vht,"__esModule",{value:!0});Vht.default=void 0;var jbm=kHp();Object.defineProperty(Vht,"default",{enumerable:!0,get:function(){return Qbm(jbm).default}})});var Yrn=m(Krn=>{"use strict";var FHp=B9p(),Gbm=d6s(),Hbm=f6s(),Vbm=Z9p(),Wbm=r7p(),Kbm=g6s(),Ybm=A6s(),Jbm=yd(),Afe=PW(),$bm=E6s(),Xbm=f7p().default,Zbm=qHp().default;Krn.formAuthJSON=function(t,n,i,o,s,a){let u={data:{ACCOUNT_NAME:n,CLIENT_APP_ID:o,CLIENT_APP_VERSION:s,CLIENT_ENVIRONMENT:{OS:a.OS,OS_VERSION:a.OS_VERSION,OCSP_MODE:a.OCSP_MODE}}};return this.isOktaAuth(t)||(u.data.AUTHENTICATOR=t,u.data.LOGIN_NAME=i),u};Krn.getAuthenticator=function(t,n){let i=t.getAuthenticator(),o=t.openExternalBrowserCallback,s;return i===Afe.DEFAULT_AUTHENTICATOR||i===Afe.USER_PWD_MFA_AUTHENTICATOR?s=new FHp(t):i===Afe.EXTERNAL_BROWSER_AUTHENTICATOR?t.getClientStoreTemporaryCredential()&&t.idToken?s=new Ybm(t,n,o):s=new Gbm(t,n,o):i===Afe.KEY_PAIR_AUTHENTICATOR?s=new Hbm(t):i===Afe.OAUTH_AUTHENTICATOR?s=new Vbm(t.getToken()):i===Afe.PROGRAMMATIC_ACCESS_TOKEN?s=new Wbm(t.getToken(),t.password):i===Afe.OAUTH_AUTHORIZATION_CODE?s=new $bm(t,n):i===Afe.OAUTH_CLIENT_CREDENTIALS?s=new Xbm(t,n):this.isOktaAuth(i)?s=new Kbm(t,n):i===Afe.WORKLOAD_IDENTITY?s=new Zbm(t,n):(Jbm.getInstance().warn(`No authenticator found for '${i}'. Using default authenticator as a fallback`),s=new FHp(t)),s};Krn.isOktaAuth=function(t){return t.toUpperCase().startsWith("HTTPS://")}});var HHp=m(Jrn=>{"use strict";var QHp=require("os"),eEm=require("path"),v7s=require("fs"),{isString:UHp,exists:Wht,getDriverDirectory:tEm,isWindows:rEm}=Tc(),H0=yd(),{IsFileExisted:nEm}=rN(),iEm="sf_client_config.json",jHp=Object.freeze({Off:"OFF",Error:"ERROR",Warn:"WARN",Info:"INFO",Debug:"DEBUG",Trace:"TRACE"}),zHp=oEm();function oEm(){let r=[],t=tEm();H0.getInstance().debug(`Detected driver directory: ${t}`),t?r.push({dir:t,dirDescription:"driver"}):H0.getInstance().warn("Driver directory is not defined");let n=QHp.homedir();return H0.getInstance().debug(`Detected home directory: ${n}`),Wht(n)?r.push({dir:n,dirDescription:"home"}):H0.getInstance().warn("Home directory of the user is not defined"),H0.getInstance().debug(`Detected default directories: ${t}`),r}var sEm=["log_level","log_path"],aEm=Object.values(jHp),T7s=class{constructor(t,n){this.configPath=t,this.loggingConfig=n}},_7s=class{constructor(t,n){this.logLevel=t,this.logPath=n}},mfe=class extends Error{name="ConfigurationError";constructor(t,n){super(t),this.cause=n,Error.captureStackTrace(this,this.constructor)}toString(){return this.message+": "+this.cause.toString()}};function GHp(r){let t=r.toUpperCase();if(!aEm.includes(t))throw H0.getInstance().error(`Tried to create unsupported log level from string: ${r}`),new Error("Unknown log level: "+r);return t}function uEm(r,t){let n=typeof r<"u"?r:require("fs/promises"),i=typeof t<"u"?t:require("process"),o=null,s=null;this.getClientConfig=async function(H,V=!1,W=0){H0.getInstance().debug("Retrieving client config");let F=await w(H);if(!Wht(F)||F==="")return H0.getInstance().info("No config file path found. Client config will not be used."),null;if(!(V||nEm(F)))return H0.getInstance().info(`No config file not found on ${F}. Client config will not be used.`),null;try{if(s=await c(F),rEm())o=await l(s).catch(Y=>{throw H0.getInstance().debug(`Reading configuration from the file failed. Path: ${F}`),new mfe("Finding client configuration failed",Y)});else{let Y=await s.stat(),z=Y.mode&511;if(!a(z))throw H0.getInstance().warn(`Config file path permissions are invalid. File: ${F} can be modified by group or others. Client config will not be used.`),new mfe(`Configuration file: ${F} can be modified by group or others`,"IncorrectPerms");if(!u(Y))throw H0.getInstance().warn("This config file is not owned by the current user. Client config will not be used."),new mfe("Configuration file: not owned by the current user","Invalid Ownership");H0.getInstance().debug(`Config file path permissions are valid. Path: ${F}`),V&&await new Promise(Z=>setTimeout(Z,W)),o=await l(s).catch(Z=>{throw H0.getInstance().debug(`Reading configuration from the file failed. Path: ${F}`),new mfe("Finding client configuration failed",Z)});let X=await n.stat(F);if(!p(Y,X))throw H0.getInstance().error("The file was modified after the driver opened the config file and can no longer be used."),new mfe("The config file has been modified","InvalidConfigFile")}H0.getInstance().info("Using client configuration from path: %s",F)}catch(Y){throw Y.syscall==="open"?(H0.getInstance().debug(`Fail to open the configuration file from. Path: ${F}. If the file is a symlink, please change the path to the real path`),new mfe("Fail to open the configuration file",Y)):Y}finally{await s?.close()}return o==null?null:d(F,o)};function a(H){return(H&16)===0&&(H&2)===0}function u(H){let V=QHp.userInfo();return H.uid===V.uid&&H.gid===V.gid}function p(H,V){return["uid","mtimeMs","mode","birthtimeMs","ctimeMs"].every(F=>H[F]===V[F])}async function c(H){return n.open(H,v7s.constants.O_NOFOLLOW|v7s.constants.O_RDONLY)}async function l(H){return H.readFile({encoding:"utf8"})}function d(H,V){H0.getInstance().debug("Parsing config file: %s",H);try{let W=JSON.parse(V);H0.getInstance().trace("Config file contains correct JSON structure. Validating the input."),f(W),h(W),H0.getInstance().debug("Config file contains valid configuration input.");let F=new T7s(H,new _7s(v(W),T(W)));return H0.getInstance().info("Client Configuration created with Log Level: %s and Log Path: %s",F.loggingConfig.logLevel,F.loggingConfig.logPath),F}catch(W){throw H0.getInstance().error("Parsing client configuration failed. Used config file from path: %s",H),new mfe("Parsing client configuration failed",W)}}function f(H){for(let V in H.common)sEm.includes(V.toLowerCase())||H0.getInstance().warn("Unknown configuration entry: %s with value: %s",V,H.common[V])}function h(H){A(H),E(H)}function A(H){let V=v(H);if(V==null){H0.getInstance().debug("Log level is not specified.");return}if(!UHp(V)){let W="Log level is not a string.";throw H0.getInstance().error(W),new Error(W)}GHp(V)}function E(H){let V=T(H);if(V==null){H0.getInstance().debug("Log path is not specified");return}if(!UHp(V)){let W="Log path is not a string.";throw H0.getInstance().error(W),new Error(W)}}function v(H){return H.common.log_level}function T(H){return H.common.log_path}async function w(H){if(H0.getInstance().trace(`findConfig() called with param: ${H}`),Wht(H))return H0.getInstance().info("Found client configuration path in a connection string. Path: %s",H),H;let V=await k();if(Wht(V))return H0.getInstance().info("Found client configuration path in an environment variable. Path: %s",V),V;let W=await L();return Wht(W)?(H0.getInstance().info("Found client configuration path in %s directory. Path: %s",W.dirDescription,W.configPath),W.configPath):(H0.getInstance().info("No client config detected."),null)}async function N(H){return H||null}function k(){return N(i.env.SF_CLIENT_CONFIG_FILE)}async function L(){H0.getInstance().debug(`Searching for config in default directories: ${JSON.stringify(zHp)}`);for(let H of zHp){let V=await q(H.dir,H.dirDescription);if(Wht(V))return H0.getInstance().debug(`Config found in the default directory: ${H.dir}. Path: ${V}`),{configPath:V,dirDescription:H.dirDescription}}return H0.getInstance().debug("Unable to find config in any default directory."),null}async function q(H,V){try{let W=eEm.join(H,iEm);return await G(W)}catch(W){return H0.getInstance().error("Error while searching for the client config in %s directory: %s",V,W),null}}async function G(H){return await n.access(H,v7s.constants.F_OK).then(()=>H).catch(()=>null)}}Jrn.Levels=jHp;Jrn.levelFromString=GHp;Jrn.ConfigurationUtil=uEm});var WHp=m(R7s=>{"use strict";var cEm=require("os"),VHp=require("path"),I7s=require("fs/promises"),lEm=require("fs"),{logTagToLevel:pEm}=o9t(),{ConfigurationUtil:dEm,Levels:fEm}=HHp(),yfe=yd(),{isFileModeCorrect:hEm}=rN(),{exists:gEm}=Tc(),AEm=new dEm,mEm=AEm.getClientConfig,Kht;R7s.init=async function(r){try{if(!yEm(r))return;yfe.getInstance().info("Trying to initialize Easy Logging");let t=await mEm(r);if(!t){yfe.getInstance().info("Easy Logging is disabled as no config has been found"),Kht={configFilePathFromConnectionString:r};return}let n=bEm(t),i=await CEm(t),o=yfe.getInstance();o.info("Initializing Easy Logging with logPath=%s and logLevel=%s from file: %s",i,t.loggingConfig.logLevel,t.configPath),o.configure({level:n,filePath:VHp.join(i,"snowflake.log"),additionalLogToConsole:!1}),o.easyLoggingConfigureCounter=(o.easyLoggingConfigureCounter??0)+1,Kht={configFilePathFromConnectionString:r}}catch(t){let n=new HQt("Failed to initialize easy logging",t);throw yfe.getInstance().error(n),n}};R7s.reset=function(){Kht=void 0,yfe.getInstance().easyLoggingConfigureCounter=void 0};function yEm(r){let t=!!Kht,n=t&&Kht.configFilePathFromConnectionString==null,o=!t||n&&!!r;return!o&&Kht.configFilePathFromConnectionString!==r&&yfe.getInstance().warn(`Easy logging will not be configured for CLIENT_CONFIG_FILE=${r} because it was previously configured for a different client config`),o}function bEm(r){let t=EEm(r),n=pEm(t);if(n==null)throw new Error("Failed to convert configuration log level into internal one");return n}function EEm(r){let t=r.loggingConfig.logLevel;return t||(yfe.getInstance().warn("LogLevel in client config not found. Using default value: OFF"),fEm.Off)}async function CEm(r){let t=r.loggingConfig.logPath;if(!t&&(yfe.getInstance().warn("LogPath in client config not found. Using home directory as a default value"),t=cEm.homedir(),!gEm(t)))throw new HQt("Home directory does not exist");let n=VHp.join(t,"nodejs");return await I7s.access(n,lEm.constants.F_OK).then(async()=>{await hEm(n,448,I7s)||yfe.getInstance().warn("Log directory: %s could potentially be accessed by others",n)}).catch(async()=>{try{await I7s.mkdir(n,{recursive:!0,mode:448})}catch{throw new HQt(`Failed to create the directory for logs: ${n}`)}}),n}var HQt=class extends Error{name="EasyLoggingError";constructor(t,n){super(t),this.cause=n,Error.captureStackTrace(this,this.constructor)}toString(){return this.message+": "+this.cause.toString()}}});var YHp=m((LAS,x7s)=>{"use strict";var O7s=require("path"),Nne=yd(),Bx=require("node:fs/promises"),Yht=Tc(),KHp=require("os"),SEm=require("crypto"),{getSecureHandle:w7s,closeHandle:M7s}=rN(),$rn={win32:["AppData","Local","Snowflake","Caches"],linux:[".cache","snowflake"],darwin:["Library","Caches","Snowflake"]};function vEm(r,t=6e4){let n="tokens";this.hashKey=function(s){return SEm.createHash("sha256").update(s).digest("hex")},this.getTokenDirCandidates=function(){let s=[];switch(s.push({folder:r,subfolders:[]}),s.push({folder:process.env.SF_TEMPORARY_CREDENTIAL_CACHE_DIR,subfolders:[]}),process.platform){case"win32":s.push({folder:KHp.homedir(),subfolders:$rn.win32});break;case"linux":s.push({folder:process.env.XDG_CACHE_HOME,subfolders:["snowflake"]}),s.push({folder:process.env.HOME,subfolders:$rn.linux});break;case"darwin":s.push({folder:process.env.HOME,subfolders:$rn.darwin})}return s},this.createCacheDir=async function(s){let a={recursive:!0};process.platform!=="win32"&&(a.mode=493),await Bx.mkdir(s,a),process.platform!=="win32"&&await Bx.chmod(s,448)},this.tryTokenDir=async function(s,a){if(!Yht.exists(s))return!1;let u=O7s.join(s,...a);try{if(!(await Bx.stat(s)).isDirectory())return Nne.getInstance().info(`Path ${s} is not a directory`),!1;let c=await Bx.stat(u).catch(async l=>{if(l.code!=="ENOENT")throw l;return await this.createCacheDir(u),await Bx.stat(u)});return c.isDirectory()?(process.platform==="win32"||(c.uid!==KHp.userInfo().uid?Nne.getInstance().warn(`Token cache directory ${u} has insecure owner.`):(c.mode&511)!==448&&Nne.getInstance().warn(`Token cache directory ${u} has insecure permissions.`)),!0):!1}catch{return Nne.getInstance().warn(`The location ${u} is invalid. Please check this location is accessible or existing`),!1}},this.getTokenDir=async function(){let s=this.getTokenDirCandidates();for(let a of s){let{folder:u,subfolders:p}=a;if(await this.tryTokenDir(u,p))return O7s.join(u,...p)}return null},this.getTokenFilePath=async function(){let s=await this.getTokenDir();if(!Yht.exists(s))throw new Error(`Temporary credential cache directory is invalid, and the driver is unable to use the default location.
|
|
983
|
-
Please set 'credentialCacheDir' connection configuration option to enable the default credential manager.`);return O7s.join(s,"credential_cache_v1.json")},this.readJsonCredentialFile=async function(s){if(!Yht.exists(s))return null;try{let a=await s.readFile("utf8");return JSON.parse(a)}catch(a){return Nne.getInstance().warn("Failed to read token data from the file. Err: %s",a.message),null}},this.removeStale=async function(s){let a=await Bx.stat(s).catch(()=>{});if(Yht.exists(a)&&new Date().getTime()-a.birthtimeMs>t)try{await Bx.rmdir(s)}catch(u){Nne.getInstance().warn("Failed to remove stale file. Error: %s",u.message)}},this.lockFile=async function(s){let a=s+".lck";await this.removeStale(a);let u=1,p=!1,c={};for(process.platform!=="win32"&&(c.mode=384);u<=10&&(Nne.getInstance().debug("Attempting to get a lock on file %s, attempt: %d",s,u),u++,await Bx.mkdir(a,c).then(()=>{p=!0},()=>{}),!p);)await new Promise(l=>setTimeout(l,100));return p||Nne.getInstance().warn("Could not acquire lock on cache file %s",s),p},this.unlockFile=async function(s){let a=s+".lck";await Bx.rmdir(a)},this.withFileLocked=async function(s){let a=await this.getTokenFilePath();if(await this.lockFile(a)){let u=await s(a);return await this.unlockFile(a),u}return null},this.write=async function(s,a){if(!o(s))return null;let u=this.hashKey(s);await this.withFileLocked(async p=>{let c=await w7s(p,Bx.constants.O_RDWR|Bx.constants.O_CREAT,Bx),l=await this.readJsonCredentialFile(c)||{};Yht.exists(l[n])||(l[n]={}),l[n][u]=a;try{await c.truncate(),await c.write(JSON.stringify(l),0),await M7s(c)}catch(d){Nne.getInstance().warn(`Failed to write token data in ${p}. Please check the permission or the file format of the token. ${d.message}`)}})},this.read=async function(s){if(!o(s))return null;let a=this.hashKey(s);return await this.withFileLocked(async u=>{let p=await w7s(u,Bx.constants.O_RDWR,Bx),c=await this.readJsonCredentialFile(p);return await M7s(p),c&&c[n]&&c[n][a]?c[n][a]:null})},this.remove=async function(s){if(!o(s))return null;let a=this.hashKey(s);await this.withFileLocked(async u=>{let p=await w7s(u,Bx.constants.O_RDWR,Bx),c=await this.readJsonCredentialFile(p);if(c&&c[n]&&c[n][a])try{c[n][a]=null,await p.truncate(),await p.write(JSON.stringify(c),0),await M7s(p)}catch(l){Nne.getInstance().warn(`Failed to remove token data from the file in ${u}. Please check the permission or the file format of the token. ${l.message}`)}})};function o(s){return Yht.checkParametersDefined(s)}}x7s.exports.defaultJsonTokenCachePaths=$rn;x7s.exports.JsonCredentialManager=vEm});var iVp=m((kAS,nVp)=>{"use strict";var{v4:JHp}=(A6(),ut(g6)),$Hp=require("url"),TEm=require("querystring"),Uz=hap(),VQt=ljr(),D_=Tc(),ew=oA(),zz=ew.codes,tVp=require("events").EventEmitter,XHp=fXr(),Xrn=p9t(),P7s=Yrn(),N7s=PW(),Xo=yd(),{isOktaAuth:_Em}=Yrn(),{init:ZHp}=WHp(),Jht=DO(),{JsonCredentialManager:eVp}=YHp(),D7s=r_s();function rVp(r){Xo.getInstance().trace("Connection object is being constructed"),ew.assertInternal(D_.isObject(r));let t=r.getServices(),n=r.getConnectionConfig(),i=JHp();Xo.getInstance().trace("Generated connection id: %s",i),Xo.getInstance().info("Creating Connection[id: %s] with %s, password is %s, region: %s, authenticator: %s, ocsp mode: %s, os: %s, os version: %s",i,n.describeIdentityAttributes(),VQt.describePresence(n.password),n.region,n.getAuthenticator(),n.getClientEnvironment().OCSP_MODE,n.getClientEnvironment().OS,n.getClientEnvironment().OS_VERSION),Xo.getInstance().info("Connection[id: %s] additional details: passcode in password is %s, passcode is %s, private key is %s, application: %s, client name: %s, client version: %s, retry timeout: %s, private key path: %s, private key pass is %s, client store temporary credential: %s, browser response timeout: %s",i,VQt.describePresence(n.getPasscodeInPassword()),VQt.describePresence(n.getPasscode()),VQt.describePresence(n.getPrivateKey()),n.getClientApplication(),n.getClientName(),n.getClientVersion(),n.getRetryTimeout(),n.getPrivateKeyPath(),VQt.describePresence(n.getPrivateKeyPass()),n.getClientStoreTemporaryCredential(),n.getBrowserActionTimeout());let o=24,s=[1,1,2,3,4,8,10],a=500,u=new RegExp(/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);this.getTokens=function(){return n._qaMode?t.sf.getConfig()&&t.sf.getConfig().tokenInfo:{}},this.isUp=function(){let d=t.sf.isConnected();return Xo.getInstance().trace("Connection[id: %s] - isUp called. Returning: %s",this.getId(),d),d},this.isTokenValid=function(){Xo.getInstance().trace("Connection[id: %s] - isTokenValid called",this.getId());let d=t.sf.getConfig().tokenInfo,h=d.sessionTokenExpirationTime>Date.now();Xo.getInstance().trace("Connection[id: %s] - isSessionTokenValid: %s",this.getId(),h);let E=d.masterTokenExpirationTime>Date.now();Xo.getInstance().trace("Connection[id: %s] - isMasterTokenValid: %s",this.getId(),E);let v=h&&E;return Xo.getInstance().trace("Connection[id: %s] - isTokenValid returned: %s",this.getId(),v),v},this.getServiceName=function(){return t.sf.getServiceName()},this.getClientSessionKeepAlive=function(){return t.sf.getClientSessionKeepAlive()},this.getClientSessionKeepAliveHeartbeatFrequency=function(){return t.sf.getClientSessionKeepAliveHeartbeatFrequency()},this.getJsTreatIntegerAsBigInt=function(){return t.sf.getJsTreatIntegerAsBigInt()},this.getId=function(){return i},this.heartbeat=d=>{Xo.getInstance().trace("Issuing heartbeat call");let f=JHp();t.sf.request({method:"POST",url:$Hp.format({pathname:"/session/heartbeat",search:TEm.stringify({requestId:f})}),callback:D_.isFunction(d)?d:function(h,A){h?Xo.getInstance().error("Error issuing heartbeat call: %s",h.message):Xo.getInstance().trace("Heartbeat response %s",JSON.stringify(A))}})},this.heartbeatAsync=()=>new Promise((d,f)=>{Xo.getInstance().trace("Issuing async heartbeat call"),this.heartbeat(h=>h?f(h):d([{1:1}]))}),this.isValidAsync=async()=>{if(Xo.getInstance().trace("Connection[id: %s] - isValidAsync called",this.getId()),!this.isUp())return!1;try{return await this.heartbeatAsync(),!0}catch(d){return Xo.getInstance().debug("Connection[id: %s] - heartbeat failed: %s",this.getId(),JSON.stringify(d,Object.getOwnPropertyNames(d))),!1}},this.setupOcspPrivateLink=function(d){process.env.SF_OCSP_RESPONSE_CACHE_SERVER_URL=D_.createOcspResponseCacheServerUrl(d)};function p(d,f){return function(h){if(Xrn.getValue(Xrn.names.CLIENT_SESSION_KEEP_ALIVE)){let E=Xrn.getValue(Xrn.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY)*1e3;d.keepalive=setInterval(d.heartbeat,E,d),Xo.getInstance().trace("Connection[id: %s] - keepAlive internal created",i)}D_.isFunction(f)&&f(ew.externalize(h),d)}}this.determineConnectionDomain=()=>n.accessUrl&&n.accessUrl.includes("snowflakecomputing.cn")?"CHINA":"GLOBAL",this.connect=function(d){let f=new D7s().start(),h=this.determineConnectionDomain();Xo.getInstance().info("Connection[id: %s] - connecting. Associated Snowflake domain: %s",this.getId(),h),ew.checkArgumentValid(!D_.exists(d)||D_.isFunction(d),zz.ERR_CONN_CONNECT_INVALID_CALLBACK),D_.exists(n.host)&&D_.isPrivateLink(n.host)&&(Xo.getInstance().info("Connection[id: %s] - setting up private link",this.getId()),this.setupOcspPrivateLink(n.host));let A=this,E=n.getAuthenticator();if(Xo.getInstance().debug("Connection[id: %s] - using authentication type: %s",this.getId(),E),E===N7s.EXTERNAL_BROWSER_AUTHENTICATOR||_Em(E)){let T=f.getDuration();throw Xo.getInstance().error("Connection[id: %s] - connecting failed after %s milliseconds.Error: External browser and Okta are not compatible with connection process",this.getId(),T),ew.createClientError(zz.ERR_CONN_CREATE_INVALID_AUTH_CONNECT)}Xo.getInstance().debug("Connection[id: %s] - retrieving authenticator",this.getId());let v=t.sf.getAuthenticator();return Xo.getInstance().debug("Connection[id: %s] - trying to authenticate",this.getId()),v.authenticate(n.getAuthenticator(),n.getServiceName(),n.account,n.username).then(()=>{Xo.getInstance().info("Connection[id: %s] - authentication successful using: %s",this.getId(),n.getAuthenticator());let T=P7s.formAuthJSON(n.getAuthenticator(),n.account,n.username,n.getClientType(),n.getClientVersion(),n.getClientEnvironment());v.updateBody(T),Xo.getInstance().debug("Connection[id: %s] - initializing easyLogging",this.getId()),ZHp(n.clientConfigFile).then(()=>{Xo.getInstance().debug("Connection[id: %s] - easyLogging initialized",this.getId());try{Xo.getInstance().debug("Connection[id: %s] - connecting through service",this.getId()),t.sf.connect({callback:p(A,d),json:T});let w=f.getDuration();return Xo.getInstance().info("Connection[id: %s] - connected successfully after %s milliseconds",this.getId(),w),this}catch(w){let N=f.getDuration();Xo.getInstance().info("Connection[id: %s] - failed to connect after %s milliseconds. Error: Unexpected error from calling connectCallback function in snowflake service - %s",this.getId(),N,w)}},()=>{let w=f.getDuration();Xo.getInstance().error("Connection[id: %s] - failed to initialize easyLogging. Connecting failed after %s milliseconds",this.getId(),w),d(ew.createClientError(zz.ERR_CONN_CONNECT_INVALID_CLIENT_CONFIG,!0),A)})},T=>{let w=f.getDuration();Xo.getInstance().error("Connection[id: %s] - authentication failed. Error: %s. Connecting failed after %s milliseconds",this.getId(),T,w),d(T,A)}),this},this.connectAsync=async function(d){let f=new D7s().start(),h=this.determineConnectionDomain();Xo.getInstance().info("Connection[id: %s] - async connecting. Associated Snowflake domain: %s",this.getId(),h),ew.checkArgumentValid(!D_.exists(d)||D_.isFunction(d),zz.ERR_CONN_CONNECT_INVALID_CALLBACK),D_.isPrivateLink(n.host)&&(this.setupOcspPrivateLink(n.host),Xo.getInstance().info("Connection[id: %s] - setting up private link",this.getId()));let A=this;if(n.getClientStoreTemporaryCredential()){Xo.getInstance().debug("Connection[id: %s] - storing temporary credential of client",this.getId());let T=D_.buildCredentialCacheKey(n.host,n.username,N7s.ID_TOKEN_AUTHENTICATOR);Jht.getCredentialManager()===null&&(Xo.getInstance().debug("Connection[id: %s] - using default json credential manager",this.getId()),Jht.setCustomCredentialManager(new eVp(n.getCredentialCacheDir()))),Xo.getInstance().debug("Connection[id: %s] - reading idToken using credential manager",this.getId()),n.idToken=await Jht.getCredentialManager().read(T)}if(n.getClientRequestMFAToken()){Xo.getInstance().debug("Connection[id: %s] - extracting mfaToken of client",this.getId());let T=D_.buildCredentialCacheKey(n.host,n.username,N7s.USER_PWD_MFA_AUTHENTICATOR);Jht.getCredentialManager()===null&&(Xo.getInstance().debug("Connection[id: %s] - using default json credential manager",this.getId()),Jht.setCustomCredentialManager(new eVp(n.getCredentialCacheDir()))),Xo.getInstance().debug("Connection[id: %s] - reading mfaToken using credential manager",this.getId()),n.mfaToken=await Jht.getCredentialManager().read(T)}let E;try{Xo.getInstance().debug("Connection[id: %s] - retrieving authenticator",this.getId()),E=P7s.getAuthenticator(n,r.getHttpClient()),t.sf.authenticator=E}catch{let w=f.getDuration();throw Xo.getInstance().error("Connection[id: %s] - failed to initialize authenticator. Connecting failed after %s milliseconds",this.getId(),w),ew.createClientError(zz.ERR_CONN_CREATE_INVALID_AUTH_UNSUPPORTED,!0)}try{Xo.getInstance().debug("Connection[id: %s] - initializing easyLogging",this.getId()),await ZHp(n.clientConfigFile)}catch{let w=f.getDuration();throw Xo.getInstance().error("Connection[id: %s] - failed to initialize easyLogging. Connecting failed after %s milliseconds",this.getId(),w),ew.createClientError(zz.ERR_CONN_CONNECT_INVALID_CLIENT_CONFIG,!0)}let v=null;try{Xo.getInstance().debug("Connection[id: %s] - using authentication type: %s",this.getId(),n.getAuthenticator()),Xo.getInstance().debug("Connection[id: %s] - trying to authenticate",this.getId()),await E.authenticate(n.getAuthenticator(),n.getServiceName(),n.account,n.username),Xo.getInstance().info("Connection[id: %s] - authentication successful using: %s",this.getId(),n.getAuthenticator()),v=P7s.formAuthJSON(n.getAuthenticator(),n.account,n.username,n.getClientType(),n.getClientVersion(),n.getClientEnvironment()),E.updateBody(v)}catch(T){let w=f.getDuration();return Xo.getInstance().info("Connection[id: %s] - failed to connect async after %s milliseconds.Failed during authentication. Error: %s",this.getId(),w,T),Xo.getInstance().error("Connection[id: %s] - failed during authentication. Error: %s",this.getId(),T),d(T),this}try{Xo.getInstance().debug("Connection[id: %s] - connecting through service",this.getId()),t.sf.connect({callback:p(A,d),json:v});let T=f.getDuration();Xo.getInstance().info("Connection[id: %s] - connected successfully after %s milliseconds",this.getId(),T)}catch(T){let w=f.getDuration();return Xo.getInstance().info("Connection[id: %s] - failed to connect async after %s milliseconds.Error: Unexpected error from calling connectCallback function in snowflake service - %s",this.getId(),w,T),d(T),this}return this},this.execute=function(d){return Xo.getInstance().trace("Connection[id: %s] - execute called with options.",this.getId()),XHp.createStatementPreExec(d,t,n)},this.fetchResult=function(d){return Xo.getInstance().trace("Connection[id: %s] - fetchResult called with options",this.getId()),XHp.createStatementPostExec(d,t,n)},this.destroy=function(d){Xo.getInstance().trace("Connection[id: %s] - destroy called",this.getId()),ew.checkArgumentValid(!D_.exists(d)||D_.isFunction(d),zz.ERR_CONN_DESTROY_INVALID_CALLBACK),Xo.getInstance().trace("Connection[id: %s] - destroying through service",this.getId());let f=this;return t.sf.destroy({callback:function(h){D_.exists(f.keepalive)&&(clearInterval(f.keepalive),Xo.getInstance().trace("Connection[id: %s] - keepAlive interval cleared",f.getId())),D_.isFunction(d)&&d(ew.externalize(h),f)}}),Xo.getInstance().trace("Connection[id: %s] - connection destroyed successfully",this.getId()),this};async function c(d){Xo.getInstance().trace("Connection[id: %s] - requested query response for Query[id: %s]",i,d),ew.checkArgumentExists(D_.exists(d),zz.ERR_CONN_FETCH_RESULT_MISSING_QUERY_ID),ew.checkArgumentValid(u.test(d),zz.ERR_GET_RESPONSE_QUERY_INVALID_UUID,d),Xo.getInstance().debug("Connection[id: %s] - Query[id: %s] is valid",i,d);let f={method:"GET",url:$Hp.format({pathname:`/monitoring/queries/${d}`})};Xo.getInstance().debug("Connection[id: %s] - fetching query response for Query[id: %s]",i,d);let h=new D7s().start(),A=await t.sf.requestAsync(f),E=h.getDuration();return Xo.getInstance().debug("Connection[id: %s] - query response for Query[id: %s] fetched successfully after: %s milliseconds",i,d,E),A.data}function l(d){let f=Uz.code.NO_QUERY_DATA;if(!d||!d.data||!d.data.queries)return Xo.getInstance().trace("Connection[id: %s] - No query data found, returning NO_QUERY_DATA status",i),f;let h=d.data.queries;return h.length>0&&(f=h[0].status),Xo.getInstance().trace("Connection[id: %s] - Extracted query status: %s",i,f),f}this.getQueryStatus=async function(d){return Xo.getInstance().trace("Connection[id: %s] - getQueryStatus called for Query[id: %s]",this.getId(),d),l(await c(d))},this.getQueryStatusThrowIfError=async function(d){Xo.getInstance().trace("Connection[id: %s] - getQueryStatusThrowIfError called for Query[id: %s]",this.getId(),d);let f=await c(d),h=l(f),A=null;if(this.isAnError(h)){let E=f.message||"",v=f.code||-1;throw f.data&&(E+=f.data.queries.length>0?f.data.queries[0].errorMessage:"",A=f.data.sqlState),Xo.getInstance().debug("Connection[id: %s] - query error for Query[id: %s]. Error: %s. SQLState: %s",this.getId(),d,E,A),ew.createOperationFailedError(v,f,E,A)}return h},this.getResultsFromQueryId=async function(d){let f=d.queryId;Xo.getInstance().trace("Connection[id: %s] - getResultsFromQueryId called for Query[id: %s].",this.getId(),f);let h,A=0,E=0,v=!0;for(;v;){if(Xo.getInstance().trace("Connection[id: %s] - checking if Query[id: %s] is still executing. Retries with no data count: %d",this.getId(),f,A),h=await this.getQueryStatusThrowIfError(f),v=this.isStillRunning(h),!v||h===Uz.code.NO_QUERY_DATA){Xo.getInstance().trace("Connection[id: %s] - end of waiting for Query[id: %s] to finish executing. "+v?"Query is no longer executing. ":"Query status: %s.",this.getId(),f,h);break}if(await new Promise(T=>{setTimeout(()=>T(),a*s[E])}),Uz.code[h]===Uz.code.NO_DATA&&(A++,Xo.getInstance().trace("Connection[id: %s] - no data returned for Query[id: %s]. Retries with no data count: %d",this.getId(),f,A),A>o))throw Xo.getInstance().error("Connection[id: %s] - no data returned for Query[id: %s]. Retry limit: %s reached.",this.getId(),f,o),ew.createClientError(zz.ERR_GET_RESULTS_QUERY_ID_NO_DATA,!0,f);E<s.length-1&&E++}if(Uz.code[h]===Uz.code.NO_QUERY_DATA)throw Xo.getInstance().error("Connection[id: %s] - Query[id: %s] did not succeed. Final status: %s",this.getId(),f,h),ew.createClientError(zz.ERR_GET_RESULTS_QUERY_ID_NO_DATA,!0,f,h);if(Uz.code[h]!==Uz.code.SUCCESS)throw Xo.getInstance().error("Connection[id: %s] - Query[id: %s] did not succeed. Final status: %s",this.getId(),f,h),ew.createClientError(zz.ERR_GET_RESULTS_QUERY_ID_NOT_SUCCESS_STATUS,!0,f,h);return Xo.getInstance().debug("Connection[id: %s] - Query[id: %s] succeeded. Fetching the result.",this.getId(),f),this.fetchResult(d)},this.isStillRunning=function(d){return Xo.getInstance().trace("Connection[id: %s] - checking if status %s is still running",this.getId(),d),Uz.runningStatuses.includes(Uz.code[d])},this.isAnError=function(d){return Uz.errorStatuses.includes(Uz.code[d])},this.serialize=function(){return Xo.getInstance().trace("Connection[id: %s] - serialize called",this.getId()),JSON.stringify(r.getConfig())},tVp.call(this)}D_.inherits(rVp,tVp);nVp.exports=rVp});var sVp=m(oVp=>{"use strict";oVp.HEARTBEAT_FREQUENCY_MASTER_VALIDITY=14400});var TVp=m((FAS,vVp)=>{"use strict";var aVp=require("os"),IEm=require("url"),ln=Tc(),uVp=v3e(),ca=oA(),REm=sVp(),OEm=require("path"),Na=ca.codes,wEm=p3e().NativeTypes,MEm=DO(),_9=PW(),xEm=qRr(),PEm=c9t(),NEm=p3e(),B7s=yd(),{isSnowflakeHost:$ht}=Yke(),DEm=12e4,BEm="/oauth/authorize",LEm="/oauth/token-request",Zrn="LOCAL_APPLICATION",cVp=["account","application","region","host","accessUrl","username","password","authenticator","proxyHost","proxyPort","serviceName","privateKey","privateKeyPath","privateKeyPass","token","warehouse","database","schema","role","rowMode","streamResult","fetchAsString","clientSessionKeepAlive","clientSessionKeepAliveHeartbeatFrequency","jsTreatIntegerAsBigInt","sessionToken","masterToken","sessionTokenExpirationTime","masterTokenExpirationTime","agentClass","validateDefaultParameters","arrayBindingThreshold","gcsUseDownscopedCredential","forceStageBindError","includeRetryReason","disableQueryContextCache","retryTimeout","clientRequestMFAToken","clientStoreTemporaryCredential","disableConsoleLogin","forceGCPUseDownscopedCredential","representNullAsStringNull","disableSamlURLCheck","credentialCacheDir","passcodeInPassword","passcode","oauthClientId","oauthClientSecret","oauthRedirectUri","oauthAuthorizationUrl","oauthTokenRequestUrl","oauthScope","oauthChallengeMethod","oauthHttpAllowed","workloadIdentityProvider","workloadIdentityAzureEntraIdResource","queryTag"];function kEm(r){let t=-1,n,i,o=r.protocol||"https",s=ln.exists(r.port)?ln.format(":%s",r.port):"";if(ln.exists(r.region)&&(ca.checkArgumentValid(ln.isCorrectSubdomain(r.region),Na.ERR_CONN_CREATE_INVALID_REGION_REGEX),i=r.region),ln.exists(r.account)&&(ca.checkArgumentValid(ln.isString(r.account),Na.ERR_CONN_CREATE_INVALID_ACCOUNT),ca.checkArgumentValid(ln.isCorrectSubdomain(r.account),Na.ERR_CONN_CREATE_INVALID_ACCOUNT_REGEX),t=r.account.indexOf("."),n=r.account,t>0&&(i=n.substring(t+1),n=n.substring(0,t))),ln.exists(r.accessUrl))try{let a=IEm.parse(r.accessUrl);ca.checkArgumentValid(ln.exists(a.hostname),Na.ERR_CONN_CREATE_INVALID_ACCESS_URL),ln.exists(r.host)||(r.host=a.hostname);let u=a.hostname.indexOf(".");u>0&&!ln.exists(r.account)&&(n=a.hostname.substring(0,u))}catch{ca.checkArgumentValid(!1,Na.ERR_CONN_CREATE_MISSING_ACCOUNT)}else if(ln.exists(r.host)){r.accessUrl=ln.format("%s://%s%s",o,r.host,s);let a=r.host.indexOf(".");a>0&&!ln.exists(r.account)?n=r.host.substring(0,a):n=r.account}else ln.exists(r.account)&&(r.region==="us-west-2"&&(r.region=""),r.host=ln.constructHostname(i,n),r.accessUrl=ln.format("%s://%s%s",o,r.host,s));if(ln.exists(n)&&r.accessUrl.includes("global.snowflakecomputing")){let a=n.indexOf("-");a>0&&(n=n.substring(0,a))}r.account=n,r.region=i,ca.checkArgumentExists(ln.exists(r.account),Na.ERR_CONN_CREATE_MISSING_ACCOUNT),ca.checkArgumentExists(ln.exists(r.accessUrl),Na.ERR_CONN_CREATE_MISSING_ACCESS_URL)}function tw(r,t,n,i){if(ln.exists(t)||(t=!0),ca.checkArgumentExists(ln.exists(r),Na.ERR_CONN_CREATE_MISSING_OPTIONS),ca.checkArgumentValid(ln.isObject(r),Na.ERR_CONN_CREATE_INVALID_OPTIONS),t){let ke=[_9.OAUTH_AUTHENTICATOR,_9.EXTERNAL_BROWSER_AUTHENTICATOR,_9.PROGRAMMATIC_ACCESS_TOKEN,_9.OAUTH_CLIENT_CREDENTIALS,_9.OAUTH_AUTHORIZATION_CODE,_9.WORKLOAD_IDENTITY];if((!r.authenticator||!ke.includes(r.authenticator.toUpperCase()))&&ca.checkArgumentExists(ln.exists(r.username),Na.ERR_CONN_CREATE_MISSING_USERNAME),ln.exists(r.username)&&ca.checkArgumentValid(ln.isString(r.username),Na.ERR_CONN_CREATE_INVALID_USERNAME),(!ln.exists(r.authenticator)||r.authenticator===_9.DEFAULT_AUTHENTICATOR)&&(ca.checkArgumentExists(ln.exists(r.password),Na.ERR_CONN_CREATE_MISSING_PASSWORD),ca.checkArgumentValid(ln.isString(r.password),Na.ERR_CONN_CREATE_INVALID_PASSWORD)),(!ln.exists(r.authenticator)||r.authenticator===_9.PROGRAMMATIC_ACCESS_TOKEN)&&(ca.checkArgumentExists(ln.exists(r.password)||ln.exists(r.token),Na.ERR_CONN_CREATE_MISSING_PASSWORD),ln.exists(r.password)&&ca.checkArgumentValid(ln.isString(r.password),Na.ERR_CONN_CREATE_INVALID_PASSWORD),ln.exists(r.token)&&ca.checkArgumentValid(ln.isString(r.token),Na.ERR_CONN_CREATE_INVALID_OAUTH_TOKEN)),r.authenticator===_9.OAUTH_AUTHORIZATION_CODE){if(ln.exists(r.oauthAuthorizationUrl)){let we;try{we=new URL(r.oauthAuthorizationUrl)}catch{throw ca.createInvalidParameterError(Na.ERR_CONN_CREATE_INVALID_OUATH_AUTHORIZATION_URL)}ca.checkArgumentValid(we.protocol==="https:"||we.protocol==="http:",Na.ERR_CONN_CREATE_INVALID_OUATH_AUTHORIZATION_URL)}(r.oauthAuthorizationUrl&&!$ht(r.oauthAuthorizationUrl)||r.oauthTokenRequestUrl&&!$ht(r.oauthTokenRequestUrl))&&(ca.checkArgumentValid(ln.isString(r.oauthClientId),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_ID),ca.checkArgumentValid(ln.isString(r.oauthClientSecret),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_SECRET))}if(r.authenticator===_9.OAUTH_CLIENT_CREDENTIALS){if(ln.exists(r.oauthTokenRequestUrl)){let we;try{we=new URL(r.oauthTokenRequestUrl)}catch{throw ca.createInvalidParameterError(Na.ERR_CONN_CREATE_INVALID_OUATH_TOKEN_REQUEST_URL)}ca.checkArgumentValid(we.protocol==="https:"||we.protocol==="http:",Na.ERR_CONN_CREATE_INVALID_OUATH_TOKEN_REQUEST_URL)}ca.checkArgumentValid(ln.isString(r.oauthClientId),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_ID),ca.checkArgumentValid(ln.isString(r.oauthClientSecret),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_SECRET)}kEm(r)}ca.checkArgumentExists(ln.exists(r.accessUrl),Na.ERR_CONN_CREATE_MISSING_ACCESS_URL),ca.checkArgumentValid(ln.isString(r.accessUrl),Na.ERR_CONN_CREATE_INVALID_ACCESS_URL);let o=r.proxyHost,s=r.proxyPort,a=r.proxyUser,u=r.proxyPassword,p=r.proxyProtocol||"http",c=r.noProxy,l=r.useConnectionConfigProxyForOCSP??!1,d=r.oauthClientId,f=r.oauthClientSecret,h=r.oauthRedirectUri,A=r.oauthAuthorizationUrl,E=r.oauthTokenRequestUrl,v=r.oauthChallengeMethod,T=r.oauthScope,w=r.oauthHttpAllowed,N;ln.isNode()&&(ln.exists(o)||ln.exists(s))&&(N={host:o,port:s,user:a,password:u,protocol:p,noProxy:c,useForOCSP:l},uVp.validateProxy(N));let k=r.serviceName,L=r.authenticator;ln.exists(L)?L=L.toUpperCase():L=_9.DEFAULT_AUTHENTICATOR;let q=r.browserActionTimeout;ln.exists(r.browserActionTimeout)?ca.checkArgumentValid(ln.number.isPositiveInteger(q),Na.ERR_CONN_CREATE_INVALID_BROWSER_TIMEOUT):q=DEm;let G=r.privateKey;ln.exists(r.privateKey)&&ca.checkArgumentValid(ln.isString(G)&&ln.isPrivateKey(G),Na.ERR_CONN_CREATE_INVALID_PRIVATE_KEY);let H=r.privateKeyPath;ln.exists(r.privateKeyPath)&&ca.checkArgumentValid(ln.isString(H),Na.ERR_CONN_CREATE_INVALID_PRIVATE_KEY_PATH);let V=r.privateKeyPass;ln.exists(r.privateKeyPass)&&ca.checkArgumentValid(ln.isString(V),Na.ERR_CONN_CREATE_INVALID_PRIVATE_KEY_PASS);let W=r.token;ln.exists(W)&&ca.checkArgumentValid(ln.isString(W),Na.ERR_CONN_CREATE_INVALID_OAUTH_TOKEN);let F=r.warehouse,J=r.database,Y=r.schema,z=r.role;ln.exists(F)&&ca.checkArgumentValid(ln.isString(F),Na.ERR_CONN_CREATE_INVALID_WAREHOUSE),ln.exists(J)&&ca.checkArgumentValid(ln.isString(J),Na.ERR_CONN_CREATE_INVALID_DATABASE),ln.exists(Y)&&ca.checkArgumentValid(ln.isString(Y),Na.ERR_CONN_CREATE_INVALID_SCHEMA),ln.exists(z)&&ca.checkArgumentValid(ln.isString(z),Na.ERR_CONN_CREATE_INVALID_ROLE);let X=r.streamResult;ln.exists(X)&&ca.checkArgumentValid(ln.isBoolean(X),Na.ERR_CONN_CREATE_INVALID_STREAM_RESULT);let Z=r.fetchAsString;if(ln.exists(Z)){ca.checkArgumentValid(ln.isArray(Z),Na.ERR_CONN_CREATE_INVALID_FETCH_AS_STRING);let ke=wEm.findInvalidValue(Z);ca.checkArgumentValid(ke===-1,Na.ERR_CONN_CREATE_INVALID_FETCH_AS_STRING_VALUES,JSON.stringify(Z[ke]))}let re=r.rowMode;ln.exists(re)&&PEm.checkRowModeValid(re);let oe=r.clientSessionKeepAlive;ln.exists(oe)&&ca.checkArgumentValid(ln.isBoolean(oe),Na.ERR_CONN_CREATE_INVALID_KEEP_ALIVE);let ee=r.clientSessionKeepAliveHeartbeatFrequency;ln.exists(ee)&&(ca.checkArgumentValid(ln.isNumber(ee),Na.ERR_CONN_CREATE_INVALID_KEEP_ALIVE_HEARTBEAT_FREQ),ee=ln.validateClientSessionKeepAliveHeartbeatFrequency(ee,REm.HEARTBEAT_FREQUENCY_MASTER_VALIDITY));let ce=r.jsTreatIntegerAsBigInt;ln.exists(ce)&&ca.checkArgumentValid(ln.isBoolean(ce),Na.ERR_CONN_CREATE_INVALID_TREAT_INTEGER_AS_BIGINT);let de=r.gcsUseDownscopedCredential;ln.exists(de)&&ca.checkArgumentValid(ln.isBoolean(de),Na.ERR_CONN_CREATE_INVALID_GCS_USE_DOWNSCOPED_CREDENTIAL);let pe=r.clientConfigFile;ln.exists(pe)&&ca.checkArgumentValid(ln.isString(pe),Na.ERR_CONN_CREATE_INVALID_CLIENT_CONFIG_FILE),this._qaMode=n;let le="JavaScript",Ne,Qe,Ee;ln.exists(i)&&(ca.assertInternal(ln.isObject(i)),ca.assertInternal(ln.isString(i.version)),ca.assertInternal(ln.isObject(i.environment)),Ne=i.name,Qe=i.version,Ee=i.environment,Ee.OS=aVp.platform(),Ee.OS_VERSION=aVp.release(),Ee.OCSP_MODE=MEm.getOcspMode());let _e=r.application;if(ln.exists(_e)){ca.checkArgumentValid(ln.isString(_e),Na.ERR_CONN_CREATE_INVALID_APPLICATION);let ke=new RegExp(String.raw`^[A-Za-z]([A-Za-z0-9.\-_]){1,50}$`,"gi");ca.checkArgumentValid(ke.test(_e),Na.ERR_CONN_CREATE_INVALID_APPLICATION)}let tt=!1;ln.exists(r.validateDefaultParameters)&&(ca.checkArgumentValid(ln.isBoolean(r.validateDefaultParameters),Na.ERR_CONN_CREATE_INVALID_VALIDATE_DEFAULT_PARAMETERS),tt=r.validateDefaultParameters);let b=null;ln.exists(r.arrayBindingThreshold)&&(ca.checkArgumentValid(ln.isNumber(r.arrayBindingThreshold),Na.ERR_CONN_CREATE_INVALID_ARRAY_BINDING_THRESHOLD),b=r.arrayBindingThreshold);let R=null;ln.exists(r.forceStageBindError)&&(ca.checkArgumentValid(ln.isNumber(r.forceStageBindError),Na.ERR_CONN_CREATE_INVALID_FORCE_STAGE_BIND_ERROR),R=r.forceStageBindError);let O=!1;ln.exists(r.disableQueryContextCache)&&(ca.checkArgumentValid(ln.isBoolean(r.disableQueryContextCache),Na.ERR_CONN_CREATE_INVALID_DISABLED_QUERY_CONTEXT_CACHE),O=r.disableQueryContextCache);let j=300;ln.exists(r.retryTimeout)&&(ca.checkArgumentValid(ln.isNumber(r.retryTimeout),Na.ERR_CONN_CREATE_INVALID_MAX_RETRY_TIMEOUT),j=r.retryTimeout!==0?Math.max(j,r.retryTimeout):0);let Ae=!0;ln.exists(r.includeRetryReason)&&(ca.checkArgumentValid(ln.isBoolean(r.includeRetryReason),Na.ERR_CONN_CREATE_INVALID_INCLUDE_RETRY_REASON),Ae=r.includeRetryReason);let Te=!1;ln.exists(r.clientRequestMFAToken)&&(ca.checkArgumentValid(ln.isBoolean(r.clientRequestMFAToken),Na.ERR_CONN_CREATE_INVALID_CLIENT_REQUEST_MFA_TOKEN),Te=r.clientRequestMFAToken);let De=!0;ln.exists(r.disableConsoleLogin)&&(ca.checkArgumentValid(ln.isBoolean(r.disableConsoleLogin),Na.ERR_CONN_CREATE_INVALID_DISABLE_CONSOLE_LOGIN),De=r.disableConsoleLogin),ln.exists(r.forceGCPUseDownscopedCredential)?(ca.checkArgumentValid(ln.isBoolean(r.forceGCPUseDownscopedCredential),Na.ERR_CONN_CREATE_INVALID_FORCE_GCP_USE_DOWNSCOPED_CREDENTIAL),process.env.SNOWFLAKE_FORCE_GCP_USE_DOWNSCOPED_CREDENTIAL=r.forceGCPUseDownscopedCredential):process.env.SNOWFLAKE_FORCE_GCP_USE_DOWNSCOPED_CREDENTIAL=!1,ln.exists(r.representNullAsStringNull)&&(ca.checkArgumentValid(ln.isBoolean(r.representNullAsStringNull),Na.ERR_CONN_CREATE_INVALID_REPRESENT_NULL_AS_STRING_NULL),NEm.setIsRepresentNullAsStringNull(r.representNullAsStringNull));let y=!1;ln.exists(r.disableSamlURLCheck)&&(ca.checkArgumentValid(ln.isBoolean(r.disableSamlURLCheck),Na.ERR_CONN_CREATE_INVALID_DISABLE_SAML_URL_CHECK),y=r.disableSamlURLCheck);let I=!1;ln.exists(r.clientStoreTemporaryCredential)&&(ca.checkArgumentValid(ln.isBoolean(r.clientStoreTemporaryCredential),Na.ERR_CONN_CREATE_INVALID_CLIENT_STORE_TEMPORARY_CREDENTIAL),I=r.clientStoreTemporaryCredential);let P=null;if(ln.exists(r.credentialCacheDir)){let ke=OEm.resolve(r.credentialCacheDir);ca.checkArgumentValid(ln.validatePath(ke),Na.ERR_CONN_CREATE_INVALID_CREDENTIAL_CACHE_DIR),P=ke}let g=!1;ln.exists(r.passcodeInPassword)&&(ca.checkArgumentValid(ln.isBoolean(r.passcodeInPassword),Na.ERR_CONN_CREATE_INVALID_PASSCODE_IN_PASSWORD),g=r.passcodeInPassword);let _=null;if(ln.exists(r.passcode)&&(ca.checkArgumentValid(ln.isString(r.passcode),Na.ERR_CONN_CREATE_INVALID_PASSCODE),_=r.passcode),r.queryTag&&(ca.checkArgumentValid(ln.isString(r.queryTag)&&r.queryTag.length<=2e3,Na.ERR_CONN_CREATE_INVALID_QUERY_TAG),this.queryTag=r.queryTag),tt){for(let[ke]of Object.entries(r))if(!cVp.includes(ke)){let we=xEm.closest(ke,cVp);B7s.getInstance().error(`'${ke}' is an unknown connection parameter. Did you mean '${we}'?`)}}this.getProxy=function(){return N},this.getWarehouse=function(){return F},this.getDatabase=function(){return J},this.getSchema=function(){return Y},this.getRole=function(){return z},this.getServiceName=function(){return k},this.getAuthenticator=function(){return L},this.getBrowserActionTimeout=function(){return q},this.getPrivateKey=function(){return G},this.getPrivateKeyPath=function(){return H},this.getPrivateKeyPass=function(){return V},this.getToken=function(){return W},this.getStreamResult=function(){return X},this.getFetchAsString=function(){return Z},this.getRowMode=function(){return re},this.getClientType=function(){return le},this.getClientName=function(){return Ne},this.getClientVersion=function(){return Qe},this.getClientApplication=function(){return _e},this.getClientEnvironment=function(){return Ee},this.getClientSessionKeepAlive=function(){return oe},this.getClientSessionKeepAliveHeartbeatFrequency=function(){return ee},this.getJsTreatIntegerAsBigInt=function(){return ce},this.getGcsUseDownscopedCredential=function(){return de},this.getbindThreshold=function(){return b},this.getForceStageBindError=function(){return R},this.getIncludeRetryReason=function(){return Ae},this.getDisableQueryContextCache=function(){return O},this.getClientConfigFile=function(){return pe},this.getRetryTimeout=function(){return j},this.getDisableConsoleLogin=function(){return De},this.getDisableSamlURLCheck=function(){return y},this.getCredentialCacheDir=function(){return P},this.getClientRequestMFAToken=function(){return Te},this.getClientStoreTemporaryCredential=function(){return I},this.getPasscodeInPassword=function(){return g},this.getPasscode=function(){return _},this.getOauthClientId=function(){return!ln.isNotEmptyString(r.oauthClientId)&&!ln.isNotEmptyString(r.oauthClientSecret)&&L===_9.OAUTH_AUTHORIZATION_CODE&&$ht(this.getOauthAuthorizationUrl())&&$ht(this.getOauthTokenRequestUrl())&&(B7s.getInstance().debug(`Using default values for oauthClientId: ${Zrn}`),d=Zrn),d},this.getOauthClientSecret=function(){return!r.oauthClientId&&!r.oauthClientSecret&&L===_9.OAUTH_AUTHORIZATION_CODE&&$ht(this.getOauthAuthorizationUrl())&&$ht(this.getOauthTokenRequestUrl())&&(B7s.getInstance().debug(`Using default values for oauthClientSecret: ${Zrn}`),f=Zrn),f},this.getOauthAuthorizationUrl=function(){return A??r.accessUrl+BEm},this.getOauthTokenRequestUrl=function(){return E??r.accessUrl+LEm},this.getOauthRedirectUri=function(){return h},this.getOauthScope=function(){return T},this.getOauthChallengeMethod=function(){return v},this.getOauthHttpAllowed=function(){return w||!1},this.describeIdentityAttributes=function(){return`host: ${this.host}, account: ${this.account}, accessUrl: ${this.accessUrl}, user: ${this.username}, role: ${this.getRole()}, database: ${this.getDatabase()}, schema: ${this.getSchema()}, warehouse: ${this.getWarehouse()}, `+uVp.describeProxy(this.getProxy())},this.username=r.username,this.password=r.password,this.accessUrl=r.accessUrl,this.region=r.region,this.account=r.account,this.token=r.token,this.host=r.host,this.sessionToken=r.sessionToken,this.masterToken=r.masterToken,this.masterTokenExpirationTime=r.masterTokenExpirationTime,this.sessionTokenExpirationTime=r.sessionTokenExpirationTime,this.clientConfigFile=r.clientConfigFile,this.openExternalBrowserCallback=r.openExternalBrowserCallback,this.oauthEnableSingleUseRefreshTokens=r.oauthEnableSingleUseRefreshTokens,this.workloadIdentityProvider=r.workloadIdentityProvider,this.workloadIdentityAzureEntraIdResource=r.workloadIdentityAzureEntraIdResource;let M=qEm(),K={},st,Ie,He;for(st=0,Ie=M.length;st<Ie;st++)He=M[st],K[He.name]=He,He.value=He.defaultValue;let Xe,at;for(Xe in r)Object.prototype.hasOwnProperty.call(r,Xe)&&Object.prototype.hasOwnProperty.call(K,Xe)&&(at=r[Xe],He=K[Xe],He.external&&He.validate(at)&&(He.value=at));this._mapParameters=K,this.agentClass=r.agentClass}tw.prototype.isQaMode=function(){return this._qaMode};tw.prototype.clearCredentials=function(){this.password=null};var lVp="timeout",pVp="resultPrefetch",dVp="resultStreamInterrupts",fVp="resultChunkCacheSize",hVp="resultProcessingBatchSize",gVp="resultProcessingBatchDuration",AVp="rowStreamHighWaterMark",mVp="largeResultSetRetryMaxNumRetries",yVp="largeResultSetRetryMaxSleepTime",bVp="sfRetryMaxLoginRetries",EVp="sfRetryMaxNumRetries",CVp="sfRetryStartingSleepTime",SVp="sfRetryMaxSleepTime";function qEm(){let r=ln.number.isNonNegativeInteger.bind(ln.number),t=ln.number.isPositiveInteger.bind(ln.number),n=ln.number.isNonNegative.bind(ln.number);return[{name:lVp,defaultValue:90*1e3,external:!0,validate:t},{name:pVp,defaultValue:2,external:!0,validate:t},{name:dVp,defaultValue:3,validate:t},{name:fVp,defaultValue:1,validate:t},{name:hVp,defaultValue:1e3,validate:t},{name:gVp,defaultValue:100,validate:t},{name:AVp,defaultValue:10,validate:t},{name:mVp,defaultValue:10,validate:r},{name:yVp,defaultValue:16,validate:r},{name:bVp,defaultValue:7,external:!0,validate:r},{name:EVp,defaultValue:1e3,validate:r},{name:CVp,defaultValue:1,validate:n},{name:SVp,defaultValue:16,validate:n}]}tw.prototype.getTimeout=function(){return this._getParameterValue(lVp)};tw.prototype.getResultPrefetch=function(){return this._getParameterValue(pVp)};tw.prototype.getResultStreamInterrupts=function(){return this._getParameterValue(dVp)};tw.prototype.getResultChunkCacheSize=function(){return this._getParameterValue(fVp)};tw.prototype.getResultProcessingBatchSize=function(){return this._getParameterValue(hVp)};tw.prototype.getResultProcessingBatchDuration=function(){return this._getParameterValue(gVp)};tw.prototype.getRowStreamHighWaterMark=function(){return this._getParameterValue(AVp)};tw.prototype.getRetryLargeResultSetMaxNumRetries=function(){return this._getParameterValue(mVp)};tw.prototype.getRetryLargeResultSetMaxSleepTime=function(){return this._getParameterValue(yVp)};tw.prototype.getRetrySfMaxNumRetries=function(){return this._getParameterValue(EVp)};tw.prototype.getRetrySfMaxLoginRetries=function(){return this._getParameterValue(bVp)};tw.prototype.getRetrySfStartingSleepTime=function(){return this._getParameterValue(CVp)};tw.prototype.getRetrySfMaxSleepTime=function(){return this._getParameterValue(SVp)};tw.prototype._getParameterValue=function(r){let t=this._mapParameters[r];return t?t.value:void 0};vVp.exports=tw});var IVp=m(_Vp=>{"use strict";var gRe={};gRe.INCORRECT_USERNAME_PASSWORD="390100";gRe.SESSION_TOKEN_INVALID="390104";gRe.GONE_SESSION="390111";gRe.SESSION_TOKEN_EXPIRED="390112";gRe.OAUTH_TOKEN_EXPIRED="390318";gRe.MASTER_TOKEN_EXPIRED="390114";gRe.ID_TOKEN_INVALID="390195";_Vp.code=gRe});var OVp=m((zAS,RVp)=>{"use strict";var fb=yd();function FEm(r,t,n,i){this.id=r,this.timestamp=t,this.priority=n,this.context=i}function SN(r,t){fb.getInstance().debug(`Creating new QueryContextCache with capacity ${r} for session ${t}`),this.sessionId=t,this.capacity=r,this.idMap=new Map,this.treeSet=new Set,this.priorityMap=new Map}SN.prototype.sortTreeSet=function(){this.treeSet=new Set(Array.from(this.treeSet).sort((r,t)=>r.priority-t.priority))};SN.prototype.addQCE=function(r){this.idMap.set(r.id,r),this.priorityMap.set(r.priority,r),this.treeSet.add(r),this.sortTreeSet(),fb.getInstance().trace(`QCC session ${this.sessionId} - Added QCE: ${JSON.stringify(r)}`)};SN.prototype.removeQCE=function(r){this.idMap.delete(r.id),this.priorityMap.delete(r.priority),this.treeSet.delete(r),fb.getInstance().trace(`QCC session ${this.sessionId} - Removed QCE: ${JSON.stringify(r)}`)};SN.prototype.replaceQCE=function(r,t){this.removeQCE(r),this.addQCE(t),fb.getInstance().debug(`QCC session ${this.sessionId} - Replaced QCE: ${JSON.stringify(r)} with ${JSON.stringify(t)}`)};SN.prototype.merge=function(r){if(fb.getInstance().debug(`QCC session ${this.sessionId} - Merging QCE: ${JSON.stringify(r)}`),this.idMap.has(r.id)){fb.getInstance().debug(`QCC session ${this.sessionId} - Element id ${r.id} found in cache`);let t=this.idMap.get(r.id);r.timestamp>t.timestamp?(fb.getInstance().trace(`QCC session ${this.sessionId} - New element is more recent. Current timestamp: ${t.timestamp}, new timestamp: ${r.timestamp}`),t.priority===r.priority?(fb.getInstance().trace(`QCC session ${this.sessionId} - Element priority (${t.priority}) is the same`),t.timestamp=r.timestamp,t.context=r.context):(fb.getInstance().trace(`QCC session ${this.sessionId} - Element priority changed. Current priority: ${t.priority}, new priority: ${r.priority}`),this.replaceQCE(t,r))):r.timestamp===t.timestamp&&t.priority!==r.priority?(fb.getInstance().trace(`QCC session ${this.sessionId} - Element timestamp is the same, but priority changes. Current priority: ${t.priority}, new priority: ${r.priority}`),this.replaceQCE(t,r)):fb.getInstance().trace(`QCC session ${this.sessionId} - Element is the same. Doing nothing.`)}else if(fb.getInstance().trace(`QCC session ${this.sessionId} - New element`),this.priorityMap.has(r.priority)){let t=this.priorityMap.get(r.priority);fb.getInstance().trace(`QCC session ${this.sessionId} - Element with the same priority found: ${JSON.stringify(t)}. Replacing with new element: ${JSON.stringify(r)}`),this.replaceQCE(t,r)}else fb.getInstance().debug(`QCC session ${this.sessionId} - Adding new element to the cache: ${JSON.stringify(r)}`),this.addQCE(r,r)};SN.prototype.checkCacheCapacity=function(){for(fb.getInstance().trace(`QCC session ${this.sessionId} - checkCacheCapacity() called. treeSet size ${this.treeSet.size}, cache capacity ${this.capacity}`);this.treeSet.size>this.capacity;){let r=Array.from(this.treeSet).pop();this.removeQCE(r)}fb.getInstance().trace(`QCC session ${this.sessionId} - checkCacheCapacity() returns. treeSet size ${this.treeSet.size}, cache capacity ${this.capacity}`)};SN.prototype.clearCache=function(){fb.getInstance().trace(`QCC session ${this.sessionId} - clearCache() called`),this.idMap.clear(),this.priorityMap.clear(),this.treeSet.clear(),fb.getInstance().trace(`QCC session ${this.sessionId} - clearCache() returns. Number of entries in cache now ${this.treeSet.size}`)};SN.prototype.getElements=function(){return this.treeSet};SN.prototype.deserializeQueryContext=function(r){let t=JSON.stringify(r);if(fb.getInstance().debug(`QCC session ${this.sessionId} - deserializeQueryContext() called: data from server: ${t}`),!r||t==="{}"||r.entries===null){this.clearCache(),fb.getInstance().trace(`QCC session ${this.sessionId} - deserializeQueryContext() returns`),this.logCacheEntries();return}try{let n=r.entries;if(n!==null&&Array.isArray(n))for(let i of n){let o=this.deserializeQueryContextElement(i);if(o!=null)this.merge(o);else{fb.getInstance().warn(`QCC session ${this.sessionId} - deserializeQueryContextJson: deserializeQueryContextElement meets mismatch field type. Clear the QueryContextCache.`),this.clearCache();return}}}catch(n){fb.getInstance().debug(`QCC session ${this.sessionId} - deserializeQueryContextJson: Exception = ${n.getMessage}`),this.clearCache()}this.checkCacheCapacity(),this.logCacheEntries()};SN.prototype.deserializeQueryContextElement=function(r){let{id:t,timestamp:n,priority:i,context:o}=r,s=new FEm(t,n,i,null);if(typeof o=="string")s.context=o;else if(o==null)s.context=null,fb.getInstance().debug(`QCC session ${this.sessionId} - deserializeQueryContextElement \`context\` field is empty`);else return fb.getInstance().warn(`QCC session ${this.sessionId} - deserializeQueryContextElement: \`context\` field is not String type`),null;return s};SN.prototype.logCacheEntries=function(){this.treeSet.forEach(function(r){fb.getInstance().debug(`QCC session ${this.sessionId} - Cache Entry: id: ${r.id} timestamp: ${r.timestamp} priority: ${r.priority}`)},this)};SN.prototype.getSize=function(){return this.treeSet.size};SN.prototype.getQueryContextDTO=function(){let r=[],t=Array.from(this.getElements());for(let n=0;n<this.treeSet.size;n++)r.push({id:t[n].id,timestamp:t[n].timestamp,priority:t[n].priority,context:{base64Data:t[n].context}});return{entries:r}};SN.prototype.getSerializeQueryContext=function(){let r=[],t=Array.from(this.getElements());for(let n=0;n<this.treeSet.size;n++)r.push({id:t[n].id,timestamp:t[n].timestamp,priority:t[n].priority,context:t[n].context||null});return{entries:r}};RVp.exports=SN});var NVp=m((QAS,PVp)=>{"use strict";var{v4:L7s}=(A6(),ut(g6)),UEm=require("events").EventEmitter,$s=Tc(),V0=oA(),rw=V0.codes,zEm=require("url"),QEm=require("querystring"),rB=p9t(),ARe=IVp(),jEm=OVp(),Lx=yd(),wVp=DO(),MVp=PW(),GEm=g6s(),HEm=f6s(),VEm=A6s(),WEm=Yrn(),KEm=E6s(),YEm=__s();function JEm(r){return!Object.prototype.hasOwnProperty.call(r,"cause")||r.cause===void 0||!Object.prototype.hasOwnProperty.call(r.cause,"code")||r.cause.code!==rw.ERR_OCSP_REVOKED&&r.cause.code!=="DEPTH_ZERO_SELF_SIGNED_CERT"&&r.cause.code!=="CERT_HAS_EXPIRED"&&r.cause.code!=="UNABLE_TO_VERIFY_LEAF_SIGNATURE"&&r.cause.code!=="SELF_SIGNED_CERT_IN_CHAIN"}function $Em(r){return Object.prototype.hasOwnProperty.call(r,"response")&&$s.isRetryableHttpError(r.response,!1)}function xVp(r,t,n){V0.assertInternal($s.isObject(r)),V0.assertInternal($s.isObject(t)),V0.assertInternal(!$s.exists(n)||$s.isObject(n));let i;$s.exists(n)?(V0.assertInternal($s.isObject(n)),V0.assertInternal($s.isObject(n.tokenInfo)),i=n.tokenInfo):r.sessionToken&&(i={sessionToken:r.sessionToken,masterToken:r.masterToken||r.sessionToken,sessionTokenExpirationTime:r.sessionTokenExpirationTime||Date.now()+1e3*60*60*24,masterTokenExpirationTime:r.masterTokenExpirationTime||Date.now()+1e3*60*60*24});let o=new ZEm(i);try{Lx.getInstance().debug("Retrieving authenticator"),this.authenticator=WEm.getAuthenticator(r,t)}catch(N){let k=`Failed to initialize authenticator: ${N}`;throw Lx.getInstance().error(k),V0.createClientError(rw.ERR_CONN_CREATE_INVALID_AUTH_UNSUPPORTED,!0,k)}let s={snowflakeService:this,httpClient:t,connectionConfig:r,tokenInfo:o},a=new WQt(s),u=new mRe(s),p=new Xht(s),c=new Zht(s),l=new KQt(s),d,f=function(N,k){d!==N&&(d&&d.exit(),d=N,d.enter(k))};this.setSessionId=function(N){this.sessionId=N},this.getSessionId=function(){return this.sessionId},this.transitionToPristine=function(N){f(a,N)},this.transitionToConnecting=function(N){f(u,N)},this.transitionToConnected=function(N){f(p,N)},this.transitionToRenewing=function(N){f(c,N)},this.transitionToDisconnected=function(N){f(l,N),o.clearTokens()},this.getConfig=function(){return{tokenInfo:o.getConfig()}},this.connect=function(N){new A(N).validate().execute()},this.continue=function(N){new E(N).validate().execute()},this.request=function(N){new v(N).validate().execute()},this.requestAsync=async function(N){return await new v(N).validate().executeAsync()},this.destroy=function(N){this.clearCache(),new T(N).validate().execute()};function h(N){this.options=N}h.prototype.validate=function(){return this},h.prototype.execute=function(){};function A(N){h.apply(this,[N])}$s.inherits(A,h),A.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)&&$s.isFunction(N.callback)),this},A.prototype.execute=function(){d.connect(this.options)};function E(N){h.apply(this,[N])}$s.inherits(E,h),E.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)&&$s.isObject(N.json)),this},E.prototype.execute=function(){d.continue(this.options)};function v(N){h.apply(this,[N])}$s.inherits(v,h),v.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)),V0.assertInternal($s.isString(N.method)),V0.assertInternal(!$s.exists(N.headers)||$s.isObject(N.headers)),V0.assertInternal($s.isString(N.url)),V0.assertInternal(!$s.exists(N.json)||$s.isObject(N.json)),this},v.prototype.execute=function(){d.request(this.options)},v.prototype.executeAsync=async function(){return await d.requestAsync(this.options)};function T(N){h.apply(this,[N])}$s.inherits(T,h),T.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)&&$s.isFunction(N.callback)),this},T.prototype.execute=function(){d.destroy(this.options)};let w=[];this.enqueueRequest=function(N){w.push(new v(N))},this.enqueueDestroy=function(N){w.push(new T(N))},this.drainOperationQueue=function(){for(let N=0,k=w.length;N<k;N++)w[N].execute();w.length=0},this.isConnected=function(){return d===p||d===u||d===c},this.getServiceName=function(){return rB.getValue(rB.names.SERVICE_NAME)},this.getClientSessionKeepAlive=function(){return rB.getValue(rB.names.CLIENT_SESSION_KEEP_ALIVE)},this.getClientSessionKeepAliveHeartbeatFrequency=function(){return rB.getValue(rB.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY)},this.getJsTreatIntegerAsBigInt=function(){return rB.getValue(rB.names.JS_TREAT_INTEGER_AS_BIGINT)},this.getAuthenticator=function(){return this.authenticator},o.isEmpty()?this.transitionToPristine():this.transitionToConnected(),this.postAsync=function(N){return new v(N).validate().executeAsync()},this.getQueryContextDTO=function(){if(this.qcc)return this.qcc.getQueryContextDTO()},this.deserializeQueryContext=function(N){this.qcc&&this.qcc.deserializeQueryContext(N)},this.clearCache=function(){this.qcc&&this.qcc.clearCache()},this.initializeQueryContextCache=function(N){r.getDisableQueryContextCache()?Lx.getInstance().debug(`QueryContextCache initialization skipped as it is disabled for connection with sessionId: ${this.sessionId}`):this.qcc=new jEm(N,this.getSessionId())},this.getQueryContextCacheSize=function(){if(this.qcc)return this.qcc.getSize()}}$s.inherits(xVp,UEm);PVp.exports=xVp;function kx(r){function t(l,d,f){let h=l.params||{};l.excludeGuid||a(h);let A={method:l.method,headers:l.headers,url:l.absoluteUrl,gzip:l.gzip,json:l.json,params:h,callback:async function(E,v,T){if(E)Lx.getInstance().debug("Encountered an error when sending the request. Details: "+JSON.stringify(E,Object.getOwnPropertyNames(E))),E=V0.createNetworkError(rw.ERR_SF_NETWORK_COULD_NOT_CONNECT,E);else if(!v)E=V0.createUnexpectedContentError(rw.ERR_SF_RESPONSE_NOT_JSON,"(EMPTY)");else if(Object.prototype.hasOwnProperty.call(v,"statusCode")&&v.statusCode!==200)if(v.statusCode===401&&v.body){let w;try{w=JSON.parse(v.body).code}catch{E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_FAILURE,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode)}w==="390104"?(E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_INVALID_TOKEN,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode)):(E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_FAILURE,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode))}else E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_FAILURE,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode);else{if($s.isString(T)&&v.getResponseHeader("Content-Type")==="application/json")try{T.includes("smkId")&&(T=$s.convertSmkIdToString(T)),T=JSON.parse(T)}catch{E=V0.createUnexpectedContentError(rw.ERR_SF_RESPONSE_NOT_JSON,v.body)}if(T&&!T.success){let w=T.data;if(T.code===ARe.code.ID_TOKEN_INVALID&&f instanceof VEm||T.code===ARe.code.OAUTH_TOKEN_EXPIRED&&f instanceof KEm)return Lx.getInstance().debug("ID Token being used has expired. Reauthenticating"),await f.reauthenticate(l.json),d.request(A);E=V0.createOperationFailedError(T.code,w,T.message,w&&w.sqlState?w.sqlState:void 0)}}E&&(T=void 0),$s.isFunction(l.callback)&&await l.callback.apply(l.scope,[E,T])}};if(l.retry>2){let E=l.url.includes("?");A.url+=E?"&":"?",A.url+="clientStartTime="+l.startTime+"&retryCount="+(l.retry-1)}return d.request(A)}this.snowflakeService=r.snowflakeService,this.httpClient=r.httpClient,this.connectionConfig=r.connectionConfig,this.tokenInfo=r.tokenInfo;let n=r.connectionConfig,i=r.snowflakeService,o=r.httpClient;function s(l){this.requestOptions=l}s.prototype.sendAsync=async function(){this.preprocessOptions(this.requestOptions);let l=this.requestOptions.params||{};this.requestOptions.excludeGuid||a(l);let d={method:this.requestOptions.method,headers:this.requestOptions.headers,url:this.requestOptions.absoluteUrl,json:this.requestOptions.json,params:l};return await o.requestAsync(d)};function a(l){let d=L7s();l[YEm.paramsNames.SF_REQUEST_GUID]=d}s.prototype.send=function(){this.preprocessOptions(this.requestOptions),t(this.requestOptions,o,i.getAuthenticator())},s.prototype.preprocessOptions=function(l){l.headers=$s.apply(this.getDefaultReqHeaders(),l.headers||{}),$s.isLoginRequest(l.url)&&$s.apply(l.headers,{CLIENT_APP_VERSION:l.json.data.CLIENT_APP_VERSION,CLIENT_APP_ID:l.json.data.CLIENT_APP_ID}),l.absoluteUrl=this.buildFullUrl(l.url),l.excludeGuid=$s.exists(l.excludeGuid)?l.excludeGuid:!1},s.prototype.buildFullUrl=function(l){return n.accessUrl+l},s.prototype.getDefaultReqHeaders=function(){return{Accept:"application/json","Content-Type":"application/json"}};function u(){s.apply(this,arguments)}$s.inherits(u,s),u.prototype.preprocessOptions=function(l){s.prototype.preprocessOptions.apply(this,arguments),l.headers=l.headers||{},l.headers.Authorization='Snowflake Token="'+r.tokenInfo.getSessionToken()+'"',$s.string.isNotNullOrEmpty(rB.getValue(rB.names.SERVICE_NAME))&&(l.headers["X-Snowflake-Service"]=rB.getValue(rB.names.SERVICE_NAME))};function p(){s.apply(this,arguments)}$s.inherits(p,s),p.prototype.preprocessOptions=function(l){s.prototype.preprocessOptions.apply(this,arguments),l.headers=l.headers||{},l.headers.Authorization='Snowflake Token="'+r.tokenInfo.getMasterToken()+'"'};function c(){s.apply(this,arguments)}$s.inherits(c,s),this.createSessionTokenRequest=function(l){return new u(l)},this.createMasterTokenRequest=function(l){return new p(l)},this.createUnauthenticatedRequest=function(l){return new c(l)}}kx.prototype.enter=function(){};kx.prototype.exit=function(){};kx.prototype.connect=function(){};kx.prototype.continue=function(){};kx.prototype.request=function(){};kx.prototype.destroy=function(){};function WQt(){kx.apply(this,arguments)}$s.inherits(WQt,kx);WQt.prototype.connect=function(r){this.snowflakeService.transitionToConnecting({options:r})};WQt.prototype.request=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_REQUEST_STATUS_PRISTINE))})};WQt.prototype.destroy=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_DESTROY_STATUS_PRISTINE))})};function mRe(){kx.apply(this,arguments)}$s.inherits(mRe,kx);mRe.prototype.enter=function(r){this.context=r,this.continue()};mRe.prototype.exit=function(){this.context=null};mRe.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_CONNECTING))})};mRe.prototype.continue=function(){let r=this.context,t=r.options.err,n=r.options.json;n||(n={data:{ACCOUNT_NAME:this.connectionConfig.account,LOGIN_NAME:this.connectionConfig.username,PASSWORD:this.connectionConfig.password}}),t&&t.data&&t.data.inFlightCtx&&(n.inFlightCtx=t.data.inFlightCtx),n.data=n.data||{};let i={CLIENT_APP_ID:this.connectionConfig.getClientType(),CLIENT_APP_VERSION:this.connectionConfig.getClientVersion()},o=this.connectionConfig.getClientEnvironment();$s.isObject(o)&&(i.CLIENT_ENVIRONMENT={...n.data.CLIENT_ENVIRONMENT,...o});let s=this.connectionConfig.getClientApplication();$s.isString(s)&&(o.APPLICATION=s);let a={SESSION_PARAMETERS:{}};$s.exists(this.connectionConfig.getClientSessionKeepAlive())&&(a.SESSION_PARAMETERS.CLIENT_SESSION_KEEP_ALIVE=this.connectionConfig.getClientSessionKeepAlive()),$s.exists(this.connectionConfig.getClientSessionKeepAliveHeartbeatFrequency())&&(a.SESSION_PARAMETERS.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY=this.connectionConfig.getClientSessionKeepAliveHeartbeatFrequency()),$s.exists(this.connectionConfig.getJsTreatIntegerAsBigInt())&&(a.SESSION_PARAMETERS.JS_TREAT_INTEGER_AS_BIGINT=this.connectionConfig.getJsTreatIntegerAsBigInt()),$s.exists(this.connectionConfig.getGcsUseDownscopedCredential())&&(a.SESSION_PARAMETERS.GCS_USE_DOWNSCOPED_CREDENTIAL=this.connectionConfig.getGcsUseDownscopedCredential()),$s.exists(this.connectionConfig.getClientRequestMFAToken())&&(a.SESSION_PARAMETERS.CLIENT_REQUEST_MFA_TOKEN=this.connectionConfig.getClientRequestMFAToken()),$s.exists(this.connectionConfig.getClientStoreTemporaryCredential())&&(a.SESSION_PARAMETERS.CLIENT_STORE_TEMPORARY_CREDENTIAL=this.connectionConfig.getClientStoreTemporaryCredential()),$s.exists(this.connectionConfig.queryTag)&&(a.SESSION_PARAMETERS.QUERY_TAG=this.connectionConfig.queryTag),$s.apply(n.data,i),$s.apply(n.data,a);let u=this.connectionConfig,p=u.getRetrySfMaxLoginRetries(),c=u.getRetryTimeout(),l=u.accessUrl.startsWith("https://")?Date.now():"FIXEDTIMESTAMP",d=0,f=u.getRetrySfStartingSleepTime(),h=0;Lx.getInstance().debug("Total retryTimeout is for the retries = "+c===0?"unlimited":c);let A=this,E=async function(T,w){if(u.clearCredentials(),T)if(V0.isNetworkError(T)||V0.isRequestFailedError(T))if(d<p&&(JEm(T)||$Em(T))&&(c===0||h<c)){d++;let N=$s.getJitteredSleepTime(d,f,h,c);f=N.sleep,h=N.totalElapsedTime,f<=0&&(Lx.getInstance().debug("Reached out to the max Login Timeout"),A.snowflakeService.transitionToDisconnected());let k=A.snowflakeService.getAuthenticator();if(k instanceof GEm){Lx.getInstance().debug("OKTA authentication requires token refresh.");let L={totalElapsedTime:h,numRetries:d};await k.reauthenticate(r.options.json,L),d=L.numRetries,h=L.totalElapsedTime}else k instanceof HEm&&(Lx.getInstance().debug("AuthKeyPair authentication requires token refresh."),await k.reauthenticate(r.options.json));setTimeout(v,f*1e3);return}else Lx.getInstance().debug("Failed to all retries to SF."),A.snowflakeService.transitionToDisconnected();else A.snowflakeService.transitionToDisconnected();else{if(V0.assertInternal($s.exists(w)),V0.assertInternal($s.exists(w.data)),A.snowflakeService.setSessionId(w.data.sessionId),Lx.getInstance().debug(`New session with id ${A.snowflakeService.getSessionId()} initialized`),rB.update(w.data.parameters),A.tokenInfo.update(w.data),u.getClientRequestMFAToken()&&w.data.mfaToken){let k=$s.buildCredentialCacheKey(u.host,u.username,MVp.USER_PWD_MFA_AUTHENTICATOR);await wVp.getCredentialManager().write(k,w.data.mfaToken)}if(u.getClientStoreTemporaryCredential()&&w.data.idToken){let k=$s.buildCredentialCacheKey(u.host,u.username,MVp.ID_TOKEN_AUTHENTICATOR);await wVp.getCredentialManager().write(k,w.data.idToken)}A.snowflakeService.transitionToConnected();let N=rB.getValue("QUERY_CONTEXT_CACHE_SIZE");A.snowflakeService.initializeQueryContextCache(N)}$s.isFunction(r.options.callback)&&r.options.callback(T),A.snowflakeService.drainOperationQueue()},v=function(){let T=XEm(u);Lx.getInstance().debug("Contacting SF: %s, (%s/%s)",T,d,p),A.createUnauthenticatedRequest({method:"POST",url:T,json:n,scope:this,startTime:l,retry:d,callback:E}).send()};v()};function XEm(r){let t=[{name:"warehouse",value:r.getWarehouse()},{name:"databaseName",value:r.getDatabase()},{name:"schemaName",value:r.getSchema()},{name:"roleName",value:r.getRole()}],n={};r.isQaMode()||(n.requestId=L7s());for(let i=0,o=t.length;i<o;i++){let s=t[i];$s.string.isNotNullOrEmpty(s.value)&&(n[s.name]=s.value)}return zEm.format({pathname:"/session/v1/login-request",search:QEm.stringify(n)})}mRe.prototype.request=function(r){this.snowflakeService.enqueueRequest(r)};mRe.prototype.destroy=function(r){this.snowflakeService.enqueueDestroy(r)};function Xht(){kx.apply(this,arguments)}$s.inherits(Xht,kx);Xht.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_CONNECTED))})};Xht.prototype.requestAsync=async function(r){return await this.createSessionTokenRequest(r).sendAsync()};Xht.prototype.request=function(r){let t=r.scope,n=r.callback;r.scope=this,r.callback=async function(i,o){i?(r.scope=t,r.callback=n,i.code===ARe.code.SESSION_TOKEN_EXPIRED?(this.snowflakeService.enqueueRequest(r),this.snowflakeService.transitionToRenewing()):i.code===ARe.code.SESSION_TOKEN_INVALID||i.code===ARe.code.GONE_SESSION?(this.snowflakeService.enqueueRequest(r),this.snowflakeService.transitionToDisconnected(),this.snowflakeService.drainOperationQueue()):$s.isFunction(n)&&n.apply(t,[i,o])):$s.isFunction(n)&&await n.apply(t,[i,o])},this.createSessionTokenRequest(r).send()};Xht.prototype.destroy=function(r){let t=L7s();this.createSessionTokenRequest({method:"POST",url:`/session?delete=true&requestId=${t}`,scope:this,callback:function(n){(!n||n.code===ARe.code.GONE_SESSION||n.code===ARe.code.SESSION_TOKEN_EXPIRED)&&(n=void 0,this.snowflakeService.transitionToDisconnected()),r.callback(n)}}).send()};function Zht(){kx.apply(this,arguments)}$s.inherits(Zht,kx);Zht.prototype.enter=function(){this.createMasterTokenRequest({method:"POST",url:"/session/token-request",headers:{CLIENT_APP_ID:this.connectionConfig.getClientType(),CLIENT_APP_VERSION:this.connectionConfig.getClientVersion()},json:{REQUEST_TYPE:"RENEW",oldSessionToken:this.tokenInfo.getSessionToken()},scope:this,callback:function(r,t){r?r.code===ARe.code.MASTER_TOKEN_EXPIRED?this.snowflakeService.transitionToDisconnected():V0.isNetworkError(r)?this.snowflakeService.transitionToConnected():this.snowflakeService.transitionToDisconnected():(this.tokenInfo.update(t.data),this.snowflakeService.transitionToConnected()),this.snowflakeService.drainOperationQueue()}}).send()};Zht.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_CONNECTED))})};Zht.prototype.request=function(r){this.snowflakeService.enqueueRequest(r)};Zht.prototype.destroy=function(r){this.snowflakeService.enqueueDestroy(r)};function KQt(){kx.apply(this,arguments)}$s.inherits(KQt,kx);KQt.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_DISCONNECTED))})};KQt.prototype.request=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_REQUEST_STATUS_DISCONNECTED,!0))})};KQt.prototype.destroy=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_DESTROY_STATUS_DISCONNECTED))})};function ZEm(r){let t,n,i,o;$s.isObject(r)&&(t=r.masterToken,n=r.sessionToken,i=r.masterTokenExpirationTime,o=r.sessionTokenExpirationTime),this.isEmpty=function(){return!$s.exists(t)||!$s.exists(i)||!$s.exists(n)||!$s.exists(o)},this.clearTokens=function(){t=void 0,i=void 0,n=void 0,o=void 0},this.update=function(s){t=s.masterToken,n=s.token||s.sessionToken;let a=new Date().getTime();i=a+1e3*(s.masterValidityInSeconds||s.validityInSecondsMT),o=a+1e3*(s.validityInSeconds||s.validityInSecondsST)},this.getMasterToken=function(){return t},this.getMasterTokenExpirationTime=function(){return i},this.getSessionToken=function(){return n},this.getSessionTokenExpirationTime=function(){return o},this.getConfig=function(){return{masterToken:t,masterTokenExpirationTime:i,sessionToken:n,sessionTokenExpirationTime:o}}}});var kVp=m((jAS,LVp)=>{"use strict";var e2m=require("events").EventEmitter,yRe=Tc(),e1t=oA(),YQt=yd(),DVp=e1t.codes;function BVp(r,t){e1t.assertInternal(yRe.isObject(r)),e1t.assertInternal(yRe.isObject(t));function n(s){return s&&(s.code==="ECONNRESET"||s.code==="ETIMEDOUT"||s.name==="AxiosError"&&s.code==="ECONNABORTED")}function i(s,a){return yRe.isRetryableHttpError(s,!0)||n(a)}function o(s){return s&&(s.statusCode!==200||s.getResponseHeader("Content-Type")==="application/xml")}this.getObject=function(a){let u=0,p=1,c=a.maxNumRetries;yRe.exists(c)||(c=r.getRetryLargeResultSetMaxNumRetries()),e1t.assertInternal(yRe.isNumber(c)&&c>=0);let l=function(h,A,E){if(h||o(A)){let v=h?JSON.stringify(h,Object.getOwnPropertyNames(h)):`status: ${JSON.stringify(A.status)} ${JSON.stringify(A.statusText)} headers: ${JSON.stringify(A.headers)}`;if(YQt.getInstance().debug("Encountered an error when getting data from cloud storage: "+v),u<c&&i(A,h)){u++;let T=r.getRetryLargeResultSetMaxSleepTime();p=yRe.nextSleepTime(1,T,p);let w=p*1e3;YQt.getInstance().trace("Request will be retried after %d milliseconds",Math.floor(w)),setTimeout(d,w);return}else YQt.getInstance().trace("Request won't be retried"),o(A)?h=e1t.createLargeResultSetError(DVp.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE,A):h=e1t.createNetworkError(DVp.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT,h)}if(A&&YQt.getInstance().trace(`Response headers are: ${JSON.stringify(A.headers)}`),h&&(E=null),yRe.isFunction(a.callback))try{a.callback(h,E)}catch(v){YQt.getInstance().error(`Callback failed with ${v}`)}},d=function(){t.request({method:"GET",url:a.url,headers:a.headers,gzip:!0,appendRequestId:!1,callback:l})};d()}}yRe.inherits(BVp,e2m);LVp.exports=BVp});var FVp=m((GAS,qVp)=>{"use strict";var t1t=Tc(),JQt=oA(),t2m=NVp(),r2m=kVp(),enn=yd();function n2m(r,t,n){enn.getInstance().trace("Creating ConnectionContext object."),JQt.assertInternal(t1t.isObject(r)),JQt.assertInternal(t1t.isObject(t));let i;t1t.exists(n)&&(enn.getInstance().trace("ConnectionContext - validating received config."),JQt.assertInternal(t1t.isObject(n)),JQt.assertInternal(t1t.isObject(n.services)),JQt.assertInternal(t1t.isObject(n.services.sf)),i=n.services.sf),enn.getInstance().debug("ConnectionContext - received data was validated.");let o={sf:new t2m(r,t,i),largeResultSet:new r2m(r,t)};enn.getInstance().debug("ConnectionContext - services were instantiated."),this.getConnectionConfig=function(){return r},this.getServices=function(){return o},this.getConfig=function(){return{services:{sf:o.sf.getConfig()}}},this.getHttpClient=function(){return t}}qVp.exports=n2m});var zVp=m((HAS,UVp)=>{UVp.exports=(function(){function r(i,o){function s(){this.constructor=i}s.prototype=o.prototype,i.prototype=new s}function t(i,o,s,a,u,p){this.message=i,this.expected=o,this.found=s,this.offset=a,this.line=u,this.column=p,this.name="SyntaxError"}r(t,Error);function n(i){var o=arguments.length>1?arguments[1]:{},s={},a={start:Tm},u=Tm,p=[],c=function(){return ME},l=s,d="#",f={type:"literal",value:"#",description:'"#"'},h=void 0,A={type:"any",description:"any character"},E="[",v={type:"literal",value:"[",description:'"["'},T="]",w={type:"literal",value:"]",description:'"]"'},N=function(Ce){D2(c1("ObjectPath",Ce,Nu,Zu))},k=function(Ce){D2(c1("ArrayPath",Ce,Nu,Zu))},L=function(Ce,Ze){return Ce.concat(Ze)},q=function(Ce){return[Ce]},G=function(Ce){return Ce},H=".",V={type:"literal",value:".",description:'"."'},W="=",F={type:"literal",value:"=",description:'"="'},J=function(Ce,Ze){D2(c1("Assign",Ze,Nu,Zu,Ce))},Y=function(Ce){return Ce.join("")},z=function(Ce){return Ce.value},X='"""',Z={type:"literal",value:'"""',description:'"\\"\\"\\""'},re=null,oe=function(Ce){return c1("String",Ce.join(""),Nu,Zu)},ee='"',ce={type:"literal",value:'"',description:'"\\""'},de="'''",pe={type:"literal",value:"'''",description:`"'''"`},le="'",Ne={type:"literal",value:"'",description:`"'"`},Qe=function(Ce){return Ce},Ee=function(Ce){return Ce},_e="\\",tt={type:"literal",value:"\\",description:'"\\\\"'},b=function(){return""},R="e",O={type:"literal",value:"e",description:'"e"'},j="E",Ae={type:"literal",value:"E",description:'"E"'},Te=function(Ce,Ze){return c1("Float",parseFloat(Ce+"e"+Ze),Nu,Zu)},De=function(Ce){return c1("Float",parseFloat(Ce),Nu,Zu)},y="+",I={type:"literal",value:"+",description:'"+"'},P=function(Ce){return Ce.join("")},g="-",_={type:"literal",value:"-",description:'"-"'},M=function(Ce){return"-"+Ce.join("")},K=function(Ce){return c1("Integer",parseInt(Ce,10),Nu,Zu)},st="true",Ie={type:"literal",value:"true",description:'"true"'},He=function(){return c1("Boolean",!0,Nu,Zu)},Xe="false",at={type:"literal",value:"false",description:'"false"'},ke=function(){return c1("Boolean",!1,Nu,Zu)},we=function(){return c1("Array",[],Nu,Zu)},Ge=function(Ce){return c1("Array",Ce?[Ce]:[],Nu,Zu)},dt=function(Ce){return c1("Array",Ce,Nu,Zu)},mt=function(Ce,Ze){return c1("Array",Ce.concat(Ze),Nu,Zu)},Kt=function(Ce){return Ce},Zt=",",Pe={type:"literal",value:",",description:'","'},Be="{",Nt={type:"literal",value:"{",description:'"{"'},It="}",Ft={type:"literal",value:"}",description:'"}"'},Et=function(Ce){return c1("InlineTable",Ce,Nu,Zu)},Bt=function(Ce,Ze){return c1("InlineTableValue",Ze,Nu,Zu,Ce)},lt=function(Ce){return"."+Ce},Xt=function(Ce){return Ce.join("")},me=":",Ve={type:"literal",value:":",description:'":"'},$e=function(Ce){return Ce.join("")},rt="T",bt={type:"literal",value:"T",description:'"T"'},dr="Z",hr={type:"literal",value:"Z",description:'"Z"'},ir=function(Ce,Ze){return c1("Date",new Date(Ce+"T"+Ze+"Z"),Nu,Zu)},Wn=function(Ce,Ze){return c1("Date",new Date(Ce+"T"+Ze),Nu,Zu)},$n=/^[ \t]/,ai={type:"class",value:"[ \\t]",description:"[ \\t]"},Md=`
|
|
983
|
+
Please set 'credentialCacheDir' connection configuration option to enable the default credential manager.`);return O7s.join(s,"credential_cache_v1.json")},this.readJsonCredentialFile=async function(s){if(!Yht.exists(s))return null;try{let a=await s.readFile("utf8");return JSON.parse(a)}catch(a){return Nne.getInstance().warn("Failed to read token data from the file. Err: %s",a.message),null}},this.removeStale=async function(s){let a=await Bx.stat(s).catch(()=>{});if(Yht.exists(a)&&new Date().getTime()-a.birthtimeMs>t)try{await Bx.rmdir(s)}catch(u){Nne.getInstance().warn("Failed to remove stale file. Error: %s",u.message)}},this.lockFile=async function(s){let a=s+".lck";await this.removeStale(a);let u=1,p=!1,c={};for(process.platform!=="win32"&&(c.mode=384);u<=10&&(Nne.getInstance().debug("Attempting to get a lock on file %s, attempt: %d",s,u),u++,await Bx.mkdir(a,c).then(()=>{p=!0},()=>{}),!p);)await new Promise(l=>setTimeout(l,100));return p||Nne.getInstance().warn("Could not acquire lock on cache file %s",s),p},this.unlockFile=async function(s){let a=s+".lck";await Bx.rmdir(a)},this.withFileLocked=async function(s){let a=await this.getTokenFilePath();if(await this.lockFile(a)){let u=await s(a);return await this.unlockFile(a),u}return null},this.write=async function(s,a){if(!o(s))return null;let u=this.hashKey(s);await this.withFileLocked(async p=>{let c=await w7s(p,Bx.constants.O_RDWR|Bx.constants.O_CREAT,Bx),l=await this.readJsonCredentialFile(c)||{};Yht.exists(l[n])||(l[n]={}),l[n][u]=a;try{await c.truncate(),await c.write(JSON.stringify(l),0),await M7s(c)}catch(d){Nne.getInstance().warn(`Failed to write token data in ${p}. Please check the permission or the file format of the token. ${d.message}`)}})},this.read=async function(s){if(!o(s))return null;let a=this.hashKey(s);return await this.withFileLocked(async u=>{let p=await w7s(u,Bx.constants.O_RDWR,Bx),c=await this.readJsonCredentialFile(p);return await M7s(p),c&&c[n]&&c[n][a]?c[n][a]:null})},this.remove=async function(s){if(!o(s))return null;let a=this.hashKey(s);await this.withFileLocked(async u=>{let p=await w7s(u,Bx.constants.O_RDWR,Bx),c=await this.readJsonCredentialFile(p);if(c&&c[n]&&c[n][a])try{c[n][a]=null,await p.truncate(),await p.write(JSON.stringify(c),0),await M7s(p)}catch(l){Nne.getInstance().warn(`Failed to remove token data from the file in ${u}. Please check the permission or the file format of the token. ${l.message}`)}})};function o(s){return Yht.checkParametersDefined(s)}}x7s.exports.defaultJsonTokenCachePaths=$rn;x7s.exports.JsonCredentialManager=vEm});var iVp=m((kAS,nVp)=>{"use strict";var{v4:JHp}=(A6(),ut(g6)),$Hp=require("url"),TEm=require("querystring"),Uz=hap(),VQt=ljr(),D_=Tc(),ew=oA(),zz=ew.codes,tVp=require("events").EventEmitter,XHp=fXr(),Xrn=p9t(),P7s=Yrn(),N7s=PW(),Xo=yd(),{isOktaAuth:_Em}=Yrn(),{init:ZHp}=WHp(),Jht=DO(),{JsonCredentialManager:eVp}=YHp(),D7s=r_s();function rVp(r){Xo.getInstance().trace("Connection object is being constructed"),ew.assertInternal(D_.isObject(r));let t=r.getServices(),n=r.getConnectionConfig(),i=JHp();Xo.getInstance().trace("Generated connection id: %s",i),Xo.getInstance().info("Creating Connection[id: %s] with %s, password is %s, region: %s, authenticator: %s, ocsp mode: %s, os: %s, os version: %s",i,n.describeIdentityAttributes(),VQt.describePresence(n.password),n.region,n.getAuthenticator(),n.getClientEnvironment().OCSP_MODE,n.getClientEnvironment().OS,n.getClientEnvironment().OS_VERSION),Xo.getInstance().info("Connection[id: %s] additional details: passcode in password is %s, passcode is %s, private key is %s, application: %s, client name: %s, client version: %s, retry timeout: %s, private key path: %s, private key pass is %s, client store temporary credential: %s, browser response timeout: %s",i,VQt.describePresence(n.getPasscodeInPassword()),VQt.describePresence(n.getPasscode()),VQt.describePresence(n.getPrivateKey()),n.getClientApplication(),n.getClientName(),n.getClientVersion(),n.getRetryTimeout(),n.getPrivateKeyPath(),VQt.describePresence(n.getPrivateKeyPass()),n.getClientStoreTemporaryCredential(),n.getBrowserActionTimeout());let o=24,s=[1,1,2,3,4,8,10],a=500,u=new RegExp(/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);this.getTokens=function(){return n._qaMode?t.sf.getConfig()&&t.sf.getConfig().tokenInfo:{}},this.isUp=function(){let d=t.sf.isConnected();return Xo.getInstance().trace("Connection[id: %s] - isUp called. Returning: %s",this.getId(),d),d},this.isTokenValid=function(){Xo.getInstance().trace("Connection[id: %s] - isTokenValid called",this.getId());let d=t.sf.getConfig().tokenInfo,h=d.sessionTokenExpirationTime>Date.now();Xo.getInstance().trace("Connection[id: %s] - isSessionTokenValid: %s",this.getId(),h);let E=d.masterTokenExpirationTime>Date.now();Xo.getInstance().trace("Connection[id: %s] - isMasterTokenValid: %s",this.getId(),E);let v=h&&E;return Xo.getInstance().trace("Connection[id: %s] - isTokenValid returned: %s",this.getId(),v),v},this.getServiceName=function(){return t.sf.getServiceName()},this.getClientSessionKeepAlive=function(){return t.sf.getClientSessionKeepAlive()},this.getClientSessionKeepAliveHeartbeatFrequency=function(){return t.sf.getClientSessionKeepAliveHeartbeatFrequency()},this.getJsTreatIntegerAsBigInt=function(){return t.sf.getJsTreatIntegerAsBigInt()},this.getId=function(){return i},this.heartbeat=d=>{Xo.getInstance().trace("Issuing heartbeat call");let f=JHp();t.sf.request({method:"POST",url:$Hp.format({pathname:"/session/heartbeat",search:TEm.stringify({requestId:f})}),callback:D_.isFunction(d)?d:function(h,A){h?Xo.getInstance().error("Error issuing heartbeat call: %s",h.message):Xo.getInstance().trace("Heartbeat response %s",JSON.stringify(A))}})},this.heartbeatAsync=()=>new Promise((d,f)=>{Xo.getInstance().trace("Issuing async heartbeat call"),this.heartbeat(h=>h?f(h):d([{1:1}]))}),this.isValidAsync=async()=>{if(Xo.getInstance().trace("Connection[id: %s] - isValidAsync called",this.getId()),!this.isUp())return!1;try{return await this.heartbeatAsync(),!0}catch(d){return Xo.getInstance().debug("Connection[id: %s] - heartbeat failed: %s",this.getId(),JSON.stringify(d,Object.getOwnPropertyNames(d))),!1}},this.setupOcspPrivateLink=function(d){process.env.SF_OCSP_RESPONSE_CACHE_SERVER_URL=D_.createOcspResponseCacheServerUrl(d)};function p(d,f){return function(h){if(Xrn.getValue(Xrn.names.CLIENT_SESSION_KEEP_ALIVE)){let E=Xrn.getValue(Xrn.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY)*1e3;d.keepalive=setInterval(d.heartbeat,E,d),Xo.getInstance().trace("Connection[id: %s] - keepAlive internal created",i)}D_.isFunction(f)&&f(ew.externalize(h),d)}}this.determineConnectionDomain=()=>n.accessUrl&&n.accessUrl.includes("snowflakecomputing.cn")?"CHINA":"GLOBAL",this.connect=function(d){let f=new D7s().start(),h=this.determineConnectionDomain();Xo.getInstance().info("Connection[id: %s] - connecting. Associated Snowflake domain: %s",this.getId(),h),ew.checkArgumentValid(!D_.exists(d)||D_.isFunction(d),zz.ERR_CONN_CONNECT_INVALID_CALLBACK),D_.exists(n.host)&&D_.isPrivateLink(n.host)&&(Xo.getInstance().info("Connection[id: %s] - setting up private link",this.getId()),this.setupOcspPrivateLink(n.host));let A=this,E=n.getAuthenticator();if(Xo.getInstance().debug("Connection[id: %s] - using authentication type: %s",this.getId(),E),E===N7s.EXTERNAL_BROWSER_AUTHENTICATOR||_Em(E)){let T=f.getDuration();throw Xo.getInstance().error("Connection[id: %s] - connecting failed after %s milliseconds.Error: External browser and Okta are not compatible with connection process",this.getId(),T),ew.createClientError(zz.ERR_CONN_CREATE_INVALID_AUTH_CONNECT)}Xo.getInstance().debug("Connection[id: %s] - retrieving authenticator",this.getId());let v=t.sf.getAuthenticator();return Xo.getInstance().debug("Connection[id: %s] - trying to authenticate",this.getId()),v.authenticate(n.getAuthenticator(),n.getServiceName(),n.account,n.username).then(()=>{Xo.getInstance().info("Connection[id: %s] - authentication successful using: %s",this.getId(),n.getAuthenticator());let T=P7s.formAuthJSON(n.getAuthenticator(),n.account,n.username,n.getClientType(),n.getClientVersion(),n.getClientEnvironment());v.updateBody(T),Xo.getInstance().debug("Connection[id: %s] - initializing easyLogging",this.getId()),ZHp(n.clientConfigFile).then(()=>{Xo.getInstance().debug("Connection[id: %s] - easyLogging initialized",this.getId());try{Xo.getInstance().debug("Connection[id: %s] - connecting through service",this.getId()),t.sf.connect({callback:p(A,d),json:T});let w=f.getDuration();return Xo.getInstance().info("Connection[id: %s] - connected successfully after %s milliseconds",this.getId(),w),this}catch(w){let N=f.getDuration();Xo.getInstance().info("Connection[id: %s] - failed to connect after %s milliseconds. Error: Unexpected error from calling connectCallback function in snowflake service - %s",this.getId(),N,w)}},()=>{let w=f.getDuration();Xo.getInstance().error("Connection[id: %s] - failed to initialize easyLogging. Connecting failed after %s milliseconds",this.getId(),w),d(ew.createClientError(zz.ERR_CONN_CONNECT_INVALID_CLIENT_CONFIG,!0),A)})},T=>{let w=f.getDuration();Xo.getInstance().error("Connection[id: %s] - authentication failed. Error: %s. Connecting failed after %s milliseconds",this.getId(),T,w),d(T,A)}),this},this.connectAsync=async function(d){let f=new D7s().start(),h=this.determineConnectionDomain();Xo.getInstance().info("Connection[id: %s] - async connecting. Associated Snowflake domain: %s",this.getId(),h),ew.checkArgumentValid(!D_.exists(d)||D_.isFunction(d),zz.ERR_CONN_CONNECT_INVALID_CALLBACK),D_.isPrivateLink(n.host)&&(this.setupOcspPrivateLink(n.host),Xo.getInstance().info("Connection[id: %s] - setting up private link",this.getId()));let A=this;if(n.getClientStoreTemporaryCredential()){Xo.getInstance().debug("Connection[id: %s] - storing temporary credential of client",this.getId());let T=D_.buildCredentialCacheKey(n.host,n.username,N7s.ID_TOKEN_AUTHENTICATOR);Jht.getCredentialManager()===null&&(Xo.getInstance().debug("Connection[id: %s] - using default json credential manager",this.getId()),Jht.setCustomCredentialManager(new eVp(n.getCredentialCacheDir()))),Xo.getInstance().debug("Connection[id: %s] - reading idToken using credential manager",this.getId()),n.idToken=await Jht.getCredentialManager().read(T)}if(n.getClientRequestMFAToken()){Xo.getInstance().debug("Connection[id: %s] - extracting mfaToken of client",this.getId());let T=D_.buildCredentialCacheKey(n.host,n.username,N7s.USER_PWD_MFA_AUTHENTICATOR);Jht.getCredentialManager()===null&&(Xo.getInstance().debug("Connection[id: %s] - using default json credential manager",this.getId()),Jht.setCustomCredentialManager(new eVp(n.getCredentialCacheDir()))),Xo.getInstance().debug("Connection[id: %s] - reading mfaToken using credential manager",this.getId()),n.mfaToken=await Jht.getCredentialManager().read(T)}let E;try{Xo.getInstance().debug("Connection[id: %s] - retrieving authenticator",this.getId()),E=P7s.getAuthenticator(n,r.getHttpClient()),t.sf.authenticator=E}catch{let w=f.getDuration();throw Xo.getInstance().error("Connection[id: %s] - failed to initialize authenticator. Connecting failed after %s milliseconds",this.getId(),w),ew.createClientError(zz.ERR_CONN_CREATE_INVALID_AUTH_UNSUPPORTED,!0)}try{Xo.getInstance().debug("Connection[id: %s] - initializing easyLogging",this.getId()),await ZHp(n.clientConfigFile)}catch{let w=f.getDuration();throw Xo.getInstance().error("Connection[id: %s] - failed to initialize easyLogging. Connecting failed after %s milliseconds",this.getId(),w),ew.createClientError(zz.ERR_CONN_CONNECT_INVALID_CLIENT_CONFIG,!0)}let v=null;try{Xo.getInstance().debug("Connection[id: %s] - using authentication type: %s",this.getId(),n.getAuthenticator()),Xo.getInstance().debug("Connection[id: %s] - trying to authenticate",this.getId()),await E.authenticate(n.getAuthenticator(),n.getServiceName(),n.account,n.username),Xo.getInstance().info("Connection[id: %s] - authentication successful using: %s",this.getId(),n.getAuthenticator()),v=P7s.formAuthJSON(n.getAuthenticator(),n.account,n.username,n.getClientType(),n.getClientVersion(),n.getClientEnvironment()),E.updateBody(v)}catch(T){let w=f.getDuration();return Xo.getInstance().info("Connection[id: %s] - failed to connect async after %s milliseconds.Failed during authentication. Error: %s",this.getId(),w,T),Xo.getInstance().error("Connection[id: %s] - failed during authentication. Error: %s",this.getId(),T),d(T),this}try{Xo.getInstance().debug("Connection[id: %s] - connecting through service",this.getId()),t.sf.connect({callback:p(A,d),json:v});let T=f.getDuration();Xo.getInstance().info("Connection[id: %s] - connected successfully after %s milliseconds",this.getId(),T)}catch(T){let w=f.getDuration();return Xo.getInstance().info("Connection[id: %s] - failed to connect async after %s milliseconds.Error: Unexpected error from calling connectCallback function in snowflake service - %s",this.getId(),w,T),d(T),this}return this},this.execute=function(d){return Xo.getInstance().trace("Connection[id: %s] - execute called with options.",this.getId()),XHp.createStatementPreExec(d,t,n)},this.fetchResult=function(d){return Xo.getInstance().trace("Connection[id: %s] - fetchResult called with options",this.getId()),XHp.createStatementPostExec(d,t,n)},this.destroy=function(d){Xo.getInstance().trace("Connection[id: %s] - destroy called",this.getId()),ew.checkArgumentValid(!D_.exists(d)||D_.isFunction(d),zz.ERR_CONN_DESTROY_INVALID_CALLBACK),Xo.getInstance().trace("Connection[id: %s] - destroying through service",this.getId());let f=this;return t.sf.destroy({callback:function(h){D_.exists(f.keepalive)&&(clearInterval(f.keepalive),Xo.getInstance().trace("Connection[id: %s] - keepAlive interval cleared",f.getId())),D_.isFunction(d)&&d(ew.externalize(h),f)}}),Xo.getInstance().trace("Connection[id: %s] - connection destroyed successfully",this.getId()),this};async function c(d){Xo.getInstance().trace("Connection[id: %s] - requested query response for Query[id: %s]",i,d),ew.checkArgumentExists(D_.exists(d),zz.ERR_CONN_FETCH_RESULT_MISSING_QUERY_ID),ew.checkArgumentValid(u.test(d),zz.ERR_GET_RESPONSE_QUERY_INVALID_UUID,d),Xo.getInstance().debug("Connection[id: %s] - Query[id: %s] is valid",i,d);let f={method:"GET",url:$Hp.format({pathname:`/monitoring/queries/${d}`})};Xo.getInstance().debug("Connection[id: %s] - fetching query response for Query[id: %s]",i,d);let h=new D7s().start(),A=await t.sf.requestAsync(f),E=h.getDuration();return Xo.getInstance().debug("Connection[id: %s] - query response for Query[id: %s] fetched successfully after: %s milliseconds",i,d,E),A.data}function l(d){let f=Uz.code.NO_QUERY_DATA;if(!d||!d.data||!d.data.queries)return Xo.getInstance().trace("Connection[id: %s] - No query data found, returning NO_QUERY_DATA status",i),f;let h=d.data.queries;return h.length>0&&(f=h[0].status),Xo.getInstance().trace("Connection[id: %s] - Extracted query status: %s",i,f),f}this.getQueryStatus=async function(d){return Xo.getInstance().trace("Connection[id: %s] - getQueryStatus called for Query[id: %s]",this.getId(),d),l(await c(d))},this.getQueryStatusThrowIfError=async function(d){Xo.getInstance().trace("Connection[id: %s] - getQueryStatusThrowIfError called for Query[id: %s]",this.getId(),d);let f=await c(d),h=l(f),A=null;if(this.isAnError(h)){let E=f.message||"",v=f.code||-1;throw f.data&&(E+=f.data.queries.length>0?f.data.queries[0].errorMessage:"",A=f.data.sqlState),Xo.getInstance().debug("Connection[id: %s] - query error for Query[id: %s]. Error: %s. SQLState: %s",this.getId(),d,E,A),ew.createOperationFailedError(v,f,E,A)}return h},this.getResultsFromQueryId=async function(d){let f=d.queryId;Xo.getInstance().trace("Connection[id: %s] - getResultsFromQueryId called for Query[id: %s].",this.getId(),f);let h,A=0,E=0,v=!0;for(;v;){if(Xo.getInstance().trace("Connection[id: %s] - checking if Query[id: %s] is still executing. Retries with no data count: %d",this.getId(),f,A),h=await this.getQueryStatusThrowIfError(f),v=this.isStillRunning(h),!v||h===Uz.code.NO_QUERY_DATA){Xo.getInstance().trace("Connection[id: %s] - end of waiting for Query[id: %s] to finish executing. "+v?"Query is no longer executing. ":"Query status: %s.",this.getId(),f,h);break}if(await new Promise(T=>{setTimeout(()=>T(),a*s[E])}),Uz.code[h]===Uz.code.NO_DATA&&(A++,Xo.getInstance().trace("Connection[id: %s] - no data returned for Query[id: %s]. Retries with no data count: %d",this.getId(),f,A),A>o))throw Xo.getInstance().error("Connection[id: %s] - no data returned for Query[id: %s]. Retry limit: %s reached.",this.getId(),f,o),ew.createClientError(zz.ERR_GET_RESULTS_QUERY_ID_NO_DATA,!0,f);E<s.length-1&&E++}if(Uz.code[h]===Uz.code.NO_QUERY_DATA)throw Xo.getInstance().error("Connection[id: %s] - Query[id: %s] did not succeed. Final status: %s",this.getId(),f,h),ew.createClientError(zz.ERR_GET_RESULTS_QUERY_ID_NO_DATA,!0,f,h);if(Uz.code[h]!==Uz.code.SUCCESS)throw Xo.getInstance().error("Connection[id: %s] - Query[id: %s] did not succeed. Final status: %s",this.getId(),f,h),ew.createClientError(zz.ERR_GET_RESULTS_QUERY_ID_NOT_SUCCESS_STATUS,!0,f,h);return Xo.getInstance().debug("Connection[id: %s] - Query[id: %s] succeeded. Fetching the result.",this.getId(),f),this.fetchResult(d)},this.isStillRunning=function(d){return Xo.getInstance().trace("Connection[id: %s] - checking if status %s is still running",this.getId(),d),Uz.runningStatuses.includes(Uz.code[d])},this.isAnError=function(d){return Uz.errorStatuses.includes(Uz.code[d])},this.serialize=function(){return Xo.getInstance().trace("Connection[id: %s] - serialize called",this.getId()),JSON.stringify(r.getConfig())},tVp.call(this)}D_.inherits(rVp,tVp);nVp.exports=rVp});var sVp=m(oVp=>{"use strict";oVp.HEARTBEAT_FREQUENCY_MASTER_VALIDITY=14400});var TVp=m((FAS,vVp)=>{"use strict";var aVp=require("os"),IEm=require("url"),ln=Tc(),uVp=v3e(),ua=oA(),REm=sVp(),OEm=require("path"),Na=ua.codes,wEm=p3e().NativeTypes,MEm=DO(),_9=PW(),xEm=qRr(),PEm=c9t(),NEm=p3e(),B7s=yd(),{isSnowflakeHost:$ht}=Yke(),DEm=12e4,BEm="/oauth/authorize",LEm="/oauth/token-request",Zrn="LOCAL_APPLICATION",cVp=["account","application","region","host","accessUrl","username","password","authenticator","proxyHost","proxyPort","serviceName","privateKey","privateKeyPath","privateKeyPass","token","warehouse","database","schema","role","rowMode","streamResult","fetchAsString","clientSessionKeepAlive","clientSessionKeepAliveHeartbeatFrequency","jsTreatIntegerAsBigInt","sessionToken","masterToken","sessionTokenExpirationTime","masterTokenExpirationTime","agentClass","validateDefaultParameters","arrayBindingThreshold","gcsUseDownscopedCredential","forceStageBindError","includeRetryReason","disableQueryContextCache","retryTimeout","clientRequestMFAToken","clientStoreTemporaryCredential","disableConsoleLogin","forceGCPUseDownscopedCredential","representNullAsStringNull","disableSamlURLCheck","credentialCacheDir","passcodeInPassword","passcode","oauthClientId","oauthClientSecret","oauthRedirectUri","oauthAuthorizationUrl","oauthTokenRequestUrl","oauthScope","oauthChallengeMethod","oauthHttpAllowed","workloadIdentityProvider","workloadIdentityAzureEntraIdResource","queryTag"];function kEm(r){let t=-1,n,i,o=r.protocol||"https",s=ln.exists(r.port)?ln.format(":%s",r.port):"";if(ln.exists(r.region)&&(ua.checkArgumentValid(ln.isCorrectSubdomain(r.region),Na.ERR_CONN_CREATE_INVALID_REGION_REGEX),i=r.region),ln.exists(r.account)&&(ua.checkArgumentValid(ln.isString(r.account),Na.ERR_CONN_CREATE_INVALID_ACCOUNT),ua.checkArgumentValid(ln.isCorrectSubdomain(r.account),Na.ERR_CONN_CREATE_INVALID_ACCOUNT_REGEX),t=r.account.indexOf("."),n=r.account,t>0&&(i=n.substring(t+1),n=n.substring(0,t))),ln.exists(r.accessUrl))try{let a=IEm.parse(r.accessUrl);ua.checkArgumentValid(ln.exists(a.hostname),Na.ERR_CONN_CREATE_INVALID_ACCESS_URL),ln.exists(r.host)||(r.host=a.hostname);let u=a.hostname.indexOf(".");u>0&&!ln.exists(r.account)&&(n=a.hostname.substring(0,u))}catch{ua.checkArgumentValid(!1,Na.ERR_CONN_CREATE_MISSING_ACCOUNT)}else if(ln.exists(r.host)){r.accessUrl=ln.format("%s://%s%s",o,r.host,s);let a=r.host.indexOf(".");a>0&&!ln.exists(r.account)?n=r.host.substring(0,a):n=r.account}else ln.exists(r.account)&&(r.region==="us-west-2"&&(r.region=""),r.host=ln.constructHostname(i,n),r.accessUrl=ln.format("%s://%s%s",o,r.host,s));if(ln.exists(n)&&r.accessUrl.includes("global.snowflakecomputing")){let a=n.indexOf("-");a>0&&(n=n.substring(0,a))}r.account=n,r.region=i,ua.checkArgumentExists(ln.exists(r.account),Na.ERR_CONN_CREATE_MISSING_ACCOUNT),ua.checkArgumentExists(ln.exists(r.accessUrl),Na.ERR_CONN_CREATE_MISSING_ACCESS_URL)}function tw(r,t,n,i){if(ln.exists(t)||(t=!0),ua.checkArgumentExists(ln.exists(r),Na.ERR_CONN_CREATE_MISSING_OPTIONS),ua.checkArgumentValid(ln.isObject(r),Na.ERR_CONN_CREATE_INVALID_OPTIONS),t){let ke=[_9.OAUTH_AUTHENTICATOR,_9.EXTERNAL_BROWSER_AUTHENTICATOR,_9.PROGRAMMATIC_ACCESS_TOKEN,_9.OAUTH_CLIENT_CREDENTIALS,_9.OAUTH_AUTHORIZATION_CODE,_9.WORKLOAD_IDENTITY];if((!r.authenticator||!ke.includes(r.authenticator.toUpperCase()))&&ua.checkArgumentExists(ln.exists(r.username),Na.ERR_CONN_CREATE_MISSING_USERNAME),ln.exists(r.username)&&ua.checkArgumentValid(ln.isString(r.username),Na.ERR_CONN_CREATE_INVALID_USERNAME),(!ln.exists(r.authenticator)||r.authenticator===_9.DEFAULT_AUTHENTICATOR)&&(ua.checkArgumentExists(ln.exists(r.password),Na.ERR_CONN_CREATE_MISSING_PASSWORD),ua.checkArgumentValid(ln.isString(r.password),Na.ERR_CONN_CREATE_INVALID_PASSWORD)),(!ln.exists(r.authenticator)||r.authenticator===_9.PROGRAMMATIC_ACCESS_TOKEN)&&(ua.checkArgumentExists(ln.exists(r.password)||ln.exists(r.token),Na.ERR_CONN_CREATE_MISSING_PASSWORD),ln.exists(r.password)&&ua.checkArgumentValid(ln.isString(r.password),Na.ERR_CONN_CREATE_INVALID_PASSWORD),ln.exists(r.token)&&ua.checkArgumentValid(ln.isString(r.token),Na.ERR_CONN_CREATE_INVALID_OAUTH_TOKEN)),r.authenticator===_9.OAUTH_AUTHORIZATION_CODE){if(ln.exists(r.oauthAuthorizationUrl)){let we;try{we=new URL(r.oauthAuthorizationUrl)}catch{throw ua.createInvalidParameterError(Na.ERR_CONN_CREATE_INVALID_OUATH_AUTHORIZATION_URL)}ua.checkArgumentValid(we.protocol==="https:"||we.protocol==="http:",Na.ERR_CONN_CREATE_INVALID_OUATH_AUTHORIZATION_URL)}(r.oauthAuthorizationUrl&&!$ht(r.oauthAuthorizationUrl)||r.oauthTokenRequestUrl&&!$ht(r.oauthTokenRequestUrl))&&(ua.checkArgumentValid(ln.isString(r.oauthClientId),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_ID),ua.checkArgumentValid(ln.isString(r.oauthClientSecret),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_SECRET))}if(r.authenticator===_9.OAUTH_CLIENT_CREDENTIALS){if(ln.exists(r.oauthTokenRequestUrl)){let we;try{we=new URL(r.oauthTokenRequestUrl)}catch{throw ua.createInvalidParameterError(Na.ERR_CONN_CREATE_INVALID_OUATH_TOKEN_REQUEST_URL)}ua.checkArgumentValid(we.protocol==="https:"||we.protocol==="http:",Na.ERR_CONN_CREATE_INVALID_OUATH_TOKEN_REQUEST_URL)}ua.checkArgumentValid(ln.isString(r.oauthClientId),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_ID),ua.checkArgumentValid(ln.isString(r.oauthClientSecret),Na.ERR_CONN_CREATE_INVALID_OUATH_CLIENT_SECRET)}kEm(r)}ua.checkArgumentExists(ln.exists(r.accessUrl),Na.ERR_CONN_CREATE_MISSING_ACCESS_URL),ua.checkArgumentValid(ln.isString(r.accessUrl),Na.ERR_CONN_CREATE_INVALID_ACCESS_URL);let o=r.proxyHost,s=r.proxyPort,a=r.proxyUser,u=r.proxyPassword,p=r.proxyProtocol||"http",c=r.noProxy,l=r.useConnectionConfigProxyForOCSP??!1,d=r.oauthClientId,f=r.oauthClientSecret,h=r.oauthRedirectUri,A=r.oauthAuthorizationUrl,E=r.oauthTokenRequestUrl,v=r.oauthChallengeMethod,T=r.oauthScope,w=r.oauthHttpAllowed,N;ln.isNode()&&(ln.exists(o)||ln.exists(s))&&(N={host:o,port:s,user:a,password:u,protocol:p,noProxy:c,useForOCSP:l},uVp.validateProxy(N));let k=r.serviceName,L=r.authenticator;ln.exists(L)?L=L.toUpperCase():L=_9.DEFAULT_AUTHENTICATOR;let q=r.browserActionTimeout;ln.exists(r.browserActionTimeout)?ua.checkArgumentValid(ln.number.isPositiveInteger(q),Na.ERR_CONN_CREATE_INVALID_BROWSER_TIMEOUT):q=DEm;let G=r.privateKey;ln.exists(r.privateKey)&&ua.checkArgumentValid(ln.isString(G)&&ln.isPrivateKey(G),Na.ERR_CONN_CREATE_INVALID_PRIVATE_KEY);let H=r.privateKeyPath;ln.exists(r.privateKeyPath)&&ua.checkArgumentValid(ln.isString(H),Na.ERR_CONN_CREATE_INVALID_PRIVATE_KEY_PATH);let V=r.privateKeyPass;ln.exists(r.privateKeyPass)&&ua.checkArgumentValid(ln.isString(V),Na.ERR_CONN_CREATE_INVALID_PRIVATE_KEY_PASS);let W=r.token;ln.exists(W)&&ua.checkArgumentValid(ln.isString(W),Na.ERR_CONN_CREATE_INVALID_OAUTH_TOKEN);let F=r.warehouse,J=r.database,Y=r.schema,z=r.role;ln.exists(F)&&ua.checkArgumentValid(ln.isString(F),Na.ERR_CONN_CREATE_INVALID_WAREHOUSE),ln.exists(J)&&ua.checkArgumentValid(ln.isString(J),Na.ERR_CONN_CREATE_INVALID_DATABASE),ln.exists(Y)&&ua.checkArgumentValid(ln.isString(Y),Na.ERR_CONN_CREATE_INVALID_SCHEMA),ln.exists(z)&&ua.checkArgumentValid(ln.isString(z),Na.ERR_CONN_CREATE_INVALID_ROLE);let X=r.streamResult;ln.exists(X)&&ua.checkArgumentValid(ln.isBoolean(X),Na.ERR_CONN_CREATE_INVALID_STREAM_RESULT);let Z=r.fetchAsString;if(ln.exists(Z)){ua.checkArgumentValid(ln.isArray(Z),Na.ERR_CONN_CREATE_INVALID_FETCH_AS_STRING);let ke=wEm.findInvalidValue(Z);ua.checkArgumentValid(ke===-1,Na.ERR_CONN_CREATE_INVALID_FETCH_AS_STRING_VALUES,JSON.stringify(Z[ke]))}let re=r.rowMode;ln.exists(re)&&PEm.checkRowModeValid(re);let oe=r.clientSessionKeepAlive;ln.exists(oe)&&ua.checkArgumentValid(ln.isBoolean(oe),Na.ERR_CONN_CREATE_INVALID_KEEP_ALIVE);let ee=r.clientSessionKeepAliveHeartbeatFrequency;ln.exists(ee)&&(ua.checkArgumentValid(ln.isNumber(ee),Na.ERR_CONN_CREATE_INVALID_KEEP_ALIVE_HEARTBEAT_FREQ),ee=ln.validateClientSessionKeepAliveHeartbeatFrequency(ee,REm.HEARTBEAT_FREQUENCY_MASTER_VALIDITY));let ce=r.jsTreatIntegerAsBigInt;ln.exists(ce)&&ua.checkArgumentValid(ln.isBoolean(ce),Na.ERR_CONN_CREATE_INVALID_TREAT_INTEGER_AS_BIGINT);let de=r.gcsUseDownscopedCredential;ln.exists(de)&&ua.checkArgumentValid(ln.isBoolean(de),Na.ERR_CONN_CREATE_INVALID_GCS_USE_DOWNSCOPED_CREDENTIAL);let pe=r.clientConfigFile;ln.exists(pe)&&ua.checkArgumentValid(ln.isString(pe),Na.ERR_CONN_CREATE_INVALID_CLIENT_CONFIG_FILE),this._qaMode=n;let le="JavaScript",Ne,Qe,Ee;ln.exists(i)&&(ua.assertInternal(ln.isObject(i)),ua.assertInternal(ln.isString(i.version)),ua.assertInternal(ln.isObject(i.environment)),Ne=i.name,Qe=i.version,Ee=i.environment,Ee.OS=aVp.platform(),Ee.OS_VERSION=aVp.release(),Ee.OCSP_MODE=MEm.getOcspMode());let _e=r.application;if(ln.exists(_e)){ua.checkArgumentValid(ln.isString(_e),Na.ERR_CONN_CREATE_INVALID_APPLICATION);let ke=new RegExp(String.raw`^[A-Za-z]([A-Za-z0-9.\-_]){1,50}$`,"gi");ua.checkArgumentValid(ke.test(_e),Na.ERR_CONN_CREATE_INVALID_APPLICATION)}let tt=!1;ln.exists(r.validateDefaultParameters)&&(ua.checkArgumentValid(ln.isBoolean(r.validateDefaultParameters),Na.ERR_CONN_CREATE_INVALID_VALIDATE_DEFAULT_PARAMETERS),tt=r.validateDefaultParameters);let b=null;ln.exists(r.arrayBindingThreshold)&&(ua.checkArgumentValid(ln.isNumber(r.arrayBindingThreshold),Na.ERR_CONN_CREATE_INVALID_ARRAY_BINDING_THRESHOLD),b=r.arrayBindingThreshold);let R=null;ln.exists(r.forceStageBindError)&&(ua.checkArgumentValid(ln.isNumber(r.forceStageBindError),Na.ERR_CONN_CREATE_INVALID_FORCE_STAGE_BIND_ERROR),R=r.forceStageBindError);let O=!1;ln.exists(r.disableQueryContextCache)&&(ua.checkArgumentValid(ln.isBoolean(r.disableQueryContextCache),Na.ERR_CONN_CREATE_INVALID_DISABLED_QUERY_CONTEXT_CACHE),O=r.disableQueryContextCache);let j=300;ln.exists(r.retryTimeout)&&(ua.checkArgumentValid(ln.isNumber(r.retryTimeout),Na.ERR_CONN_CREATE_INVALID_MAX_RETRY_TIMEOUT),j=r.retryTimeout!==0?Math.max(j,r.retryTimeout):0);let Ae=!0;ln.exists(r.includeRetryReason)&&(ua.checkArgumentValid(ln.isBoolean(r.includeRetryReason),Na.ERR_CONN_CREATE_INVALID_INCLUDE_RETRY_REASON),Ae=r.includeRetryReason);let Te=!1;ln.exists(r.clientRequestMFAToken)&&(ua.checkArgumentValid(ln.isBoolean(r.clientRequestMFAToken),Na.ERR_CONN_CREATE_INVALID_CLIENT_REQUEST_MFA_TOKEN),Te=r.clientRequestMFAToken);let De=!0;ln.exists(r.disableConsoleLogin)&&(ua.checkArgumentValid(ln.isBoolean(r.disableConsoleLogin),Na.ERR_CONN_CREATE_INVALID_DISABLE_CONSOLE_LOGIN),De=r.disableConsoleLogin),ln.exists(r.forceGCPUseDownscopedCredential)?(ua.checkArgumentValid(ln.isBoolean(r.forceGCPUseDownscopedCredential),Na.ERR_CONN_CREATE_INVALID_FORCE_GCP_USE_DOWNSCOPED_CREDENTIAL),process.env.SNOWFLAKE_FORCE_GCP_USE_DOWNSCOPED_CREDENTIAL=r.forceGCPUseDownscopedCredential):process.env.SNOWFLAKE_FORCE_GCP_USE_DOWNSCOPED_CREDENTIAL=!1,ln.exists(r.representNullAsStringNull)&&(ua.checkArgumentValid(ln.isBoolean(r.representNullAsStringNull),Na.ERR_CONN_CREATE_INVALID_REPRESENT_NULL_AS_STRING_NULL),NEm.setIsRepresentNullAsStringNull(r.representNullAsStringNull));let y=!1;ln.exists(r.disableSamlURLCheck)&&(ua.checkArgumentValid(ln.isBoolean(r.disableSamlURLCheck),Na.ERR_CONN_CREATE_INVALID_DISABLE_SAML_URL_CHECK),y=r.disableSamlURLCheck);let I=!1;ln.exists(r.clientStoreTemporaryCredential)&&(ua.checkArgumentValid(ln.isBoolean(r.clientStoreTemporaryCredential),Na.ERR_CONN_CREATE_INVALID_CLIENT_STORE_TEMPORARY_CREDENTIAL),I=r.clientStoreTemporaryCredential);let P=null;if(ln.exists(r.credentialCacheDir)){let ke=OEm.resolve(r.credentialCacheDir);ua.checkArgumentValid(ln.validatePath(ke),Na.ERR_CONN_CREATE_INVALID_CREDENTIAL_CACHE_DIR),P=ke}let g=!1;ln.exists(r.passcodeInPassword)&&(ua.checkArgumentValid(ln.isBoolean(r.passcodeInPassword),Na.ERR_CONN_CREATE_INVALID_PASSCODE_IN_PASSWORD),g=r.passcodeInPassword);let _=null;if(ln.exists(r.passcode)&&(ua.checkArgumentValid(ln.isString(r.passcode),Na.ERR_CONN_CREATE_INVALID_PASSCODE),_=r.passcode),r.queryTag&&(ua.checkArgumentValid(ln.isString(r.queryTag)&&r.queryTag.length<=2e3,Na.ERR_CONN_CREATE_INVALID_QUERY_TAG),this.queryTag=r.queryTag),tt){for(let[ke]of Object.entries(r))if(!cVp.includes(ke)){let we=xEm.closest(ke,cVp);B7s.getInstance().error(`'${ke}' is an unknown connection parameter. Did you mean '${we}'?`)}}this.getProxy=function(){return N},this.getWarehouse=function(){return F},this.getDatabase=function(){return J},this.getSchema=function(){return Y},this.getRole=function(){return z},this.getServiceName=function(){return k},this.getAuthenticator=function(){return L},this.getBrowserActionTimeout=function(){return q},this.getPrivateKey=function(){return G},this.getPrivateKeyPath=function(){return H},this.getPrivateKeyPass=function(){return V},this.getToken=function(){return W},this.getStreamResult=function(){return X},this.getFetchAsString=function(){return Z},this.getRowMode=function(){return re},this.getClientType=function(){return le},this.getClientName=function(){return Ne},this.getClientVersion=function(){return Qe},this.getClientApplication=function(){return _e},this.getClientEnvironment=function(){return Ee},this.getClientSessionKeepAlive=function(){return oe},this.getClientSessionKeepAliveHeartbeatFrequency=function(){return ee},this.getJsTreatIntegerAsBigInt=function(){return ce},this.getGcsUseDownscopedCredential=function(){return de},this.getbindThreshold=function(){return b},this.getForceStageBindError=function(){return R},this.getIncludeRetryReason=function(){return Ae},this.getDisableQueryContextCache=function(){return O},this.getClientConfigFile=function(){return pe},this.getRetryTimeout=function(){return j},this.getDisableConsoleLogin=function(){return De},this.getDisableSamlURLCheck=function(){return y},this.getCredentialCacheDir=function(){return P},this.getClientRequestMFAToken=function(){return Te},this.getClientStoreTemporaryCredential=function(){return I},this.getPasscodeInPassword=function(){return g},this.getPasscode=function(){return _},this.getOauthClientId=function(){return!ln.isNotEmptyString(r.oauthClientId)&&!ln.isNotEmptyString(r.oauthClientSecret)&&L===_9.OAUTH_AUTHORIZATION_CODE&&$ht(this.getOauthAuthorizationUrl())&&$ht(this.getOauthTokenRequestUrl())&&(B7s.getInstance().debug(`Using default values for oauthClientId: ${Zrn}`),d=Zrn),d},this.getOauthClientSecret=function(){return!r.oauthClientId&&!r.oauthClientSecret&&L===_9.OAUTH_AUTHORIZATION_CODE&&$ht(this.getOauthAuthorizationUrl())&&$ht(this.getOauthTokenRequestUrl())&&(B7s.getInstance().debug(`Using default values for oauthClientSecret: ${Zrn}`),f=Zrn),f},this.getOauthAuthorizationUrl=function(){return A??r.accessUrl+BEm},this.getOauthTokenRequestUrl=function(){return E??r.accessUrl+LEm},this.getOauthRedirectUri=function(){return h},this.getOauthScope=function(){return T},this.getOauthChallengeMethod=function(){return v},this.getOauthHttpAllowed=function(){return w||!1},this.describeIdentityAttributes=function(){return`host: ${this.host}, account: ${this.account}, accessUrl: ${this.accessUrl}, user: ${this.username}, role: ${this.getRole()}, database: ${this.getDatabase()}, schema: ${this.getSchema()}, warehouse: ${this.getWarehouse()}, `+uVp.describeProxy(this.getProxy())},this.username=r.username,this.password=r.password,this.accessUrl=r.accessUrl,this.region=r.region,this.account=r.account,this.token=r.token,this.host=r.host,this.sessionToken=r.sessionToken,this.masterToken=r.masterToken,this.masterTokenExpirationTime=r.masterTokenExpirationTime,this.sessionTokenExpirationTime=r.sessionTokenExpirationTime,this.clientConfigFile=r.clientConfigFile,this.openExternalBrowserCallback=r.openExternalBrowserCallback,this.oauthEnableSingleUseRefreshTokens=r.oauthEnableSingleUseRefreshTokens,this.workloadIdentityProvider=r.workloadIdentityProvider,this.workloadIdentityAzureEntraIdResource=r.workloadIdentityAzureEntraIdResource;let M=qEm(),K={},st,Ie,He;for(st=0,Ie=M.length;st<Ie;st++)He=M[st],K[He.name]=He,He.value=He.defaultValue;let Xe,at;for(Xe in r)Object.prototype.hasOwnProperty.call(r,Xe)&&Object.prototype.hasOwnProperty.call(K,Xe)&&(at=r[Xe],He=K[Xe],He.external&&He.validate(at)&&(He.value=at));this._mapParameters=K,this.agentClass=r.agentClass}tw.prototype.isQaMode=function(){return this._qaMode};tw.prototype.clearCredentials=function(){this.password=null};var lVp="timeout",pVp="resultPrefetch",dVp="resultStreamInterrupts",fVp="resultChunkCacheSize",hVp="resultProcessingBatchSize",gVp="resultProcessingBatchDuration",AVp="rowStreamHighWaterMark",mVp="largeResultSetRetryMaxNumRetries",yVp="largeResultSetRetryMaxSleepTime",bVp="sfRetryMaxLoginRetries",EVp="sfRetryMaxNumRetries",CVp="sfRetryStartingSleepTime",SVp="sfRetryMaxSleepTime";function qEm(){let r=ln.number.isNonNegativeInteger.bind(ln.number),t=ln.number.isPositiveInteger.bind(ln.number),n=ln.number.isNonNegative.bind(ln.number);return[{name:lVp,defaultValue:90*1e3,external:!0,validate:t},{name:pVp,defaultValue:2,external:!0,validate:t},{name:dVp,defaultValue:3,validate:t},{name:fVp,defaultValue:1,validate:t},{name:hVp,defaultValue:1e3,validate:t},{name:gVp,defaultValue:100,validate:t},{name:AVp,defaultValue:10,validate:t},{name:mVp,defaultValue:10,validate:r},{name:yVp,defaultValue:16,validate:r},{name:bVp,defaultValue:7,external:!0,validate:r},{name:EVp,defaultValue:1e3,validate:r},{name:CVp,defaultValue:1,validate:n},{name:SVp,defaultValue:16,validate:n}]}tw.prototype.getTimeout=function(){return this._getParameterValue(lVp)};tw.prototype.getResultPrefetch=function(){return this._getParameterValue(pVp)};tw.prototype.getResultStreamInterrupts=function(){return this._getParameterValue(dVp)};tw.prototype.getResultChunkCacheSize=function(){return this._getParameterValue(fVp)};tw.prototype.getResultProcessingBatchSize=function(){return this._getParameterValue(hVp)};tw.prototype.getResultProcessingBatchDuration=function(){return this._getParameterValue(gVp)};tw.prototype.getRowStreamHighWaterMark=function(){return this._getParameterValue(AVp)};tw.prototype.getRetryLargeResultSetMaxNumRetries=function(){return this._getParameterValue(mVp)};tw.prototype.getRetryLargeResultSetMaxSleepTime=function(){return this._getParameterValue(yVp)};tw.prototype.getRetrySfMaxNumRetries=function(){return this._getParameterValue(EVp)};tw.prototype.getRetrySfMaxLoginRetries=function(){return this._getParameterValue(bVp)};tw.prototype.getRetrySfStartingSleepTime=function(){return this._getParameterValue(CVp)};tw.prototype.getRetrySfMaxSleepTime=function(){return this._getParameterValue(SVp)};tw.prototype._getParameterValue=function(r){let t=this._mapParameters[r];return t?t.value:void 0};vVp.exports=tw});var IVp=m(_Vp=>{"use strict";var gRe={};gRe.INCORRECT_USERNAME_PASSWORD="390100";gRe.SESSION_TOKEN_INVALID="390104";gRe.GONE_SESSION="390111";gRe.SESSION_TOKEN_EXPIRED="390112";gRe.OAUTH_TOKEN_EXPIRED="390318";gRe.MASTER_TOKEN_EXPIRED="390114";gRe.ID_TOKEN_INVALID="390195";_Vp.code=gRe});var OVp=m((zAS,RVp)=>{"use strict";var fb=yd();function FEm(r,t,n,i){this.id=r,this.timestamp=t,this.priority=n,this.context=i}function SN(r,t){fb.getInstance().debug(`Creating new QueryContextCache with capacity ${r} for session ${t}`),this.sessionId=t,this.capacity=r,this.idMap=new Map,this.treeSet=new Set,this.priorityMap=new Map}SN.prototype.sortTreeSet=function(){this.treeSet=new Set(Array.from(this.treeSet).sort((r,t)=>r.priority-t.priority))};SN.prototype.addQCE=function(r){this.idMap.set(r.id,r),this.priorityMap.set(r.priority,r),this.treeSet.add(r),this.sortTreeSet(),fb.getInstance().trace(`QCC session ${this.sessionId} - Added QCE: ${JSON.stringify(r)}`)};SN.prototype.removeQCE=function(r){this.idMap.delete(r.id),this.priorityMap.delete(r.priority),this.treeSet.delete(r),fb.getInstance().trace(`QCC session ${this.sessionId} - Removed QCE: ${JSON.stringify(r)}`)};SN.prototype.replaceQCE=function(r,t){this.removeQCE(r),this.addQCE(t),fb.getInstance().debug(`QCC session ${this.sessionId} - Replaced QCE: ${JSON.stringify(r)} with ${JSON.stringify(t)}`)};SN.prototype.merge=function(r){if(fb.getInstance().debug(`QCC session ${this.sessionId} - Merging QCE: ${JSON.stringify(r)}`),this.idMap.has(r.id)){fb.getInstance().debug(`QCC session ${this.sessionId} - Element id ${r.id} found in cache`);let t=this.idMap.get(r.id);r.timestamp>t.timestamp?(fb.getInstance().trace(`QCC session ${this.sessionId} - New element is more recent. Current timestamp: ${t.timestamp}, new timestamp: ${r.timestamp}`),t.priority===r.priority?(fb.getInstance().trace(`QCC session ${this.sessionId} - Element priority (${t.priority}) is the same`),t.timestamp=r.timestamp,t.context=r.context):(fb.getInstance().trace(`QCC session ${this.sessionId} - Element priority changed. Current priority: ${t.priority}, new priority: ${r.priority}`),this.replaceQCE(t,r))):r.timestamp===t.timestamp&&t.priority!==r.priority?(fb.getInstance().trace(`QCC session ${this.sessionId} - Element timestamp is the same, but priority changes. Current priority: ${t.priority}, new priority: ${r.priority}`),this.replaceQCE(t,r)):fb.getInstance().trace(`QCC session ${this.sessionId} - Element is the same. Doing nothing.`)}else if(fb.getInstance().trace(`QCC session ${this.sessionId} - New element`),this.priorityMap.has(r.priority)){let t=this.priorityMap.get(r.priority);fb.getInstance().trace(`QCC session ${this.sessionId} - Element with the same priority found: ${JSON.stringify(t)}. Replacing with new element: ${JSON.stringify(r)}`),this.replaceQCE(t,r)}else fb.getInstance().debug(`QCC session ${this.sessionId} - Adding new element to the cache: ${JSON.stringify(r)}`),this.addQCE(r,r)};SN.prototype.checkCacheCapacity=function(){for(fb.getInstance().trace(`QCC session ${this.sessionId} - checkCacheCapacity() called. treeSet size ${this.treeSet.size}, cache capacity ${this.capacity}`);this.treeSet.size>this.capacity;){let r=Array.from(this.treeSet).pop();this.removeQCE(r)}fb.getInstance().trace(`QCC session ${this.sessionId} - checkCacheCapacity() returns. treeSet size ${this.treeSet.size}, cache capacity ${this.capacity}`)};SN.prototype.clearCache=function(){fb.getInstance().trace(`QCC session ${this.sessionId} - clearCache() called`),this.idMap.clear(),this.priorityMap.clear(),this.treeSet.clear(),fb.getInstance().trace(`QCC session ${this.sessionId} - clearCache() returns. Number of entries in cache now ${this.treeSet.size}`)};SN.prototype.getElements=function(){return this.treeSet};SN.prototype.deserializeQueryContext=function(r){let t=JSON.stringify(r);if(fb.getInstance().debug(`QCC session ${this.sessionId} - deserializeQueryContext() called: data from server: ${t}`),!r||t==="{}"||r.entries===null){this.clearCache(),fb.getInstance().trace(`QCC session ${this.sessionId} - deserializeQueryContext() returns`),this.logCacheEntries();return}try{let n=r.entries;if(n!==null&&Array.isArray(n))for(let i of n){let o=this.deserializeQueryContextElement(i);if(o!=null)this.merge(o);else{fb.getInstance().warn(`QCC session ${this.sessionId} - deserializeQueryContextJson: deserializeQueryContextElement meets mismatch field type. Clear the QueryContextCache.`),this.clearCache();return}}}catch(n){fb.getInstance().debug(`QCC session ${this.sessionId} - deserializeQueryContextJson: Exception = ${n.getMessage}`),this.clearCache()}this.checkCacheCapacity(),this.logCacheEntries()};SN.prototype.deserializeQueryContextElement=function(r){let{id:t,timestamp:n,priority:i,context:o}=r,s=new FEm(t,n,i,null);if(typeof o=="string")s.context=o;else if(o==null)s.context=null,fb.getInstance().debug(`QCC session ${this.sessionId} - deserializeQueryContextElement \`context\` field is empty`);else return fb.getInstance().warn(`QCC session ${this.sessionId} - deserializeQueryContextElement: \`context\` field is not String type`),null;return s};SN.prototype.logCacheEntries=function(){this.treeSet.forEach(function(r){fb.getInstance().debug(`QCC session ${this.sessionId} - Cache Entry: id: ${r.id} timestamp: ${r.timestamp} priority: ${r.priority}`)},this)};SN.prototype.getSize=function(){return this.treeSet.size};SN.prototype.getQueryContextDTO=function(){let r=[],t=Array.from(this.getElements());for(let n=0;n<this.treeSet.size;n++)r.push({id:t[n].id,timestamp:t[n].timestamp,priority:t[n].priority,context:{base64Data:t[n].context}});return{entries:r}};SN.prototype.getSerializeQueryContext=function(){let r=[],t=Array.from(this.getElements());for(let n=0;n<this.treeSet.size;n++)r.push({id:t[n].id,timestamp:t[n].timestamp,priority:t[n].priority,context:t[n].context||null});return{entries:r}};RVp.exports=SN});var NVp=m((QAS,PVp)=>{"use strict";var{v4:L7s}=(A6(),ut(g6)),UEm=require("events").EventEmitter,$s=Tc(),V0=oA(),rw=V0.codes,zEm=require("url"),QEm=require("querystring"),rB=p9t(),ARe=IVp(),jEm=OVp(),Lx=yd(),wVp=DO(),MVp=PW(),GEm=g6s(),HEm=f6s(),VEm=A6s(),WEm=Yrn(),KEm=E6s(),YEm=__s();function JEm(r){return!Object.prototype.hasOwnProperty.call(r,"cause")||r.cause===void 0||!Object.prototype.hasOwnProperty.call(r.cause,"code")||r.cause.code!==rw.ERR_OCSP_REVOKED&&r.cause.code!=="DEPTH_ZERO_SELF_SIGNED_CERT"&&r.cause.code!=="CERT_HAS_EXPIRED"&&r.cause.code!=="UNABLE_TO_VERIFY_LEAF_SIGNATURE"&&r.cause.code!=="SELF_SIGNED_CERT_IN_CHAIN"}function $Em(r){return Object.prototype.hasOwnProperty.call(r,"response")&&$s.isRetryableHttpError(r.response,!1)}function xVp(r,t,n){V0.assertInternal($s.isObject(r)),V0.assertInternal($s.isObject(t)),V0.assertInternal(!$s.exists(n)||$s.isObject(n));let i;$s.exists(n)?(V0.assertInternal($s.isObject(n)),V0.assertInternal($s.isObject(n.tokenInfo)),i=n.tokenInfo):r.sessionToken&&(i={sessionToken:r.sessionToken,masterToken:r.masterToken||r.sessionToken,sessionTokenExpirationTime:r.sessionTokenExpirationTime||Date.now()+1e3*60*60*24,masterTokenExpirationTime:r.masterTokenExpirationTime||Date.now()+1e3*60*60*24});let o=new ZEm(i);try{Lx.getInstance().debug("Retrieving authenticator"),this.authenticator=WEm.getAuthenticator(r,t)}catch(N){let k=`Failed to initialize authenticator: ${N}`;throw Lx.getInstance().error(k),V0.createClientError(rw.ERR_CONN_CREATE_INVALID_AUTH_UNSUPPORTED,!0,k)}let s={snowflakeService:this,httpClient:t,connectionConfig:r,tokenInfo:o},a=new WQt(s),u=new mRe(s),p=new Xht(s),c=new Zht(s),l=new KQt(s),d,f=function(N,k){d!==N&&(d&&d.exit(),d=N,d.enter(k))};this.setSessionId=function(N){this.sessionId=N},this.getSessionId=function(){return this.sessionId},this.transitionToPristine=function(N){f(a,N)},this.transitionToConnecting=function(N){f(u,N)},this.transitionToConnected=function(N){f(p,N)},this.transitionToRenewing=function(N){f(c,N)},this.transitionToDisconnected=function(N){f(l,N),o.clearTokens()},this.getConfig=function(){return{tokenInfo:o.getConfig()}},this.connect=function(N){new A(N).validate().execute()},this.continue=function(N){new E(N).validate().execute()},this.request=function(N){new v(N).validate().execute()},this.requestAsync=async function(N){return await new v(N).validate().executeAsync()},this.destroy=function(N){this.clearCache(),new T(N).validate().execute()};function h(N){this.options=N}h.prototype.validate=function(){return this},h.prototype.execute=function(){};function A(N){h.apply(this,[N])}$s.inherits(A,h),A.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)&&$s.isFunction(N.callback)),this},A.prototype.execute=function(){d.connect(this.options)};function E(N){h.apply(this,[N])}$s.inherits(E,h),E.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)&&$s.isObject(N.json)),this},E.prototype.execute=function(){d.continue(this.options)};function v(N){h.apply(this,[N])}$s.inherits(v,h),v.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)),V0.assertInternal($s.isString(N.method)),V0.assertInternal(!$s.exists(N.headers)||$s.isObject(N.headers)),V0.assertInternal($s.isString(N.url)),V0.assertInternal(!$s.exists(N.json)||$s.isObject(N.json)),this},v.prototype.execute=function(){d.request(this.options)},v.prototype.executeAsync=async function(){return await d.requestAsync(this.options)};function T(N){h.apply(this,[N])}$s.inherits(T,h),T.prototype.validate=function(){let N=this.options;return V0.assertInternal($s.isObject(N)&&$s.isFunction(N.callback)),this},T.prototype.execute=function(){d.destroy(this.options)};let w=[];this.enqueueRequest=function(N){w.push(new v(N))},this.enqueueDestroy=function(N){w.push(new T(N))},this.drainOperationQueue=function(){for(let N=0,k=w.length;N<k;N++)w[N].execute();w.length=0},this.isConnected=function(){return d===p||d===u||d===c},this.getServiceName=function(){return rB.getValue(rB.names.SERVICE_NAME)},this.getClientSessionKeepAlive=function(){return rB.getValue(rB.names.CLIENT_SESSION_KEEP_ALIVE)},this.getClientSessionKeepAliveHeartbeatFrequency=function(){return rB.getValue(rB.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY)},this.getJsTreatIntegerAsBigInt=function(){return rB.getValue(rB.names.JS_TREAT_INTEGER_AS_BIGINT)},this.getAuthenticator=function(){return this.authenticator},o.isEmpty()?this.transitionToPristine():this.transitionToConnected(),this.postAsync=function(N){return new v(N).validate().executeAsync()},this.getQueryContextDTO=function(){if(this.qcc)return this.qcc.getQueryContextDTO()},this.deserializeQueryContext=function(N){this.qcc&&this.qcc.deserializeQueryContext(N)},this.clearCache=function(){this.qcc&&this.qcc.clearCache()},this.initializeQueryContextCache=function(N){r.getDisableQueryContextCache()?Lx.getInstance().debug(`QueryContextCache initialization skipped as it is disabled for connection with sessionId: ${this.sessionId}`):this.qcc=new jEm(N,this.getSessionId())},this.getQueryContextCacheSize=function(){if(this.qcc)return this.qcc.getSize()}}$s.inherits(xVp,UEm);PVp.exports=xVp;function kx(r){function t(l,d,f){let h=l.params||{};l.excludeGuid||a(h);let A={method:l.method,headers:l.headers,url:l.absoluteUrl,gzip:l.gzip,json:l.json,params:h,callback:async function(E,v,T){if(E)Lx.getInstance().debug("Encountered an error when sending the request. Details: "+JSON.stringify(E,Object.getOwnPropertyNames(E))),E=V0.createNetworkError(rw.ERR_SF_NETWORK_COULD_NOT_CONNECT,E);else if(!v)E=V0.createUnexpectedContentError(rw.ERR_SF_RESPONSE_NOT_JSON,"(EMPTY)");else if(Object.prototype.hasOwnProperty.call(v,"statusCode")&&v.statusCode!==200)if(v.statusCode===401&&v.body){let w;try{w=JSON.parse(v.body).code}catch{E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_FAILURE,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode)}w==="390104"?(E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_INVALID_TOKEN,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode)):(E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_FAILURE,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode))}else E=V0.createRequestFailedError(rw.ERR_SF_RESPONSE_FAILURE,v),Lx.getInstance().debug("HTTP Error: %s",v.statusCode);else{if($s.isString(T)&&v.getResponseHeader("Content-Type")==="application/json")try{T.includes("smkId")&&(T=$s.convertSmkIdToString(T)),T=JSON.parse(T)}catch{E=V0.createUnexpectedContentError(rw.ERR_SF_RESPONSE_NOT_JSON,v.body)}if(T&&!T.success){let w=T.data;if(T.code===ARe.code.ID_TOKEN_INVALID&&f instanceof VEm||T.code===ARe.code.OAUTH_TOKEN_EXPIRED&&f instanceof KEm)return Lx.getInstance().debug("ID Token being used has expired. Reauthenticating"),await f.reauthenticate(l.json),d.request(A);E=V0.createOperationFailedError(T.code,w,T.message,w&&w.sqlState?w.sqlState:void 0)}}E&&(T=void 0),$s.isFunction(l.callback)&&await l.callback.apply(l.scope,[E,T])}};if(l.retry>2){let E=l.url.includes("?");A.url+=E?"&":"?",A.url+="clientStartTime="+l.startTime+"&retryCount="+(l.retry-1)}return d.request(A)}this.snowflakeService=r.snowflakeService,this.httpClient=r.httpClient,this.connectionConfig=r.connectionConfig,this.tokenInfo=r.tokenInfo;let n=r.connectionConfig,i=r.snowflakeService,o=r.httpClient;function s(l){this.requestOptions=l}s.prototype.sendAsync=async function(){this.preprocessOptions(this.requestOptions);let l=this.requestOptions.params||{};this.requestOptions.excludeGuid||a(l);let d={method:this.requestOptions.method,headers:this.requestOptions.headers,url:this.requestOptions.absoluteUrl,json:this.requestOptions.json,params:l};return await o.requestAsync(d)};function a(l){let d=L7s();l[YEm.paramsNames.SF_REQUEST_GUID]=d}s.prototype.send=function(){this.preprocessOptions(this.requestOptions),t(this.requestOptions,o,i.getAuthenticator())},s.prototype.preprocessOptions=function(l){l.headers=$s.apply(this.getDefaultReqHeaders(),l.headers||{}),$s.isLoginRequest(l.url)&&$s.apply(l.headers,{CLIENT_APP_VERSION:l.json.data.CLIENT_APP_VERSION,CLIENT_APP_ID:l.json.data.CLIENT_APP_ID}),l.absoluteUrl=this.buildFullUrl(l.url),l.excludeGuid=$s.exists(l.excludeGuid)?l.excludeGuid:!1},s.prototype.buildFullUrl=function(l){return n.accessUrl+l},s.prototype.getDefaultReqHeaders=function(){return{Accept:"application/json","Content-Type":"application/json"}};function u(){s.apply(this,arguments)}$s.inherits(u,s),u.prototype.preprocessOptions=function(l){s.prototype.preprocessOptions.apply(this,arguments),l.headers=l.headers||{},l.headers.Authorization='Snowflake Token="'+r.tokenInfo.getSessionToken()+'"',$s.string.isNotNullOrEmpty(rB.getValue(rB.names.SERVICE_NAME))&&(l.headers["X-Snowflake-Service"]=rB.getValue(rB.names.SERVICE_NAME))};function p(){s.apply(this,arguments)}$s.inherits(p,s),p.prototype.preprocessOptions=function(l){s.prototype.preprocessOptions.apply(this,arguments),l.headers=l.headers||{},l.headers.Authorization='Snowflake Token="'+r.tokenInfo.getMasterToken()+'"'};function c(){s.apply(this,arguments)}$s.inherits(c,s),this.createSessionTokenRequest=function(l){return new u(l)},this.createMasterTokenRequest=function(l){return new p(l)},this.createUnauthenticatedRequest=function(l){return new c(l)}}kx.prototype.enter=function(){};kx.prototype.exit=function(){};kx.prototype.connect=function(){};kx.prototype.continue=function(){};kx.prototype.request=function(){};kx.prototype.destroy=function(){};function WQt(){kx.apply(this,arguments)}$s.inherits(WQt,kx);WQt.prototype.connect=function(r){this.snowflakeService.transitionToConnecting({options:r})};WQt.prototype.request=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_REQUEST_STATUS_PRISTINE))})};WQt.prototype.destroy=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_DESTROY_STATUS_PRISTINE))})};function mRe(){kx.apply(this,arguments)}$s.inherits(mRe,kx);mRe.prototype.enter=function(r){this.context=r,this.continue()};mRe.prototype.exit=function(){this.context=null};mRe.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_CONNECTING))})};mRe.prototype.continue=function(){let r=this.context,t=r.options.err,n=r.options.json;n||(n={data:{ACCOUNT_NAME:this.connectionConfig.account,LOGIN_NAME:this.connectionConfig.username,PASSWORD:this.connectionConfig.password}}),t&&t.data&&t.data.inFlightCtx&&(n.inFlightCtx=t.data.inFlightCtx),n.data=n.data||{};let i={CLIENT_APP_ID:this.connectionConfig.getClientType(),CLIENT_APP_VERSION:this.connectionConfig.getClientVersion()},o=this.connectionConfig.getClientEnvironment();$s.isObject(o)&&(i.CLIENT_ENVIRONMENT={...n.data.CLIENT_ENVIRONMENT,...o});let s=this.connectionConfig.getClientApplication();$s.isString(s)&&(o.APPLICATION=s);let a={SESSION_PARAMETERS:{}};$s.exists(this.connectionConfig.getClientSessionKeepAlive())&&(a.SESSION_PARAMETERS.CLIENT_SESSION_KEEP_ALIVE=this.connectionConfig.getClientSessionKeepAlive()),$s.exists(this.connectionConfig.getClientSessionKeepAliveHeartbeatFrequency())&&(a.SESSION_PARAMETERS.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY=this.connectionConfig.getClientSessionKeepAliveHeartbeatFrequency()),$s.exists(this.connectionConfig.getJsTreatIntegerAsBigInt())&&(a.SESSION_PARAMETERS.JS_TREAT_INTEGER_AS_BIGINT=this.connectionConfig.getJsTreatIntegerAsBigInt()),$s.exists(this.connectionConfig.getGcsUseDownscopedCredential())&&(a.SESSION_PARAMETERS.GCS_USE_DOWNSCOPED_CREDENTIAL=this.connectionConfig.getGcsUseDownscopedCredential()),$s.exists(this.connectionConfig.getClientRequestMFAToken())&&(a.SESSION_PARAMETERS.CLIENT_REQUEST_MFA_TOKEN=this.connectionConfig.getClientRequestMFAToken()),$s.exists(this.connectionConfig.getClientStoreTemporaryCredential())&&(a.SESSION_PARAMETERS.CLIENT_STORE_TEMPORARY_CREDENTIAL=this.connectionConfig.getClientStoreTemporaryCredential()),$s.exists(this.connectionConfig.queryTag)&&(a.SESSION_PARAMETERS.QUERY_TAG=this.connectionConfig.queryTag),$s.apply(n.data,i),$s.apply(n.data,a);let u=this.connectionConfig,p=u.getRetrySfMaxLoginRetries(),c=u.getRetryTimeout(),l=u.accessUrl.startsWith("https://")?Date.now():"FIXEDTIMESTAMP",d=0,f=u.getRetrySfStartingSleepTime(),h=0;Lx.getInstance().debug("Total retryTimeout is for the retries = "+c===0?"unlimited":c);let A=this,E=async function(T,w){if(u.clearCredentials(),T)if(V0.isNetworkError(T)||V0.isRequestFailedError(T))if(d<p&&(JEm(T)||$Em(T))&&(c===0||h<c)){d++;let N=$s.getJitteredSleepTime(d,f,h,c);f=N.sleep,h=N.totalElapsedTime,f<=0&&(Lx.getInstance().debug("Reached out to the max Login Timeout"),A.snowflakeService.transitionToDisconnected());let k=A.snowflakeService.getAuthenticator();if(k instanceof GEm){Lx.getInstance().debug("OKTA authentication requires token refresh.");let L={totalElapsedTime:h,numRetries:d};await k.reauthenticate(r.options.json,L),d=L.numRetries,h=L.totalElapsedTime}else k instanceof HEm&&(Lx.getInstance().debug("AuthKeyPair authentication requires token refresh."),await k.reauthenticate(r.options.json));setTimeout(v,f*1e3);return}else Lx.getInstance().debug("Failed to all retries to SF."),A.snowflakeService.transitionToDisconnected();else A.snowflakeService.transitionToDisconnected();else{if(V0.assertInternal($s.exists(w)),V0.assertInternal($s.exists(w.data)),A.snowflakeService.setSessionId(w.data.sessionId),Lx.getInstance().debug(`New session with id ${A.snowflakeService.getSessionId()} initialized`),rB.update(w.data.parameters),A.tokenInfo.update(w.data),u.getClientRequestMFAToken()&&w.data.mfaToken){let k=$s.buildCredentialCacheKey(u.host,u.username,MVp.USER_PWD_MFA_AUTHENTICATOR);await wVp.getCredentialManager().write(k,w.data.mfaToken)}if(u.getClientStoreTemporaryCredential()&&w.data.idToken){let k=$s.buildCredentialCacheKey(u.host,u.username,MVp.ID_TOKEN_AUTHENTICATOR);await wVp.getCredentialManager().write(k,w.data.idToken)}A.snowflakeService.transitionToConnected();let N=rB.getValue("QUERY_CONTEXT_CACHE_SIZE");A.snowflakeService.initializeQueryContextCache(N)}$s.isFunction(r.options.callback)&&r.options.callback(T),A.snowflakeService.drainOperationQueue()},v=function(){let T=XEm(u);Lx.getInstance().debug("Contacting SF: %s, (%s/%s)",T,d,p),A.createUnauthenticatedRequest({method:"POST",url:T,json:n,scope:this,startTime:l,retry:d,callback:E}).send()};v()};function XEm(r){let t=[{name:"warehouse",value:r.getWarehouse()},{name:"databaseName",value:r.getDatabase()},{name:"schemaName",value:r.getSchema()},{name:"roleName",value:r.getRole()}],n={};r.isQaMode()||(n.requestId=L7s());for(let i=0,o=t.length;i<o;i++){let s=t[i];$s.string.isNotNullOrEmpty(s.value)&&(n[s.name]=s.value)}return zEm.format({pathname:"/session/v1/login-request",search:QEm.stringify(n)})}mRe.prototype.request=function(r){this.snowflakeService.enqueueRequest(r)};mRe.prototype.destroy=function(r){this.snowflakeService.enqueueDestroy(r)};function Xht(){kx.apply(this,arguments)}$s.inherits(Xht,kx);Xht.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_CONNECTED))})};Xht.prototype.requestAsync=async function(r){return await this.createSessionTokenRequest(r).sendAsync()};Xht.prototype.request=function(r){let t=r.scope,n=r.callback;r.scope=this,r.callback=async function(i,o){i?(r.scope=t,r.callback=n,i.code===ARe.code.SESSION_TOKEN_EXPIRED?(this.snowflakeService.enqueueRequest(r),this.snowflakeService.transitionToRenewing()):i.code===ARe.code.SESSION_TOKEN_INVALID||i.code===ARe.code.GONE_SESSION?(this.snowflakeService.enqueueRequest(r),this.snowflakeService.transitionToDisconnected(),this.snowflakeService.drainOperationQueue()):$s.isFunction(n)&&n.apply(t,[i,o])):$s.isFunction(n)&&await n.apply(t,[i,o])},this.createSessionTokenRequest(r).send()};Xht.prototype.destroy=function(r){let t=L7s();this.createSessionTokenRequest({method:"POST",url:`/session?delete=true&requestId=${t}`,scope:this,callback:function(n){(!n||n.code===ARe.code.GONE_SESSION||n.code===ARe.code.SESSION_TOKEN_EXPIRED)&&(n=void 0,this.snowflakeService.transitionToDisconnected()),r.callback(n)}}).send()};function Zht(){kx.apply(this,arguments)}$s.inherits(Zht,kx);Zht.prototype.enter=function(){this.createMasterTokenRequest({method:"POST",url:"/session/token-request",headers:{CLIENT_APP_ID:this.connectionConfig.getClientType(),CLIENT_APP_VERSION:this.connectionConfig.getClientVersion()},json:{REQUEST_TYPE:"RENEW",oldSessionToken:this.tokenInfo.getSessionToken()},scope:this,callback:function(r,t){r?r.code===ARe.code.MASTER_TOKEN_EXPIRED?this.snowflakeService.transitionToDisconnected():V0.isNetworkError(r)?this.snowflakeService.transitionToConnected():this.snowflakeService.transitionToDisconnected():(this.tokenInfo.update(t.data),this.snowflakeService.transitionToConnected()),this.snowflakeService.drainOperationQueue()}}).send()};Zht.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_CONNECTED))})};Zht.prototype.request=function(r){this.snowflakeService.enqueueRequest(r)};Zht.prototype.destroy=function(r){this.snowflakeService.enqueueDestroy(r)};function KQt(){kx.apply(this,arguments)}$s.inherits(KQt,kx);KQt.prototype.connect=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_CONNECT_STATUS_DISCONNECTED))})};KQt.prototype.request=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_REQUEST_STATUS_DISCONNECTED,!0))})};KQt.prototype.destroy=function(r){let t=r.callback;process.nextTick(function(){t(V0.createClientError(rw.ERR_CONN_DESTROY_STATUS_DISCONNECTED))})};function ZEm(r){let t,n,i,o;$s.isObject(r)&&(t=r.masterToken,n=r.sessionToken,i=r.masterTokenExpirationTime,o=r.sessionTokenExpirationTime),this.isEmpty=function(){return!$s.exists(t)||!$s.exists(i)||!$s.exists(n)||!$s.exists(o)},this.clearTokens=function(){t=void 0,i=void 0,n=void 0,o=void 0},this.update=function(s){t=s.masterToken,n=s.token||s.sessionToken;let a=new Date().getTime();i=a+1e3*(s.masterValidityInSeconds||s.validityInSecondsMT),o=a+1e3*(s.validityInSeconds||s.validityInSecondsST)},this.getMasterToken=function(){return t},this.getMasterTokenExpirationTime=function(){return i},this.getSessionToken=function(){return n},this.getSessionTokenExpirationTime=function(){return o},this.getConfig=function(){return{masterToken:t,masterTokenExpirationTime:i,sessionToken:n,sessionTokenExpirationTime:o}}}});var kVp=m((jAS,LVp)=>{"use strict";var e2m=require("events").EventEmitter,yRe=Tc(),e1t=oA(),YQt=yd(),DVp=e1t.codes;function BVp(r,t){e1t.assertInternal(yRe.isObject(r)),e1t.assertInternal(yRe.isObject(t));function n(s){return s&&(s.code==="ECONNRESET"||s.code==="ETIMEDOUT"||s.name==="AxiosError"&&s.code==="ECONNABORTED")}function i(s,a){return yRe.isRetryableHttpError(s,!0)||n(a)}function o(s){return s&&(s.statusCode!==200||s.getResponseHeader("Content-Type")==="application/xml")}this.getObject=function(a){let u=0,p=1,c=a.maxNumRetries;yRe.exists(c)||(c=r.getRetryLargeResultSetMaxNumRetries()),e1t.assertInternal(yRe.isNumber(c)&&c>=0);let l=function(h,A,E){if(h||o(A)){let v=h?JSON.stringify(h,Object.getOwnPropertyNames(h)):`status: ${JSON.stringify(A.status)} ${JSON.stringify(A.statusText)} headers: ${JSON.stringify(A.headers)}`;if(YQt.getInstance().debug("Encountered an error when getting data from cloud storage: "+v),u<c&&i(A,h)){u++;let T=r.getRetryLargeResultSetMaxSleepTime();p=yRe.nextSleepTime(1,T,p);let w=p*1e3;YQt.getInstance().trace("Request will be retried after %d milliseconds",Math.floor(w)),setTimeout(d,w);return}else YQt.getInstance().trace("Request won't be retried"),o(A)?h=e1t.createLargeResultSetError(DVp.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE,A):h=e1t.createNetworkError(DVp.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT,h)}if(A&&YQt.getInstance().trace(`Response headers are: ${JSON.stringify(A.headers)}`),h&&(E=null),yRe.isFunction(a.callback))try{a.callback(h,E)}catch(v){YQt.getInstance().error(`Callback failed with ${v}`)}},d=function(){t.request({method:"GET",url:a.url,headers:a.headers,gzip:!0,appendRequestId:!1,callback:l})};d()}}yRe.inherits(BVp,e2m);LVp.exports=BVp});var FVp=m((GAS,qVp)=>{"use strict";var t1t=Tc(),JQt=oA(),t2m=NVp(),r2m=kVp(),enn=yd();function n2m(r,t,n){enn.getInstance().trace("Creating ConnectionContext object."),JQt.assertInternal(t1t.isObject(r)),JQt.assertInternal(t1t.isObject(t));let i;t1t.exists(n)&&(enn.getInstance().trace("ConnectionContext - validating received config."),JQt.assertInternal(t1t.isObject(n)),JQt.assertInternal(t1t.isObject(n.services)),JQt.assertInternal(t1t.isObject(n.services.sf)),i=n.services.sf),enn.getInstance().debug("ConnectionContext - received data was validated.");let o={sf:new t2m(r,t,i),largeResultSet:new r2m(r,t)};enn.getInstance().debug("ConnectionContext - services were instantiated."),this.getConnectionConfig=function(){return r},this.getServices=function(){return o},this.getConfig=function(){return{services:{sf:o.sf.getConfig()}}},this.getHttpClient=function(){return t}}qVp.exports=n2m});var zVp=m((HAS,UVp)=>{UVp.exports=(function(){function r(i,o){function s(){this.constructor=i}s.prototype=o.prototype,i.prototype=new s}function t(i,o,s,a,u,p){this.message=i,this.expected=o,this.found=s,this.offset=a,this.line=u,this.column=p,this.name="SyntaxError"}r(t,Error);function n(i){var o=arguments.length>1?arguments[1]:{},s={},a={start:Tm},u=Tm,p=[],c=function(){return ME},l=s,d="#",f={type:"literal",value:"#",description:'"#"'},h=void 0,A={type:"any",description:"any character"},E="[",v={type:"literal",value:"[",description:'"["'},T="]",w={type:"literal",value:"]",description:'"]"'},N=function(Ce){D2(c1("ObjectPath",Ce,Nu,Zu))},k=function(Ce){D2(c1("ArrayPath",Ce,Nu,Zu))},L=function(Ce,Ze){return Ce.concat(Ze)},q=function(Ce){return[Ce]},G=function(Ce){return Ce},H=".",V={type:"literal",value:".",description:'"."'},W="=",F={type:"literal",value:"=",description:'"="'},J=function(Ce,Ze){D2(c1("Assign",Ze,Nu,Zu,Ce))},Y=function(Ce){return Ce.join("")},z=function(Ce){return Ce.value},X='"""',Z={type:"literal",value:'"""',description:'"\\"\\"\\""'},re=null,oe=function(Ce){return c1("String",Ce.join(""),Nu,Zu)},ee='"',ce={type:"literal",value:'"',description:'"\\""'},de="'''",pe={type:"literal",value:"'''",description:`"'''"`},le="'",Ne={type:"literal",value:"'",description:`"'"`},Qe=function(Ce){return Ce},Ee=function(Ce){return Ce},_e="\\",tt={type:"literal",value:"\\",description:'"\\\\"'},b=function(){return""},R="e",O={type:"literal",value:"e",description:'"e"'},j="E",Ae={type:"literal",value:"E",description:'"E"'},Te=function(Ce,Ze){return c1("Float",parseFloat(Ce+"e"+Ze),Nu,Zu)},De=function(Ce){return c1("Float",parseFloat(Ce),Nu,Zu)},y="+",I={type:"literal",value:"+",description:'"+"'},P=function(Ce){return Ce.join("")},g="-",_={type:"literal",value:"-",description:'"-"'},M=function(Ce){return"-"+Ce.join("")},K=function(Ce){return c1("Integer",parseInt(Ce,10),Nu,Zu)},st="true",Ie={type:"literal",value:"true",description:'"true"'},He=function(){return c1("Boolean",!0,Nu,Zu)},Xe="false",at={type:"literal",value:"false",description:'"false"'},ke=function(){return c1("Boolean",!1,Nu,Zu)},we=function(){return c1("Array",[],Nu,Zu)},Ge=function(Ce){return c1("Array",Ce?[Ce]:[],Nu,Zu)},dt=function(Ce){return c1("Array",Ce,Nu,Zu)},mt=function(Ce,Ze){return c1("Array",Ce.concat(Ze),Nu,Zu)},Kt=function(Ce){return Ce},Zt=",",Pe={type:"literal",value:",",description:'","'},Be="{",Nt={type:"literal",value:"{",description:'"{"'},It="}",Ft={type:"literal",value:"}",description:'"}"'},Et=function(Ce){return c1("InlineTable",Ce,Nu,Zu)},Bt=function(Ce,Ze){return c1("InlineTableValue",Ze,Nu,Zu,Ce)},lt=function(Ce){return"."+Ce},Xt=function(Ce){return Ce.join("")},me=":",Ve={type:"literal",value:":",description:'":"'},$e=function(Ce){return Ce.join("")},rt="T",bt={type:"literal",value:"T",description:'"T"'},dr="Z",hr={type:"literal",value:"Z",description:'"Z"'},ir=function(Ce,Ze){return c1("Date",new Date(Ce+"T"+Ze+"Z"),Nu,Zu)},Wn=function(Ce,Ze){return c1("Date",new Date(Ce+"T"+Ze),Nu,Zu)},$n=/^[ \t]/,ai={type:"class",value:"[ \\t]",description:"[ \\t]"},Md=`
|
|
984
984
|
`,ni={type:"literal",value:`
|
|
985
985
|
`,description:'"\\n"'},Qo="\r",sd={type:"literal",value:"\r",description:'"\\r"'},wi=/^[0-9a-f]/i,Ro={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},cc=/^[0-9]/,fs={type:"class",value:"[0-9]",description:"[0-9]"},za="_",Jd={type:"literal",value:"_",description:'"_"'},zp=function(){return""},If=/^[A-Za-z0-9_\-]/,$d={type:"class",value:"[A-Za-z0-9_\\-]",description:"[A-Za-z0-9_\\-]"},Nh=function(Ce){return Ce.join("")},Pu='\\"',lc={type:"literal",value:'\\"',description:'"\\\\\\""'},gg=function(){return'"'},O0="\\\\",w1={type:"literal",value:"\\\\",description:'"\\\\\\\\"'},o1=function(){return"\\"},s1="\\b",M1={type:"literal",value:"\\b",description:'"\\\\b"'},$l=function(){return"\b"},ih="\\t",x1={type:"literal",value:"\\t",description:'"\\\\t"'},Rf=function(){return" "},rf="\\n",ad={type:"literal",value:"\\n",description:'"\\\\n"'},pc=function(){return`
|
|
986
986
|
`},N2="\\f",Sm={type:"literal",value:"\\f",description:'"\\\\f"'},xd=function(){return"\f"},SA="\\r",vm={type:"literal",value:"\\r",description:'"\\\\r"'},vA=function(){return"\r"},jg="\\U",oh={type:"literal",value:"\\U",description:'"\\\\U"'},_y=function(Ce){return Cae(Ce.join(""))},a1="\\u",Dh={type:"literal",value:"\\u",description:'"\\\\u"'},Me=0,Ji=0,ct=0,ht={line:1,column:1,seenCR:!1},Pt=0,gr=[],or=0,ar={},qn;if("startRule"in o){if(!(o.startRule in a))throw new Error(`Can't start parsing from rule "`+o.startRule+'".');u=a[o.startRule]}function to(){return i.substring(Ji,Me)}function Il(){return Ji}function Nu(){return TA(Ji).line}function Zu(){return TA(Ji).column}function Of(Ce){throw of(null,[{type:"other",description:Ce}],Ji)}function nf(Ce){throw of(Ce,null,Ji)}function TA(Ce){function Ze(gt,Ut,tr){var _r,un;for(_r=Ut;_r<tr;_r++)un=i.charAt(_r),un===`
|
|
@@ -2092,9 +2092,9 @@ ${"".padEnd(t)}${"^".repeat(n)}`}function Xhc(r){return Rah(m_o,r)}function SG(r
|
|
|
2092
2092
|
\f\u200B`,wordwrap:80},Cch=(r,t,n)=>[...r,...t],z1c=(r,t,n)=>[...t],Sch=(r,t,n)=>r.some(i=>typeof i=="object")?Cch(r,t):z1c(r,t);function vch(r={}){return r=(0,L_o.default)(Ech,r,{arrayMerge:z1c,customMerge:t=>t==="selectors"?Sch:void 0}),r.formatters=Object.assign({},Xuh,bch,r.formatters),r.selectors=D1c(r.selectors,(t=>t.selector)),Tch(r),kuh(r)}function ydr(r,t={},n=void 0){return vch(t)(r,n)}function Tch(r){if(r.tags){let n=Object.entries(r.tags).map(([i,o])=>({...o,selector:i||"*"}));r.selectors.push(...n),r.selectors=D1c(r.selectors,(i=>i.selector))}function t(n,i,o){let s=i.pop();for(let a of i){let u=n[a];u||(u={},n[a]=u),n=u}n[s]=o}if(r.baseElement){let n=r.baseElement;t(r,["baseElements","selectors"],Array.isArray(n)?n:[n])}r.returnDomByDefault!==void 0&&t(r,["baseElements","returnDomByDefault"],r.returnDomByDefault);for(let n of r.selectors)n.format==="anchor"&&YVe(n,["options","noLinkBrackets"])&&t(n,["options","linkBrackets"],!1)}var Q1c=r=>typeof r=="object"&&r instanceof Gw,j1c=r=>{let t=r.issues,n=t[0]?.message||"Unknown error",i=t[0]?.code||"Unknown error";return wq(n,i)};var cL=yt(Mq());var r3o=(r,t,n,i,...o)=>{let s=Ml(),a={...t,area:r},u=c=>{if(typeof c=="object")try{return JSON.stringify(c)}catch(l){return s.error("Could not stringify argument.",{error:l}),""}else return String(c)},p=`${i} ${o.map(u).join(" ")}`;s.log(n,p,a)};var r$=class{valid=!1;failures;originalValue;constructor(t,n){this.originalValue=Z1e(t),this.failures=n}get failureMessage(){return this.failures.map(t=>t.path.length>0?`${t.path}: ${t.message}`:t.message).join(`
|
|
2093
2093
|
`)}},iWe=null,FP=class extends nt{code;result;constructor(t,n,i=400){super(t,typeof n=="string"?n:n?.failureMessage),this.result=typeof n=="string"?void 0:n,this.code=i}statusCode(){return this.code}get validationResult(){return this.result}get failureDetails(){return this.result?`${this.message}: ${this.result.failureMessage}`:this.message}},nWe=class{constructor(t){this.name=t}name;is(t){return this.validate(t).valid}assert(t,n){return this.doAssert(t,!0,n)}verify(t,n){let i=!!(n?.throwOnVerify??!1);return this.doAssert(t,i,n)}doAssert(t,n,i){let{logContext:o,logArea:s,failureLogLevel:a,successLogLevel:u,statusCode:p,errorMessage:c}=i||{},l=this.validate(t),d=i?.additionalValidation?.(t)||{valid:!0},f=d.valid?l:d;if(!f.valid){let h=typeof c=="function"?c(f):c??`Found ${f.failures.length} validation failure(s) for ${this.name}`,A=new FP(h,f,p);if(a!==iWe){let E=t;E&&typeof E=="object"&&(E=Z1e(E)),r3o(s,o,a||"error",A,E)}if(n)throw A;return t}return u&&r3o(s,o,u,`${this.name} validation succeeded`,t),f.value}};var n3o=class extends nWe{constructor(n,i){super(n);this.runtype=i;if(!i)throw new nt(`Missing runtype for ${n} validator. Did you use a circular import?`)}runtype;validate(n){try{let i=this.runtype.validate(n);return i.success?{valid:!0,value:n}:this.createValidationFailedResult(i,n)}catch(i){return Ml().error(`RuntypesValidator: Unable to validate ${this.name} value.
|
|
2094
2094
|
Error: ${i}
|
|
2095
|
-
Value: ${n}`),new r$(n,[{path:"",message:"value triggered unknown runtypes error"}])}}createValidationFailedResult(n,i){let o=[],s=(a,u)=>{for(let[p,c]of Object.entries(u)){let l=a.concat(p);typeof c=="string"?o.push({path:l.join("."),message:c}):s(l,c)}};if(n.code==="TYPE_INCORRECT"||n.code==="CONSTRAINT_FAILED")o.push({path:"",message:n.message});else{let a=n.details;a&&s([],a)}return new r$(i,o)}},TM=(r,t)=>new n3o(r,t);var Jlh=r=>r.code==="unrecognized_keys"?r.keys.length:r.code==="invalid_type"&&r.received==="undefined"&&r.message==="Required"?1:r.code==="invalid_literal"?10:0,$lh=r=>Hpo(r.issues.map(t=>Jlh(t))),i3o=class extends nWe{constructor(n,i,o){super(n);this.zodType=i;this.errorMappers=o;if(!i)throw new nt(`Missing Zod type for ${n} validator. Did you use a circular import?`)}zodType;errorMappers;convertZodError=n=>{let i=[];for(let o of n.issues)if(o.code==="invalid_union"){let s=Upo(o.unionErrors,a=>$lh(a));s&&i.push(...this.convertZodError(s))}else o.code==="invalid_type"&&o.received==="undefined"&&o.message==="Required"&&o.path.length===0?i.push({path:"",message:`Expected ${o.expected}, received undefined`}):i.push({path:o.path.join("."),message:o.message});return i};validate(n){try{let i=this.zodType.safeParse(n);if(i.success)return{valid:!0,value:i.data};let o=this.errorMappers.reduce((a,u)=>u(a,n),i.error),s=this.convertZodError(o);return new r$(n,s)}catch(i){let o=`ZodValidator: Unable to validate ${this.name} value error:${i} value:${n}`;return i instanceof B.ZodError&&(o=`${o} ${i.flatten()} ${i.issues}`),Ml().error(o),new r$(n,[{path:"",message:"value triggered unknown Zod error"}])}}},Mr=(r,t,n=[])=>new i3o(r,t,n);var Xlh=["private_key","private_key_id","client_email"],o3o=r=>{for(let t of Xlh)if(typeof r[t]!="string"||!String(r[t]).trim())return`The file is not a valid Google Service Account key. Missing required field: ${t}.`};var jdr=cL.Record({errorDetail:cL.String,errorString:cL.String}),Zlh=cL.Record({error:jdr,runDetails:cL.Record({compiledSQL:cL.String}).nullable().optional(),validationDetails:cL.Record({id:cL.String,type:cL.String,value:cL.Unknown}).optional()}),s3o=TM("TRunErrorContents",jdr),a3o=TM("TRunError",Zlh),Ome=r=>{try{return a3o.is(r)}catch(t){if(t instanceof TypeError)return!1;throw t}},jgc=r=>{if(typeof r.statusCode!="number")return!1;try{return s3o.is(r.error)}catch{return!1}},oWe=(r,t,n=!1)=>{let i=r.error?.errorDetail??"",o=r.error?.errorString??"",s=n?i:i.toLowerCase(),a=n?o:o.toLowerCase(),u=n?t:t.toLowerCase();return s.includes(u)||a.includes(u)};var Ggc=Je("RUNNER_BACKEND"),Hgc=Je("ERROR_OPERATIONS");var Vgc="Failed to parse runtime parameters";var Wgc=r=>{let t;if(r instanceof Error)t=r;else{let i=r?.error?.errorString||"Something went wrong";t=new Error(i)}return t},sWe=r=>{if(r instanceof Error)return r.message?r.message:(Hgc.error("instance of Error did not have a message property. original error: ",r),"Unknown error");{let t=r;return!t.error?.errorString&&!t.error?.errorDetail?(Hgc.error("instance of TRunError did not have a errorString or errorDetail property. original error: ",r),"Unknown error"):t.error.errorString||t.error.errorDetail}},u3o=(r,t)=>({errorString:r,errorDetail:t}),wq=(r,t,n,i)=>({error:u3o(r,t),...!!n&&{runDetails:n},...!!i&&{validationDetails:i}}),eph=r=>r instanceof Error,tph=r=>{if(r instanceof nt)return r.toTRunError();let t=r.message,n=r.stack||r.name&&r.message&&`${r.name}: ${r.message}`||"";return wq(t,n)},rph=r=>{let t=r.message,n=r.code;return wq(t,n)},c3o=r=>{let t=r.response?.data,n=t?.error,i="(unknown URL)",o=t?t.message:void 0,s=r?.config?.url||r.response?.config.url,a=r?.config?.baseURL||r.response?.config.baseURL;if(s){let l;if(s.startsWith("http")?l=s:a&&(l=a+s),l)try{let d=new URL(l);i=d.origin+d.pathname}catch{i="(invalid URL)"}}let u=n?.errorString||n?.message||o||r.message||`${r}`,p=`Axios Error ${r?.config?.method} ${i} ${r?.response?.status||"(no status)"}: ${n?.errorDetail||r.stack||n?.message||r.message||r}, code=${r.response?.status||r.code||"unknown"}`,c=n?.runDetails?.compiledSQL?{compiledSQL:n.runDetails.compiledSQL}:null;return wq(u,p,c)},nph=r=>!!(typeof r=="object"&&r&&"error"in r),aWe=r=>{try{return a3o.is(r)}catch{return!1}},
|
|
2095
|
+
Value: ${n}`),new r$(n,[{path:"",message:"value triggered unknown runtypes error"}])}}createValidationFailedResult(n,i){let o=[],s=(a,u)=>{for(let[p,c]of Object.entries(u)){let l=a.concat(p);typeof c=="string"?o.push({path:l.join("."),message:c}):s(l,c)}};if(n.code==="TYPE_INCORRECT"||n.code==="CONSTRAINT_FAILED")o.push({path:"",message:n.message});else{let a=n.details;a&&s([],a)}return new r$(i,o)}},TM=(r,t)=>new n3o(r,t);var Jlh=r=>r.code==="unrecognized_keys"?r.keys.length:r.code==="invalid_type"&&r.received==="undefined"&&r.message==="Required"?1:r.code==="invalid_literal"?10:0,$lh=r=>Hpo(r.issues.map(t=>Jlh(t))),i3o=class extends nWe{constructor(n,i,o){super(n);this.zodType=i;this.errorMappers=o;if(!i)throw new nt(`Missing Zod type for ${n} validator. Did you use a circular import?`)}zodType;errorMappers;convertZodError=n=>{let i=[];for(let o of n.issues)if(o.code==="invalid_union"){let s=Upo(o.unionErrors,a=>$lh(a));s&&i.push(...this.convertZodError(s))}else o.code==="invalid_type"&&o.received==="undefined"&&o.message==="Required"&&o.path.length===0?i.push({path:"",message:`Expected ${o.expected}, received undefined`}):i.push({path:o.path.join("."),message:o.message});return i};validate(n){try{let i=this.zodType.safeParse(n);if(i.success)return{valid:!0,value:i.data};let o=this.errorMappers.reduce((a,u)=>u(a,n),i.error),s=this.convertZodError(o);return new r$(n,s)}catch(i){let o=`ZodValidator: Unable to validate ${this.name} value error:${i} value:${n}`;return i instanceof B.ZodError&&(o=`${o} ${i.flatten()} ${i.issues}`),Ml().error(o),new r$(n,[{path:"",message:"value triggered unknown Zod error"}])}}},Mr=(r,t,n=[])=>new i3o(r,t,n);var Xlh=["private_key","private_key_id","client_email"],o3o=r=>{for(let t of Xlh)if(typeof r[t]!="string"||!String(r[t]).trim())return`The file is not a valid Google Service Account key. Missing required field: ${t}.`};var jdr=cL.Record({errorDetail:cL.String,errorString:cL.String}),Zlh=cL.Record({error:jdr,runDetails:cL.Record({compiledSQL:cL.String}).nullable().optional(),validationDetails:cL.Record({id:cL.String,type:cL.String,value:cL.Unknown}).optional()}),s3o=TM("TRunErrorContents",jdr),a3o=TM("TRunError",Zlh),Ome=r=>{try{return a3o.is(r)}catch(t){if(t instanceof TypeError)return!1;throw t}},jgc=r=>{if(typeof r.statusCode!="number")return!1;try{return s3o.is(r.error)}catch{return!1}},oWe=(r,t,n=!1)=>{let i=r.error?.errorDetail??"",o=r.error?.errorString??"",s=n?i:i.toLowerCase(),a=n?o:o.toLowerCase(),u=n?t:t.toLowerCase();return s.includes(u)||a.includes(u)};var Ggc=Je("RUNNER_BACKEND"),Hgc=Je("ERROR_OPERATIONS");var Vgc="Failed to parse runtime parameters";var Wgc=r=>{let t;if(r instanceof Error)t=r;else{let i=r?.error?.errorString||"Something went wrong";t=new Error(i)}return t},sWe=r=>{if(r instanceof Error)return r.message?r.message:(Hgc.error("instance of Error did not have a message property. original error: ",r),"Unknown error");{let t=r;return!t.error?.errorString&&!t.error?.errorDetail?(Hgc.error("instance of TRunError did not have a errorString or errorDetail property. original error: ",r),"Unknown error"):t.error.errorString||t.error.errorDetail}},u3o=(r,t)=>({errorString:r,errorDetail:t}),wq=(r,t,n,i)=>({error:u3o(r,t),...!!n&&{runDetails:n},...!!i&&{validationDetails:i}}),eph=r=>r instanceof Error,tph=r=>{if(r instanceof nt)return r.toTRunError();let t=r.message,n=r.stack||r.name&&r.message&&`${r.name}: ${r.message}`||"";return wq(t,n)},rph=r=>{let t=r.message,n=r.code;return wq(t,n)},c3o=r=>{let t=r.response?.data,n=t?.error,i="(unknown URL)",o=t?t.message:void 0,s=r?.config?.url||r.response?.config.url,a=r?.config?.baseURL||r.response?.config.baseURL;if(s){let l;if(s.startsWith("http")?l=s:a&&(l=a+s),l)try{let d=new URL(l);i=d.origin+d.pathname}catch{i="(invalid URL)"}}let u=n?.errorString||n?.message||o||r.message||`${r}`,p=`Axios Error ${r?.config?.method} ${i} ${r?.response?.status||"(no status)"}: ${n?.errorDetail||r.stack||n?.message||r.message||r}, code=${r.response?.status||r.code||"unknown"}`,c=n?.runDetails?.compiledSQL?{compiledSQL:n.runDetails.compiledSQL}:null;return wq(u,p,c)},nph=r=>!!(typeof r=="object"&&r&&"error"in r),aWe=r=>{try{return a3o.is(r)}catch{return!1}},aa=(r,t=!1)=>{if(typeof r=="object"&&r){if(aWe(r))return r;if(LE(r))return r.toTRunError();if(N1(r))return c3o(r);if(UXt(r))return rph(r);if(Q1c(r))return j1c(r);if(eph(r))return tph(r);if(nph(r)&&r.error)return aa(r.error,t);if(s3o.is(r))return wq(r.errorString,r.errorDetail);t||Ggc.assert("CreateTRunError received a non-error object",r,new Error().stack)}else{if(typeof r=="string")return r.includes("html>")?wq("Coalesce was served HTML possibly indicating a service failure",ydr(r)):wq(r,r);t||Ggc.assert("CreateTRunError received error of unknown shape: ",r,new Error().stack)}return wq("","")};var Gdr=r=>{try{let t=r instanceof Error?r.stack:"<no stack>",{error:{errorDetail:n,errorString:i}}=aa(r);return i+`
|
|
2096
2096
|
`+n+`
|
|
2097
|
-
`+t}catch{return"<failed to get stack>"}},yg=(r,t="")=>{let n=
|
|
2097
|
+
`+t}catch{return"<failed to get stack>"}},yg=(r,t="")=>{let n=aa(r);return new nt(t+n.error.errorString,n.error.errorDetail)};var sph;var Hdr=Je("COMMON");function wme(r,t,n){return kpo(r,t)?DEt(r,t):n}var Vdr=(r,t,n)=>({statusCode:r,error:{errorString:t,errorDetail:n},toString:()=>`${t} DETAIL:${n} STATUS CODE:${r}`});var BR=r=>r.replace(/[^a-zA-Z0-9_-]+/g,"");var Kgc=()=>{let r=new Error().stack;if(r)return r.split(`
|
|
2098
2098
|
`).slice(3)},Bm=(r,t,n,...i)=>hh(r,t,{},n,...i),hh=(r,t,n,i,...o)=>{let s=Je(r);if(!t){let a=`orgID: ${sph}, ${i||"assertion failed"}`;s.assertContext(n,a,...o,`
|
|
2099
2099
|
Stack: ${Kgc()?.join(`
|
|
2100
2100
|
`)}`)}};function pd(r,t,n,i={},...o){if(!r){let s=Je(n),a=`ASSERTION FAILED: ${t}`;throw s.assertContext(i,a,...o),new nt(a)}}var Ygc=(r,t,n,i,o={},...s)=>(pd(t(r),n,i,o,...s),r),l3o=r=>r.length!==new Set(r).size;var dce=async(r,t)=>{try{let n=new aL(t);return await Promise.all(r.map(i=>n.runExclusive(i)))}catch(n){throw Hdr.error("failed to complete barrel",n),n}},aph=async(r,t)=>{let n=new aL(t);return await Promise.allSettled(r.map(i=>n.runExclusive(i)))},Jgc=async(r,t,n)=>{let i=await aph(r,t),o=i.filter(s=>s.status==="rejected").map(s=>s.reason instanceof nt?s.reason:yg(s.reason));if(o.length)throw new nt(n+`:
|
|
@@ -2129,7 +2129,7 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
2129
2129
|
`)+`
|
|
2130
2130
|
)`}copy(t,n){let i=new r;return i.comparator=this.comparator,i.keyedMap=t,i.sortedSet=n,i}};var w1r=class{constructor(){this.changeMap=new ky(Bo.comparator)}track(t){let n=t.doc.key,i=this.changeMap.get(n);if(!i){this.changeMap=this.changeMap.insert(n,t);return}t.type!==0&&i.type===3?this.changeMap=this.changeMap.insert(n,t):t.type===3&&i.type!==1?this.changeMap=this.changeMap.insert(n,{type:i.type,doc:t.doc}):t.type===2&&i.type===2?this.changeMap=this.changeMap.insert(n,{type:2,doc:t.doc}):t.type===2&&i.type===0?this.changeMap=this.changeMap.insert(n,{type:0,doc:t.doc}):t.type===1&&i.type===0?this.changeMap=this.changeMap.remove(n):t.type===1&&i.type===2?this.changeMap=this.changeMap.insert(n,{type:1,doc:i.doc}):t.type===0&&i.type===1?this.changeMap=this.changeMap.insert(n,{type:2,doc:t.doc}):Rs()}getChanges(){let t=[];return this.changeMap.inorderTraversal((n,i)=>{t.push(i)}),t}},GKe=class r{constructor(t,n,i,o,s,a,u,p,c){this.query=t,this.docs=n,this.oldDocs=i,this.docChanges=o,this.mutatedKeys=s,this.fromCache=a,this.syncStateChanged=u,this.excludesMetadataChanges=p,this.hasCachedResults=c}static fromInitialDocuments(t,n,i,o,s){let a=[];return n.forEach(u=>{a.push({type:0,doc:u})}),new r(t,n,O1r.emptySet(n),a,i,o,!0,!1,s)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(t){if(this.fromCache!==t.fromCache||this.hasCachedResults!==t.hasCachedResults||this.syncStateChanged!==t.syncStateChanged||!this.mutatedKeys.isEqual(t.mutatedKeys)||!J_t(this.query,t.query)||!this.docs.isEqual(t.docs)||!this.oldDocs.isEqual(t.oldDocs))return!1;let n=this.docChanges,i=t.docChanges;if(n.length!==i.length)return!1;for(let o=0;o<n.length;o++)if(n[o].type!==i[o].type||!n[o].doc.isEqual(i[o].doc))return!1;return!0}};var pxo=class{constructor(){this.viewSnap=void 0,this.listeners=[]}hasRemoteListeners(){return this.listeners.some(t=>t.listensToRemoteStore())}};function t_h(){return new dxo}var dxo=class{constructor(){this.queries=new B$(t=>kSc(t),J_t),this.onlineState="Unknown",this.snapshotsInSyncListeners=new Set}};async function dPo(r,t){let n=Go(r),i=3,o=t.query,s=n.queries.get(o);s?!s.hasRemoteListeners()&&t.listensToRemoteStore()&&(i=2):(s=new pxo,i=t.listensToRemoteStore()?0:1);try{switch(i){case 0:s.viewSnap=await n.onListen(o,!0);break;case 1:s.viewSnap=await n.onListen(o,!1);break;case 2:await n.onFirstRemoteStoreListen(o);break;default:break}}catch(a){let u=oYe(a,`Initialization of query '${vKe(t.query)}' failed`);t.onError(u);return}n.queries.set(o,s),s.listeners.push(t),t.applyOnlineStateChange(n.onlineState),s.viewSnap&&t.onViewSnapshot(s.viewSnap)&&hPo(n)}async function fPo(r,t){let n=Go(r),i=t.query,o=3,s=n.queries.get(i);if(s){let a=s.listeners.indexOf(t);a>=0&&(s.listeners.splice(a,1),s.listeners.length===0?o=t.listensToRemoteStore()?0:1:!s.hasRemoteListeners()&&t.listensToRemoteStore()&&(o=2))}switch(o){case 0:return n.queries.delete(i),n.onUnlisten(i,!0);case 1:return n.queries.delete(i),n.onUnlisten(i,!1);case 2:return n.onLastRemoteStoreUnlisten(i);default:return}}function r_h(r,t){let n=Go(r),i=!1;for(let o of t){let s=o.query,a=n.queries.get(s);if(a){for(let u of a.listeners)u.onViewSnapshot(o)&&(i=!0);a.viewSnap=o}}i&&hPo(n)}function n_h(r,t,n){let i=Go(r),o=i.queries.get(t);if(o)for(let s of o.listeners)s.onError(n);i.queries.delete(t)}function i_h(r,t){let n=Go(r);n.onlineState=t;let i=!1;n.queries.forEach((o,s)=>{for(let a of s.listeners)a.applyOnlineStateChange(t)&&(i=!0)}),i&&hPo(n)}function o_h(r,t){Go(r).snapshotsInSyncListeners.add(t),t.next()}function s_h(r,t){Go(r).snapshotsInSyncListeners.delete(t)}function hPo(r){r.snapshotsInSyncListeners.forEach(t=>{t.next()})}var fxo;(function(r){r.Default="default",r.Cache="cache"})(fxo||(fxo={}));var U_t=class{constructor(t,n,i){this.query=t,this.queryObserver=n,this.raisedInitialEvent=!1,this.snap=null,this.onlineState="Unknown",this.options=i||{}}onViewSnapshot(t){if(!this.options.includeMetadataChanges){let i=[];for(let o of t.docChanges)o.type!==3&&i.push(o);t=new GKe(t.query,t.docs,t.oldDocs,i,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0,t.hasCachedResults)}let n=!1;return this.raisedInitialEvent?this.shouldRaiseEvent(t)&&(this.queryObserver.next(t),n=!0):this.shouldRaiseInitialEvent(t,this.onlineState)&&(this.raiseInitialEvent(t),n=!0),this.snap=t,n}onError(t){this.queryObserver.error(t)}applyOnlineStateChange(t){this.onlineState=t;let n=!1;return this.snap&&!this.raisedInitialEvent&&this.shouldRaiseInitialEvent(this.snap,t)&&(this.raiseInitialEvent(this.snap),n=!0),n}shouldRaiseInitialEvent(t,n){if(!t.fromCache||!this.listensToRemoteStore())return!0;let i=n!=="Offline";return this.options.waitForSyncWhenOnline&&i?!1:!t.docs.isEmpty()||t.hasCachedResults||n==="Offline"}shouldRaiseEvent(t){if(t.docChanges.length>0)return!0;let n=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return t.syncStateChanged||n?this.options.includeMetadataChanges===!0:!1}raiseInitialEvent(t){t=GKe.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache,t.hasCachedResults),this.raisedInitialEvent=!0,this.queryObserver.next(t)}listensToRemoteStore(){return this.options.source!==fxo.Cache}};var hxo=class r{constructor(t,n,i,o){this.targetId=t,this.fromCache=n,this.addedKeys=i,this.removedKeys=o}static fromSnapshot(t,n){let i=rp(),o=rp();for(let s of n.docChanges)switch(s.type){case 0:i=i.add(s.doc.key);break;case 1:o=o.add(s.doc.key);break}return new r(t,n.fromCache,i,o)}};var M1r=class{constructor(t){this.serializer=t}toDocumentKey(t){return P$(this.serializer,t)}toMutableDocument(t){return t.metadata.exists?avc(this.serializer,t.document,!1):_v.newNoDocument(this.toDocumentKey(t.metadata.name),this.toSnapshotVersion(t.metadata.readTime))}toSnapshotVersion(t){return uS(t)}},gxo=class{constructor(t,n,i){this.bundleMetadata=t,this.localStore=n,this.serializer=i,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=zvc(t)}addSizedElement(t){this.progress.bytesLoaded+=t.byteLength;let n=this.progress.documentsLoaded;if(t.payload.namedQuery)this.queries.push(t.payload.namedQuery);else if(t.payload.documentMetadata){this.documents.push({metadata:t.payload.documentMetadata}),t.payload.documentMetadata.exists||++n;let i=Nf.fromString(t.payload.documentMetadata.name);this.collectionGroups.add(i.get(i.length-2))}else t.payload.document&&(this.documents[this.documents.length-1].document=t.payload.document,++n);return n!==this.progress.documentsLoaded?(this.progress.documentsLoaded=n,Object.assign({},this.progress)):null}getQueryDocumentMapping(t){let n=new Map,i=new M1r(this.serializer);for(let o of t)if(o.metadata.queries){let s=i.toDocumentKey(o.metadata.name);for(let a of o.metadata.queries){let u=(n.get(a)||rp()).add(s);n.set(a,u)}}return n}async complete(){let t=await Zvh(this.localStore,new M1r(this.serializer),this.documents,this.bundleMetadata.id),n=this.getQueryDocumentMapping(this.documents);for(let i of this.queries)await nTh(this.localStore,i,n.get(i.name));return this.progress.taskState="Success",{progress:this.progress,changedCollectionGroups:this.collectionGroups,changedDocs:t}}};function zvc(r){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:r.totalDocuments,totalBytes:r.totalBytes}}function a_h(r){return{taskState:"Success",documentsLoaded:r.totalDocuments,bytesLoaded:r.totalBytes,totalDocuments:r.totalDocuments,totalBytes:r.totalBytes}}var x1r=class{constructor(t){this.key=t}},P1r=class{constructor(t){this.key=t}},N1r=class{constructor(t,n){this.query=t,this._syncedDocuments=n,this.syncState=null,this.hasCachedResults=!1,this.current=!1,this.limboDocuments=rp(),this.mutatedKeys=rp(),this.docComparator=FSc(t),this.documentSet=new O1r(this.docComparator)}get syncedDocuments(){return this._syncedDocuments}computeDocChanges(t,n){let i=n?n.changeSet:new w1r,o=n?n.documentSet:this.documentSet,s=n?n.mutatedKeys:this.mutatedKeys,a=o,u=!1,p=this.query.limitType==="F"&&o.size===this.query.limit?o.last():null,c=this.query.limitType==="L"&&o.size===this.query.limit?o.first():null;if(t.inorderTraversal((l,d)=>{let f=o.get(l),h=$_t(this.query,d)?d:null,A=f?this.mutatedKeys.has(f.key):!1,E=h?h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations:!1,v=!1;f&&h?f.data.isEqual(h.data)?A!==E&&(i.track({type:3,doc:h}),v=!0):this.shouldWaitForSyncedDocument(f,h)||(i.track({type:2,doc:h}),v=!0,(p&&this.docComparator(h,p)>0||c&&this.docComparator(h,c)<0)&&(u=!0)):!f&&h?(i.track({type:0,doc:h}),v=!0):f&&!h&&(i.track({type:1,doc:f}),v=!0,(p||c)&&(u=!0)),v&&(h?(a=a.add(h),E?s=s.add(l):s=s.delete(l)):(a=a.delete(l),s=s.delete(l)))}),this.query.limit!==null)for(;a.size>this.query.limit;){let l=this.query.limitType==="F"?a.last():a.first();a=a.delete(l.key),s=s.delete(l.key),i.track({type:1,doc:l})}return{documentSet:a,changeSet:i,needsRefill:u,mutatedKeys:s}}shouldWaitForSyncedDocument(t,n){return t.hasLocalMutations&&n.hasCommittedMutations&&!n.hasLocalMutations}applyChanges(t,n,i,o){let s=this.documentSet;this.documentSet=t.documentSet,this.mutatedKeys=t.mutatedKeys;let a=t.changeSet.getChanges();a.sort((d,f)=>u_h(d.type,f.type)||this.docComparator(d.doc,f.doc)),this.applyTargetChange(i),o=o??!1;let u=n&&!o?this.updateLimboDocuments():[],c=this.limboDocuments.size===0&&this.current&&!o?1:0,l=c!==this.syncState;return this.syncState=c,a.length===0&&!l?{limboChanges:u}:{snapshot:new GKe(this.query,t.documentSet,s,a,t.mutatedKeys,c===0,l,!1,i?i.resumeToken.approximateByteSize()>0:!1),limboChanges:u}}applyOnlineStateChange(t){return this.current&&t==="Offline"?(this.current=!1,this.applyChanges({documentSet:this.documentSet,changeSet:new w1r,mutatedKeys:this.mutatedKeys,needsRefill:!1},!1)):{limboChanges:[]}}shouldBeInLimbo(t){return!(this._syncedDocuments.has(t)||!this.documentSet.has(t)||this.documentSet.get(t).hasLocalMutations)}applyTargetChange(t){t&&(t.addedDocuments.forEach(n=>this._syncedDocuments=this._syncedDocuments.add(n)),t.modifiedDocuments.forEach(n=>{}),t.removedDocuments.forEach(n=>this._syncedDocuments=this._syncedDocuments.delete(n)),this.current=t.current)}updateLimboDocuments(){if(!this.current)return[];let t=this.limboDocuments;this.limboDocuments=rp(),this.documentSet.forEach(i=>{this.shouldBeInLimbo(i.key)&&(this.limboDocuments=this.limboDocuments.add(i.key))});let n=[];return t.forEach(i=>{this.limboDocuments.has(i)||n.push(new P1r(i))}),this.limboDocuments.forEach(i=>{t.has(i)||n.push(new x1r(i))}),n}synchronizeWithPersistedState(t){this._syncedDocuments=t.remoteKeys,this.limboDocuments=rp();let n=this.computeDocChanges(t.documents);return this.applyChanges(n,!0)}computeInitialSnapshot(){return GKe.fromInitialDocuments(this.query,this.documentSet,this.mutatedKeys,this.syncState===0,this.hasCachedResults)}};function u_h(r,t){let n=i=>{switch(i){case 0:return 1;case 2:return 2;case 3:return 2;case 1:return 0;default:return Rs()}};return n(r)-n(t)}var wye="SyncEngine",Axo=class{constructor(t,n,i){this.query=t,this.targetId=n,this.view=i}},mxo=class{constructor(t){this.key=t,this.receivedDocument=!1}},yxo=class{constructor(t,n,i,o,s,a){this.localStore=t,this.remoteStore=n,this.eventManager=i,this.sharedClientState=o,this.currentUser=s,this.maxConcurrentLimboResolutions=a,this.syncEngineListener={},this.queryViewsByQuery=new B$(u=>kSc(u),J_t),this.queriesByTarget=new Map,this.enqueuedLimboResolutions=new Set,this.activeLimboTargetsByKey=new ky(Bo.comparator),this.activeLimboResolutionsByTarget=new Map,this.limboDocumentRefs=new L_t,this.mutationUserCallbacks={},this.pendingWritesCallbacks=new Map,this.limboTargetIdGenerator=zKe.forSyncEngine(),this.onlineState="Unknown",this._isPrimaryClient=void 0}get isPrimaryClient(){return this._isPrimaryClient===!0}};function c_h(r,t,n,i,o,s,a){let u=new yxo(r,t,n,i,o,s);return a&&(u._isPrimaryClient=!0),u}async function l_h(r,t,n=!0){let i=egr(r),o,s=i.queryViewsByQuery.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),o=s.view.computeInitialSnapshot()):o=await Qvc(i,t,n,!0),o}async function p_h(r,t){let n=egr(r);await Qvc(n,t,!0,!1)}async function Qvc(r,t,n,i){let o=await QKe(r.localStore,WP(t)),s=o.targetId,a=n?r.sharedClientState.addLocalQueryTarget(s):"not-current",u;return i&&(u=await gPo(r,t,s,a==="current",o.resumeToken)),r.isPrimaryClient&&n&&Z1r(r.remoteStore,o),u}async function gPo(r,t,n,i,o){r.applyDocChanges=(d,f,h)=>S_h(r,d,f,h);let s=await X1r(r.localStore,t,!0),a=new N1r(t,s.remoteKeys),u=a.computeDocChanges(s.documents),p=P_t.createSynthesizedTargetChangeForCurrentChange(n,i&&r.onlineState!=="Offline",o),c=a.applyChanges(u,r.isPrimaryClient,p);yPo(r,n,c.limboChanges);let l=new Axo(t,n,a);return r.queryViewsByQuery.set(t,l),r.queriesByTarget.has(n)?r.queriesByTarget.get(n).push(t):r.queriesByTarget.set(n,[t]),c.snapshot}async function d_h(r,t,n){let i=Go(r),o=i.queryViewsByQuery.get(t),s=i.queriesByTarget.get(o.targetId);if(s.length>1){i.queriesByTarget.set(o.targetId,s.filter(a=>!J_t(a,t))),i.queryViewsByQuery.delete(t);return}i.isPrimaryClient?(i.sharedClientState.removeLocalQueryTarget(o.targetId),i.sharedClientState.isActiveQueryTarget(o.targetId)||await jKe(i.localStore,o.targetId,!1).then(()=>{i.sharedClientState.clearQueryState(o.targetId),n&&rYe(i.remoteStore,o.targetId),HKe(i,o.targetId)}).catch(_ye)):(HKe(i,o.targetId),await jKe(i.localStore,o.targetId,!0))}async function f_h(r,t){let n=Go(r),i=n.queryViewsByQuery.get(t),o=n.queriesByTarget.get(i.targetId);n.isPrimaryClient&&o.length===1&&(n.sharedClientState.removeLocalQueryTarget(i.targetId),rYe(n.remoteStore,i.targetId))}async function h_h(r,t,n){let i=EPo(r);try{let o=await kvh(i.localStore,t);i.sharedClientState.addPendingMutation(o.batchId),E_h(i,o.batchId,n),await Pce(i,o.changes),await nYe(i.remoteStore)}catch(o){let s=oYe(o,"Failed to persist write");n.reject(s)}}async function jvc(r,t){let n=Go(r);try{let i=await Qvh(n.localStore,t);t.targetChanges.forEach((o,s)=>{let a=n.activeLimboResolutionsByTarget.get(s);a&&(Ua(o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size<=1),o.addedDocuments.size>0?a.receivedDocument=!0:o.modifiedDocuments.size>0?Ua(a.receivedDocument):o.removedDocuments.size>0&&(Ua(a.receivedDocument),a.receivedDocument=!1))}),await Pce(n,i,t)}catch(i){await _ye(i)}}function UCc(r,t,n){let i=Go(r);if(i.isPrimaryClient&&n===0||!i.isPrimaryClient&&n===1){let o=[];i.queryViewsByQuery.forEach((s,a)=>{let u=a.view.applyOnlineStateChange(t);u.snapshot&&o.push(u.snapshot)}),i_h(i.eventManager,t),o.length&&i.syncEngineListener.onWatchChange(o),i.onlineState=t,i.isPrimaryClient&&i.sharedClientState.setOnlineState(t)}}async function g_h(r,t,n){let i=Go(r);i.sharedClientState.updateQueryState(t,"rejected",n);let o=i.activeLimboResolutionsByTarget.get(t),s=o&&o.key;if(s){let a=new ky(Bo.comparator);a=a.insert(s,_v.newNoDocument(s,nu.min()));let u=rp().add(s),p=new x_t(nu.min(),new Map,new ky(Bl),a,u);await jvc(i,p),i.activeLimboTargetsByKey=i.activeLimboTargetsByKey.remove(s),i.activeLimboResolutionsByTarget.delete(t),bPo(i)}else await jKe(i.localStore,t,!1).then(()=>HKe(i,t,n)).catch(_ye)}async function A_h(r,t){let n=Go(r),i=t.batch.batchId;try{let o=await qvh(n.localStore,t);mPo(n,i,null),APo(n,i),n.sharedClientState.updateMutationState(i,"acknowledged"),await Pce(n,o)}catch(o){await _ye(o)}}async function m_h(r,t,n){let i=Go(r);try{let o=await Uvh(i.localStore,t);mPo(i,t,n),APo(i,t),i.sharedClientState.updateMutationState(t,"rejected",n),await Pce(i,o)}catch(o){await _ye(o)}}async function y_h(r,t){let n=Go(r);Rye(n.remoteStore)||Bi(wye,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{let i=await zvh(n.localStore);if(i===fye){t.resolve();return}let o=n.pendingWritesCallbacks.get(i)||[];o.push(t),n.pendingWritesCallbacks.set(i,o)}catch(i){let o=oYe(i,"Initialization of waitForPendingWrites() operation failed");t.reject(o)}}function APo(r,t){(r.pendingWritesCallbacks.get(t)||[]).forEach(n=>{n.resolve()}),r.pendingWritesCallbacks.delete(t)}function b_h(r,t){r.pendingWritesCallbacks.forEach(n=>{n.forEach(i=>{i.reject(new oi(Zr.CANCELLED,t))})}),r.pendingWritesCallbacks.clear()}function E_h(r,t,n){let i=r.mutationUserCallbacks[r.currentUser.toKey()];i||(i=new ky(Bl)),i=i.insert(t,n),r.mutationUserCallbacks[r.currentUser.toKey()]=i}function mPo(r,t,n){let i=Go(r),o=i.mutationUserCallbacks[i.currentUser.toKey()];if(o){let s=o.get(t);s&&(n?s.reject(n):s.resolve(),o=o.remove(t)),i.mutationUserCallbacks[i.currentUser.toKey()]=o}}function HKe(r,t,n=null){r.sharedClientState.removeLocalQueryTarget(t);for(let i of r.queriesByTarget.get(t))r.queryViewsByQuery.delete(i),n&&r.syncEngineListener.onWatchError(i,n);r.queriesByTarget.delete(t),r.isPrimaryClient&&r.limboDocumentRefs.removeReferencesForId(t).forEach(o=>{r.limboDocumentRefs.containsKey(o)||Gvc(r,o)})}function Gvc(r,t){r.enqueuedLimboResolutions.delete(t.path.canonicalString());let n=r.activeLimboTargetsByKey.get(t);n!==null&&(rYe(r.remoteStore,n),r.activeLimboTargetsByKey=r.activeLimboTargetsByKey.remove(t),r.activeLimboResolutionsByTarget.delete(n),bPo(r))}function yPo(r,t,n){for(let i of n)i instanceof x1r?(r.limboDocumentRefs.addReference(i.key,t),C_h(r,i)):i instanceof P1r?(Bi(wye,"Document no longer in limbo: "+i.key),r.limboDocumentRefs.removeReference(i.key,t),r.limboDocumentRefs.containsKey(i.key)||Gvc(r,i.key)):Rs()}function C_h(r,t){let n=t.key,i=n.path.canonicalString();!r.activeLimboTargetsByKey.get(n)&&!r.enqueuedLimboResolutions.has(i)&&(Bi(wye,"New document in limbo: "+n),r.enqueuedLimboResolutions.add(i),bPo(r))}function bPo(r){for(;r.enqueuedLimboResolutions.size>0&&r.activeLimboTargetsByKey.size<r.maxConcurrentLimboResolutions;){let t=r.enqueuedLimboResolutions.values().next().value;r.enqueuedLimboResolutions.delete(t);let n=new Bo(Nf.fromString(t)),i=r.limboTargetIdGenerator.next();r.activeLimboResolutionsByTarget.set(i,new mxo(n)),r.activeLimboTargetsByKey=r.activeLimboTargetsByKey.insert(n,i),Z1r(r.remoteStore,new UKe(WP(eYe(n.path)),i,"TargetPurposeLimboResolution",NM.INVALID))}}async function Pce(r,t,n){let i=Go(r),o=[],s=[],a=[];i.queryViewsByQuery.isEmpty()||(i.queryViewsByQuery.forEach((u,p)=>{a.push(i.applyDocChanges(p,t,n).then(c=>{if((c||n)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(p.targetId,c?.fromCache?"not-current":"current"),c){o.push(c);let l=hxo.fromSnapshot(p.targetId,c);s.push(l)}}))}),await Promise.all(a),i.syncEngineListener.onWatchChange(o),await Gvh(i.localStore,s))}async function S_h(r,t,n,i){let o=t.view.computeDocChanges(n);o.needsRefill&&(o=await X1r(r.localStore,t.query,!1).then(({documents:p})=>t.view.computeDocChanges(p,o)));let s=i&&i.targetChanges.get(t.targetId),a=i&&i.targetMismatches.get(t.targetId)!=null,u=t.view.applyChanges(o,r.isPrimaryClient,s,a);return yPo(r,t.targetId,u.limboChanges),u.snapshot}async function v_h(r,t){let n=Go(r);if(!n.currentUser.isEqual(t)){Bi(wye,"User change. New user:",t.toKey());let o=await _vc(n.localStore,t);n.currentUser=t,b_h(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(t,o.removedBatchIds,o.addedBatchIds),await Pce(n,o.affectedDocuments)}}function T_h(r,t){let n=Go(r),i=n.activeLimboResolutionsByTarget.get(t);if(i&&i.receivedDocument)return rp().add(i.key);{let o=rp(),s=n.queriesByTarget.get(t);if(!s)return o;for(let a of s){let u=n.queryViewsByQuery.get(a);o=o.unionWith(u.view.syncedDocuments)}return o}}async function __h(r,t){let n=Go(r),i=await X1r(n.localStore,t.query,!0),o=t.view.synchronizeWithPersistedState(i);return n.isPrimaryClient&&yPo(n,t.targetId,o.limboChanges),o}async function I_h(r,t){let n=Go(r);return wvc(n.localStore,t).then(i=>Pce(n,i))}async function R_h(r,t,n,i){let o=Go(r),s=await Yvh(o.localStore,t);if(s===null){Bi(wye,"Cannot apply mutation batch with id: "+t);return}n==="pending"?await nYe(o.remoteStore):n==="acknowledged"||n==="rejected"?(mPo(o,t,i||null),APo(o,t),Jvh(o.localStore,t)):Rs(),await Pce(o,s)}async function O_h(r,t){let n=Go(r);if(egr(n),EPo(n),t===!0&&n._isPrimaryClient!==!0){let i=n.sharedClientState.getAllActiveQueryTargets(),o=await zCc(n,i.toArray());n._isPrimaryClient=!0,await cxo(n.remoteStore,!0);for(let s of o)Z1r(n.remoteStore,s)}else if(t===!1&&n._isPrimaryClient!==!1){let i=[],o=Promise.resolve();n.queriesByTarget.forEach((s,a)=>{n.sharedClientState.isLocalQueryTarget(a)?i.push(a):o=o.then(()=>(HKe(n,a),jKe(n.localStore,a,!0))),rYe(n.remoteStore,a)}),await o,await zCc(n,i),w_h(n),n._isPrimaryClient=!1,await cxo(n.remoteStore,!1)}}function w_h(r){let t=Go(r);t.activeLimboResolutionsByTarget.forEach((n,i)=>{rYe(t.remoteStore,i)}),t.limboDocumentRefs.removeAllReferences(),t.activeLimboResolutionsByTarget=new Map,t.activeLimboTargetsByKey=new ky(Bo.comparator)}async function zCc(r,t,n){let i=Go(r),o=[],s=[];for(let a of t){let u,p=i.queriesByTarget.get(a);if(p&&p.length!==0){u=await QKe(i.localStore,WP(p[0]));for(let c of p){let l=i.queryViewsByQuery.get(c),d=await __h(i,l);d.snapshot&&s.push(d.snapshot)}}else{let c=await Ovc(i.localStore,a);u=await QKe(i.localStore,c),await gPo(i,Hvc(c),a,!1,u.resumeToken)}o.push(u)}return i.syncEngineListener.onWatchChange(s),o}function Hvc(r){return LSc(r.path,r.collectionGroup,r.orderBy,r.filters,r.limit,"F",r.startAt,r.endAt)}function M_h(r){let t=Go(r);return $vh(t.localStore)}async function x_h(r,t,n,i){let o=Go(r);if(o._isPrimaryClient){Bi(wye,"Ignoring unexpected query state notification.");return}let s=o.queriesByTarget.get(t);if(s&&s.length>0)switch(n){case"current":case"not-current":{let a=await wvc(o.localStore,qSc(s[0])),u=x_t.createSynthesizedRemoteEventForCurrentChange(t,n==="current",P3.EMPTY_BYTE_STRING);await Pce(o,a,u);break}case"rejected":{await jKe(o.localStore,t,!0),HKe(o,t,i);break}default:Rs()}}async function P_h(r,t,n){let i=egr(r);if(i._isPrimaryClient){for(let o of t){if(i.queriesByTarget.has(o)&&i.sharedClientState.isActiveQueryTarget(o)){Bi(wye,"Adding an already active target "+o);continue}let a=await Ovc(i.localStore,o),u=await QKe(i.localStore,a);await gPo(i,Hvc(a),u.targetId,!1,u.resumeToken),Z1r(i.remoteStore,u)}for(let o of n)i.queriesByTarget.has(o)&&await jKe(i.localStore,o,!1).then(()=>{rYe(i.remoteStore,o),HKe(i,o)}).catch(_ye)}}function egr(r){let t=Go(r);return t.remoteStore.remoteSyncer.applyRemoteEvent=jvc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=T_h.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=g_h.bind(null,t),t.syncEngineListener.onWatchChange=r_h.bind(null,t.eventManager),t.syncEngineListener.onWatchError=n_h.bind(null,t.eventManager),t}function EPo(r){let t=Go(r);return t.remoteStore.remoteSyncer.applySuccessfulWrite=A_h.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=m_h.bind(null,t),t}function N_h(r,t,n){let i=Go(r);D_h(i,t,n).then(o=>{i.sharedClientState.notifyBundleLoaded(o)})}async function D_h(r,t,n){try{let i=await t.getMetadata();if(await eTh(r.localStore,i))return await t.close(),n._completeWith(a_h(i)),Promise.resolve(new Set);n._updateProgress(zvc(i));let s=new gxo(i,r.localStore,t.serializer),a=await t.nextElement();for(;a;){let p=await s.addSizedElement(a);p&&n._updateProgress(p),a=await t.nextElement()}let u=await s.complete();return await Pce(r,u.changedDocs,void 0),await tTh(r.localStore,i),n._completeWith(u.progress),Promise.resolve(u.changedCollectionGroups)}catch(i){return Gq(wye,`Loading bundle failed with ${i}`),n._failWith(i),Promise.resolve(new Set)}}var z_t=class{constructor(){this.synchronizeTabs=!1}async initialize(t){this.serializer=Z_t(t.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(t),this.persistence=this.createPersistence(t),await this.persistence.start(),this.localStore=this.createLocalStore(t),this.gcScheduler=this.createGarbageCollectionScheduler(t,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(t,this.localStore)}createGarbageCollectionScheduler(t,n){return null}createIndexBackfillerScheduler(t,n){return null}createLocalStore(t){return Tvc(this.persistence,new S1r,t.initialUser,this.serializer)}createPersistence(t){return new E1r(C1r.factory,this.serializer)}createSharedClientState(t){return new _1r}async terminate(){var t,n;(t=this.gcScheduler)===null||t===void 0||t.stop(),(n=this.indexBackfillerScheduler)===null||n===void 0||n.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}};var D1r=class extends z_t{constructor(t,n,i){super(),this.onlineComponentProvider=t,this.cacheSizeBytes=n,this.forceOwnership=i,this.synchronizeTabs=!1}async initialize(t){await super.initialize(t),await this.onlineComponentProvider.initialize(this,t),await EPo(this.onlineComponentProvider.syncEngine),await nYe(this.onlineComponentProvider.remoteStore),await this.persistence.setPrimaryStateListener(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(t){return Tvc(this.persistence,new S1r,t.initialUser,this.serializer)}createGarbageCollectionScheduler(t,n){let i=this.persistence.referenceDelegate.garbageCollector;return new kMo(i,t.asyncQueue,n)}createIndexBackfillerScheduler(t,n){let i=new Zwo(n,this.persistence);return new Xwo(t.asyncQueue,i)}createPersistence(t){let n=aPo(t.databaseInfo.databaseId,t.databaseInfo.persistenceKey),i=this.cacheSizeBytes!==void 0?jq.withCacheSize(this.cacheSizeBytes):jq.DEFAULT;return new $Mo(this.synchronizeTabs,n,t.clientId,i,t.asyncQueue,Bvc(),vTh(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(t){return new _1r}},bxo=class extends D1r{constructor(t,n){super(t,n,!1),this.onlineComponentProvider=t,this.cacheSizeBytes=n,this.synchronizeTabs=!0}async initialize(t){await super.initialize(t);let n=this.onlineComponentProvider.syncEngine;this.sharedClientState instanceof b_t&&(this.sharedClientState.syncEngine={applyBatchState:R_h.bind(null,n),applyTargetState:x_h.bind(null,n),applyActiveTargetsChange:P_h.bind(null,n),getActiveClients:M_h.bind(null,n),synchronizeWithChangedDocuments:I_h.bind(null,n)},await this.sharedClientState.start()),await this.persistence.setPrimaryStateListener(async i=>{await O_h(this.onlineComponentProvider.syncEngine,i),this.gcScheduler&&(i&&!this.gcScheduler.started?this.gcScheduler.start():i||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(i&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():i||this.indexBackfillerScheduler.stop())})}createSharedClientState(t){let n=Bvc();if(!b_t.isAvailable(n))throw new oi(Zr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let i=aPo(t.databaseInfo.databaseId,t.databaseInfo.persistenceKey);return new b_t(n,t.asyncQueue,i,t.clientId,t.initialUser)}},Q_t=class{async initialize(t,n){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(n),this.remoteStore=this.createRemoteStore(n),this.eventManager=this.createEventManager(n),this.syncEngine=this.createSyncEngine(n,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=i=>UCc(this.syncEngine,i,1),this.remoteStore.remoteSyncer.handleCredentialChange=v_h.bind(null,this.syncEngine),await cxo(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return t_h()}createDatastore(t){let n=Z_t(t.databaseInfo.databaseId),i=CTh(t.databaseInfo);return MTh(t.authCredentials,t.appCheckCredentials,i,n)}createRemoteStore(t){return kTh(this.localStore,this.datastore,t.asyncQueue,n=>UCc(this.syncEngine,n,0),STh())}createSyncEngine(t,n){return c_h(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,t.initialUser,t.maxConcurrentLimboResolutions,n)}async terminate(){var t;await UTh(this.remoteStore),(t=this.datastore)===null||t===void 0||t.terminate()}};var B_h=10240;function L_h(r,t=B_h){let n=0;return{async read(){if(n<r.byteLength){let o={value:r.slice(n,n+t),done:!1};return n+=t,o}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}function CPo(r,t,n){if(!n)throw new oi(Zr.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${t}.`)}function SPo(r,t,n,i){if(t===!0&&i===!0)throw new oi(Zr.INVALID_ARGUMENT,`${r} and ${n} cannot be used together.`)}function QCc(r){if(!Bo.isDocumentKey(r))throw new oi(Zr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${r} has ${r.length}.`)}function jCc(r){if(Bo.isDocumentKey(r))throw new oi(Zr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${r} has ${r.length}.`)}function k_h(r){return typeof r=="object"&&r!==null&&(Object.getPrototypeOf(r)===Object.prototype||Object.getPrototypeOf(r)===null)}function t3t(r){if(r===void 0)return"undefined";if(r===null)return"null";if(typeof r=="string")return r.length>20&&(r=`${r.substring(0,20)}...`),JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean")return""+r;if(typeof r=="object"){if(r instanceof Array)return"an array";{let t=q_h(r);return t?`a custom ${t} object`:"an object"}}else return typeof r=="function"?"a function":Rs()}function q_h(r){return r.constructor?r.constructor.name:null}function Df(r,t){if("_delegate"in r&&(r=r._delegate),!(r instanceof t)){if(t.name===r.constructor.name)throw new oi(Zr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=t3t(r);throw new oi(Zr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return r}function Vvc(r,t){if(t<=0)throw new oi(Zr.INVALID_ARGUMENT,`Function ${r}() requires a positive number, but it was: ${t}.`)}function F_h(r,t){if(!(r instanceof Uint8Array))throw new oi(Zr.INVALID_ARGUMENT,`NodePlatform.toByteStreamReader expects source to be Uint8Array, got ${t3t(r)}`);return L_h(r,t)}var VKe=class{constructor(t){this.observer=t,this.muted=!1}next(t){this.observer.next&&this.scheduleEvent(this.observer.next,t)}error(t){this.observer.error?this.scheduleEvent(this.observer.error,t):VE("Uncaught Error in snapshot listener:",t.toString())}mute(){this.muted=!0}scheduleEvent(t,n){this.muted||setTimeout(()=>{this.muted||t(n)},0)}};var Exo=class{constructor(t,n){this.payload=t,this.byteLength=n}isBundleMetadata(){return"metadata"in this.payload}};var Cxo=class{constructor(t,n){this.reader=t,this.serializer=n,this.metadata=new aS,this.buffer=new Uint8Array,this.textDecoder=TCh(),this.nextElementImpl().then(i=>{i&&i.isBundleMetadata()?this.metadata.resolve(i.payload.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is
|
|
2131
2131
|
${JSON.stringify(i?.payload)}`))},i=>this.metadata.reject(i))}close(){return this.reader.cancel()}async getMetadata(){return this.metadata.promise}async nextElement(){return await this.getMetadata(),this.nextElementImpl()}async nextElementImpl(){let t=await this.readLength();if(t===null)return null;let n=this.textDecoder.decode(t),i=Number(n);isNaN(i)&&this.raiseError(`length string (${n}) is not valid number`);let o=await this.readJsonString(i);return new Exo(JSON.parse(o),t.length+i)}indexOfOpenBracket(){return this.buffer.findIndex(t=>t===123)}async readLength(){for(;this.indexOfOpenBracket()<0&&!await this.pullMoreDataToBuffer(););if(this.buffer.length===0)return null;let t=this.indexOfOpenBracket();t<0&&this.raiseError("Reached the end of bundle when a length string is expected.");let n=this.buffer.slice(0,t);return this.buffer=this.buffer.slice(t),n}async readJsonString(t){for(;this.buffer.length<t;)await this.pullMoreDataToBuffer()&&this.raiseError("Reached the end of bundle when more is expected.");let n=this.textDecoder.decode(this.buffer.slice(0,t));return this.buffer=this.buffer.slice(t),n}raiseError(t){throw this.reader.cancel(),new Error(`Invalid bundle format: ${t}`)}async pullMoreDataToBuffer(){let t=await this.reader.read();if(!t.done){let n=new Uint8Array(this.buffer.length+t.value.length);n.set(this.buffer),n.set(t.value,this.buffer.length),this.buffer=n}return t.done}};function U_h(r,t){return new Cxo(r,t)}var Sxo=class{constructor(t){this.datastore=t,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(t){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new oi(Zr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let n=await PTh(this.datastore,t);return n.forEach(i=>this.recordVersion(i)),n}set(t,n){this.write(n.toMutation(t,this.precondition(t))),this.writtenDocs.add(t.toString())}update(t,n){try{this.write(n.toMutation(t,this.preconditionForUpdate(t)))}catch(i){this.lastTransactionError=i}this.writtenDocs.add(t.toString())}delete(t){this.write(new Sye(t,this.precondition(t))),this.writtenDocs.add(t.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let t=this.readVersions;this.mutations.forEach(n=>{t.delete(n.key.toString())}),t.forEach((n,i)=>{let o=Bo.fromPath(i);this.mutations.push(new O_t(o,this.precondition(o)))}),await xTh(this.datastore,this.mutations),this.committed=!0}recordVersion(t){let n;if(t.isFoundDocument())n=t.version;else if(t.isNoDocument())n=nu.min();else throw Rs();let i=this.readVersions.get(t.key.toString());if(i){if(!n.isEqual(i))throw new oi(Zr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(t.key.toString(),n)}precondition(t){let n=this.readVersions.get(t.toString());return!this.writtenDocs.has(t.toString())&&n?n.isEqual(nu.min())?J2.exists(!1):J2.updateTime(n):J2.none()}preconditionForUpdate(t){let n=this.readVersions.get(t.toString());if(!this.writtenDocs.has(t.toString())&&n){if(n.isEqual(nu.min()))throw new oi(Zr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return J2.updateTime(n)}else return J2.exists(!0)}write(t){this.ensureCommitNotCalled(),this.mutations.push(t)}ensureCommitNotCalled(){}};var vxo=class{constructor(t,n,i,o,s){this.asyncQueue=t,this.datastore=n,this.options=i,this.updateFunction=o,this.deferred=s,this.attemptsRemaining=i.maxAttempts,this.backoff=new F_t(this.asyncQueue,"transaction_retry")}run(){this.attemptsRemaining-=1,this.runWithBackOff()}runWithBackOff(){this.backoff.backoffAndRun(async()=>{let t=new Sxo(this.datastore),n=this.tryRunUpdateFunction(t);n&&n.then(i=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(i)}).catch(o=>{this.handleTransactionError(o)}))}).catch(i=>{this.handleTransactionError(i)})})}tryRunUpdateFunction(t){try{let n=this.updateFunction(t);return K_t(n)||!n.catch||!n.then?(this.deferred.reject(Error("Transaction callback must return a Promise")),null):n}catch(n){return this.deferred.reject(n),null}}handleTransactionError(t){this.attemptsRemaining>0&&this.isRetryableTransactionError(t)?(this.attemptsRemaining-=1,this.asyncQueue.enqueueAndForget(()=>(this.runWithBackOff(),Promise.resolve()))):this.deferred.reject(t)}isRetryableTransactionError(t){if(t.name==="FirebaseError"){let n=t.code;return n==="aborted"||n==="failed-precondition"||n==="already-exists"||!evc(n)}return!1}};var vye="FirestoreClient",z_h=100,Q_h=11,j_h=20,G_h=22,Txo=class{constructor(t,n,i,o){this.authCredentials=t,this.appCheckCredentials=n,this.asyncQueue=i,this.databaseInfo=o,this.user=Iv.UNAUTHENTICATED,this.clientId=Zhr.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(i,async s=>{Bi(vye,"Received user=",s.uid),await this.authCredentialListener(s),this.user=s}),this.appCheckCredentials.start(i,s=>(Bi(vye,"Received new app check token=",s),this.appCheckCredentialListener(s,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:z_h}}setCredentialChangeListener(t){this.authCredentialListener=t}setAppCheckTokenChangeListener(t){this.appCheckCredentialListener=t}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new oi(Zr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();let t=new aS;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),t.resolve()}catch(n){let i=oYe(n,"Failed to shutdown persistence");t.reject(i)}}),t.promise}};async function $hr(r,t){r.asyncQueue.verifyOperationInProgress(),Bi(vye,"Initializing OfflineComponentProvider");let n=r.configuration;await t.initialize(n);let i=n.initialUser;r.setCredentialChangeListener(async o=>{i.isEqual(o)||(await _vc(t.localStore,o),i=o)}),t.persistence.setDatabaseDeletedListener(()=>r.terminate()),r._offlineComponents=t}async function _xo(r,t){r.asyncQueue.verifyOperationInProgress();let n=await vPo(r);Bi(vye,"Initializing OnlineComponentProvider"),await t.initialize(n,r.configuration),r.setCredentialChangeListener(i=>FCc(t.remoteStore,i)),r.setAppCheckTokenChangeListener((i,o)=>FCc(t.remoteStore,o)),r._onlineComponents=t}function Wvc(r){return r.name==="FirebaseError"?r.code===Zr.FAILED_PRECONDITION||r.code===Zr.UNIMPLEMENTED:typeof DOMException<"u"&&r instanceof DOMException?r.code===G_h||r.code===j_h||r.code===Q_h:!0}async function vPo(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){Bi(vye,"Using user provided OfflineComponentProvider");try{await $hr(r,r._uninitializedComponentsProvider._offline)}catch(t){let n=t;if(!Wvc(n))throw n;Gq("Error using user provided cache. Falling back to memory cache: "+n),await $hr(r,new z_t)}}else Bi(vye,"Using default OfflineComponentProvider"),await $hr(r,new z_t);return r._offlineComponents}async function tgr(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(Bi(vye,"Using user provided OnlineComponentProvider"),await _xo(r,r._uninitializedComponentsProvider._online)):(Bi(vye,"Using default OnlineComponentProvider"),await _xo(r,new Q_t))),r._onlineComponents}function Kvc(r){return vPo(r).then(t=>t.persistence)}function TPo(r){return vPo(r).then(t=>t.localStore)}function Yvc(r){return tgr(r).then(t=>t.remoteStore)}function _Po(r){return tgr(r).then(t=>t.syncEngine)}function H_h(r){return tgr(r).then(t=>t.datastore)}async function WKe(r){let t=await tgr(r),n=t.eventManager;return n.onListen=l_h.bind(null,t.syncEngine),n.onUnlisten=d_h.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=p_h.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=f_h.bind(null,t.syncEngine),n}function V_h(r){return r.asyncQueue.enqueue(async()=>{let t=await Kvc(r),n=await Yvc(r);return t.setNetworkEnabled(!0),qTh(n)})}function W_h(r){return r.asyncQueue.enqueue(async()=>{let t=await Kvc(r),n=await Yvc(r);return t.setNetworkEnabled(!1),FTh(n)})}function K_h(r){let t=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let n=await _Po(r);return y_h(n,t)}),t.promise}function Y_h(r,t,n,i){let o=new VKe(i),s=new U_t(t,o,n);return r.asyncQueue.enqueueAndForget(async()=>{let a=await WKe(r);return dPo(a,s)}),()=>{o.mute(),r.asyncQueue.enqueueAndForget(async()=>{let a=await WKe(r);return fPo(a,s)})}}function J_h(r,t){let n=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let i=await TPo(r);return t3h(i,t,n)}),n.promise}function Jvc(r,t,n={}){let i=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let o=await WKe(r);return r3h(o,r.asyncQueue,t,n,i)}),i.promise}function $_h(r,t){let n=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let i=await TPo(r);return n3h(i,t,n)}),n.promise}function $vc(r,t,n={}){let i=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let o=await WKe(r);return i3h(o,r.asyncQueue,t,n,i)}),i.promise}function X_h(r,t){let n=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let i=await _Po(r);return h_h(i,t,n)}),n.promise}function Z_h(r,t){let n=new VKe(t);return r.asyncQueue.enqueueAndForget(async()=>{let i=await WKe(r);return o_h(i,n)}),()=>{n.mute(),r.asyncQueue.enqueueAndForget(async()=>{let i=await WKe(r);return s_h(i,n)})}}function e3h(r,t,n){let i=new aS;return r.asyncQueue.enqueueAndForget(async()=>{let o=await H_h(r);new vxo(r.asyncQueue,o,n,t,i).run()}),i.promise}async function t3h(r,t,n){try{let i=await Vvh(r,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new oi(Zr.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(i){let o=oYe(i,`Failed to get document '${t} from cache`);n.reject(o)}}function r3h(r,t,n,i,o){let s=new VKe({next:u=>{t.enqueueAndForget(()=>fPo(r,a));let p=u.docs.has(n);!p&&u.fromCache?o.reject(new oi(Zr.UNAVAILABLE,"Failed to get document because the client is offline.")):p&&u.fromCache&&i&&i.source==="server"?o.reject(new oi(Zr.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):o.resolve(u)},error:u=>o.reject(u)}),a=new U_t(eYe(n.path),s,{includeMetadataChanges:!0,waitForSyncWhenOnline:!0});return dPo(r,a)}async function n3h(r,t,n){try{let i=await X1r(r,t,!0),o=new N1r(t,i.remoteKeys),s=o.computeDocChanges(i.documents),a=o.applyChanges(s,!1);n.resolve(a.snapshot)}catch(i){let o=oYe(i,`Failed to execute query '${t} against cache`);n.reject(o)}}function i3h(r,t,n,i,o){let s=new VKe({next:u=>{t.enqueueAndForget(()=>fPo(r,a)),u.fromCache&&i.source==="server"?o.reject(new oi(Zr.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):o.resolve(u)},error:u=>o.reject(u)}),a=new U_t(n,s,{includeMetadataChanges:!0,waitForSyncWhenOnline:!0});return dPo(r,a)}function o3h(r,t,n,i){let o=a3h(n,Z_t(t));r.asyncQueue.enqueueAndForget(async()=>{N_h(await _Po(r),o,i)})}function s3h(r,t){return r.asyncQueue.enqueue(async()=>rTh(await TPo(r),t))}function a3h(r,t){let n;return typeof r=="string"?n=tvc().encode(r):n=r,U_h(F_h(n),t)}function u3h(r,t){return r.timeoutSeconds===t.timeoutSeconds}function Xvc(r){let t={};return r.timeoutSeconds!==void 0&&(t.timeoutSeconds=r.timeoutSeconds),t}var c3h="ComponentProvider",GCc=new Map;function l3h(r){let t=GCc.get(r);t&&(Bi(c3h,"Removing Datastore"),GCc.delete(r),t.terminate())}function p3h(r,t,n,i){return new oMo(r,t,n,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,Xvc(i.experimentalLongPollingOptions),i.useFetchStreams)}var Zvc="firestore.googleapis.com",HCc=!0,VCc=5,WCc=30,d3h=!0,B1r=class{constructor(t){var n,i;if(t.host===void 0){if(t.ssl!==void 0)throw new oi(Zr.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Zvc,this.ssl=HCc}else this.host=t.host,this.ssl=(n=t.ssl)!==null&&n!==void 0?n:HCc;if(this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,this.localCache=t.localCache,t.cacheSizeBytes===void 0)this.cacheSizeBytes=Cvc;else{if(t.cacheSizeBytes!==X_t&&t.cacheSizeBytes<OCc)throw new oi(Zr.INVALID_ARGUMENT,`cacheSizeBytes must be at least ${OCc}`);this.cacheSizeBytes=t.cacheSizeBytes}SPo("experimentalForceLongPolling",t.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",t.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:t.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=d3h:this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Xvc((i=t.experimentalLongPollingOptions)!==null&&i!==void 0?i:{}),f3h(this.experimentalLongPollingOptions),this.useFetchStreams=!!t.useFetchStreams}isEqual(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.experimentalForceLongPolling===t.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===t.experimentalAutoDetectLongPolling&&u3h(this.experimentalLongPollingOptions,t.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===t.ignoreUndefinedProperties&&this.useFetchStreams===t.useFetchStreams}};function f3h(r){if(r.timeoutSeconds!==void 0){if(isNaN(r.timeoutSeconds))throw new oi(Zr.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (must not be NaN)`);if(r.timeoutSeconds<VCc)throw new oi(Zr.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (minimum allowed value is ${VCc})`);if(r.timeoutSeconds>WCc)throw new oi(Zr.INVALID_ARGUMENT,`invalid long polling timeout: ${r.timeoutSeconds} (maximum allowed value is ${WCc})`)}}var I4e=class{constructor(t,n,i,o){this._authCredentials=t,this._appCheckCredentials=n,this._databaseId=i,this._app=o,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new B1r({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new oi(Zr.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return this._terminateTask!==void 0}_setSettings(t){if(this._settingsFrozen)throw new oi(Zr.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new B1r(t),t.credentials!==void 0&&(this._authCredentials=lEh(t.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return l3h(this),Promise.resolve()}};function eTc(r,t,n,i={}){var o;r=Df(r,I4e);let s=r._getSettings(),a=`${t}:${n}`;if(s.host!==Zvc&&s.host!==a&&Gq("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),r._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),i.mockUserToken){let u,p;if(typeof i.mockUserToken=="string")u=i.mockUserToken,p=Iv.MOCK_USER;else{u=k0r(i.mockUserToken,(o=r._app)===null||o===void 0?void 0:o.options.projectId);let c=i.mockUserToken.sub||i.mockUserToken.user_id;if(!c)throw new oi(Zr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");p=new Iv(c)}r._authCredentials=new Gwo(new Xhr(u,p))}}var FR=class r{constructor(t,n,i){this.converter=n,this._query=i,this.type="query",this.firestore=t}withConverter(t){return new r(this.firestore,t,this._query)}},Fm=class r{constructor(t,n,i){this.converter=n,this._key=i,this.type="document",this.firestore=t}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new N$(this.firestore,this.converter,this._key.path.popLast())}withConverter(t){return new r(this.firestore,t,this._key)}},N$=class r extends FR{constructor(t,n,i){super(t,n,eYe(i)),this._path=i,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let t=this._path.popLast();return t.isEmpty()?null:new Fm(this.firestore,null,new Bo(t))}withConverter(t){return new r(this.firestore,t,this._path)}};function IPo(r,t,...n){if(r=ja(r),CPo("collection","path",t),r instanceof I4e){let i=Nf.fromString(t,...n);return jCc(i),new N$(r,null,i)}else{if(!(r instanceof Fm)&&!(r instanceof N$))throw new oi(Zr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let i=r._path.child(Nf.fromString(t,...n));return jCc(i),new N$(r.firestore,null,i)}}function tTc(r,t){if(r=Df(r,I4e),CPo("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new oi(Zr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new FR(r,null,V2h(t))}function r3t(r,t,...n){if(r=ja(r),arguments.length===1&&(t=Zhr.newId()),CPo("doc","path",t),r instanceof I4e){let i=Nf.fromString(t,...n);return QCc(i),new Fm(r,null,new Bo(i))}else{if(!(r instanceof Fm)&&!(r instanceof N$))throw new oi(Zr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let i=r._path.child(Nf.fromString(t,...n));return QCc(i),new Fm(r.firestore,r instanceof N$?r.converter:null,new Bo(i))}}function RPo(r,t){return r=ja(r),t=ja(t),(r instanceof Fm||r instanceof N$)&&(t instanceof Fm||t instanceof N$)?r.firestore===t.firestore&&r.path===t.path&&r.converter===t.converter:!1}function OPo(r,t){return r=ja(r),t=ja(t),r instanceof FR&&t instanceof FR?r.firestore===t.firestore&&J_t(r._query,t._query)&&r.converter===t.converter:!1}var h3h="AsyncQueue",Ixo=class{constructor(){this.tail=Promise.resolve(),this.retryableOps=[],this._isShuttingDown=!1,this.delayedOperations=[],this.failure=null,this.operationInProgress=!1,this.skipNonRestrictedTasks=!1,this.timerIdsToSkip=[],this.backoff=new F_t(this,"async_queue_retry"),this.visibilityHandler=()=>{this.backoff.skipBackoff()}}get isShuttingDown(){return this._isShuttingDown}enqueueAndForget(t){this.enqueue(t)}enqueueAndForgetEvenWhileRestricted(t){this.verifyNotFailed(),this.enqueueInternal(t)}enterRestrictedMode(t){this._isShuttingDown||(this._isShuttingDown=!0,this.skipNonRestrictedTasks=t||!1)}enqueue(t){if(this.verifyNotFailed(),this._isShuttingDown)return new Promise(()=>{});let n=new aS;return this.enqueueInternal(()=>this._isShuttingDown&&this.skipNonRestrictedTasks?Promise.resolve():(t().then(n.resolve,n.reject),n.promise)).then(()=>n.promise)}enqueueRetryable(t){this.enqueueAndForget(()=>(this.retryableOps.push(t),this.retryNextOp()))}async retryNextOp(){if(this.retryableOps.length!==0){try{await this.retryableOps[0](),this.retryableOps.shift(),this.backoff.reset()}catch(t){if(Iye(t))Bi(h3h,"Operation failed with retryable error: "+t);else throw t}this.retryableOps.length>0&&this.backoff.backoffAndRun(()=>this.retryNextOp())}}enqueueInternal(t){let n=this.tail.then(()=>(this.operationInProgress=!0,t().catch(i=>{this.failure=i,this.operationInProgress=!1;let o=A3h(i);throw VE("INTERNAL UNHANDLED ERROR: ",o),i}).then(i=>(this.operationInProgress=!1,i))));return this.tail=n,n}enqueueAfterDelay(t,n,i){this.verifyNotFailed(),this.timerIdsToSkip.indexOf(t)>-1&&(n=0);let o=lxo.createAndSchedule(this,t,n,i,s=>this.removeDelayedOperation(s));return this.delayedOperations.push(o),o}verifyNotFailed(){this.failure&&Rs()}verifyOperationInProgress(){}async drain(){let t;do t=this.tail,await t;while(t!==this.tail)}containsDelayedOperation(t){for(let n of this.delayedOperations)if(n.timerId===t)return!0;return!1}runAllDelayedOperationsUntil(t){return this.drain().then(()=>{this.delayedOperations.sort((n,i)=>n.targetTimeMs-i.targetTimeMs);for(let n of this.delayedOperations)if(n.skipDelay(),t!=="all"&&n.timerId===t)break;return this.drain()})}skipDelaysForTimerId(t){this.timerIdsToSkip.push(t)}removeDelayedOperation(t){let n=this.delayedOperations.indexOf(t);this.delayedOperations.splice(n,1)}};function g3h(){return new Ixo}function A3h(r){let t=r.message||"";return r.stack&&(r.stack.includes(r.message)?t=r.stack:t=r.message+`
|
|
2132
|
-
`+r.stack),t}var Rxo=class{constructor(){this._progressObserver={},this._taskCompletionResolver=new aS,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(t,n,i){this._progressObserver={next:t,error:n,complete:i}}catch(t){return this._taskCompletionResolver.promise.catch(t)}then(t,n){return this._taskCompletionResolver.promise.then(t,n)}_completeWith(t){this._updateProgress(t),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(t)}_failWith(t){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(t),this._taskCompletionResolver.reject(t)}_updateProgress(t){this._lastProgress=t,this._progressObserver.next&&this._progressObserver.next(t)}};var rTc=X_t,Qb=class extends I4e{constructor(t,n,i,o){super(t,n,i,o),this.type="firestore",this._queue=g3h(),this._persistenceKey=o?.name||"[DEFAULT]"}_terminate(){return this._firestoreClient||nTc(this),this._firestoreClient.terminate()}};function VT(r){return r._firestoreClient||nTc(r),r._firestoreClient.verifyNotTerminated(),r._firestoreClient}function nTc(r){var t,n,i;let o=r._freezeSettings(),s=p3h(r._databaseId,((t=r._app)===null||t===void 0?void 0:t.options.appId)||"",r._persistenceKey,o);r._firestoreClient=new Txo(r._authCredentials,r._appCheckCredentials,r._queue,s),!((n=o.localCache)===null||n===void 0)&&n._offlineComponentProvider&&(!((i=o.localCache)===null||i===void 0)&&i._onlineComponentProvider)&&(r._firestoreClient._uninitializedComponentsProvider={_offlineKind:o.localCache.kind,_offline:o.localCache._offlineComponentProvider,_online:o.localCache._onlineComponentProvider})}function iTc(r,t){r=Df(r,Qb),fTc(r);let n=VT(r);if(n._uninitializedComponentsProvider)throw new oi(Zr.FAILED_PRECONDITION,"SDK cache is already specified.");Gq("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let i=r._freezeSettings(),o=new Q_t,s=new D1r(o,i.cacheSizeBytes,t?.forceOwnership);return sTc(n,o,s)}function oTc(r){r=Df(r,Qb),fTc(r);let t=VT(r);if(t._uninitializedComponentsProvider)throw new oi(Zr.FAILED_PRECONDITION,"SDK cache is already specified.");Gq("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let n=r._freezeSettings(),i=new Q_t,o=new bxo(i,n.cacheSizeBytes);return sTc(t,i,o)}function sTc(r,t,n){let i=new aS;return r.asyncQueue.enqueue(async()=>{try{await $hr(r,n),await _xo(r,t),i.resolve()}catch(o){let s=o;if(!Wvc(s))throw s;Gq("Error enabling indexeddb cache. Falling back to memory cache: "+s),i.reject(s)}}).then(()=>i.promise)}function aTc(r){if(r._initialized&&!r._terminated)throw new oi(Zr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let t=new aS;return r._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await Bvh(aPo(r._databaseId,r._persistenceKey)),t.resolve()}catch(n){t.reject(n)}}),t.promise}function uTc(r){r=Df(r,Qb);let t=VT(r);return K_h(t)}function cTc(r){r=Df(r,Qb);let t=VT(r);return V_h(t)}function lTc(r){r=Df(r,Qb);let t=VT(r);return W_h(t)}function pTc(r,t){r=Df(r,Qb);let n=VT(r),i=new Rxo;return o3h(n,r._databaseId,t,i),i}function dTc(r,t){r=Df(r,Qb);let n=VT(r);return s3h(n,t).then(i=>i?new FR(r,null,i.query):null)}function fTc(r){if(r._initialized||r._terminated)throw new oi(Zr.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}function m3h(r,t=!0){uEh(hL),zP(new km("firestore",(n,{instanceIdentifier:i,options:o})=>{let s=n.getProvider("app").getImmediate(),a=new Qb(new Hwo(n.getProvider("auth-internal")),new Ywo(n.getProvider("app-check-internal")),o2h(s,i),s);return o=Object.assign({useFetchStreams:t},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),vv(F2c,U2c,r),vv(F2c,U2c,"esm2017")}var L$=class r{constructor(t){this._byteString=t}static fromBase64String(t){try{return new r(P3.fromBase64String(t))}catch(n){throw new oi(Zr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+n)}}static fromUint8Array(t){return new r(P3.fromUint8Array(t))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(t){return this._byteString.isEqual(t._byteString)}};var DG=class{constructor(...t){for(let n=0;n<t.length;++n)if(t[n].length===0)throw new oi(Zr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new cS(t)}isEqual(t){return this._internalPath.isEqual(t._internalPath)}};var wce=class{constructor(t){this._methodName=t}};var R4e=class{constructor(t,n){if(!isFinite(t)||t<-90||t>90)throw new oi(Zr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(n)||n<-180||n>180)throw new oi(Zr.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=t,this._long=n}get latitude(){return this._lat}get longitude(){return this._long}isEqual(t){return this._lat===t._lat&&this._long===t._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(t){return Bl(this._lat,t._lat)||Bl(this._long,t._long)}};var y3h=/^__.*__$/,Oxo=class{constructor(t,n,i){this.data=t,this.fieldMask=n,this.fieldTransforms=i}toMutation(t,n){return this.fieldMask!==null?new NG(t,this.data,this.fieldMask,n,this.fieldTransforms):new Cye(t,this.data,n,this.fieldTransforms)}},L1r=class{constructor(t,n,i){this.data=t,this.fieldMask=n,this.fieldTransforms=i}toMutation(t,n){return new NG(t,this.data,this.fieldMask,n,this.fieldTransforms)}};function hTc(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Rs()}}var k1r=class r{constructor(t,n,i,o,s,a){this.settings=t,this.databaseId=n,this.serializer=i,this.ignoreUndefinedProperties=o,s===void 0&&this.validatePath(),this.fieldTransforms=s||[],this.fieldMask=a||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(t){return new r(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(t){var n;let i=(n=this.path)===null||n===void 0?void 0:n.child(t),o=this.contextWith({path:i,arrayElement:!1});return o.validatePathSegment(t),o}childContextForFieldPath(t){var n;let i=(n=this.path)===null||n===void 0?void 0:n.child(t),o=this.contextWith({path:i,arrayElement:!1});return o.validatePath(),o}childContextForArray(t){return this.contextWith({path:void 0,arrayElement:!0})}createError(t){return q1r(t,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(t){return this.fieldMask.find(n=>t.isPrefixOf(n))!==void 0||this.fieldTransforms.find(n=>t.isPrefixOf(n.field))!==void 0}validatePath(){if(this.path)for(let t=0;t<this.path.length;t++)this.validatePathSegment(this.path.get(t))}validatePathSegment(t){if(t.length===0)throw this.createError("Document fields must not be empty");if(hTc(this.dataSource)&&y3h.test(t))throw this.createError('Document fields cannot begin and end with "__"')}},wxo=class{constructor(t,n,i){this.databaseId=t,this.ignoreUndefinedProperties=n,this.serializer=i||Z_t(t)}createContext(t,n,i,o=!1){return new k1r({dataSource:t,methodName:n,targetDoc:i,path:cS.emptyPath(),arrayElement:!1,hasConverter:o},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function P4e(r){let t=r._freezeSettings(),n=Z_t(r._databaseId);return new wxo(r._databaseId,!!t.ignoreUndefinedProperties,n)}function rgr(r,t,n,i,o,s={}){let a=r.createContext(s.merge||s.mergeFields?2:0,t,n,o);xPo("Data must be an object, but it was:",a,i);let u=mTc(i,a),p,c;if(s.merge)p=new yL(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){let l=[];for(let d of s.mergeFields){let f=Dxo(t,d,n);if(!a.contains(f))throw new oi(Zr.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);bTc(l,f)||l.push(f)}p=new yL(l),c=a.fieldTransforms.filter(d=>p.covers(d.field))}else p=null,c=a.fieldTransforms;return new Oxo(new PM(u),p,c)}var j_t=class r extends wce{_toFieldTransform(t){if(t.dataSource===2)t.fieldMask.push(t.path);else throw t.dataSource===1?t.createError(`${this._methodName}() can only appear at the top level of your update data`):t.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return null}isEqual(t){return t instanceof r}};function gTc(r,t,n){return new k1r({dataSource:3,targetDoc:t.settings.targetDoc,methodName:r._methodName,arrayElement:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}var Mxo=class r extends wce{_toFieldTransform(t){return new S4e(t.path,new bye)}isEqual(t){return t instanceof r}},xxo=class r extends wce{constructor(t,n){super(t),this._elements=n}_toFieldTransform(t){let n=gTc(this,t,!0),i=this._elements.map(s=>N4e(s,n)),o=new Rce(i);return new S4e(t.path,o)}isEqual(t){return t instanceof r&&yce(this._elements,t._elements)}},Pxo=class r extends wce{constructor(t,n){super(t),this._elements=n}_toFieldTransform(t){let n=gTc(this,t,!0),i=this._elements.map(s=>N4e(s,n)),o=new Oce(i);return new S4e(t.path,o)}isEqual(t){return t instanceof r&&yce(this._elements,t._elements)}},Nxo=class r extends wce{constructor(t,n){super(t),this._operand=n}_toFieldTransform(t){let n=new Eye(t.serializer,HSc(t.serializer,this._operand));return new S4e(t.path,n)}isEqual(t){return t instanceof r&&this._operand===t._operand}};function wPo(r,t,n,i){let o=r.createContext(1,t,n);xPo("Data must be an object, but it was:",o,i);let s=[],a=PM.empty();x4e(i,(p,c)=>{let l=PPo(t,p,n);c=ja(c);let d=o.childContextForFieldPath(l);if(c instanceof j_t)s.push(l);else{let f=N4e(c,d);f!=null&&(s.push(l),a.set(l,f))}});let u=new yL(s);return new L1r(a,u,o.fieldTransforms)}function MPo(r,t,n,i,o,s){let a=r.createContext(1,t,n),u=[Dxo(t,i,n)],p=[o];if(s.length%2!==0)throw new oi(Zr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)u.push(Dxo(t,s[f])),p.push(s[f+1]);let c=[],l=PM.empty();for(let f=u.length-1;f>=0;--f)if(!bTc(c,u[f])){let h=u[f],A=p[f];A=ja(A);let E=a.childContextForFieldPath(h);if(A instanceof j_t)c.push(h);else{let v=N4e(A,E);v!=null&&(c.push(h),l.set(h,v))}}let d=new yL(c);return new L1r(l,d,a.fieldTransforms)}function ATc(r,t,n,i=!1){let o=r.createContext(i?4:3,t);return N4e(n,o)}function N4e(r,t){if(r=ja(r),yTc(r))return xPo("Unsupported field value:",t,r),mTc(r,t);if(r instanceof wce)return E3h(r,t),null;if(r===void 0&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),r instanceof Array){if(t.settings.arrayElement&&t.dataSource!==4)throw t.createError("Nested arrays are not supported");return b3h(r,t)}else return C3h(r,t)}function mTc(r,t){let n={};return ySc(r)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):x4e(r,(i,o)=>{let s=N4e(o,t.childContextForField(i));s!=null&&(n[i]=s)}),{mapValue:{fields:n}}}function b3h(r,t){let n=[],i=0;for(let o of r){let s=N4e(o,t.childContextForArray(i));s==null&&(s={nullValue:"NULL_VALUE"}),n.push(s),i++}return{arrayValue:{values:n}}}function E3h(r,t){if(!hTc(t.dataSource))throw t.createError(`${r._methodName}() can only be used with update() and set()`);if(!t.path)throw t.createError(`${r._methodName}() is not currently supported inside arrays`);let n=r._toFieldTransform(t);n&&t.fieldTransforms.push(n)}function C3h(r,t){if(r=ja(r),r===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return HSc(t.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){let n=WE.fromDate(r);return{timestampValue:FKe(t.serializer,n)}}else if(r instanceof WE){let n=new WE(r.seconds,Math.floor(r.nanoseconds/1e3)*1e3);return{timestampValue:FKe(t.serializer,n)}}else{if(r instanceof R4e)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof L$)return{bytesValue:rvc(t.serializer,r._byteString)};if(r instanceof Fm){let n=t.databaseId,i=r.firestore._databaseId;if(!i.isEqual(n))throw t.createError(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:rPo(r.firestore._databaseId||t.databaseId,r._key.path)}}else throw t.createError(`Unsupported field value: ${t3t(r)}`)}}function yTc(r){return typeof r=="object"&&r!==null&&!(r instanceof Array)&&!(r instanceof Date)&&!(r instanceof WE)&&!(r instanceof R4e)&&!(r instanceof L$)&&!(r instanceof Fm)&&!(r instanceof wce)}function xPo(r,t,n){if(!yTc(n)||!k_h(n)){let i=t3t(n);throw i==="an object"?t.createError(r+" a custom object"):t.createError(r+" "+i)}}function Dxo(r,t,n){if(t=ja(t),t instanceof DG)return t._internalPath;if(typeof t=="string")return PPo(r,t);throw q1r("Field path arguments must be of type string or ",r,!1,void 0,n)}var S3h=new RegExp("[~\\*/\\[\\]]");function PPo(r,t,n){if(t.search(S3h)>=0)throw q1r(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,n);try{return new DG(...t.split("."))._internalPath}catch{throw q1r(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,n)}}function q1r(r,t,n,i,o){let s=i&&!i.isEmpty(),a=o!==void 0,u=`Function ${t}() called with invalid data`;n&&(u+=" (via `toFirestore()`)"),u+=". ";let p="";return(s||a)&&(p+=" (found",s&&(p+=` in field ${i}`),a&&(p+=` in document ${o}`),p+=")"),new oi(Zr.INVALID_ARGUMENT,u+r+p)}function bTc(r,t){return r.some(n=>n.isEqual(t))}var O4e=class{constructor(t,n,i,o,s){this._firestore=t,this._userDataWriter=n,this._key=i,this._document=o,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Fm(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document)if(this._converter){let t=new Bxo(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}else return this._userDataWriter.convertValue(this._document.data.value);else return}get(t){if(this._document){let n=this._document.data.field(ngr("DocumentSnapshot.get",t));if(n!==null)return this._userDataWriter.convertValue(n)}}},Bxo=class extends O4e{data(){return super.data()}};function ngr(r,t){return typeof t=="string"?PPo(r,t):t instanceof DG?t._internalPath:t._delegate._internalPath}function ETc(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new oi(Zr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var G_t=class{},w4e=class extends G_t{};function Nce(r,t,...n){let i=[];t instanceof G_t&&i.push(t),i=i.concat(n),M3h(i);for(let o of i)r=o._apply(r);return r}var F1r=class r extends w4e{constructor(t,n,i){super(),this._field=t,this._op=n,this._value=i,this.type="where"}static _create(t,n,i){return new r(t,n,i)}_apply(t){let n=this._parse(t);return MTc(t._query,n),new FR(t.firestore,t.converter,ePo(t._query,n))}_parse(t){let n=P4e(t.firestore);return v3h(t._query,"where",n,t.firestore._databaseId,this._field,this._op,this._value)}};function CTc(r,t,n){let i=t,o=ngr("where",r);return F1r._create(o,i,n)}var Lxo=class r extends G_t{constructor(t,n){super(),this.type=t,this._queryConstraints=n}static _create(t,n){return new r(t,n)}_parse(t){let n=this._queryConstraints.map(i=>i._parse(t)).filter(i=>i.getFilters().length>0);return n.length===1?n[0]:Eg.create(n,this._getOperator())}_apply(t){let n=this._parse(t);return n.getFilters().length===0?t:(O3h(t._query,n),new FR(t.firestore,t.converter,ePo(t._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};var kxo=class r extends w4e{constructor(t,n){super(),this._field=t,this._direction=n,this.type="orderBy"}static _create(t,n){return new r(t,n)}_apply(t){let n=T3h(t._query,this._field,this._direction);return new FR(t.firestore,t.converter,Y2h(t._query,n))}};function STc(r,t="asc"){let n=t,i=ngr("orderBy",r);return kxo._create(i,n)}var U1r=class r extends w4e{constructor(t,n,i){super(),this.type=t,this._limit=n,this._limitType=i}static _create(t,n,i){return new r(t,n,i)}_apply(t){return new FR(t.firestore,t.converter,u1r(t._query,this._limit,this._limitType))}};function vTc(r){return Vvc("limit",r),U1r._create("limit",r,"F")}function TTc(r){return Vvc("limitToLast",r),U1r._create("limitToLast",r,"L")}var z1r=class r extends w4e{constructor(t,n,i){super(),this.type=t,this._docOrFields=n,this._inclusive=i}static _create(t,n,i){return new r(t,n,i)}_apply(t){let n=wTc(t,this.type,this._docOrFields,this._inclusive);return new FR(t.firestore,t.converter,J2h(t._query,n))}};function _Tc(...r){return z1r._create("startAt",r,!0)}function ITc(...r){return z1r._create("startAfter",r,!1)}var Q1r=class r extends w4e{constructor(t,n,i){super(),this.type=t,this._docOrFields=n,this._inclusive=i}static _create(t,n,i){return new r(t,n,i)}_apply(t){let n=wTc(t,this.type,this._docOrFields,this._inclusive);return new FR(t.firestore,t.converter,$2h(t._query,n))}};function RTc(...r){return Q1r._create("endBefore",r,!1)}function OTc(...r){return Q1r._create("endAt",r,!0)}function wTc(r,t,n,i){if(n[0]=ja(n[0]),n[0]instanceof O4e)return _3h(r._query,r.firestore._databaseId,t,n[0]._document,i);{let o=P4e(r.firestore);return I3h(r._query,r.firestore._databaseId,o,t,n,i)}}function v3h(r,t,n,i,o,s,a){let u;if(o.isKeyField()){if(s==="array-contains"||s==="array-contains-any")throw new oi(Zr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if(s==="in"||s==="not-in"){YCc(a,s);let c=[];for(let l of a)c.push(KCc(i,r,l));u={arrayValue:{values:c}}}else u=KCc(i,r,a)}else(s==="in"||s==="not-in"||s==="array-contains-any")&&YCc(a,s),u=ATc(n,t,a,s==="in"||s==="not-in");return P0.create(o,s,u)}function T3h(r,t,n){if(r.startAt!==null)throw new oi(Zr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(r.endAt!==null)throw new oi(Zr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new E4e(t,n)}function _3h(r,t,n,i,o){if(!i)throw new oi(Zr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);let s=[];for(let a of LKe(r))if(a.field.isKeyField())s.push(b4e(t,i.key));else{let u=i.data.field(a.field);if(K1r(u))throw new oi(Zr.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+a.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(u!==null)s.push(u);else{let p=a.field.canonicalString();throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${p}' (used as the orderBy) does not exist.`)}}return new D$(s,o)}function I3h(r,t,n,i,o,s){let a=r.explicitOrderBy;if(o.length>a.length)throw new oi(Zr.INVALID_ARGUMENT,`Too many arguments provided to ${i}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let u=[];for(let p=0;p<o.length;p++){let c=o[p];if(a[p].field.isKeyField()){if(typeof c!="string")throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${i}(), but got a ${typeof c}`);if(!Zxo(r)&&c.indexOf("/")!==-1)throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${i}() must be a plain document ID, but '${c}' contains a slash.`);let d=r.path.child(Nf.fromString(c));if(!Bo.isDocumentKey(d))throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${i}() must result in a valid document path, but '${d}' is not because it contains an odd number of segments.`);let f=new Bo(d);u.push(b4e(t,f))}else{let d=ATc(n,i,c);u.push(d)}}return new D$(u,s)}function KCc(r,t,n){if(n=ja(n),typeof n=="string"){if(n==="")throw new oi(Zr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Zxo(t)&&n.indexOf("/")!==-1)throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let i=t.path.child(Nf.fromString(n));if(!Bo.isDocumentKey(i))throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${i}' is not because it has an odd number of segments (${i.length}).`);return b4e(r,new Bo(i))}else{if(n instanceof Fm)return b4e(r,n._key);throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${t3t(n)}.`)}}function YCc(r,t){if(!Array.isArray(r)||r.length===0)throw new oi(Zr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function R3h(r){switch(r){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}function MTc(r,t){let n=w3h(r.filters,R3h(t.op));if(n!==null)throw n===t.op?new oi(Zr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new oi(Zr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function O3h(r,t){let n=r,i=t.getFlattenedFilters();for(let o of i)MTc(n,o),n=ePo(n,o)}function w3h(r,t){for(let n of r)for(let i of n.getFlattenedFilters())if(t.indexOf(i.op)>=0)return i.op;return null}function M3h(r){let t=r.filter(i=>i instanceof Lxo).length,n=r.filter(i=>i instanceof F1r).length;if(t>1||t>0&&n>0)throw new oi(Zr.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}var KKe=class{convertValue(t,n="none"){switch(y4e(t)){case 0:return null;case 1:return t.booleanValue;case 2:return $2(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,n);case 5:return t.stringValue;case 6:return this.convertBytes(Aye(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,n);case 10:return this.convertObject(t.mapValue,n);default:throw Rs()}}convertObject(t,n){return this.convertObjectMap(t.fields,n)}convertObjectMap(t,n="none"){let i={};return x4e(t,(o,s)=>{i[o]=this.convertValue(s,n)}),i}convertGeoPoint(t){return new R4e($2(t.latitude),$2(t.longitude))}convertArray(t,n){return(t.values||[]).map(i=>this.convertValue(i,n))}convertServerTimestamp(t,n){switch(n){case"previous":let i=Jxo(t);return i==null?null:this.convertValue(i,n);case"estimate":return this.convertTimestamp(v_t(t));default:return null}}convertTimestamp(t){let n=gye(t);return new WE(n.seconds,n.nanos)}convertDocumentKey(t,n){let i=Nf.fromString(t);Ua(fvc(i));let o=new mye(i.get(1),i.get(3)),s=new Bo(i.popFirst(5));return o.isEqual(n)||VE(`Document ${s} contains a document reference within a different database (${o.projectId}/${o.database}) which is not supported. It will be treated as a reference in the current database (${n.projectId}/${n.database}) instead.`),s}};function igr(r,t,n){let i;return r?n&&(n.merge||n.mergeFields)?i=r.toFirestore(t,n):i=r.toFirestore(t):i=t,i}var qxo=class extends KKe{constructor(t){super(),this.firestore=t}convertBytes(t){return new L$(t)}convertReference(t){let n=this.convertDocumentKey(t,this.firestore._databaseId);return new Fm(this.firestore,null,n)}};function Fxo(r){return x3h(r,["next","error","complete"])}function x3h(r,t){if(typeof r!="object"||r===null)return!1;let n=r;for(let i of t)if(i in n&&typeof n[i]=="function")return!0;return!1}var Mce=class{constructor(t,n){this.hasPendingWrites=t,this.fromCache=n}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}},Vq=class extends O4e{constructor(t,n,i,o,s,a){super(t,n,i,o,a),this._firestore=t,this._firestoreImpl=t,this.metadata=s}exists(){return super.exists()}data(t={}){if(this._document)if(this._converter){let n=new Tye(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(n,t)}else return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps);else return}get(t,n={}){if(this._document){let i=this._document.data.field(ngr("DocumentSnapshot.get",t));if(i!==null)return this._userDataWriter.convertValue(i,n.serverTimestamps)}}},Tye=class extends Vq{data(t={}){return super.data(t)}},BG=class{constructor(t,n,i,o){this._firestore=t,this._userDataWriter=n,this._snapshot=o,this.metadata=new Mce(o.hasPendingWrites,o.fromCache),this.query=i}get docs(){let t=[];return this.forEach(n=>t.push(n)),t}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(t,n){this._snapshot.docs.forEach(i=>{t.call(n,new Tye(this._firestore,this._userDataWriter,i.key,i,new Mce(this._snapshot.mutatedKeys.has(i.key),this._snapshot.fromCache),this.query.converter))})}docChanges(t={}){let n=!!t.includeMetadataChanges;if(n&&this._snapshot.excludesMetadataChanges)throw new oi(Zr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return(!this._cachedChanges||this._cachedChangesIncludeMetadataChanges!==n)&&(this._cachedChanges=P3h(this,n),this._cachedChangesIncludeMetadataChanges=n),this._cachedChanges}};function P3h(r,t){if(r._snapshot.oldDocs.isEmpty()){let n=0;return r._snapshot.docChanges.map(i=>{let o=new Tye(r._firestore,r._userDataWriter,i.doc.key,i.doc,new Mce(r._snapshot.mutatedKeys.has(i.doc.key),r._snapshot.fromCache),r.query.converter);return i.doc,{type:"added",doc:o,oldIndex:-1,newIndex:n++}})}else{let n=r._snapshot.oldDocs;return r._snapshot.docChanges.filter(i=>t||i.type!==3).map(i=>{let o=new Tye(r._firestore,r._userDataWriter,i.doc.key,i.doc,new Mce(r._snapshot.mutatedKeys.has(i.doc.key),r._snapshot.fromCache),r.query.converter),s=-1,a=-1;return i.type!==0&&(s=n.indexOf(i.doc.key),n=n.delete(i.doc.key)),i.type!==1&&(n=n.add(i.doc),a=n.indexOf(i.doc.key)),{type:N3h(i.type),doc:o,oldIndex:s,newIndex:a}})}}function N3h(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Rs()}}function NPo(r,t){return r instanceof Vq&&t instanceof Vq?r._firestore===t._firestore&&r._key.isEqual(t._key)&&(r._document===null?t._document===null:r._document.isEqual(t._document))&&r._converter===t._converter:r instanceof BG&&t instanceof BG?r._firestore===t._firestore&&OPo(r.query,t.query)&&r.metadata.isEqual(t.metadata)&&r._snapshot.isEqual(t._snapshot):!1}function xTc(r){r=Df(r,Fm);let t=Df(r.firestore,Qb),n=VT(t);return Jvc(n,r._key).then(i=>kPo(t,r,i))}var xce=class extends KKe{constructor(t){super(),this.firestore=t}convertBytes(t){return new L$(t)}convertReference(t){let n=this.convertDocumentKey(t,this.firestore._databaseId);return new Fm(this.firestore,null,n)}};function PTc(r){r=Df(r,Fm);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return J_h(n,r._key).then(o=>new Vq(t,i,r._key,o,new Mce(o!==null&&o.hasLocalMutations,!0),r.converter))}function NTc(r){r=Df(r,Fm);let t=Df(r.firestore,Qb),n=VT(t);return Jvc(n,r._key,{source:"server"}).then(i=>kPo(t,r,i))}function DTc(r){r=Df(r,FR);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return ETc(r._query),$vc(n,r._query).then(o=>new BG(t,i,r,o))}function BTc(r){r=Df(r,FR);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return $_h(n,r._query).then(o=>new BG(t,i,r,o))}function LTc(r){r=Df(r,FR);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return $vc(n,r._query,{source:"server"}).then(o=>new BG(t,i,r,o))}function DPo(r,t,n){r=Df(r,Fm);let i=Df(r.firestore,Qb),o=igr(r.converter,t,n),s=P4e(i),u=rgr(s,"setDoc",r._key,o,r.converter!==null,n).toMutation(r._key,J2.none());return sYe(i,[u])}function BPo(r,t,n,...i){r=Df(r,Fm);let o=Df(r.firestore,Qb),s=P4e(o);t=ja(t);let a;typeof t=="string"||t instanceof DG?a=MPo(s,"updateDoc",r._key,t,n,i):a=wPo(s,"updateDoc",r._key,t);let u=a.toMutation(r._key,J2.exists(!0));return sYe(o,[u])}function kTc(r){let t=Df(r.firestore,Qb),n=[new Sye(r._key,J2.none())];return sYe(t,n)}function qTc(r,t){let n=Df(r.firestore,Qb),i=r3t(r),o=igr(r.converter,t),s=P4e(r.firestore),u=rgr(s,"addDoc",i._key,o,r.converter!==null,{}).toMutation(i._key,J2.exists(!1));return sYe(n,[u]).then(()=>i)}function LPo(r,...t){var n,i,o;r=ja(r);let s={includeMetadataChanges:!1,source:"default"},a=0;typeof t[a]=="object"&&!Fxo(t[a])&&(s=t[a],a++);let u={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(Fxo(t[a])){let f=t[a];t[a]=(n=f.next)===null||n===void 0?void 0:n.bind(f),t[a+1]=(i=f.error)===null||i===void 0?void 0:i.bind(f),t[a+2]=(o=f.complete)===null||o===void 0?void 0:o.bind(f)}let p,c,l;if(r instanceof Fm)c=Df(r.firestore,Qb),l=eYe(r._key.path),p={next:f=>{t[a]&&t[a](kPo(c,r,f))},error:t[a+1],complete:t[a+2]};else{let f=Df(r,FR);c=Df(f.firestore,Qb),l=f._query;let h=new xce(c);p={next:A=>{t[a]&&t[a](new BG(c,h,f,A))},error:t[a+1],complete:t[a+2]},ETc(r._query)}let d=VT(c);return Y_h(d,l,u,p)}function FTc(r,t){r=Df(r,Qb);let n=VT(r),i=Fxo(t)?t:{next:t};return Z_h(n,i)}function sYe(r,t){let n=VT(r);return X_h(n,t)}function kPo(r,t,n){let i=n.docs.get(t._key),o=new xce(r);return new Vq(r,o,t._key,i,new Mce(n.hasPendingWrites,n.fromCache),t.converter)}var D3h={maxAttempts:5};function B3h(r){if(r.maxAttempts<1)throw new oi(Zr.INVALID_ARGUMENT,"Max attempts must be at least 1")}var j1r=class{constructor(t,n){this._firestore=t,this._commitHandler=n,this._mutations=[],this._committed=!1,this._dataReader=P4e(t)}set(t,n,i){this._verifyNotCommitted();let o=dye(t,this._firestore),s=igr(o.converter,n,i),a=rgr(this._dataReader,"WriteBatch.set",o._key,s,o.converter!==null,i);return this._mutations.push(a.toMutation(o._key,J2.none())),this}update(t,n,i,...o){this._verifyNotCommitted();let s=dye(t,this._firestore);n=ja(n);let a;return typeof n=="string"||n instanceof DG?a=MPo(this._dataReader,"WriteBatch.update",s._key,n,i,o):a=wPo(this._dataReader,"WriteBatch.update",s._key,n),this._mutations.push(a.toMutation(s._key,J2.exists(!0))),this}delete(t){this._verifyNotCommitted();let n=dye(t,this._firestore);return this._mutations=this._mutations.concat(new Sye(n._key,J2.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new oi(Zr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}};function dye(r,t){if(r=ja(r),r.firestore!==t)throw new oi(Zr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return r}var Uxo=class{constructor(t,n){this._firestore=t,this._transaction=n,this._dataReader=P4e(t)}get(t){let n=dye(t,this._firestore),i=new qxo(this._firestore);return this._transaction.lookup([n._key]).then(o=>{if(!o||o.length!==1)return Rs();let s=o[0];if(s.isFoundDocument())return new O4e(this._firestore,i,s.key,s,n.converter);if(s.isNoDocument())return new O4e(this._firestore,i,n._key,null,n.converter);throw Rs()})}set(t,n,i){let o=dye(t,this._firestore),s=igr(o.converter,n,i),a=rgr(this._dataReader,"Transaction.set",o._key,s,o.converter!==null,i);return this._transaction.set(o._key,a),this}update(t,n,i,...o){let s=dye(t,this._firestore);n=ja(n);let a;return typeof n=="string"||n instanceof DG?a=MPo(this._dataReader,"Transaction.update",s._key,n,i,o):a=wPo(this._dataReader,"Transaction.update",s._key,n),this._transaction.update(s._key,a),this}delete(t){let n=dye(t,this._firestore);return this._transaction.delete(n._key),this}};var zxo=class extends Uxo{constructor(t,n){super(t,n),this._firestore=t}get(t){let n=dye(t,this._firestore),i=new xce(this._firestore);return super.get(t).then(o=>new Vq(this._firestore,i,n._key,o._document,new Mce(!1,!1),n.converter))}};function UTc(r,t,n){r=Df(r,Qb);let i=Object.assign(Object.assign({},D3h),n);B3h(i);let o=VT(r);return e3h(o,s=>t(new zxo(r,s)),i)}function zTc(){return new j_t("deleteField")}function QTc(){return new Mxo("serverTimestamp")}function jTc(...r){return new xxo("arrayUnion",r)}function GTc(...r){return new Pxo("arrayRemove",r)}function HTc(r){return new Nxo("increment",r)}m3h("node");var L3h="@firebase/firestore-compat",k3h="0.3.28";function jPo(r,t){if(t===void 0)return{merge:!1};if(t.mergeFields!==void 0&&t.merge!==void 0)throw new oi("invalid-argument",`Invalid options passed to function ${r}(): You cannot specify both "merge" and "mergeFields".`);return t}function VTc(){if(typeof Uint8Array>"u")throw new oi("unimplemented","Uint8Arrays are not available in this environment.")}function WTc(){if(!bSc())throw new oi("unimplemented","Blobs are unavailable in Firestore in this environment.")}var ogr=class r{constructor(t){this._delegate=t}static fromBase64String(t){return WTc(),new r(L$.fromBase64String(t))}static fromUint8Array(t){return VTc(),new r(L$.fromUint8Array(t))}toBase64(){return WTc(),this._delegate.toBase64()}toUint8Array(){return VTc(),this._delegate.toUint8Array()}isEqual(t){return this._delegate.isEqual(t._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}};function qPo(r){return q3h(r,["next","error","complete"])}function q3h(r,t){if(typeof r!="object"||r===null)return!1;let n=r;for(let i of t)if(i in n&&typeof n[i]=="function")return!0;return!1}var FPo=class{enableIndexedDbPersistence(t,n){return iTc(t._delegate,{forceOwnership:n})}enableMultiTabIndexedDbPersistence(t){return oTc(t._delegate)}clearIndexedDbPersistence(t){return aTc(t._delegate)}},sgr=class{constructor(t,n,i){this._delegate=n,this._persistenceProvider=i,this.INTERNAL={delete:()=>this.terminate()},t instanceof mye||(this._appCompat=t)}get _databaseId(){return this._delegate._databaseId}settings(t){let n=this._delegate._getSettings();!t.merge&&n.host!==t.host&&Gq("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),t.merge&&(t=Object.assign(Object.assign({},n),t),delete t.merge),this._delegate._setSettings(t)}useEmulator(t,n,i={}){eTc(this._delegate,t,n,i)}enableNetwork(){return cTc(this._delegate)}disableNetwork(){return lTc(this._delegate)}enablePersistence(t){let n=!1,i=!1;return t&&(n=!!t.synchronizeTabs,i=!!t.experimentalForceOwningTab,SPo("synchronizeTabs",n,"experimentalForceOwningTab",i)),n?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,i)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return uTc(this._delegate)}onSnapshotsInSync(t){return FTc(this._delegate,t)}get app(){if(!this._appCompat)throw new oi("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(t){try{return new cYe(this,IPo(this._delegate,t))}catch(n){throw KP(n,"collection()","Firestore.collection()")}}doc(t){try{return new k$(this,r3t(this._delegate,t))}catch(n){throw KP(n,"doc()","Firestore.doc()")}}collectionGroup(t){try{return new k4e(this,tTc(this._delegate,t))}catch(n){throw KP(n,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return UTc(this._delegate,n=>t(new agr(this,n)))}batch(){return VT(this._delegate),new ugr(new j1r(this._delegate,t=>sYe(this._delegate,t)))}loadBundle(t){return pTc(this._delegate,t)}namedQuery(t){return dTc(this._delegate,t).then(n=>n?new k4e(this,n):null)}},aYe=class extends KKe{constructor(t){super(),this.firestore=t}convertBytes(t){return new ogr(new L$(t))}convertReference(t){let n=this.convertDocumentKey(t,this.firestore._databaseId);return k$.forKey(n,this.firestore,null)}};function F3h(r){ZCc(r)}var agr=class{constructor(t,n){this._firestore=t,this._delegate=n,this._userDataWriter=new aYe(t)}get(t){let n=D4e(t);return this._delegate.get(n).then(i=>new B4e(this._firestore,new Vq(this._firestore._delegate,this._userDataWriter,i._key,i._document,i.metadata,n.converter)))}set(t,n,i){let o=D4e(t);return i?(jPo("Transaction.set",i),this._delegate.set(o,n,i)):this._delegate.set(o,n),this}update(t,n,i,...o){let s=D4e(t);return arguments.length===2?this._delegate.update(s,n):this._delegate.update(s,n,i,...o),this}delete(t){let n=D4e(t);return this._delegate.delete(n),this}},ugr=class{constructor(t){this._delegate=t}set(t,n,i){let o=D4e(t);return i?(jPo("WriteBatch.set",i),this._delegate.set(o,n,i)):this._delegate.set(o,n),this}update(t,n,i,...o){let s=D4e(t);return arguments.length===2?this._delegate.update(s,n):this._delegate.update(s,n,i,...o),this}delete(t){let n=D4e(t);return this._delegate.delete(n),this}commit(){return this._delegate.commit()}},uYe=class r{constructor(t,n,i){this._firestore=t,this._userDataWriter=n,this._delegate=i}fromFirestore(t,n){let i=new Tye(this._firestore._delegate,this._userDataWriter,t._key,t._document,t.metadata,null);return this._delegate.fromFirestore(new L4e(this._firestore,i),n??{})}toFirestore(t,n){return n?this._delegate.toFirestore(t,n):this._delegate.toFirestore(t)}static getInstance(t,n){let i=r.INSTANCES,o=i.get(t);o||(o=new WeakMap,i.set(t,o));let s=o.get(n);return s||(s=new r(t,new aYe(t),n),o.set(n,s)),s}};uYe.INSTANCES=new WeakMap;var k$=class r{constructor(t,n){this.firestore=t,this._delegate=n,this._userDataWriter=new aYe(t)}static forPath(t,n,i){if(t.length%2!==0)throw new oi("invalid-argument",`Invalid document reference. Document references must have an even number of segments, but ${t.canonicalString()} has ${t.length}`);return new r(n,new Fm(n._delegate,i,new Bo(t)))}static forKey(t,n,i){return new r(n,new Fm(n._delegate,i,t))}get id(){return this._delegate.id}get parent(){return new cYe(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(t){try{return new cYe(this.firestore,IPo(this._delegate,t))}catch(n){throw KP(n,"collection()","DocumentReference.collection()")}}isEqual(t){return t=ja(t),t instanceof Fm?RPo(this._delegate,t):!1}set(t,n){n=jPo("DocumentReference.set",n);try{return n?DPo(this._delegate,t,n):DPo(this._delegate,t)}catch(i){throw KP(i,"setDoc()","DocumentReference.set()")}}update(t,n,...i){try{return arguments.length===1?BPo(this._delegate,t):BPo(this._delegate,t,n,...i)}catch(o){throw KP(o,"updateDoc()","DocumentReference.update()")}}delete(){return kTc(this._delegate)}onSnapshot(...t){let n=KTc(t),i=YTc(t,o=>new B4e(this.firestore,new Vq(this.firestore._delegate,this._userDataWriter,o._key,o._document,o.metadata,this._delegate.converter)));return LPo(this._delegate,n,i)}get(t){let n;return t?.source==="cache"?n=PTc(this._delegate):t?.source==="server"?n=NTc(this._delegate):n=xTc(this._delegate),n.then(i=>new B4e(this.firestore,new Vq(this.firestore._delegate,this._userDataWriter,i._key,i._document,i.metadata,this._delegate.converter)))}withConverter(t){return new r(this.firestore,t?this._delegate.withConverter(uYe.getInstance(this.firestore,t)):this._delegate.withConverter(null))}};function KP(r,t,n){return r.message=r.message.replace(t,n),r}function KTc(r){for(let t of r)if(typeof t=="object"&&!qPo(t))return t;return{}}function YTc(r,t){var n,i;let o;return qPo(r[0])?o=r[0]:qPo(r[1])?o=r[1]:typeof r[0]=="function"?o={next:r[0],error:r[1],complete:r[2]}:o={next:r[1],error:r[2],complete:r[3]},{next:s=>{o.next&&o.next(t(s))},error:(n=o.error)===null||n===void 0?void 0:n.bind(o),complete:(i=o.complete)===null||i===void 0?void 0:i.bind(o)}}var B4e=class{constructor(t,n){this._firestore=t,this._delegate=n}get ref(){return new k$(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(t){return this._delegate.data(t)}get(t,n){return this._delegate.get(t,n)}isEqual(t){return NPo(this._delegate,t._delegate)}},L4e=class extends B4e{data(t){let n=this._delegate.data(t);return this._delegate._converter||eSc(n!==void 0,"Document in a QueryDocumentSnapshot should exist"),n}},k4e=class r{constructor(t,n){this.firestore=t,this._delegate=n,this._userDataWriter=new aYe(t)}where(t,n,i){try{return new r(this.firestore,Nce(this._delegate,CTc(t,n,i)))}catch(o){throw KP(o,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(t,n){try{return new r(this.firestore,Nce(this._delegate,STc(t,n)))}catch(i){throw KP(i,/(orderBy|where)\(\)/,"Query.$1()")}}limit(t){try{return new r(this.firestore,Nce(this._delegate,vTc(t)))}catch(n){throw KP(n,"limit()","Query.limit()")}}limitToLast(t){try{return new r(this.firestore,Nce(this._delegate,TTc(t)))}catch(n){throw KP(n,"limitToLast()","Query.limitToLast()")}}startAt(...t){try{return new r(this.firestore,Nce(this._delegate,_Tc(...t)))}catch(n){throw KP(n,"startAt()","Query.startAt()")}}startAfter(...t){try{return new r(this.firestore,Nce(this._delegate,ITc(...t)))}catch(n){throw KP(n,"startAfter()","Query.startAfter()")}}endBefore(...t){try{return new r(this.firestore,Nce(this._delegate,RTc(...t)))}catch(n){throw KP(n,"endBefore()","Query.endBefore()")}}endAt(...t){try{return new r(this.firestore,Nce(this._delegate,OTc(...t)))}catch(n){throw KP(n,"endAt()","Query.endAt()")}}isEqual(t){return OPo(this._delegate,t._delegate)}get(t){let n;return t?.source==="cache"?n=BTc(this._delegate):t?.source==="server"?n=LTc(this._delegate):n=DTc(this._delegate),n.then(i=>new n3t(this.firestore,new BG(this.firestore._delegate,this._userDataWriter,this._delegate,i._snapshot)))}onSnapshot(...t){let n=KTc(t),i=YTc(t,o=>new n3t(this.firestore,new BG(this.firestore._delegate,this._userDataWriter,this._delegate,o._snapshot)));return LPo(this._delegate,n,i)}withConverter(t){return new r(this.firestore,t?this._delegate.withConverter(uYe.getInstance(this.firestore,t)):this._delegate.withConverter(null))}},UPo=class{constructor(t,n){this._firestore=t,this._delegate=n}get type(){return this._delegate.type}get doc(){return new L4e(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}},n3t=class{constructor(t,n){this._firestore=t,this._delegate=n}get query(){return new k4e(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(t=>new L4e(this._firestore,t))}docChanges(t){return this._delegate.docChanges(t).map(n=>new UPo(this._firestore,n))}forEach(t,n){this._delegate.forEach(i=>{t.call(n,new L4e(this._firestore,i))})}isEqual(t){return NPo(this._delegate,t._delegate)}},cYe=class r extends k4e{constructor(t,n){super(t,n),this.firestore=t,this._delegate=n}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){let t=this._delegate.parent;return t?new k$(this.firestore,t):null}doc(t){try{return t===void 0?new k$(this.firestore,r3t(this._delegate)):new k$(this.firestore,r3t(this._delegate,t))}catch(n){throw KP(n,"doc()","CollectionReference.doc()")}}add(t){return qTc(this._delegate,t).then(n=>new k$(this.firestore,n))}isEqual(t){return RPo(this._delegate,t._delegate)}withConverter(t){return new r(this.firestore,t?this._delegate.withConverter(uYe.getInstance(this.firestore,t)):this._delegate.withConverter(null))}};function D4e(r){return Df(r,Fm)}var zPo=class r{constructor(...t){this._delegate=new DG(...t)}static documentId(){return new r(cS.keyField().canonicalString())}isEqual(t){return t=ja(t),t instanceof DG?this._delegate._internalPath.isEqual(t._internalPath):!1}};var QPo=class r{constructor(t){this._delegate=t}static serverTimestamp(){let t=QTc();return t._methodName="FieldValue.serverTimestamp",new r(t)}static delete(){let t=zTc();return t._methodName="FieldValue.delete",new r(t)}static arrayUnion(...t){let n=jTc(...t);return n._methodName="FieldValue.arrayUnion",new r(n)}static arrayRemove(...t){let n=GTc(...t);return n._methodName="FieldValue.arrayRemove",new r(n)}static increment(t){let n=HTc(t);return n._methodName="FieldValue.increment",new r(n)}isEqual(t){return this._delegate.isEqual(t._delegate)}};var U3h={Firestore:sgr,GeoPoint:R4e,Timestamp:WE,Blob:ogr,Transaction:agr,WriteBatch:ugr,DocumentReference:k$,DocumentSnapshot:B4e,Query:k4e,QueryDocumentSnapshot:L4e,QuerySnapshot:n3t,CollectionReference:cYe,FieldPath:zPo,FieldValue:QPo,setLogLevel:F3h,CACHE_SIZE_UNLIMITED:rTc};function z3h(r,t){r.INTERNAL.registerComponent(new km("firestore-compat",n=>{let i=n.getProvider("app-compat").getImmediate(),o=n.getProvider("firestore").getImmediate();return t(i,o)},"PUBLIC").setServiceProps(Object.assign({},U3h)))}function Q3h(r){z3h(r,(t,n)=>new sgr(t,n,new FPo)),r.registerVersion(L3h,k3h,"node")}Q3h(Gh);var UR=[];for(let r=0;r<256;++r)UR.push((r+256).toString(16).slice(1));function JTc(r,t=0){return(UR[r[t+0]]+UR[r[t+1]]+UR[r[t+2]]+UR[r[t+3]]+"-"+UR[r[t+4]]+UR[r[t+5]]+"-"+UR[r[t+6]]+UR[r[t+7]]+"-"+UR[r[t+8]]+UR[r[t+9]]+"-"+UR[r[t+10]]+UR[r[t+11]]+UR[r[t+12]]+UR[r[t+13]]+UR[r[t+14]]+UR[r[t+15]]).toLowerCase()}var $Tc=require("crypto"),lgr=new Uint8Array(256),cgr=lgr.length;function GPo(){return cgr>lgr.length-16&&((0,$Tc.randomFillSync)(lgr),cgr=0),lgr.slice(cgr,cgr+=16)}var XTc=require("crypto"),HPo={randomUUID:XTc.randomUUID};function j3h(r,t,n){if(HPo.randomUUID&&!t&&!r)return HPo.randomUUID();r=r||{};let i=r.random??r.rng?.()??GPo();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)t[n+o]=i[o];return t}return JTc(i)}var mu=j3h;var pgr=yt(ZTc()),n_c=yt(e_c()),i_c=yt(t_c()),o_c=yt(r_c());pgr.default.extend(o_c.default);pgr.default.extend(n_c.default);pgr.default.extend(i_c.default);var Xc=class r{static _instance;logger;static setInstance(t){this._instance=t}static get instance(){return kE(!!this._instance,"ClientAuthService instance is not set",Ml()),this._instance}static get isInitialized(){return!!this._instance}static resolveAuthToken(){return r.instance.resolveAuthToken()}constructor(t){this.logger=t.child({category:"auth"}),this.getAuthToken=this.getAuthToken.bind(this)}async getAuthToken(){if(!this.isLoggedIn)throw new nt("Unable to obtain auth token, no user is logged in");if(this.isUsingBearerToken){let t=await this.resolveAuthToken();return kE(!!t,"Missing token from resolveAuthToken",this.logger),t}throw new nt("Auth token unavailable with cookie auth")}get isLoggedIn(){return!!this.currentUser}};var G3h=Je("RUNNER");function i3t(r){let t=Z1e(ua(r));return G3h.error("RunPost formattedRealError:",t,"raw error"),t}function o3t(r){return N1(r)&&(r.code==="ECONNABORTED"||r.code==="ETIMEDOUT")}var LG={None:null,sysCreateDate:"isSystemCreateDate",sysUpdateDate:"isSystemUpdateDate",sysStartDate:"isSystemStartDate",sysEndDate:"isSystemEndDate",sysVersion:"isSystemVersion",sysCurrentFlag:"isSystemCurrentFlag"},e4o={isChangeTracking:"isChangeTracking",isSurrogateKey:"isSurrogateKey",isBusinessKey:"isBusinessKey",none:"None"},dgr={isBusinessKey:"primaryBusinessKey",isSurrogateKey:"surrogateKey"},t4o=r=>!!(typeof r=="object"&&r!==null&&"items"in r&&Array.isArray(r.items)),r4o={[LG.sysCreateDate]:"sysCreateDate",[LG.sysUpdateDate]:"sysUpdateDate",[LG.sysStartDate]:"sysStartDate",[LG.sysEndDate]:"sysEndDate",[LG.sysVersion]:"sysVersion",[LG.sysCurrentFlag]:"sysCurrentFlag"};var V3h=Je("TIMING_UTILS"),kG=r=>new Promise(t=>setTimeout(t,r)),Ah=async(r,t,n,i,o="debug",...s)=>{let a=Je(n);a.logContextAtLevel(o,t,r,"starting");let u=performance.now();try{return await i()}catch(p){let{error:{errorString:c,errorDetail:l}}=ua(p);throw a.errorContext(t,r,`
|
|
2132
|
+
`+r.stack),t}var Rxo=class{constructor(){this._progressObserver={},this._taskCompletionResolver=new aS,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(t,n,i){this._progressObserver={next:t,error:n,complete:i}}catch(t){return this._taskCompletionResolver.promise.catch(t)}then(t,n){return this._taskCompletionResolver.promise.then(t,n)}_completeWith(t){this._updateProgress(t),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(t)}_failWith(t){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(t),this._taskCompletionResolver.reject(t)}_updateProgress(t){this._lastProgress=t,this._progressObserver.next&&this._progressObserver.next(t)}};var rTc=X_t,Qb=class extends I4e{constructor(t,n,i,o){super(t,n,i,o),this.type="firestore",this._queue=g3h(),this._persistenceKey=o?.name||"[DEFAULT]"}_terminate(){return this._firestoreClient||nTc(this),this._firestoreClient.terminate()}};function VT(r){return r._firestoreClient||nTc(r),r._firestoreClient.verifyNotTerminated(),r._firestoreClient}function nTc(r){var t,n,i;let o=r._freezeSettings(),s=p3h(r._databaseId,((t=r._app)===null||t===void 0?void 0:t.options.appId)||"",r._persistenceKey,o);r._firestoreClient=new Txo(r._authCredentials,r._appCheckCredentials,r._queue,s),!((n=o.localCache)===null||n===void 0)&&n._offlineComponentProvider&&(!((i=o.localCache)===null||i===void 0)&&i._onlineComponentProvider)&&(r._firestoreClient._uninitializedComponentsProvider={_offlineKind:o.localCache.kind,_offline:o.localCache._offlineComponentProvider,_online:o.localCache._onlineComponentProvider})}function iTc(r,t){r=Df(r,Qb),fTc(r);let n=VT(r);if(n._uninitializedComponentsProvider)throw new oi(Zr.FAILED_PRECONDITION,"SDK cache is already specified.");Gq("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let i=r._freezeSettings(),o=new Q_t,s=new D1r(o,i.cacheSizeBytes,t?.forceOwnership);return sTc(n,o,s)}function oTc(r){r=Df(r,Qb),fTc(r);let t=VT(r);if(t._uninitializedComponentsProvider)throw new oi(Zr.FAILED_PRECONDITION,"SDK cache is already specified.");Gq("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let n=r._freezeSettings(),i=new Q_t,o=new bxo(i,n.cacheSizeBytes);return sTc(t,i,o)}function sTc(r,t,n){let i=new aS;return r.asyncQueue.enqueue(async()=>{try{await $hr(r,n),await _xo(r,t),i.resolve()}catch(o){let s=o;if(!Wvc(s))throw s;Gq("Error enabling indexeddb cache. Falling back to memory cache: "+s),i.reject(s)}}).then(()=>i.promise)}function aTc(r){if(r._initialized&&!r._terminated)throw new oi(Zr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let t=new aS;return r._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await Bvh(aPo(r._databaseId,r._persistenceKey)),t.resolve()}catch(n){t.reject(n)}}),t.promise}function uTc(r){r=Df(r,Qb);let t=VT(r);return K_h(t)}function cTc(r){r=Df(r,Qb);let t=VT(r);return V_h(t)}function lTc(r){r=Df(r,Qb);let t=VT(r);return W_h(t)}function pTc(r,t){r=Df(r,Qb);let n=VT(r),i=new Rxo;return o3h(n,r._databaseId,t,i),i}function dTc(r,t){r=Df(r,Qb);let n=VT(r);return s3h(n,t).then(i=>i?new FR(r,null,i.query):null)}function fTc(r){if(r._initialized||r._terminated)throw new oi(Zr.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}function m3h(r,t=!0){uEh(hL),zP(new km("firestore",(n,{instanceIdentifier:i,options:o})=>{let s=n.getProvider("app").getImmediate(),a=new Qb(new Hwo(n.getProvider("auth-internal")),new Ywo(n.getProvider("app-check-internal")),o2h(s,i),s);return o=Object.assign({useFetchStreams:t},o),a._setSettings(o),a},"PUBLIC").setMultipleInstances(!0)),vv(F2c,U2c,r),vv(F2c,U2c,"esm2017")}var L$=class r{constructor(t){this._byteString=t}static fromBase64String(t){try{return new r(P3.fromBase64String(t))}catch(n){throw new oi(Zr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+n)}}static fromUint8Array(t){return new r(P3.fromUint8Array(t))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(t){return this._byteString.isEqual(t._byteString)}};var DG=class{constructor(...t){for(let n=0;n<t.length;++n)if(t[n].length===0)throw new oi(Zr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new cS(t)}isEqual(t){return this._internalPath.isEqual(t._internalPath)}};var wce=class{constructor(t){this._methodName=t}};var R4e=class{constructor(t,n){if(!isFinite(t)||t<-90||t>90)throw new oi(Zr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(n)||n<-180||n>180)throw new oi(Zr.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+n);this._lat=t,this._long=n}get latitude(){return this._lat}get longitude(){return this._long}isEqual(t){return this._lat===t._lat&&this._long===t._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(t){return Bl(this._lat,t._lat)||Bl(this._long,t._long)}};var y3h=/^__.*__$/,Oxo=class{constructor(t,n,i){this.data=t,this.fieldMask=n,this.fieldTransforms=i}toMutation(t,n){return this.fieldMask!==null?new NG(t,this.data,this.fieldMask,n,this.fieldTransforms):new Cye(t,this.data,n,this.fieldTransforms)}},L1r=class{constructor(t,n,i){this.data=t,this.fieldMask=n,this.fieldTransforms=i}toMutation(t,n){return new NG(t,this.data,this.fieldMask,n,this.fieldTransforms)}};function hTc(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Rs()}}var k1r=class r{constructor(t,n,i,o,s,a){this.settings=t,this.databaseId=n,this.serializer=i,this.ignoreUndefinedProperties=o,s===void 0&&this.validatePath(),this.fieldTransforms=s||[],this.fieldMask=a||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(t){return new r(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(t){var n;let i=(n=this.path)===null||n===void 0?void 0:n.child(t),o=this.contextWith({path:i,arrayElement:!1});return o.validatePathSegment(t),o}childContextForFieldPath(t){var n;let i=(n=this.path)===null||n===void 0?void 0:n.child(t),o=this.contextWith({path:i,arrayElement:!1});return o.validatePath(),o}childContextForArray(t){return this.contextWith({path:void 0,arrayElement:!0})}createError(t){return q1r(t,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(t){return this.fieldMask.find(n=>t.isPrefixOf(n))!==void 0||this.fieldTransforms.find(n=>t.isPrefixOf(n.field))!==void 0}validatePath(){if(this.path)for(let t=0;t<this.path.length;t++)this.validatePathSegment(this.path.get(t))}validatePathSegment(t){if(t.length===0)throw this.createError("Document fields must not be empty");if(hTc(this.dataSource)&&y3h.test(t))throw this.createError('Document fields cannot begin and end with "__"')}},wxo=class{constructor(t,n,i){this.databaseId=t,this.ignoreUndefinedProperties=n,this.serializer=i||Z_t(t)}createContext(t,n,i,o=!1){return new k1r({dataSource:t,methodName:n,targetDoc:i,path:cS.emptyPath(),arrayElement:!1,hasConverter:o},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function P4e(r){let t=r._freezeSettings(),n=Z_t(r._databaseId);return new wxo(r._databaseId,!!t.ignoreUndefinedProperties,n)}function rgr(r,t,n,i,o,s={}){let a=r.createContext(s.merge||s.mergeFields?2:0,t,n,o);xPo("Data must be an object, but it was:",a,i);let u=mTc(i,a),p,c;if(s.merge)p=new yL(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){let l=[];for(let d of s.mergeFields){let f=Dxo(t,d,n);if(!a.contains(f))throw new oi(Zr.INVALID_ARGUMENT,`Field '${f}' is specified in your field mask but missing from your input data.`);bTc(l,f)||l.push(f)}p=new yL(l),c=a.fieldTransforms.filter(d=>p.covers(d.field))}else p=null,c=a.fieldTransforms;return new Oxo(new PM(u),p,c)}var j_t=class r extends wce{_toFieldTransform(t){if(t.dataSource===2)t.fieldMask.push(t.path);else throw t.dataSource===1?t.createError(`${this._methodName}() can only appear at the top level of your update data`):t.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return null}isEqual(t){return t instanceof r}};function gTc(r,t,n){return new k1r({dataSource:3,targetDoc:t.settings.targetDoc,methodName:r._methodName,arrayElement:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}var Mxo=class r extends wce{_toFieldTransform(t){return new S4e(t.path,new bye)}isEqual(t){return t instanceof r}},xxo=class r extends wce{constructor(t,n){super(t),this._elements=n}_toFieldTransform(t){let n=gTc(this,t,!0),i=this._elements.map(s=>N4e(s,n)),o=new Rce(i);return new S4e(t.path,o)}isEqual(t){return t instanceof r&&yce(this._elements,t._elements)}},Pxo=class r extends wce{constructor(t,n){super(t),this._elements=n}_toFieldTransform(t){let n=gTc(this,t,!0),i=this._elements.map(s=>N4e(s,n)),o=new Oce(i);return new S4e(t.path,o)}isEqual(t){return t instanceof r&&yce(this._elements,t._elements)}},Nxo=class r extends wce{constructor(t,n){super(t),this._operand=n}_toFieldTransform(t){let n=new Eye(t.serializer,HSc(t.serializer,this._operand));return new S4e(t.path,n)}isEqual(t){return t instanceof r&&this._operand===t._operand}};function wPo(r,t,n,i){let o=r.createContext(1,t,n);xPo("Data must be an object, but it was:",o,i);let s=[],a=PM.empty();x4e(i,(p,c)=>{let l=PPo(t,p,n);c=ja(c);let d=o.childContextForFieldPath(l);if(c instanceof j_t)s.push(l);else{let f=N4e(c,d);f!=null&&(s.push(l),a.set(l,f))}});let u=new yL(s);return new L1r(a,u,o.fieldTransforms)}function MPo(r,t,n,i,o,s){let a=r.createContext(1,t,n),u=[Dxo(t,i,n)],p=[o];if(s.length%2!==0)throw new oi(Zr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)u.push(Dxo(t,s[f])),p.push(s[f+1]);let c=[],l=PM.empty();for(let f=u.length-1;f>=0;--f)if(!bTc(c,u[f])){let h=u[f],A=p[f];A=ja(A);let E=a.childContextForFieldPath(h);if(A instanceof j_t)c.push(h);else{let v=N4e(A,E);v!=null&&(c.push(h),l.set(h,v))}}let d=new yL(c);return new L1r(l,d,a.fieldTransforms)}function ATc(r,t,n,i=!1){let o=r.createContext(i?4:3,t);return N4e(n,o)}function N4e(r,t){if(r=ja(r),yTc(r))return xPo("Unsupported field value:",t,r),mTc(r,t);if(r instanceof wce)return E3h(r,t),null;if(r===void 0&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),r instanceof Array){if(t.settings.arrayElement&&t.dataSource!==4)throw t.createError("Nested arrays are not supported");return b3h(r,t)}else return C3h(r,t)}function mTc(r,t){let n={};return ySc(r)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):x4e(r,(i,o)=>{let s=N4e(o,t.childContextForField(i));s!=null&&(n[i]=s)}),{mapValue:{fields:n}}}function b3h(r,t){let n=[],i=0;for(let o of r){let s=N4e(o,t.childContextForArray(i));s==null&&(s={nullValue:"NULL_VALUE"}),n.push(s),i++}return{arrayValue:{values:n}}}function E3h(r,t){if(!hTc(t.dataSource))throw t.createError(`${r._methodName}() can only be used with update() and set()`);if(!t.path)throw t.createError(`${r._methodName}() is not currently supported inside arrays`);let n=r._toFieldTransform(t);n&&t.fieldTransforms.push(n)}function C3h(r,t){if(r=ja(r),r===null)return{nullValue:"NULL_VALUE"};if(typeof r=="number")return HSc(t.serializer,r);if(typeof r=="boolean")return{booleanValue:r};if(typeof r=="string")return{stringValue:r};if(r instanceof Date){let n=WE.fromDate(r);return{timestampValue:FKe(t.serializer,n)}}else if(r instanceof WE){let n=new WE(r.seconds,Math.floor(r.nanoseconds/1e3)*1e3);return{timestampValue:FKe(t.serializer,n)}}else{if(r instanceof R4e)return{geoPointValue:{latitude:r.latitude,longitude:r.longitude}};if(r instanceof L$)return{bytesValue:rvc(t.serializer,r._byteString)};if(r instanceof Fm){let n=t.databaseId,i=r.firestore._databaseId;if(!i.isEqual(n))throw t.createError(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:rPo(r.firestore._databaseId||t.databaseId,r._key.path)}}else throw t.createError(`Unsupported field value: ${t3t(r)}`)}}function yTc(r){return typeof r=="object"&&r!==null&&!(r instanceof Array)&&!(r instanceof Date)&&!(r instanceof WE)&&!(r instanceof R4e)&&!(r instanceof L$)&&!(r instanceof Fm)&&!(r instanceof wce)}function xPo(r,t,n){if(!yTc(n)||!k_h(n)){let i=t3t(n);throw i==="an object"?t.createError(r+" a custom object"):t.createError(r+" "+i)}}function Dxo(r,t,n){if(t=ja(t),t instanceof DG)return t._internalPath;if(typeof t=="string")return PPo(r,t);throw q1r("Field path arguments must be of type string or ",r,!1,void 0,n)}var S3h=new RegExp("[~\\*/\\[\\]]");function PPo(r,t,n){if(t.search(S3h)>=0)throw q1r(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,n);try{return new DG(...t.split("."))._internalPath}catch{throw q1r(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,n)}}function q1r(r,t,n,i,o){let s=i&&!i.isEmpty(),a=o!==void 0,u=`Function ${t}() called with invalid data`;n&&(u+=" (via `toFirestore()`)"),u+=". ";let p="";return(s||a)&&(p+=" (found",s&&(p+=` in field ${i}`),a&&(p+=` in document ${o}`),p+=")"),new oi(Zr.INVALID_ARGUMENT,u+r+p)}function bTc(r,t){return r.some(n=>n.isEqual(t))}var O4e=class{constructor(t,n,i,o,s){this._firestore=t,this._userDataWriter=n,this._key=i,this._document=o,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Fm(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document)if(this._converter){let t=new Bxo(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}else return this._userDataWriter.convertValue(this._document.data.value);else return}get(t){if(this._document){let n=this._document.data.field(ngr("DocumentSnapshot.get",t));if(n!==null)return this._userDataWriter.convertValue(n)}}},Bxo=class extends O4e{data(){return super.data()}};function ngr(r,t){return typeof t=="string"?PPo(r,t):t instanceof DG?t._internalPath:t._delegate._internalPath}function ETc(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new oi(Zr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var G_t=class{},w4e=class extends G_t{};function Nce(r,t,...n){let i=[];t instanceof G_t&&i.push(t),i=i.concat(n),M3h(i);for(let o of i)r=o._apply(r);return r}var F1r=class r extends w4e{constructor(t,n,i){super(),this._field=t,this._op=n,this._value=i,this.type="where"}static _create(t,n,i){return new r(t,n,i)}_apply(t){let n=this._parse(t);return MTc(t._query,n),new FR(t.firestore,t.converter,ePo(t._query,n))}_parse(t){let n=P4e(t.firestore);return v3h(t._query,"where",n,t.firestore._databaseId,this._field,this._op,this._value)}};function CTc(r,t,n){let i=t,o=ngr("where",r);return F1r._create(o,i,n)}var Lxo=class r extends G_t{constructor(t,n){super(),this.type=t,this._queryConstraints=n}static _create(t,n){return new r(t,n)}_parse(t){let n=this._queryConstraints.map(i=>i._parse(t)).filter(i=>i.getFilters().length>0);return n.length===1?n[0]:Eg.create(n,this._getOperator())}_apply(t){let n=this._parse(t);return n.getFilters().length===0?t:(O3h(t._query,n),new FR(t.firestore,t.converter,ePo(t._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return this.type==="and"?"and":"or"}};var kxo=class r extends w4e{constructor(t,n){super(),this._field=t,this._direction=n,this.type="orderBy"}static _create(t,n){return new r(t,n)}_apply(t){let n=T3h(t._query,this._field,this._direction);return new FR(t.firestore,t.converter,Y2h(t._query,n))}};function STc(r,t="asc"){let n=t,i=ngr("orderBy",r);return kxo._create(i,n)}var U1r=class r extends w4e{constructor(t,n,i){super(),this.type=t,this._limit=n,this._limitType=i}static _create(t,n,i){return new r(t,n,i)}_apply(t){return new FR(t.firestore,t.converter,u1r(t._query,this._limit,this._limitType))}};function vTc(r){return Vvc("limit",r),U1r._create("limit",r,"F")}function TTc(r){return Vvc("limitToLast",r),U1r._create("limitToLast",r,"L")}var z1r=class r extends w4e{constructor(t,n,i){super(),this.type=t,this._docOrFields=n,this._inclusive=i}static _create(t,n,i){return new r(t,n,i)}_apply(t){let n=wTc(t,this.type,this._docOrFields,this._inclusive);return new FR(t.firestore,t.converter,J2h(t._query,n))}};function _Tc(...r){return z1r._create("startAt",r,!0)}function ITc(...r){return z1r._create("startAfter",r,!1)}var Q1r=class r extends w4e{constructor(t,n,i){super(),this.type=t,this._docOrFields=n,this._inclusive=i}static _create(t,n,i){return new r(t,n,i)}_apply(t){let n=wTc(t,this.type,this._docOrFields,this._inclusive);return new FR(t.firestore,t.converter,$2h(t._query,n))}};function RTc(...r){return Q1r._create("endBefore",r,!1)}function OTc(...r){return Q1r._create("endAt",r,!0)}function wTc(r,t,n,i){if(n[0]=ja(n[0]),n[0]instanceof O4e)return _3h(r._query,r.firestore._databaseId,t,n[0]._document,i);{let o=P4e(r.firestore);return I3h(r._query,r.firestore._databaseId,o,t,n,i)}}function v3h(r,t,n,i,o,s,a){let u;if(o.isKeyField()){if(s==="array-contains"||s==="array-contains-any")throw new oi(Zr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if(s==="in"||s==="not-in"){YCc(a,s);let c=[];for(let l of a)c.push(KCc(i,r,l));u={arrayValue:{values:c}}}else u=KCc(i,r,a)}else(s==="in"||s==="not-in"||s==="array-contains-any")&&YCc(a,s),u=ATc(n,t,a,s==="in"||s==="not-in");return P0.create(o,s,u)}function T3h(r,t,n){if(r.startAt!==null)throw new oi(Zr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(r.endAt!==null)throw new oi(Zr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new E4e(t,n)}function _3h(r,t,n,i,o){if(!i)throw new oi(Zr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);let s=[];for(let a of LKe(r))if(a.field.isKeyField())s.push(b4e(t,i.key));else{let u=i.data.field(a.field);if(K1r(u))throw new oi(Zr.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+a.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(u!==null)s.push(u);else{let p=a.field.canonicalString();throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${p}' (used as the orderBy) does not exist.`)}}return new D$(s,o)}function I3h(r,t,n,i,o,s){let a=r.explicitOrderBy;if(o.length>a.length)throw new oi(Zr.INVALID_ARGUMENT,`Too many arguments provided to ${i}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let u=[];for(let p=0;p<o.length;p++){let c=o[p];if(a[p].field.isKeyField()){if(typeof c!="string")throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${i}(), but got a ${typeof c}`);if(!Zxo(r)&&c.indexOf("/")!==-1)throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${i}() must be a plain document ID, but '${c}' contains a slash.`);let d=r.path.child(Nf.fromString(c));if(!Bo.isDocumentKey(d))throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${i}() must result in a valid document path, but '${d}' is not because it contains an odd number of segments.`);let f=new Bo(d);u.push(b4e(t,f))}else{let d=ATc(n,i,c);u.push(d)}}return new D$(u,s)}function KCc(r,t,n){if(n=ja(n),typeof n=="string"){if(n==="")throw new oi(Zr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Zxo(t)&&n.indexOf("/")!==-1)throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let i=t.path.child(Nf.fromString(n));if(!Bo.isDocumentKey(i))throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${i}' is not because it has an odd number of segments (${i.length}).`);return b4e(r,new Bo(i))}else{if(n instanceof Fm)return b4e(r,n._key);throw new oi(Zr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${t3t(n)}.`)}}function YCc(r,t){if(!Array.isArray(r)||r.length===0)throw new oi(Zr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function R3h(r){switch(r){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}function MTc(r,t){let n=w3h(r.filters,R3h(t.op));if(n!==null)throw n===t.op?new oi(Zr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new oi(Zr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function O3h(r,t){let n=r,i=t.getFlattenedFilters();for(let o of i)MTc(n,o),n=ePo(n,o)}function w3h(r,t){for(let n of r)for(let i of n.getFlattenedFilters())if(t.indexOf(i.op)>=0)return i.op;return null}function M3h(r){let t=r.filter(i=>i instanceof Lxo).length,n=r.filter(i=>i instanceof F1r).length;if(t>1||t>0&&n>0)throw new oi(Zr.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}var KKe=class{convertValue(t,n="none"){switch(y4e(t)){case 0:return null;case 1:return t.booleanValue;case 2:return $2(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,n);case 5:return t.stringValue;case 6:return this.convertBytes(Aye(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,n);case 10:return this.convertObject(t.mapValue,n);default:throw Rs()}}convertObject(t,n){return this.convertObjectMap(t.fields,n)}convertObjectMap(t,n="none"){let i={};return x4e(t,(o,s)=>{i[o]=this.convertValue(s,n)}),i}convertGeoPoint(t){return new R4e($2(t.latitude),$2(t.longitude))}convertArray(t,n){return(t.values||[]).map(i=>this.convertValue(i,n))}convertServerTimestamp(t,n){switch(n){case"previous":let i=Jxo(t);return i==null?null:this.convertValue(i,n);case"estimate":return this.convertTimestamp(v_t(t));default:return null}}convertTimestamp(t){let n=gye(t);return new WE(n.seconds,n.nanos)}convertDocumentKey(t,n){let i=Nf.fromString(t);Ua(fvc(i));let o=new mye(i.get(1),i.get(3)),s=new Bo(i.popFirst(5));return o.isEqual(n)||VE(`Document ${s} contains a document reference within a different database (${o.projectId}/${o.database}) which is not supported. It will be treated as a reference in the current database (${n.projectId}/${n.database}) instead.`),s}};function igr(r,t,n){let i;return r?n&&(n.merge||n.mergeFields)?i=r.toFirestore(t,n):i=r.toFirestore(t):i=t,i}var qxo=class extends KKe{constructor(t){super(),this.firestore=t}convertBytes(t){return new L$(t)}convertReference(t){let n=this.convertDocumentKey(t,this.firestore._databaseId);return new Fm(this.firestore,null,n)}};function Fxo(r){return x3h(r,["next","error","complete"])}function x3h(r,t){if(typeof r!="object"||r===null)return!1;let n=r;for(let i of t)if(i in n&&typeof n[i]=="function")return!0;return!1}var Mce=class{constructor(t,n){this.hasPendingWrites=t,this.fromCache=n}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}},Vq=class extends O4e{constructor(t,n,i,o,s,a){super(t,n,i,o,a),this._firestore=t,this._firestoreImpl=t,this.metadata=s}exists(){return super.exists()}data(t={}){if(this._document)if(this._converter){let n=new Tye(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(n,t)}else return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps);else return}get(t,n={}){if(this._document){let i=this._document.data.field(ngr("DocumentSnapshot.get",t));if(i!==null)return this._userDataWriter.convertValue(i,n.serverTimestamps)}}},Tye=class extends Vq{data(t={}){return super.data(t)}},BG=class{constructor(t,n,i,o){this._firestore=t,this._userDataWriter=n,this._snapshot=o,this.metadata=new Mce(o.hasPendingWrites,o.fromCache),this.query=i}get docs(){let t=[];return this.forEach(n=>t.push(n)),t}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(t,n){this._snapshot.docs.forEach(i=>{t.call(n,new Tye(this._firestore,this._userDataWriter,i.key,i,new Mce(this._snapshot.mutatedKeys.has(i.key),this._snapshot.fromCache),this.query.converter))})}docChanges(t={}){let n=!!t.includeMetadataChanges;if(n&&this._snapshot.excludesMetadataChanges)throw new oi(Zr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return(!this._cachedChanges||this._cachedChangesIncludeMetadataChanges!==n)&&(this._cachedChanges=P3h(this,n),this._cachedChangesIncludeMetadataChanges=n),this._cachedChanges}};function P3h(r,t){if(r._snapshot.oldDocs.isEmpty()){let n=0;return r._snapshot.docChanges.map(i=>{let o=new Tye(r._firestore,r._userDataWriter,i.doc.key,i.doc,new Mce(r._snapshot.mutatedKeys.has(i.doc.key),r._snapshot.fromCache),r.query.converter);return i.doc,{type:"added",doc:o,oldIndex:-1,newIndex:n++}})}else{let n=r._snapshot.oldDocs;return r._snapshot.docChanges.filter(i=>t||i.type!==3).map(i=>{let o=new Tye(r._firestore,r._userDataWriter,i.doc.key,i.doc,new Mce(r._snapshot.mutatedKeys.has(i.doc.key),r._snapshot.fromCache),r.query.converter),s=-1,a=-1;return i.type!==0&&(s=n.indexOf(i.doc.key),n=n.delete(i.doc.key)),i.type!==1&&(n=n.add(i.doc),a=n.indexOf(i.doc.key)),{type:N3h(i.type),doc:o,oldIndex:s,newIndex:a}})}}function N3h(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Rs()}}function NPo(r,t){return r instanceof Vq&&t instanceof Vq?r._firestore===t._firestore&&r._key.isEqual(t._key)&&(r._document===null?t._document===null:r._document.isEqual(t._document))&&r._converter===t._converter:r instanceof BG&&t instanceof BG?r._firestore===t._firestore&&OPo(r.query,t.query)&&r.metadata.isEqual(t.metadata)&&r._snapshot.isEqual(t._snapshot):!1}function xTc(r){r=Df(r,Fm);let t=Df(r.firestore,Qb),n=VT(t);return Jvc(n,r._key).then(i=>kPo(t,r,i))}var xce=class extends KKe{constructor(t){super(),this.firestore=t}convertBytes(t){return new L$(t)}convertReference(t){let n=this.convertDocumentKey(t,this.firestore._databaseId);return new Fm(this.firestore,null,n)}};function PTc(r){r=Df(r,Fm);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return J_h(n,r._key).then(o=>new Vq(t,i,r._key,o,new Mce(o!==null&&o.hasLocalMutations,!0),r.converter))}function NTc(r){r=Df(r,Fm);let t=Df(r.firestore,Qb),n=VT(t);return Jvc(n,r._key,{source:"server"}).then(i=>kPo(t,r,i))}function DTc(r){r=Df(r,FR);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return ETc(r._query),$vc(n,r._query).then(o=>new BG(t,i,r,o))}function BTc(r){r=Df(r,FR);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return $_h(n,r._query).then(o=>new BG(t,i,r,o))}function LTc(r){r=Df(r,FR);let t=Df(r.firestore,Qb),n=VT(t),i=new xce(t);return $vc(n,r._query,{source:"server"}).then(o=>new BG(t,i,r,o))}function DPo(r,t,n){r=Df(r,Fm);let i=Df(r.firestore,Qb),o=igr(r.converter,t,n),s=P4e(i),u=rgr(s,"setDoc",r._key,o,r.converter!==null,n).toMutation(r._key,J2.none());return sYe(i,[u])}function BPo(r,t,n,...i){r=Df(r,Fm);let o=Df(r.firestore,Qb),s=P4e(o);t=ja(t);let a;typeof t=="string"||t instanceof DG?a=MPo(s,"updateDoc",r._key,t,n,i):a=wPo(s,"updateDoc",r._key,t);let u=a.toMutation(r._key,J2.exists(!0));return sYe(o,[u])}function kTc(r){let t=Df(r.firestore,Qb),n=[new Sye(r._key,J2.none())];return sYe(t,n)}function qTc(r,t){let n=Df(r.firestore,Qb),i=r3t(r),o=igr(r.converter,t),s=P4e(r.firestore),u=rgr(s,"addDoc",i._key,o,r.converter!==null,{}).toMutation(i._key,J2.exists(!1));return sYe(n,[u]).then(()=>i)}function LPo(r,...t){var n,i,o;r=ja(r);let s={includeMetadataChanges:!1,source:"default"},a=0;typeof t[a]=="object"&&!Fxo(t[a])&&(s=t[a],a++);let u={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(Fxo(t[a])){let f=t[a];t[a]=(n=f.next)===null||n===void 0?void 0:n.bind(f),t[a+1]=(i=f.error)===null||i===void 0?void 0:i.bind(f),t[a+2]=(o=f.complete)===null||o===void 0?void 0:o.bind(f)}let p,c,l;if(r instanceof Fm)c=Df(r.firestore,Qb),l=eYe(r._key.path),p={next:f=>{t[a]&&t[a](kPo(c,r,f))},error:t[a+1],complete:t[a+2]};else{let f=Df(r,FR);c=Df(f.firestore,Qb),l=f._query;let h=new xce(c);p={next:A=>{t[a]&&t[a](new BG(c,h,f,A))},error:t[a+1],complete:t[a+2]},ETc(r._query)}let d=VT(c);return Y_h(d,l,u,p)}function FTc(r,t){r=Df(r,Qb);let n=VT(r),i=Fxo(t)?t:{next:t};return Z_h(n,i)}function sYe(r,t){let n=VT(r);return X_h(n,t)}function kPo(r,t,n){let i=n.docs.get(t._key),o=new xce(r);return new Vq(r,o,t._key,i,new Mce(n.hasPendingWrites,n.fromCache),t.converter)}var D3h={maxAttempts:5};function B3h(r){if(r.maxAttempts<1)throw new oi(Zr.INVALID_ARGUMENT,"Max attempts must be at least 1")}var j1r=class{constructor(t,n){this._firestore=t,this._commitHandler=n,this._mutations=[],this._committed=!1,this._dataReader=P4e(t)}set(t,n,i){this._verifyNotCommitted();let o=dye(t,this._firestore),s=igr(o.converter,n,i),a=rgr(this._dataReader,"WriteBatch.set",o._key,s,o.converter!==null,i);return this._mutations.push(a.toMutation(o._key,J2.none())),this}update(t,n,i,...o){this._verifyNotCommitted();let s=dye(t,this._firestore);n=ja(n);let a;return typeof n=="string"||n instanceof DG?a=MPo(this._dataReader,"WriteBatch.update",s._key,n,i,o):a=wPo(this._dataReader,"WriteBatch.update",s._key,n),this._mutations.push(a.toMutation(s._key,J2.exists(!0))),this}delete(t){this._verifyNotCommitted();let n=dye(t,this._firestore);return this._mutations=this._mutations.concat(new Sye(n._key,J2.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new oi(Zr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}};function dye(r,t){if(r=ja(r),r.firestore!==t)throw new oi(Zr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return r}var Uxo=class{constructor(t,n){this._firestore=t,this._transaction=n,this._dataReader=P4e(t)}get(t){let n=dye(t,this._firestore),i=new qxo(this._firestore);return this._transaction.lookup([n._key]).then(o=>{if(!o||o.length!==1)return Rs();let s=o[0];if(s.isFoundDocument())return new O4e(this._firestore,i,s.key,s,n.converter);if(s.isNoDocument())return new O4e(this._firestore,i,n._key,null,n.converter);throw Rs()})}set(t,n,i){let o=dye(t,this._firestore),s=igr(o.converter,n,i),a=rgr(this._dataReader,"Transaction.set",o._key,s,o.converter!==null,i);return this._transaction.set(o._key,a),this}update(t,n,i,...o){let s=dye(t,this._firestore);n=ja(n);let a;return typeof n=="string"||n instanceof DG?a=MPo(this._dataReader,"Transaction.update",s._key,n,i,o):a=wPo(this._dataReader,"Transaction.update",s._key,n),this._transaction.update(s._key,a),this}delete(t){let n=dye(t,this._firestore);return this._transaction.delete(n._key),this}};var zxo=class extends Uxo{constructor(t,n){super(t,n),this._firestore=t}get(t){let n=dye(t,this._firestore),i=new xce(this._firestore);return super.get(t).then(o=>new Vq(this._firestore,i,n._key,o._document,new Mce(!1,!1),n.converter))}};function UTc(r,t,n){r=Df(r,Qb);let i=Object.assign(Object.assign({},D3h),n);B3h(i);let o=VT(r);return e3h(o,s=>t(new zxo(r,s)),i)}function zTc(){return new j_t("deleteField")}function QTc(){return new Mxo("serverTimestamp")}function jTc(...r){return new xxo("arrayUnion",r)}function GTc(...r){return new Pxo("arrayRemove",r)}function HTc(r){return new Nxo("increment",r)}m3h("node");var L3h="@firebase/firestore-compat",k3h="0.3.28";function jPo(r,t){if(t===void 0)return{merge:!1};if(t.mergeFields!==void 0&&t.merge!==void 0)throw new oi("invalid-argument",`Invalid options passed to function ${r}(): You cannot specify both "merge" and "mergeFields".`);return t}function VTc(){if(typeof Uint8Array>"u")throw new oi("unimplemented","Uint8Arrays are not available in this environment.")}function WTc(){if(!bSc())throw new oi("unimplemented","Blobs are unavailable in Firestore in this environment.")}var ogr=class r{constructor(t){this._delegate=t}static fromBase64String(t){return WTc(),new r(L$.fromBase64String(t))}static fromUint8Array(t){return VTc(),new r(L$.fromUint8Array(t))}toBase64(){return WTc(),this._delegate.toBase64()}toUint8Array(){return VTc(),this._delegate.toUint8Array()}isEqual(t){return this._delegate.isEqual(t._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}};function qPo(r){return q3h(r,["next","error","complete"])}function q3h(r,t){if(typeof r!="object"||r===null)return!1;let n=r;for(let i of t)if(i in n&&typeof n[i]=="function")return!0;return!1}var FPo=class{enableIndexedDbPersistence(t,n){return iTc(t._delegate,{forceOwnership:n})}enableMultiTabIndexedDbPersistence(t){return oTc(t._delegate)}clearIndexedDbPersistence(t){return aTc(t._delegate)}},sgr=class{constructor(t,n,i){this._delegate=n,this._persistenceProvider=i,this.INTERNAL={delete:()=>this.terminate()},t instanceof mye||(this._appCompat=t)}get _databaseId(){return this._delegate._databaseId}settings(t){let n=this._delegate._getSettings();!t.merge&&n.host!==t.host&&Gq("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),t.merge&&(t=Object.assign(Object.assign({},n),t),delete t.merge),this._delegate._setSettings(t)}useEmulator(t,n,i={}){eTc(this._delegate,t,n,i)}enableNetwork(){return cTc(this._delegate)}disableNetwork(){return lTc(this._delegate)}enablePersistence(t){let n=!1,i=!1;return t&&(n=!!t.synchronizeTabs,i=!!t.experimentalForceOwningTab,SPo("synchronizeTabs",n,"experimentalForceOwningTab",i)),n?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,i)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return uTc(this._delegate)}onSnapshotsInSync(t){return FTc(this._delegate,t)}get app(){if(!this._appCompat)throw new oi("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(t){try{return new cYe(this,IPo(this._delegate,t))}catch(n){throw KP(n,"collection()","Firestore.collection()")}}doc(t){try{return new k$(this,r3t(this._delegate,t))}catch(n){throw KP(n,"doc()","Firestore.doc()")}}collectionGroup(t){try{return new k4e(this,tTc(this._delegate,t))}catch(n){throw KP(n,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return UTc(this._delegate,n=>t(new agr(this,n)))}batch(){return VT(this._delegate),new ugr(new j1r(this._delegate,t=>sYe(this._delegate,t)))}loadBundle(t){return pTc(this._delegate,t)}namedQuery(t){return dTc(this._delegate,t).then(n=>n?new k4e(this,n):null)}},aYe=class extends KKe{constructor(t){super(),this.firestore=t}convertBytes(t){return new ogr(new L$(t))}convertReference(t){let n=this.convertDocumentKey(t,this.firestore._databaseId);return k$.forKey(n,this.firestore,null)}};function F3h(r){ZCc(r)}var agr=class{constructor(t,n){this._firestore=t,this._delegate=n,this._userDataWriter=new aYe(t)}get(t){let n=D4e(t);return this._delegate.get(n).then(i=>new B4e(this._firestore,new Vq(this._firestore._delegate,this._userDataWriter,i._key,i._document,i.metadata,n.converter)))}set(t,n,i){let o=D4e(t);return i?(jPo("Transaction.set",i),this._delegate.set(o,n,i)):this._delegate.set(o,n),this}update(t,n,i,...o){let s=D4e(t);return arguments.length===2?this._delegate.update(s,n):this._delegate.update(s,n,i,...o),this}delete(t){let n=D4e(t);return this._delegate.delete(n),this}},ugr=class{constructor(t){this._delegate=t}set(t,n,i){let o=D4e(t);return i?(jPo("WriteBatch.set",i),this._delegate.set(o,n,i)):this._delegate.set(o,n),this}update(t,n,i,...o){let s=D4e(t);return arguments.length===2?this._delegate.update(s,n):this._delegate.update(s,n,i,...o),this}delete(t){let n=D4e(t);return this._delegate.delete(n),this}commit(){return this._delegate.commit()}},uYe=class r{constructor(t,n,i){this._firestore=t,this._userDataWriter=n,this._delegate=i}fromFirestore(t,n){let i=new Tye(this._firestore._delegate,this._userDataWriter,t._key,t._document,t.metadata,null);return this._delegate.fromFirestore(new L4e(this._firestore,i),n??{})}toFirestore(t,n){return n?this._delegate.toFirestore(t,n):this._delegate.toFirestore(t)}static getInstance(t,n){let i=r.INSTANCES,o=i.get(t);o||(o=new WeakMap,i.set(t,o));let s=o.get(n);return s||(s=new r(t,new aYe(t),n),o.set(n,s)),s}};uYe.INSTANCES=new WeakMap;var k$=class r{constructor(t,n){this.firestore=t,this._delegate=n,this._userDataWriter=new aYe(t)}static forPath(t,n,i){if(t.length%2!==0)throw new oi("invalid-argument",`Invalid document reference. Document references must have an even number of segments, but ${t.canonicalString()} has ${t.length}`);return new r(n,new Fm(n._delegate,i,new Bo(t)))}static forKey(t,n,i){return new r(n,new Fm(n._delegate,i,t))}get id(){return this._delegate.id}get parent(){return new cYe(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(t){try{return new cYe(this.firestore,IPo(this._delegate,t))}catch(n){throw KP(n,"collection()","DocumentReference.collection()")}}isEqual(t){return t=ja(t),t instanceof Fm?RPo(this._delegate,t):!1}set(t,n){n=jPo("DocumentReference.set",n);try{return n?DPo(this._delegate,t,n):DPo(this._delegate,t)}catch(i){throw KP(i,"setDoc()","DocumentReference.set()")}}update(t,n,...i){try{return arguments.length===1?BPo(this._delegate,t):BPo(this._delegate,t,n,...i)}catch(o){throw KP(o,"updateDoc()","DocumentReference.update()")}}delete(){return kTc(this._delegate)}onSnapshot(...t){let n=KTc(t),i=YTc(t,o=>new B4e(this.firestore,new Vq(this.firestore._delegate,this._userDataWriter,o._key,o._document,o.metadata,this._delegate.converter)));return LPo(this._delegate,n,i)}get(t){let n;return t?.source==="cache"?n=PTc(this._delegate):t?.source==="server"?n=NTc(this._delegate):n=xTc(this._delegate),n.then(i=>new B4e(this.firestore,new Vq(this.firestore._delegate,this._userDataWriter,i._key,i._document,i.metadata,this._delegate.converter)))}withConverter(t){return new r(this.firestore,t?this._delegate.withConverter(uYe.getInstance(this.firestore,t)):this._delegate.withConverter(null))}};function KP(r,t,n){return r.message=r.message.replace(t,n),r}function KTc(r){for(let t of r)if(typeof t=="object"&&!qPo(t))return t;return{}}function YTc(r,t){var n,i;let o;return qPo(r[0])?o=r[0]:qPo(r[1])?o=r[1]:typeof r[0]=="function"?o={next:r[0],error:r[1],complete:r[2]}:o={next:r[1],error:r[2],complete:r[3]},{next:s=>{o.next&&o.next(t(s))},error:(n=o.error)===null||n===void 0?void 0:n.bind(o),complete:(i=o.complete)===null||i===void 0?void 0:i.bind(o)}}var B4e=class{constructor(t,n){this._firestore=t,this._delegate=n}get ref(){return new k$(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(t){return this._delegate.data(t)}get(t,n){return this._delegate.get(t,n)}isEqual(t){return NPo(this._delegate,t._delegate)}},L4e=class extends B4e{data(t){let n=this._delegate.data(t);return this._delegate._converter||eSc(n!==void 0,"Document in a QueryDocumentSnapshot should exist"),n}},k4e=class r{constructor(t,n){this.firestore=t,this._delegate=n,this._userDataWriter=new aYe(t)}where(t,n,i){try{return new r(this.firestore,Nce(this._delegate,CTc(t,n,i)))}catch(o){throw KP(o,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(t,n){try{return new r(this.firestore,Nce(this._delegate,STc(t,n)))}catch(i){throw KP(i,/(orderBy|where)\(\)/,"Query.$1()")}}limit(t){try{return new r(this.firestore,Nce(this._delegate,vTc(t)))}catch(n){throw KP(n,"limit()","Query.limit()")}}limitToLast(t){try{return new r(this.firestore,Nce(this._delegate,TTc(t)))}catch(n){throw KP(n,"limitToLast()","Query.limitToLast()")}}startAt(...t){try{return new r(this.firestore,Nce(this._delegate,_Tc(...t)))}catch(n){throw KP(n,"startAt()","Query.startAt()")}}startAfter(...t){try{return new r(this.firestore,Nce(this._delegate,ITc(...t)))}catch(n){throw KP(n,"startAfter()","Query.startAfter()")}}endBefore(...t){try{return new r(this.firestore,Nce(this._delegate,RTc(...t)))}catch(n){throw KP(n,"endBefore()","Query.endBefore()")}}endAt(...t){try{return new r(this.firestore,Nce(this._delegate,OTc(...t)))}catch(n){throw KP(n,"endAt()","Query.endAt()")}}isEqual(t){return OPo(this._delegate,t._delegate)}get(t){let n;return t?.source==="cache"?n=BTc(this._delegate):t?.source==="server"?n=LTc(this._delegate):n=DTc(this._delegate),n.then(i=>new n3t(this.firestore,new BG(this.firestore._delegate,this._userDataWriter,this._delegate,i._snapshot)))}onSnapshot(...t){let n=KTc(t),i=YTc(t,o=>new n3t(this.firestore,new BG(this.firestore._delegate,this._userDataWriter,this._delegate,o._snapshot)));return LPo(this._delegate,n,i)}withConverter(t){return new r(this.firestore,t?this._delegate.withConverter(uYe.getInstance(this.firestore,t)):this._delegate.withConverter(null))}},UPo=class{constructor(t,n){this._firestore=t,this._delegate=n}get type(){return this._delegate.type}get doc(){return new L4e(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}},n3t=class{constructor(t,n){this._firestore=t,this._delegate=n}get query(){return new k4e(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(t=>new L4e(this._firestore,t))}docChanges(t){return this._delegate.docChanges(t).map(n=>new UPo(this._firestore,n))}forEach(t,n){this._delegate.forEach(i=>{t.call(n,new L4e(this._firestore,i))})}isEqual(t){return NPo(this._delegate,t._delegate)}},cYe=class r extends k4e{constructor(t,n){super(t,n),this.firestore=t,this._delegate=n}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){let t=this._delegate.parent;return t?new k$(this.firestore,t):null}doc(t){try{return t===void 0?new k$(this.firestore,r3t(this._delegate)):new k$(this.firestore,r3t(this._delegate,t))}catch(n){throw KP(n,"doc()","CollectionReference.doc()")}}add(t){return qTc(this._delegate,t).then(n=>new k$(this.firestore,n))}isEqual(t){return RPo(this._delegate,t._delegate)}withConverter(t){return new r(this.firestore,t?this._delegate.withConverter(uYe.getInstance(this.firestore,t)):this._delegate.withConverter(null))}};function D4e(r){return Df(r,Fm)}var zPo=class r{constructor(...t){this._delegate=new DG(...t)}static documentId(){return new r(cS.keyField().canonicalString())}isEqual(t){return t=ja(t),t instanceof DG?this._delegate._internalPath.isEqual(t._internalPath):!1}};var QPo=class r{constructor(t){this._delegate=t}static serverTimestamp(){let t=QTc();return t._methodName="FieldValue.serverTimestamp",new r(t)}static delete(){let t=zTc();return t._methodName="FieldValue.delete",new r(t)}static arrayUnion(...t){let n=jTc(...t);return n._methodName="FieldValue.arrayUnion",new r(n)}static arrayRemove(...t){let n=GTc(...t);return n._methodName="FieldValue.arrayRemove",new r(n)}static increment(t){let n=HTc(t);return n._methodName="FieldValue.increment",new r(n)}isEqual(t){return this._delegate.isEqual(t._delegate)}};var U3h={Firestore:sgr,GeoPoint:R4e,Timestamp:WE,Blob:ogr,Transaction:agr,WriteBatch:ugr,DocumentReference:k$,DocumentSnapshot:B4e,Query:k4e,QueryDocumentSnapshot:L4e,QuerySnapshot:n3t,CollectionReference:cYe,FieldPath:zPo,FieldValue:QPo,setLogLevel:F3h,CACHE_SIZE_UNLIMITED:rTc};function z3h(r,t){r.INTERNAL.registerComponent(new km("firestore-compat",n=>{let i=n.getProvider("app-compat").getImmediate(),o=n.getProvider("firestore").getImmediate();return t(i,o)},"PUBLIC").setServiceProps(Object.assign({},U3h)))}function Q3h(r){z3h(r,(t,n)=>new sgr(t,n,new FPo)),r.registerVersion(L3h,k3h,"node")}Q3h(Gh);var UR=[];for(let r=0;r<256;++r)UR.push((r+256).toString(16).slice(1));function JTc(r,t=0){return(UR[r[t+0]]+UR[r[t+1]]+UR[r[t+2]]+UR[r[t+3]]+"-"+UR[r[t+4]]+UR[r[t+5]]+"-"+UR[r[t+6]]+UR[r[t+7]]+"-"+UR[r[t+8]]+UR[r[t+9]]+"-"+UR[r[t+10]]+UR[r[t+11]]+UR[r[t+12]]+UR[r[t+13]]+UR[r[t+14]]+UR[r[t+15]]).toLowerCase()}var $Tc=require("crypto"),lgr=new Uint8Array(256),cgr=lgr.length;function GPo(){return cgr>lgr.length-16&&((0,$Tc.randomFillSync)(lgr),cgr=0),lgr.slice(cgr,cgr+=16)}var XTc=require("crypto"),HPo={randomUUID:XTc.randomUUID};function j3h(r,t,n){if(HPo.randomUUID&&!t&&!r)return HPo.randomUUID();r=r||{};let i=r.random??r.rng?.()??GPo();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)t[n+o]=i[o];return t}return JTc(i)}var mu=j3h;var pgr=yt(ZTc()),n_c=yt(e_c()),i_c=yt(t_c()),o_c=yt(r_c());pgr.default.extend(o_c.default);pgr.default.extend(n_c.default);pgr.default.extend(i_c.default);var Xc=class r{static _instance;logger;static setInstance(t){this._instance=t}static get instance(){return kE(!!this._instance,"ClientAuthService instance is not set",Ml()),this._instance}static get isInitialized(){return!!this._instance}static resolveAuthToken(){return r.instance.resolveAuthToken()}constructor(t){this.logger=t.child({category:"auth"}),this.getAuthToken=this.getAuthToken.bind(this)}async getAuthToken(){if(!this.isLoggedIn)throw new nt("Unable to obtain auth token, no user is logged in");if(this.isUsingBearerToken){let t=await this.resolveAuthToken();return kE(!!t,"Missing token from resolveAuthToken",this.logger),t}throw new nt("Auth token unavailable with cookie auth")}get isLoggedIn(){return!!this.currentUser}};var G3h=Je("RUNNER");function i3t(r){let t=Z1e(aa(r));return G3h.error("RunPost formattedRealError:",t,"raw error"),t}function o3t(r){return N1(r)&&(r.code==="ECONNABORTED"||r.code==="ETIMEDOUT")}var LG={None:null,sysCreateDate:"isSystemCreateDate",sysUpdateDate:"isSystemUpdateDate",sysStartDate:"isSystemStartDate",sysEndDate:"isSystemEndDate",sysVersion:"isSystemVersion",sysCurrentFlag:"isSystemCurrentFlag"},e4o={isChangeTracking:"isChangeTracking",isSurrogateKey:"isSurrogateKey",isBusinessKey:"isBusinessKey",none:"None"},dgr={isBusinessKey:"primaryBusinessKey",isSurrogateKey:"surrogateKey"},t4o=r=>!!(typeof r=="object"&&r!==null&&"items"in r&&Array.isArray(r.items)),r4o={[LG.sysCreateDate]:"sysCreateDate",[LG.sysUpdateDate]:"sysUpdateDate",[LG.sysStartDate]:"sysStartDate",[LG.sysEndDate]:"sysEndDate",[LG.sysVersion]:"sysVersion",[LG.sysCurrentFlag]:"sysCurrentFlag"};var V3h=Je("TIMING_UTILS"),kG=r=>new Promise(t=>setTimeout(t,r)),Ah=async(r,t,n,i,o="debug",...s)=>{let a=Je(n);a.logContextAtLevel(o,t,r,"starting");let u=performance.now();try{return await i()}catch(p){let{error:{errorString:c,errorDetail:l}}=aa(p);throw a.errorContext(t,r,`
|
|
2133
2133
|
rejected with an error: `,c,l),p}finally{let c=performance.now()-u;a.logContextAtLevel(o,t,r,`
|
|
2134
2134
|
completed in ${c}ms`,{name:r,"time-ms":c,params:s})}};var s_c=async(r,t,n)=>{let i=`Back-end: ${r}`;try{return await Ah(i,n,"PERFORMANCE",()=>t(r))}catch(o){let s=o;throw o.message==="Cannot read property 'currentSecretID' of undefined"&&(s=new Error("Missing password or client secret - please update your environment settings")),s}},a_c=r=>r.hasOwnProperty("seconds")&&r.hasOwnProperty("nanoseconds"),fgr=r=>typeof r=="string"?new Date(r).getTime():!r||typeof r!="object"?(V3h.assert("invalid time in GetMsFromQueryResultTime: ",r,"typeof time:",typeof r),0):a_c(r)?r.seconds*1e3+r.nanoseconds/1e6:r.getTime(),n4o=r=>{if(a_c(r)){let t=fgr(r);return new Date(t)}else return typeof r.toDate=="function"?r.toDate():r};var u_c=r=>{let t=new Date().getTime()-r.getTime();return Math.round(t/(1440*60*1e3))};var i4o=r=>+((performance.now()-r)/1e3).toFixed(3),Bf=(r,t)=>{let n="[performanceSummary]",i=[],o=performance.now(),s=(c,l)=>`${c}: ${i4o(l)} seconds`,a=(c,l)=>i.push(`
|
|
2135
2135
|
${s(c,l)};`);return{measure:async(c,l,d)=>{let f=performance.now();try{let h=await l();return a(d?`${c} (${d(h)})`:c,f),h}catch(h){throw a(`${c} (FAILED)`,f),h}},printSummary:()=>{let c=`(${s("total runtime",o)})`;Je("PERFORMANCE").infoContext(t,n,r,c,...i)}}};var W3h=Je("CLI"),K3h=(r,t)=>{let n=r||{name:"random",min:60,max:180};switch(n.name){case"nowait":return 0;case"backoff":return t*n.base*1e3;case"random":return Xgc(n.min*1e3,n.max*1e3)}},cf=async(r,t,n,i,o)=>{let s=0,a=(p,c,l,d=[])=>{let f=p==="info"?"info":p==="emerg"?"fatal":"error";n.logContextAtLevel(f,i,c,...d),l&&W3h.logContextAtLevel(f,i,c,...d)},u;for(;;)try{u&&await u();let p=await r();return s!==0&&a(o?.retryLogLevel,`Operation succeeded on retry ${s+1}`,!0),p}catch(p){s++;let c=`(attempt ${s}/${t})`,l=o?.logOnFailure,d=o?.logOnRetry,f=o?.customErrorOnRetry?o.customErrorOnRetry(p):[p],h=o?.customErrorOnFailure?o.customErrorOnFailure(p):[p];if(s>=t)throw l!==void 0&&a(o?.failureLogLevel,`${l} ${c}:`,!0,h),p;if(o?.checkError){let v=o.checkError(p,s);if(v)throw a(o?.failureLogLevel,`Error was not retryable. ${c}`,!1),v;a(o?.retryLogLevel,`Error was retryable. ${d} ${c}:`,!0,f)}let A=o?.alterRetryStrategy&&o.alterRetryStrategy(p,o?.retryStrategy)||o?.retryStrategy,E=Math.round(K3h(A,s));d&&a(o.retryLogLevel,`${d} (attempt ${s+1}/${t}) in ${E/1e3} seconds:`,!0,f),u=o?.beforeRetry&&(()=>o.beforeRetry(p)),E&&await kG(E)}};function o4o(r){let t=r.response?.status;return!!t&&t>499&&t<600}function Y3h(r,t){return r.includes("https://securetoken.googleapis.com")&&t===502}function J3h(r,t,n){let i=r.includes(Db()),o=i&&n&&n.includes("/api/json_template"),s=i&&r.startsWith("https://local.app.coalescestage.io");return o||t===502&&i||(t===504||t===503)&&s}function s4o(r){if(!o4o(r))return!1;let n=r.config&&(r.config.baseURL??Db()),i=r.config?.url,o=r.response?.status;if(!n||!o)return!1;let s=J3h(n,o,i),a=Y3h(n,o);return s||a}var c_c=Je("RUNNER");async function a4o(r,t=3,n=1e4){let i="RetryTransientErrorsWithExponentialBackoff";return cf(r,t+1,c_c,{},{retryStrategy:{name:"backoff",base:n/1e3},logOnRetry:`${i} retryable request failure`,retryLogLevel:"info",logOnFailure:`${i} failed, request never resolved after maximum allowed retries.`,failureLogLevel:"error",customErrorOnFailure:o=>{let s=new Error().stack,a=N1(o)&&o.config?o.config.baseURL:"";return[o,s,a]},checkError:o=>{if(!N1(o)||o.response?.status===401)return o;if(o3t(o)){let a=o.config?.url??o.config?.baseURL??"unknown";c_c.info(`${i} request timed out (url: ${a}), scheduling retry`);return}if(!s4o(o))return o}})}var $3h=Je("RUNNER");async function u4o(r){return await cf(r,3,$3h,{},{checkError:i=>(i instanceof Error?i.toString():"").toLowerCase().includes("getaddrinfo")?null:i,logOnRetry:"Got an error that looks like DNS, retrying"})}function c4o(r){return()=>u4o(r)}var X3h=1e4;function lYe(){let r=process.env.SCHEDULER_REQUEST_TIMEOUT_MS;if(typeof r=="string"&&r!==""){let t=Number(r);if(!Number.isNaN(t))return t}return X3h}var bL={getFormattedRealErrorFromAxiosError:i3t,isAxiosTimeoutError:o3t,RetryTransientErrorsWithExponentialBackoff:a4o,WrapRequestInDNSRetry:c4o};var l4o=(a=>(a.NotRun="not_run",a.Running="running",a.Success="success",a.Queued="queued",a.Failed="failed",a.TestFailed="test_failed",a))(l4o||{});var l_c=et.object({scheduledJobID:et.string(),name:et.string(),cron:et.string(),cronTimezone:et.string().optional(),userID:et.string(),orgID:et.string(),environmentID:et.number(),jobID:et.number(),runBaseUrl:et.string(),userCredentials:et.union([et.object({platformKind:et.string().optional(),snowflakeAuthType:et.string(),snowflakeUsername:et.string().optional()}),et.object({platformKind:et.string(),databricksAuthType:et.string(),databricksPath:et.string().optional()}),et.object({platformKind:et.string(),fabricAuthType:et.string(),fabricConnectionString:et.string().optional()}),et.object({platformKind:et.string(),bigQueryAuthType:et.string()})]),parameters:et.record(et.string(),et.union([et.string(),et.number(),et.null(),et.boolean(),et.unknown()])).optional(),paused:et.boolean().optional(),lastRunID:et.string().optional(),lastRunStatus:et.nativeEnum(l4o).optional(),lastRunHasTestFailures:et.boolean().optional(),lastExecution:et.string().optional(),nextExecution:et.string().optional(),retry:et.discriminatedUnion("enabled",[et.object({enabled:et.literal(!0),maxCount:et.number(),waitBetween:et.number(),action:et.string().optional()}),et.object({enabled:et.literal(!1)})]).optional(),notifications:et.object({email:et.discriminatedUnion("enabled",[et.object({emails:et.array(et.string()),enabled:et.literal(!0),trigger:et.string()}),et.object({enabled:et.literal(!1)})])})}).passthrough(),Z3h=et.object({scheduledJobs:et.array(l_c)}),SS2=et.object({orgID:et.string(),environmentID:et.number(),jobID:et.number(),paused:et.boolean().optional()}),eIh=et.object({timezones:et.array(et.string())}),p_c=Mr("JobScheduleDto",l_c),d_c=Mr("JobSchedulesDto",Z3h),f_c=Mr("JobScheduleValidTimezonesDto",eIh);var hgr=[200,201,202,204],h_c=r=>({id:r.scheduledJobID,cronExpression:r.cron,cronTimezone:r.cronTimezone||"UTC",environmentId:r.environmentID,jobId:r.jobID,name:r.name,orgId:r.orgID,userId:r.userID,runBaseUrl:r.runBaseUrl,userCredentials:r.userCredentials,paused:r.paused??!1,lastRunId:r.lastRunID,lastRunStatus:r.lastRunStatus,lastRunHasTestFailures:r.lastRunHasTestFailures,lastExecution:r.lastExecution,nextExecution:r.nextExecution,notifications:r.notifications,retry:r.retry,parameters:r.parameters}),g_c=r=>({scheduledJobID:r.id,cron:r.cronExpression,cronTimezone:r.cronTimezone,environmentID:r.environmentId,jobID:r.jobId,name:r.name,orgID:r.orgId,userID:r.userId,runBaseUrl:r.runBaseUrl,userCredentials:r.userCredentials,paused:r.paused,lastRunID:r.lastRunId,lastRunStatus:r.lastRunStatus,lastRunHasTestFailures:r.lastRunHasTestFailures,lastExecution:r.lastExecution,nextExecution:r.nextExecution,notifications:r.notifications,retry:r.retry,parameters:r.parameters}),s3t=class r{static _instance;baseUrl;token;constructor(){}static getInstance(){return r._instance||(r._instance=new r),r._instance}static getServiceInstance(t,n){let i=new r;return i.setUrl(t),i.token=n,i}isInitialized(){return this.baseUrl!==void 0}setUrl(t,n){(!this.baseUrl||n)&&(this.baseUrl=t,this.baseUrl.endsWith("/")||(this.baseUrl+="/"))}get=async(t,n)=>{if(!this.baseUrl)throw new nt("Client was not initialized.");let i={};if(Xc.isInitialized){if(!Xc.instance.currentUser)throw new nt("Unable to retrieve token, no current user!");let p=await Xc.resolveAuthToken();p&&(i.headers={Authorization:`Bearer ${p}`})}else this.token&&(i.headers={Authorization:`Bearer ${this.token}`});n&&(i.params=n);let o=async()=>dc.get(t,i),s=bL.WrapRequestInDNSRetry(o),a=await bL.RetryTransientErrorsWithExponentialBackoff(s);if(!hgr.includes(a.status))throw new nt("Error occurred trying to fetch",t);return a.data};post=async(t,n)=>{if(!this.baseUrl)throw new nt("Client was not initialized.");let i={},o;Xc.isInitialized?o=await Xc.resolveAuthToken():this.token&&(o=this.token),o&&(i.Authorization=`Bearer ${o}`);let s=async()=>dc.post(t,n,{headers:i}),a=bL.WrapRequestInDNSRetry(s),u=await bL.RetryTransientErrorsWithExponentialBackoff(a);if(!hgr.includes(u.status))throw new nt("Error occurred trying to post",t);return u.data};put=async(t,n)=>{if(!this.baseUrl)throw new nt("Client was not initialized.");let i={},o;Xc.isInitialized?o=await Xc.resolveAuthToken():this.token&&(o=this.token),o&&(i.Authorization=`Bearer ${o}`);let s=async()=>dc.put(t,n,{headers:i}),a=bL.WrapRequestInDNSRetry(s),u=await bL.RetryTransientErrorsWithExponentialBackoff(a);if(!hgr.includes(u.status))throw new nt("Error occurred trying to post",t);return u.data};delete=async t=>{if(!this.baseUrl)throw new nt("Client was not initialized.");let n={},i;Xc.isInitialized?i=await Xc.resolveAuthToken():this.token&&(i=this.token),i&&(n.Authorization=`Bearer ${i}`);let o=async()=>dc.delete(t,{headers:n}),s=bL.WrapRequestInDNSRetry(o),a=await bL.RetryTransientErrorsWithExponentialBackoff(s);if(!hgr.includes(a.status))throw new nt("Error occurred trying to delete",t);return a.data};fetchValidTimezones=async()=>{let t=`${this.baseUrl}api/job_scheduler/v1/valid_timezones`,n=await this.get(t);return f_c.assert(n).timezones};fetchJobSchedules=async()=>{let t=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs`,n=await this.get(t);return d_c.assert(n).scheduledJobs.map(h_c)};createJobSchedule=async t=>{let n=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs`,{refreshToken:i,...o}=t,s={refreshToken:i,...g_c(o)};return this.post(n,s)};updateJobSchedule=async t=>{let n=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs/${t.id}`,{refreshToken:i,...o}=t,s={refreshToken:i,...g_c(o)};return this.put(n,s)};fetchJobSchedule=async t=>{let n=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs/${t}`,i=await this.get(n),o=p_c.assert(i);return h_c(o)};deleteJobSchedule=async t=>{let n=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs/${t}`;return this.delete(n)};pauseJobSchedule=async(t,n,i,o,s)=>{let a=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs/${t}/pause`,u={orgID:n,environmentID:i,jobID:o,paused:s};return this.post(a,u)};updateEnvironmentCredentials=async(t,n)=>{let i=`${this.baseUrl}api/job_scheduler/v1/scheduled_jobs/credentials/${t}`;return this.post(i,n)}};var A_c=r=>_We(r.connectionKind,r,{snowflake:t=>({platformKind:"snowflake",snowflakeAuthType:t.connectionType,snowflakeUsername:t.connectionDetails?.user}),databricks:t=>({platformKind:"databricks",databricksAuthType:t.connectionType}),fabric:t=>({platformKind:"fabric",fabricAuthType:t.connectionType}),bigquery:t=>({platformKind:"bigquery",bigQueryAuthType:t.connectionType})},"getCredentialRequest");var M4o=r=>t=>{let n=`[object ${r}]`;return t&&(toString.call(t)===n||typeof t.toString=="function"&&t.toString()===n)},WS2=M4o("FormData"),KS2=M4o("Blob"),YS2=M4o("File");function PRh(r,t){var n;return r&&((n=t.config)!=null&&n.headers)?!t.config.headers.Authorization.includes(r):!1}function z4e(r){return{request:async(t,n)=>{let i=await r.getToken();return i?{...n,headers:{...n.headers,Authorization:`Bearer ${i}`}}:n},error:r.renewToken?async(t,n,i)=>{var o;if(dc.isAxiosError(i)&&r.renewToken&&i.config&&((o=i.response)==null?void 0:o.status)===401){let s=await r.renewToken();if(PRh(s,i)){let a={...i.config};return a.headers={...a.headers,Authorization:`Bearer ${s}`},dc(a)}}throw i}:void 0}}function NRh(r,t){let n={...r};for(let i of t)delete n[i];return n}var DRh=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;function BRh(r){let t=r.url,n=r.params;return n&&(t=t.replace(DRh,(i,o)=>o in n?`${n[o]}`:i)),t}function l3c(r,t,n){return r.find(i=>i.method===t&&i.path===n)}function LRh(r){let t=new FormData;for(let n in r)t.append(n,r[n]);return{data:t}}var hYe=class extends Error{constructor(r,t,n,i){super(r),this.config=t,this.data=n,this.cause=i}},kRh={name:"form-data",request:async(r,t)=>{if(typeof t.data!="object"||Array.isArray(t.data))throw new hYe("Zodios: multipart/form-data body must be an object",t);let n=LRh(t.data);return{...t,data:n.data,headers:{...t.headers,...n.headers}}}};function qRh(){return kRh}var FRh={name:"form-url",request:async(r,t)=>{if(typeof t.data!="object"||Array.isArray(t.data))throw new hYe("Zodios: application/x-www-form-urlencoded body must be an object",t);return{...t,data:new URLSearchParams(t.data).toString(),headers:{...t.headers,"Content-Type":"application/x-www-form-urlencoded"}}}};function URh(){return FRh}function p3c(r,t){return{request:async(n,i)=>({...i,headers:{...i.headers,[r]:t}})}}function d3c(r){return[!0,"response","all"].includes(r)}function f3c(r){return[!0,"request","all"].includes(r)}function zRh({validate:r,transform:t,sendDefaults:n}){return{name:"zod-validation",request:f3c(r)?async(i,o)=>{let s=l3c(i,o.method,o.url);if(!s)throw new Error(`No endpoint found for ${o.method} ${o.url}`);let{parameters:a}=s;if(!a)return o;let u={...o,queries:{...o.queries},headers:{...o.headers},params:{...o.params}},p={Query:d=>{var f;return(f=u.queries)==null?void 0:f[d]},Body:d=>u.data,Header:d=>{var f;return(f=u.headers)==null?void 0:f[d]},Path:d=>{var f;return(f=u.params)==null?void 0:f[d]}},c={Query:(d,f)=>u.queries[d]=f,Body:(d,f)=>u.data=f,Header:(d,f)=>u.headers[d]=f,Path:(d,f)=>u.params[d]=f},l=f3c(t);for(let d of a){let{name:f,schema:h,type:A}=d,E=p[A](f);if(n||E!==void 0){let v=await h.safeParseAsync(E);if(!v.success)throw new hYe(`Zodios: Invalid ${A} parameter '${f}'`,o,E,v.error);l&&c[A](f,v.data)}}return u}:void 0,response:d3c(r)?async(i,o,s)=>{var a,u,p,c;let l=l3c(i,o.method,o.url);if(!l)throw new Error(`No endpoint found for ${o.method} ${o.url}`);if((u=(a=s.headers)==null?void 0:a["content-type"])!=null&&u.includes("application/json")||(c=(p=s.headers)==null?void 0:p["content-type"])!=null&&c.includes("application/vnd.api+json")){let d=await l.response.safeParseAsync(s.data);if(!d.success)throw new hYe(`Zodios: Invalid response from endpoint '${l.method} ${l.path}'
|
|
@@ -9596,12 +9596,12 @@ Content-Type: application/json; charset=utf-8\r
|
|
|
9596
9596
|
Content-Type: `+c.contentType+`\r
|
|
9597
9597
|
\r
|
|
9598
9598
|
`,f=`\r
|
|
9599
|
-
--`+p+"--",h=a$e.getBlob(d,i,f);if(h===null)throw Yjc();let A={name:c.fullPath},E=Ale(s,r.host,r._protocol),v="POST",T=r.maxUploadRetryTime,w=new uF(E,v,xEr(r,n),T);return w.urlParams=A,w.headers=a,w.body=h.uploadData(),w.errorHandler=l$e(t),w}var u$e=class{constructor(t,n,i,o){this.current=t,this.total=n,this.finalized=!!i,this.metadata=o||null}};function i9o(r,t){let n=null;try{n=r.getResponseHeader("X-Goog-Upload-Status")}catch{mX(!1)}return mX(!!n&&(t||["active"]).indexOf(n)!==-1),n}function c01(r,t,n,i,o){let s=t.bucketOnlyServerUrl(),a=iGc(t,i,o),u={name:a.fullPath},p=Ale(s,r.host,r._protocol),c="POST",l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${i.size()}`,"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},d=n9o(a,n),f=r.maxUploadRetryTime;function h(E){i9o(E);let v;try{v=E.getResponseHeader("X-Goog-Upload-URL")}catch{mX(!1)}return mX(wEr(v)),v}let A=new uF(p,c,h,f);return A.urlParams=u,A.headers=l,A.body=d,A.errorHandler=l$e(t),A}function l01(r,t,n,i){let o={"X-Goog-Upload-Command":"query"};function s(c){let l=i9o(c,["active","final"]),d=null;try{d=c.getResponseHeader("X-Goog-Upload-Size-Received")}catch{mX(!1)}d||mX(!1);let f=Number(d);return mX(!isNaN(f)),new u$e(f,i.size(),l==="final")}let a="POST",u=r.maxUploadRetryTime,p=new uF(n,a,s,u);return p.headers=o,p.errorHandler=l$e(t),p}var zjc=256*1024;function p01(r,t,n,i,o,s,a,u){let p=new u$e(0,0);if(a?(p.current=a.current,p.total=a.total):(p.current=0,p.total=i.size()),i.size()!==p.total)throw _d1();let c=p.total-p.current,l=c;o>0&&(l=Math.min(l,o));let d=p.current,f=d+l,h="";l===0?h="finalize":c===l?h="upload, finalize":h="upload";let A={"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":`${p.current}`},E=i.slice(d,f);if(E===null)throw Yjc();function v(k,L){let q=i9o(k,["active","final"]),G=p.current+l,H=i.size(),V;return q==="final"?V=xEr(t,s)(k,L):V=null,new u$e(G,H,q==="final",V)}let T="POST",w=t.maxUploadRetryTime,N=new uF(n,T,v,w);return N.headers=A,N.body=E.uploadData(),N.progressCallback=u||null,N.errorHandler=l$e(r),N}var oGc={STATE_CHANGED:"state_changed"},UM={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Hko(r){switch(r){case"running":case"pausing":case"canceling":return UM.RUNNING;case"paused":return UM.PAUSED;case"success":return UM.SUCCESS;case"canceled":return UM.CANCELED;case"error":return UM.ERROR;default:return UM.ERROR}}var Yko=class{constructor(t,n,i){if(Md1(t)||n!=null||i!=null)this.next=t,this.error=n??void 0,this.complete=i??void 0;else{let s=t;this.next=s.next,this.error=s.error,this.complete=s.complete}}};function n$e(r){return(...t)=>{Promise.resolve().then(()=>r(...t))}}var Qjc=null,OEr=class{constructor(){this.errorText_="",this.sent_=!1,this.fetch_=Gjc.fetch,this.errorCode_=qNe.NO_ERROR}async send(t,n,i,o){if(this.sent_)throw i$e("cannot .send() more than once");this.sent_=!0;try{let s=await this.fetch_(t,{method:n,headers:o||{},body:i});this.headers_=s.headers,this.statusCode_=s.status,this.errorCode_=qNe.NO_ERROR,this.body_=await s.arrayBuffer()}catch(s){this.errorText_=s?.message,this.statusCode_=0,this.errorCode_=qNe.NETWORK_ERROR}}getErrorCode(){if(this.errorCode_===void 0)throw i$e("cannot .getErrorCode() before receiving response");return this.errorCode_}getStatus(){if(this.statusCode_===void 0)throw i$e("cannot .getStatus() before receiving response");return this.statusCode_}getErrorText(){return this.errorText_}abort(){}getResponseHeader(t){if(!this.headers_)throw i$e("cannot .getResponseHeader() before receiving response");return this.headers_.get(t)}addUploadProgressListener(t){}removeUploadProgressListener(t){}},Jko=class extends OEr{getResponse(){if(!this.body_)throw i$e("cannot .getResponse() before receiving response");return Buffer.from(this.body_).toString("utf-8")}};function AX(){return Qjc?Qjc():new Jko}var $ko=class extends OEr{getResponse(){if(!this.body_)throw i$e("cannot .getResponse() before sending");return this.body_}};function d01(){return new $ko}var HRt=class{constructor(t,n,i=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=t,this._blob=n,this._metadata=i,this._mappings=MEr(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=o=>{if(this._request=void 0,this._chunkMultiplier=1,o._codeEquals(Gb.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{let s=this.isExponentialBackoffExpired();if(Xjc(o.status,[]))if(s)o=Wjc();else{this.sleepTime=Math.max(this.sleepTime*2,Ad1),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=o,this._transition("error")}},this._metadataErrorHandler=o=>{this._request=void 0,o._codeEquals(Gb.CANCELED)?this.completeTransitions_():(this._error=o,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((o,s)=>{this._resolve=o,this._reject=s,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){let t=this._transferred;return n=>this._updateProgress(t+n)}_shouldDoResumable(t){return t.size()>256*1024}_start(){this._state==="running"&&this._request===void 0&&(this._resumable?this._uploadUrl===void 0?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(t){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([n,i])=>{switch(this._state){case"running":t(n,i);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((t,n)=>{let i=c01(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),o=this._ref.storage._makeRequest(i,AX,t,n);this._request=o,o.getPromise().then(s=>{this._request=void 0,this._uploadUrl=s,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let t=this._uploadUrl;this._resolveToken((n,i)=>{let o=l01(this._ref.storage,this._ref._location,t,this._blob),s=this._ref.storage._makeRequest(o,AX,n,i);this._request=s,s.getPromise().then(a=>{a=a,this._request=void 0,this._updateProgress(a.current),this._needToFetchStatus=!1,a.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let t=zjc*this._chunkMultiplier,n=new u$e(this._transferred,this._blob.size()),i=this._uploadUrl;this._resolveToken((o,s)=>{let a;try{a=p01(this._ref._location,this._ref.storage,i,this._blob,t,this._mappings,n,this._makeProgressCallback())}catch(p){this._error=p,this._transition("error");return}let u=this._ref.storage._makeRequest(a,AX,o,s,!1);this._request=u,u.getPromise().then(p=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(p.current),p.finalized?(this._metadata=p.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){zjc*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((t,n)=>{let i=nGc(this._ref.storage,this._ref._location,this._mappings),o=this._ref.storage._makeRequest(i,AX,t,n);this._request=o,o.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((t,n)=>{let i=u01(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),o=this._ref.storage._makeRequest(i,AX,t,n);this._request=o,o.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(t){let n=this._transferred;this._transferred=t,this._transferred!==n&&this._notifyObservers()}_transition(t){if(this._state!==t)switch(t){case"canceling":case"pausing":this._state=t,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let n=this._state==="paused";this._state=t,n&&(this._notifyObservers(),this._start());break;case"paused":this._state=t,this._notifyObservers();break;case"canceled":this._error=Kjc(),this._state=t,this._notifyObservers();break;case"error":this._state=t,this._notifyObservers();break;case"success":this._state=t,this._notifyObservers();break}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start();break}}get snapshot(){let t=Hko(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:t,metadata:this._metadata,task:this,ref:this._ref}}on(t,n,i,o){let s=new Yko(n||void 0,i||void 0,o||void 0);return this._addObserver(s),()=>{this._removeObserver(s)}}then(t,n){return this._promise.then(t,n)}catch(t){return this.then(null,t)}_addObserver(t){this._observers.push(t),this._notifyObserver(t)}_removeObserver(t){let n=this._observers.indexOf(t);n!==-1&&this._observers.splice(n,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(n=>{this._notifyObserver(n)})}_finishPromise(){if(this._resolve!==void 0){let t=!0;switch(Hko(this._state)){case UM.SUCCESS:n$e(this._resolve.bind(null,this.snapshot))();break;case UM.CANCELED:case UM.ERROR:let n=this._reject;n$e(n.bind(null,this._error))();break;default:t=!1;break}t&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(t){switch(Hko(this._state)){case UM.RUNNING:case UM.PAUSED:t.next&&n$e(t.next.bind(t,this.snapshot))();break;case UM.SUCCESS:t.complete&&n$e(t.complete.bind(t))();break;case UM.CANCELED:case UM.ERROR:t.error&&n$e(t.error.bind(t,this._error))();break;default:t.error&&n$e(t.error.bind(t,this._error))()}}resume(){let t=this._state==="paused"||this._state==="pausing";return t&&this._transition("running"),t}pause(){let t=this._state==="running";return t&&this._transition("pausing"),t}cancel(){let t=this._state==="running"||this._state==="pausing";return t&&this._transition("canceling"),t}};var c$e=class r{constructor(t,n){this._service=t,n instanceof s4?this._location=n:this._location=s4.makeFromUrl(n,t.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(t,n){return new r(t,n)}get root(){let t=new s4(this._location.bucket,"");return this._newRef(this._service,t)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return tGc(this._location.path)}get storage(){return this._service}get parent(){let t=Hd1(this._location.path);if(t===null)return null;let n=new s4(this._location.bucket,t);return new r(this._service,n)}_throwIfRoot(t){if(this._location.path==="")throw Zko(t)}};function f01(r,t){r._throwIfRoot("getBytes");let n=n01(r.storage,r._location,t);return r.storage.makeRequestWithTokens(n,d01).then(i=>t!==void 0?i.slice(0,t):i)}function h01(r,t,n){return r._throwIfRoot("uploadBytesResumable"),new HRt(r,new a$e(t),n)}function g01(r){let t={prefixes:[],items:[]};return sGc(r,t).then(()=>t)}async function sGc(r,t,n){let o=await aGc(r,{pageToken:n});t.prefixes.push(...o.prefixes),t.items.push(...o.items),o.nextPageToken!=null&&await sGc(r,t,o.nextPageToken)}function aGc(r,t){t!=null&&typeof t.maxResults=="number"&&Wko("options.maxResults",1,1e3,t.maxResults);let n=t||{},i=r01(r.storage,r._location,"/",n.pageToken,n.maxResults);return r.storage.makeRequestWithTokens(i,AX)}function A01(r){r._throwIfRoot("getMetadata");let t=nGc(r.storage,r._location,MEr());return r.storage.makeRequestWithTokens(t,AX)}function m01(r,t){r._throwIfRoot("updateMetadata");let n=o01(r.storage,r._location,t,MEr());return r.storage.makeRequestWithTokens(n,AX)}function y01(r){r._throwIfRoot("getDownloadURL");let t=i01(r.storage,r._location,MEr());return r.storage.makeRequestWithTokens(t,AX).then(n=>{if(n===null)throw Id1();return n})}function b01(r){r._throwIfRoot("deleteObject");let t=s01(r.storage,r._location);return r.storage.makeRequestWithTokens(t,AX)}function uGc(r,t){let n=Vd1(r._location.path,t),i=new s4(r._location.bucket,n);return new c$e(r.storage,i)}function E01(r){return/^[A-Za-z]+:\/\//.test(r)}function C01(r,t){return new c$e(r,t)}function cGc(r,t){if(r instanceof VRt){let n=r;if(n._bucket==null)throw Td1();let i=new c$e(n,n._bucket);return t!=null?cGc(i,t):i}else return t!==void 0?uGc(r,t):r}function S01(r,t){if(t&&E01(t)){if(r instanceof VRt)return C01(r,t);throw FNe("To use ref(service, url), the first argument must be a Storage instance.")}else return cGc(r,t)}function jjc(r,t){let n=t?.[Vjc];return n==null?null:s4.makeFromBucketSpec(n,r)}function v01(r,t,n,i={}){r.host=`${t}:${n}`,r._protocol="http";let{mockUserToken:o}=i;o&&(r._overrideAuthToken=typeof o=="string"?o:k0r(o,r.app.options.projectId))}var VRt=class{constructor(t,n,i,o,s){this.app=t,this._authProvider=n,this._appCheckProvider=i,this._url=o,this._firebaseVersion=s,this._bucket=null,this._host=Hjc,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=hd1,this._maxUploadRetryTime=gd1,this._requests=new Set,o!=null?this._bucket=s4.makeFromBucketSpec(o,this._host):this._bucket=jjc(this._host,this.app.options)}get host(){return this._host}set host(t){this._host=t,this._url!=null?this._bucket=s4.makeFromBucketSpec(this._url,t):this._bucket=jjc(t,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(t){Wko("time",0,Number.POSITIVE_INFINITY,t),this._maxUploadRetryTime=t}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(t){Wko("time",0,Number.POSITIVE_INFINITY,t),this._maxOperationRetryTime=t}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let t=this._authProvider.getImmediate({optional:!0});if(t){let n=await t.getToken();if(n!==null)return n.accessToken}return null}async _getAppCheckToken(){let t=this._appCheckProvider.getImmediate({optional:!0});return t?(await t.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(t=>t.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(t){return new c$e(this,t)}_makeRequest(t,n,i,o,s=!0){if(this._deleted)return new Vko(Jjc());{let a=Ld1(t,this._appId,i,o,n,this._firebaseVersion,s);return this._requests.add(a),a.getPromise().then(()=>this._requests.delete(a),()=>this._requests.delete(a)),a}}async makeRequestWithTokens(t,n){let[i,o]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(t,n,i,o).getPromise()}},T01="@firebase/storage",_01="0.12.3";var I01="storage";function lGc(r,t){return r=ja(r),f01(r,t)}function PEr(r,t,n){return r=ja(r),h01(r,t,n)}function pGc(r){return r=ja(r),A01(r)}function dGc(r,t){return r=ja(r),m01(r,t)}function fGc(r,t){return r=ja(r),aGc(r,t)}function hGc(r){return r=ja(r),g01(r)}function gGc(r){return r=ja(r),y01(r)}function AGc(r){return r=ja(r),b01(r)}function KRt(r,t){return r=ja(r),S01(r,t)}function mGc(r,t){return uGc(r,t)}function yGc(r,t,n,i={}){v01(r,t,n,i)}function R01(r,{instanceIdentifier:t}){let n=r.getProvider("app").getImmediate(),i=r.getProvider("auth-internal"),o=r.getProvider("app-check-internal");return new VRt(n,i,o,t,hL)}function O01(){zP(new km(I01,R01,"PUBLIC").setMultipleInstances(!0)),vv(T01,_01)}O01();var p$e=class{constructor(t,n,i){this._delegate=t,this.task=n,this.ref=i}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}};var NEr=class{constructor(t,n){this._delegate=t,this._ref=n,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new p$e(this._delegate.snapshot,this,this._ref)}then(t,n){return this._delegate.then(i=>{if(t)return t(new p$e(i,this,this._ref))},n)}on(t,n,i,o){let s;return n&&(typeof n=="function"?s=a=>n(new p$e(a,this,this._ref)):s={next:n.next?a=>n.next(new p$e(a,this,this._ref)):void 0,complete:n.complete||void 0,error:n.error||void 0}),this._delegate.on(t,s,i||void 0,o||void 0)}},DEr=class{constructor(t,n){this._delegate=t,this._service=n}get prefixes(){return this._delegate.prefixes.map(t=>new UNe(t,this._service))}get items(){return this._delegate.items.map(t=>new UNe(t,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}};var UNe=class r{constructor(t,n){this._delegate=t,this.storage=n}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(t){let n=mGc(this._delegate,t);return new r(n,this.storage)}get root(){return new r(this._delegate.root,this.storage)}get parent(){let t=this._delegate.parent;return t==null?null:new r(t,this.storage)}put(t,n){return this._throwIfRoot("put"),new NEr(PEr(this._delegate,t,n),this)}putString(t,n=DL.RAW,i){this._throwIfRoot("putString");let o=t9o(n,t),s=Object.assign({},i);return s.contentType==null&&o.contentType!=null&&(s.contentType=o.contentType),new NEr(new HRt(this._delegate,new a$e(o.data,!0),s),this)}listAll(){return hGc(this._delegate).then(t=>new DEr(t,this.storage))}list(t){return fGc(this._delegate,t||void 0).then(n=>new DEr(n,this.storage))}getMetadata(){return pGc(this._delegate)}updateMetadata(t){return dGc(this._delegate,t)}getDownloadURL(){return gGc(this._delegate)}delete(){return this._throwIfRoot("delete"),AGc(this._delegate)}_throwIfRoot(t){if(this._delegate._location.path==="")throw Zko(t)}};var BEr=class{constructor(t,n){this.app=t,this._delegate=n}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(t){if(bGc(t))throw FNe("ref() expected a child path but got a URL, use refFromURL instead.");return new UNe(KRt(this._delegate,t),this)}refFromURL(t){if(!bGc(t))throw FNe("refFromURL() expected a full URL but got a child path, use ref() instead.");try{s4.makeFromUrl(t,this._delegate.host)}catch{throw FNe("refFromUrl() expected a valid full URL but got an invalid one.")}return new UNe(KRt(this._delegate,t),this)}setMaxUploadRetryTime(t){this._delegate.maxUploadRetryTime=t}setMaxOperationRetryTime(t){this._delegate.maxOperationRetryTime=t}useEmulator(t,n,i={}){yGc(this._delegate,t,n,i)}};function bGc(r){return/^[A-Za-z]+:\/\//.test(r)}var w01="@firebase/storage-compat",M01="0.3.6";var x01="storage-compat";function P01(r,{instanceIdentifier:t}){let n=r.getProvider("app-compat").getImmediate(),i=r.getProvider("storage").getImmediate({identifier:t});return new BEr(n,i)}function N01(r){let t={TaskState:UM,TaskEvent:oGc,StringFormat:DL,Storage:BEr,Reference:UNe};r.INTERNAL.registerComponent(new km(x01,P01,"PUBLIC").setServiceProps(t).setMultipleInstances(!0)),r.registerVersion(w01,M01)}N01(Gh);var BB2=yt(xNe(),1);var D01="firebase",B01="10.10.0";Gh.registerVersion(D01,B01,"app-compat");var EGc,o9o=new WeakMap,L01=()=>{},k01=class vbe{constructor(t){this.subscribers=[],this.settlement=null,this[EGc]="Unpromise",t instanceof Promise?this.promise=t:this.promise=new Promise(t),this.promise.then(n=>{let{subscribers:i}=this;this.subscribers=null,this.settlement={status:"fulfilled",value:n},i?.forEach(({resolve:o})=>{o(n)})}).catch(n=>{let{subscribers:i}=this;this.subscribers=null,this.settlement={status:"rejected",reason:n},i?.forEach(({reject:o})=>{o(n)})})}subscribe(){let t,n,{settlement:i}=this;if(i===null){if(this.subscribers===null)throw new Error("Unpromise settled but still has subscribers");let o=q01();this.subscribers=F01(this.subscribers,o),t=o.promise,n=()=>{this.subscribers!==null&&(this.subscribers=z01(this.subscribers,o))}}else{let{status:o}=i;o==="fulfilled"?t=Promise.resolve(i.value):t=Promise.reject(i.reason),n=L01}return Object.assign(t,{unsubscribe:n})}then(t,n){let i=this.subscribe(),{unsubscribe:o}=i;return Object.assign(i.then(t,n),{unsubscribe:o})}catch(t){let n=this.subscribe(),{unsubscribe:i}=n;return Object.assign(n.catch(t),{unsubscribe:i})}finally(t){let n=this.subscribe(),{unsubscribe:i}=n;return Object.assign(n.finally(t),{unsubscribe:i})}static proxy(t){let n=vbe.getSubscribablePromise(t);return typeof n<"u"?n:vbe.createSubscribablePromise(t)}static createSubscribablePromise(t){let n=new vbe(t);return o9o.set(t,n),o9o.set(n,n),n}static getSubscribablePromise(t){return o9o.get(t)}static resolve(t){return vbe.proxy(t).subscribe()}static async any(t){let n=t.map(vbe.resolve);try{return await Promise.any(n)}finally{n.forEach(({unsubscribe:i})=>{i()})}}static async race(t){let n=t.map(vbe.resolve);try{return await Promise.race(n)}finally{n.forEach(({unsubscribe:i})=>{i()})}}static async raceSingletons(t){let n=t.map(i=>vbe.proxy(i).then(()=>[i]));try{return await Promise.race(n)}finally{for(let i of n)i.unsubscribe()}}};EGc=Symbol.toStringTag;var LEr=k01;function q01(){let r,t;return{promise:new Promise((n,i)=>{r=n,t=i}),resolve:r,reject:t}}function F01(r,t){return[...r,t]}function U01(r,t){return[...r.slice(0,t),...r.slice(t+1)]}function z01(r,t){let n=r.indexOf(t);return n!==-1?U01(r,n):r}var zNe=class extends nt{};var JR=async(r,t,n)=>{let i=Q01(r),o=i.promise.then(()=>{throw new zNe(t)});return await LEr.race([n,o]).finally(i.cancel)},Q01=r=>{let t=TR(),n=setTimeout(t.resolve,r),i=()=>clearTimeout(n);return{promise:t.promise,cancel:i}};var YB2=global.setImmediate??setTimeout;var ZG=(()=>{let r=o=>{if(typeof window<"u"){let s=window[o];if(typeof s=="string"&&s)return s}return process.env[o]},t=r("FIREBASE_AUTH_EMULATOR_HOST"),n=r("FIRESTORE_EMULATOR_HOST"),i=r("FIREBASE_STORAGE_EMULATOR_HOST");if(!!t!=!!n||!!t!=!!i||!!n!=!!i)throw new Error(`Inconsistent Firebase emulator use! All three emulators must be used, or none! auth=${t} firestore=${n} storage=${i}`);return t&&n&&i?{auth:t.startsWith("http")?t:`http://${t}`,firestore:n,storage:i}:null})();var j01=Pb({auth:ld(),firestore:ld(),storage:ld()}),CGc=Mr("FirebaseEmulatorInfo",j01);var YRt=Je("FIREBASE"),G01=(r,t)=>{let n;if(ZG)n=ZG;else if("emulatorInfo"in r.options)n=CGc.assert(r.options.emulatorInfo);else return!1;Hg().isTest&&(t=!1),YRt.info(`Using Firebase Auth emulator at ${n.auth}`),typeof window<"u"?LNe(oEr(r),n.auth):r.auth().useEmulator(n.auth),YRt.info(`Using Firestore emulator at ${n.firestore} over ${t?"https":"http"}`);let[i,o]=n.firestore.split(":");r.firestore().useEmulator(i,parseInt(o)),t&&r.firestore()._delegate._setSettings({...r.firestore()._delegate._getSettings(),ssl:!0}),YRt.info(`Using Firebase Storage emulator at ${n.storage} over ${t?"https":"http"}`);let[s,a]=n.storage.split(":");return r.storage().useEmulator(s,parseInt(a)),t&&(r.storage()._delegate._protocol="https"),!0},H01="[DEFAULT]";var SGc=async(r,t)=>{Gh.apps.find(n=>n.name===(t??H01))||await V01(r,t)};async function V01(r,t){let n=Gh.initializeApp(r,t);if(!G01(n,!i3())&&!i3()&&ixe(!1,"proxyFirestore")){let i=await vGc(r);YRt.info(`Using Firestore proxy host: ${i}`),n.firestore().settings({host:i})}}var vGc=r=>{if(r.emulatorInfo)return`http://${r.emulatorInfo.firestore}`;let t=new URL(sQe());return pd(t.protocol==="https:"&&(t.port==="443"||t.port==="")&&t.pathname==="/",`Unable to specify a firestore proxy host for backend URL ${t}. Only HTTPS with no port and no path is supported.`,"FIREBASE"),`${t.hostname}/firestore`};var W01=Gh;var TGc=()=>W01;var _Gc=r=>oQe()?Promise.resolve():r.delete().catch(t=>{YRt.error(`Error deleting firebase instance: ${t}`)});var kEr=r=>{let t=ep(r);return Object.values(t).forEach(n=>{n.id=n.id.toString(),n.steps=n.steps.map(i=>i.toString())}),t};var qEr=async(r,t)=>{let i=[],o;for(;;){let s=await r.nodes.select({limit:1e3,startingFrom:o,orderBy:[]},{ignoreDataTransformErrors:!!t});if(i=i.concat(s),s.length<1e3)break;o=s[s.length-1].id}return Lpo(i.map(s=>[s.id,{operation:jLc(s)}]))},IGc=async r=>{let t=await r.subgraphs.select();return kEr(X1e(t,"id"))},RGc=async r=>{let t=await r.jobs.select();return X1e(t,"id")},s9o=async r=>{let t=await r.macros.select();return X1e(t,"id")},OGc=async(r,t)=>{let n=await r.nodeTypes.select(void 0,{ignoreDataTransformErrors:!!t});return X1e(n,"id")},wGc=async(r,t)=>{let n=await r.workspaceUsers.select();return{[t]:X1e(n,"id")}},MGc=async r=>{let t=await r.installedPackages.select();return X1e(t,"id")},xGc=async r=>{let t=await r.fetch();return{locations:qIt(t),defaultStorageMapping:t.defaultStorageMapping}};var a9o=Je("FIREBASE"),cL2=Je("GIT"),PGc=Je("WORKSPACES");var d$e=r=>({...NGc({},{},{},{},lNe(r),r),defaultStorageMapping:null,locations:{},installedPackages:{}}),FEr=r=>NGc({},{},{},{},{},r),NGc=(r,t,n,i,o,s)=>({steps:r,folders:t,jobs:n,macros:i,stepTypes:o,platformKind:s}),UEr=(r,t,n,i,o)=>{let s="[getAllWorkspaceDataFromRepository]",u={orgID:t.id,workspaceID:r,...o};return cf(async()=>Ah(s,u,"WORKSPACES",async()=>{let c="getAllWorkspaceDataFromRepository()";n.logMemorySnapshot(u,`${s} Before workspace data loading`,c);let l=t.workspace(r),d=await xGc(l),[f,h,A,E,v,T,w]=await Promise.all([IGc(l),RGc(l),s9o(l),wGc(l,r),MGc(l),qEr(l,i),OGc(l,i)]),N={folders:f,jobs:h,macros:A,stepTypes:w,userConnections:E,locations:d.locations,installedPackages:v,steps:T};return n.logMemorySnapshot(u,`${s} Workspace data loading completed`,c),n.cleanup(),PGc.infoContext(u,`${s} Loaded workspace data - Steps: ${Object.keys(N.steps).length}, Step types: ${Object.keys(N.stepTypes).length}, Users: ${Object.keys(N.userConnections||{}).length}`),N},"info"),3,a9o,u,{retryStrategy:{name:"nowait"},logOnRetry:`${s} retrying`,logOnFailure:`${s} failed, exhausted allotted retry attempts`})},QNe=async(r,t,n)=>{let{steps:i,...o}=await UEr(r,t,n);return{steps:Hce(i),...o}};var DGc=async(r,t,n,i)=>{let o=r.id,s=NPe(o,n,t);(i?.connectionKind==="snowflake"||i?.connectionKind===void 0)&&hh("CONNECTION",!!i&&BGc(i),{orgID:o,userID:t},"is valid user connection data on save"),a9o.appContext({orgID:o,userID:t,workspaceID:n},`Modifying user connection for user ${t} / team ${o} / workspace ${n}`,i);let a=$3o.parse({id:t,version:1,...r3(i,["createdAt","updatedAt","createdBy","updatedBy","id"])});try{await r.workspace(n).workspaceUser(t).save(a)}catch(u){if(u instanceof Du){a9o.infoContext({orgID:o,userID:t,workspaceID:n},"Failed to save workspace user entity. Creating one instead.",a,u),await r.workspace(n).workspaceUsers.createEntity(a);return}throw u}try{if(s3t.getInstance().isInitialized()&&!await r.workspace(n).isDevEnv()){let u=A_c(a);await s3t.getInstance().updateEnvironmentCredentials(n,u)}}catch(u){PGc.errorContext(s,"Issue with updating Scheduled Job credentials",u)}};var LGc=Je("CONNECTION"),Y01=TM("UserConnectionType",dAc),J01=(r,t)=>$g({snowflake:()=>tf1(t),databricks:()=>ef1(t),fabric:()=>Z01(t),bigquery:()=>X01(t)},r,"CreateDefaultUserConnection"),$01=(r,t)=>({connectionType:r,connectionDetails:{userID:t,clientEmail:""},connectionKind:"bigquery"}),X01=r=>$01("ServiceAccount",r),Z01=(r,t="oauth")=>({connectionKind:"fabric",connectionType:t,connectionDetails:{userID:r,connectionString:""}}),ef1=r=>({connectionType:"Cloud",connectionDetails:{userID:r,path:""},connectionKind:"databricks"}),tf1=r=>rf1("Cloud",r,"",""),rf1=(r,t,n,i)=>({connectionType:r,connectionDetails:{user:n,role:i,userID:t,warehouse:""},connectionKind:"snowflake"});var BGc=r=>Y01.is(r),mle=async(r,t)=>{try{let n=await r.fetch({retryOptions:{attempts:3,tags:["[GetUserConnectionInfoByEnvironment]"],waitSeconds:60}}),i=_We(n.connectionKind,n,{snowflake:o=>({connectionType:o.connectionType,connectionDetails:{user:o.connectionDetails?.user??"",userID:o.connectionDetails?.userID??"",role:o.connectionDetails?.role,warehouse:o.connectionDetails?.warehouse}}),databricks:o=>({connectionKind:"databricks",connectionType:o.connectionType,connectionDetails:{path:o.connectionDetails?.path??"",userID:o.connectionDetails?.userID??""}}),fabric:o=>({connectionKind:"fabric",connectionType:"oauth",connectionDetails:{connectionString:o.connectionDetails?.connectionString,userID:o.connectionDetails?.userID??""}}),bigquery:o=>({connectionKind:"bigquery",connectionType:o.connectionType,connectionDetails:{userID:o.connectionDetails?.userID??"",clientEmail:o.connectionDetails?.clientEmail??""}})},"GetUserConnectionInfoByEnvironment");return LGc.infoContext(t,"User Connection found,","kind:",i.connectionKind??"snowflake","type:",i.connectionType),i}catch(n){throw LGc.errorContext(t,"Error getting user connection info",n),n instanceof Du?new Vi("Invalid Connection Information, environment or connection does not exist. Please check that the environmentID is valid, and contains a valid connection.",`environmentID: ${t.workspaceID}: ${n.detail||n.message}`):n}},Tbe=async(r,t)=>{try{await r.fetch()}catch(n){if(n instanceof Du){let{id:i,parent:{id:o,parent:s}}=r,a=Lme(t,{snowflake:p=>p.snowflakeAuthType,databricks:p=>p.databricksAuthType,fabric:p=>p.fabricAuthType,bigquery:p=>p.bigQueryAuthType},"writeBasicUserConnectionIfNoneExists");if(a==="WorkspaceUserDefault")throw new nt("Unexpected connection type 'WorkspaceUserDefault'");let u={...J01(t.platformKind??"snowflake",i),...a&&{connectionType:a}};await DGc(s,i,o,u)}else throw n}};var u9o=r=>typeof r=="object"&&r instanceof Error&&"code"in r&&(typeof r.code=="string"||typeof r.code=="number")&&"name"in r&&typeof r.name=="string",kGc=r=>u9o(r)&&(r.name==="NetworkError"||r.code===401001);var yX=class extends Mme{constructor(t,n,i){super(t,n,i)}},zEr=class extends DA{constructor(n){super("Could not identify the initial warehouse - possibly invalid credentials or warehouse");this.warehouse=n}warehouse;statusCode(){return 400}toTRunError(){let n=this.warehouse?`Tried to set a warehouse of ${this.warehouse}`:"Did not set a warehouse";return{error:{errorString:this.message,errorDetail:`${n} and snowflake did not indicate a warehouse was used, but it should have`}}}},yle=class extends nt{constructor(n){let i="Snowflake execution error",o;typeof n=="object"&&n instanceof Error&&(i=n.message||i,o=n.stack);super(i);this.coalesceCause=n;this.originalStack=o}coalesceCause;originalStack;statusCode(){switch(this.getSnowflakeErrorCode()){case"390189":case"390100":return 401;case"000604":return 499;case"001003":case"002040":default:return 422}}isCancel(){return this.getSnowflakeErrorCode()==="000604"}getSnowflakeErrorCode(){try{return this.coalesceCause.code??null}catch{return null}}getErrorDetail=()=>{if(this.coalesceCause.name==="OperationFailedError")try{let n=this.coalesceCause.data;if(n)return`name=${this.coalesceCause.name}, code=${this.coalesceCause.code}, data=${JSON.stringify(n)}`}catch{}if(this.coalesceCause.name==="NetworkError")try{let n=this.coalesceCause.coalesceCause;if(n&&n.message)return`name=${this.coalesceCause.name}, code=${this.coalesceCause.code}, cause=${n.message}`}catch{}try{return`name=${this.coalesceCause.name}, code=${this.coalesceCause.code}`}catch{}return""};getErrorData=()=>this.getSnowflakeErrorCode()==="390189"?{errorString:"Role not found or is invalid",errorDetail:this.coalesceCause.message}:{errorString:this.message,errorDetail:this.getErrorDetail()};toTRunError(){return{error:this.getErrorData()}}},cF=class extends yle{constructor(n,i,o,s,a){super(n);this.options=i;this.requestID=o;this.queryID=s;this.warehouse=a}options;requestID;queryID;warehouse};var bX=class extends nt{constructor(n,i){let{errorString:o,errorDetail:s}=ua(i).error;super(o,s);this.query=n;this.coalesceCause=i}query;coalesceCause;isCancel(){return(this.getDatabricksErrorCause()?.includes("The session was closed or has expired")||this.getDatabricksErrorCause()?.includes("canceled"))??!1}getDatabricksErrorCause(){return this.message??null}statusCode(){return this.isCancel()?499:422}},eH=class extends Mme{constructor(t,n,i){super(t,n,i)}};var if1=Je("STEPS");var c9o=(r,t,n)=>{let i={},o=new Set([t]),s=0,a=new Set,u=new Set([t]);try{for(;u.size>0;){s=s+1,a=u,u=new Set;for(let p of a){o.add(p);let c=n==="predecessors"?r.predecessors(p):r.successors(p);if(c)for(let l of c)i[s]||(i[s]=new Set),!o.has(l)&&(i[s].add(l),u.add(l))}}}catch(p){throw if1.error(`getSuccessorsOrPredecessorsWithLevels threw an error when getting ${n} for step: ${t}. error:
|
|
9599
|
+
--`+p+"--",h=a$e.getBlob(d,i,f);if(h===null)throw Yjc();let A={name:c.fullPath},E=Ale(s,r.host,r._protocol),v="POST",T=r.maxUploadRetryTime,w=new uF(E,v,xEr(r,n),T);return w.urlParams=A,w.headers=a,w.body=h.uploadData(),w.errorHandler=l$e(t),w}var u$e=class{constructor(t,n,i,o){this.current=t,this.total=n,this.finalized=!!i,this.metadata=o||null}};function i9o(r,t){let n=null;try{n=r.getResponseHeader("X-Goog-Upload-Status")}catch{mX(!1)}return mX(!!n&&(t||["active"]).indexOf(n)!==-1),n}function c01(r,t,n,i,o){let s=t.bucketOnlyServerUrl(),a=iGc(t,i,o),u={name:a.fullPath},p=Ale(s,r.host,r._protocol),c="POST",l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${i.size()}`,"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},d=n9o(a,n),f=r.maxUploadRetryTime;function h(E){i9o(E);let v;try{v=E.getResponseHeader("X-Goog-Upload-URL")}catch{mX(!1)}return mX(wEr(v)),v}let A=new uF(p,c,h,f);return A.urlParams=u,A.headers=l,A.body=d,A.errorHandler=l$e(t),A}function l01(r,t,n,i){let o={"X-Goog-Upload-Command":"query"};function s(c){let l=i9o(c,["active","final"]),d=null;try{d=c.getResponseHeader("X-Goog-Upload-Size-Received")}catch{mX(!1)}d||mX(!1);let f=Number(d);return mX(!isNaN(f)),new u$e(f,i.size(),l==="final")}let a="POST",u=r.maxUploadRetryTime,p=new uF(n,a,s,u);return p.headers=o,p.errorHandler=l$e(t),p}var zjc=256*1024;function p01(r,t,n,i,o,s,a,u){let p=new u$e(0,0);if(a?(p.current=a.current,p.total=a.total):(p.current=0,p.total=i.size()),i.size()!==p.total)throw _d1();let c=p.total-p.current,l=c;o>0&&(l=Math.min(l,o));let d=p.current,f=d+l,h="";l===0?h="finalize":c===l?h="upload, finalize":h="upload";let A={"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":`${p.current}`},E=i.slice(d,f);if(E===null)throw Yjc();function v(k,L){let q=i9o(k,["active","final"]),G=p.current+l,H=i.size(),V;return q==="final"?V=xEr(t,s)(k,L):V=null,new u$e(G,H,q==="final",V)}let T="POST",w=t.maxUploadRetryTime,N=new uF(n,T,v,w);return N.headers=A,N.body=E.uploadData(),N.progressCallback=u||null,N.errorHandler=l$e(r),N}var oGc={STATE_CHANGED:"state_changed"},UM={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Hko(r){switch(r){case"running":case"pausing":case"canceling":return UM.RUNNING;case"paused":return UM.PAUSED;case"success":return UM.SUCCESS;case"canceled":return UM.CANCELED;case"error":return UM.ERROR;default:return UM.ERROR}}var Yko=class{constructor(t,n,i){if(Md1(t)||n!=null||i!=null)this.next=t,this.error=n??void 0,this.complete=i??void 0;else{let s=t;this.next=s.next,this.error=s.error,this.complete=s.complete}}};function n$e(r){return(...t)=>{Promise.resolve().then(()=>r(...t))}}var Qjc=null,OEr=class{constructor(){this.errorText_="",this.sent_=!1,this.fetch_=Gjc.fetch,this.errorCode_=qNe.NO_ERROR}async send(t,n,i,o){if(this.sent_)throw i$e("cannot .send() more than once");this.sent_=!0;try{let s=await this.fetch_(t,{method:n,headers:o||{},body:i});this.headers_=s.headers,this.statusCode_=s.status,this.errorCode_=qNe.NO_ERROR,this.body_=await s.arrayBuffer()}catch(s){this.errorText_=s?.message,this.statusCode_=0,this.errorCode_=qNe.NETWORK_ERROR}}getErrorCode(){if(this.errorCode_===void 0)throw i$e("cannot .getErrorCode() before receiving response");return this.errorCode_}getStatus(){if(this.statusCode_===void 0)throw i$e("cannot .getStatus() before receiving response");return this.statusCode_}getErrorText(){return this.errorText_}abort(){}getResponseHeader(t){if(!this.headers_)throw i$e("cannot .getResponseHeader() before receiving response");return this.headers_.get(t)}addUploadProgressListener(t){}removeUploadProgressListener(t){}},Jko=class extends OEr{getResponse(){if(!this.body_)throw i$e("cannot .getResponse() before receiving response");return Buffer.from(this.body_).toString("utf-8")}};function AX(){return Qjc?Qjc():new Jko}var $ko=class extends OEr{getResponse(){if(!this.body_)throw i$e("cannot .getResponse() before sending");return this.body_}};function d01(){return new $ko}var HRt=class{constructor(t,n,i=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=t,this._blob=n,this._metadata=i,this._mappings=MEr(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=o=>{if(this._request=void 0,this._chunkMultiplier=1,o._codeEquals(Gb.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{let s=this.isExponentialBackoffExpired();if(Xjc(o.status,[]))if(s)o=Wjc();else{this.sleepTime=Math.max(this.sleepTime*2,Ad1),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=o,this._transition("error")}},this._metadataErrorHandler=o=>{this._request=void 0,o._codeEquals(Gb.CANCELED)?this.completeTransitions_():(this._error=o,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((o,s)=>{this._resolve=o,this._reject=s,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){let t=this._transferred;return n=>this._updateProgress(t+n)}_shouldDoResumable(t){return t.size()>256*1024}_start(){this._state==="running"&&this._request===void 0&&(this._resumable?this._uploadUrl===void 0?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(t){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([n,i])=>{switch(this._state){case"running":t(n,i);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((t,n)=>{let i=c01(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),o=this._ref.storage._makeRequest(i,AX,t,n);this._request=o,o.getPromise().then(s=>{this._request=void 0,this._uploadUrl=s,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let t=this._uploadUrl;this._resolveToken((n,i)=>{let o=l01(this._ref.storage,this._ref._location,t,this._blob),s=this._ref.storage._makeRequest(o,AX,n,i);this._request=s,s.getPromise().then(a=>{a=a,this._request=void 0,this._updateProgress(a.current),this._needToFetchStatus=!1,a.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let t=zjc*this._chunkMultiplier,n=new u$e(this._transferred,this._blob.size()),i=this._uploadUrl;this._resolveToken((o,s)=>{let a;try{a=p01(this._ref._location,this._ref.storage,i,this._blob,t,this._mappings,n,this._makeProgressCallback())}catch(p){this._error=p,this._transition("error");return}let u=this._ref.storage._makeRequest(a,AX,o,s,!1);this._request=u,u.getPromise().then(p=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(p.current),p.finalized?(this._metadata=p.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){zjc*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((t,n)=>{let i=nGc(this._ref.storage,this._ref._location,this._mappings),o=this._ref.storage._makeRequest(i,AX,t,n);this._request=o,o.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((t,n)=>{let i=u01(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),o=this._ref.storage._makeRequest(i,AX,t,n);this._request=o,o.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(t){let n=this._transferred;this._transferred=t,this._transferred!==n&&this._notifyObservers()}_transition(t){if(this._state!==t)switch(t){case"canceling":case"pausing":this._state=t,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let n=this._state==="paused";this._state=t,n&&(this._notifyObservers(),this._start());break;case"paused":this._state=t,this._notifyObservers();break;case"canceled":this._error=Kjc(),this._state=t,this._notifyObservers();break;case"error":this._state=t,this._notifyObservers();break;case"success":this._state=t,this._notifyObservers();break}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start();break}}get snapshot(){let t=Hko(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:t,metadata:this._metadata,task:this,ref:this._ref}}on(t,n,i,o){let s=new Yko(n||void 0,i||void 0,o||void 0);return this._addObserver(s),()=>{this._removeObserver(s)}}then(t,n){return this._promise.then(t,n)}catch(t){return this.then(null,t)}_addObserver(t){this._observers.push(t),this._notifyObserver(t)}_removeObserver(t){let n=this._observers.indexOf(t);n!==-1&&this._observers.splice(n,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(n=>{this._notifyObserver(n)})}_finishPromise(){if(this._resolve!==void 0){let t=!0;switch(Hko(this._state)){case UM.SUCCESS:n$e(this._resolve.bind(null,this.snapshot))();break;case UM.CANCELED:case UM.ERROR:let n=this._reject;n$e(n.bind(null,this._error))();break;default:t=!1;break}t&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(t){switch(Hko(this._state)){case UM.RUNNING:case UM.PAUSED:t.next&&n$e(t.next.bind(t,this.snapshot))();break;case UM.SUCCESS:t.complete&&n$e(t.complete.bind(t))();break;case UM.CANCELED:case UM.ERROR:t.error&&n$e(t.error.bind(t,this._error))();break;default:t.error&&n$e(t.error.bind(t,this._error))()}}resume(){let t=this._state==="paused"||this._state==="pausing";return t&&this._transition("running"),t}pause(){let t=this._state==="running";return t&&this._transition("pausing"),t}cancel(){let t=this._state==="running"||this._state==="pausing";return t&&this._transition("canceling"),t}};var c$e=class r{constructor(t,n){this._service=t,n instanceof s4?this._location=n:this._location=s4.makeFromUrl(n,t.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(t,n){return new r(t,n)}get root(){let t=new s4(this._location.bucket,"");return this._newRef(this._service,t)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return tGc(this._location.path)}get storage(){return this._service}get parent(){let t=Hd1(this._location.path);if(t===null)return null;let n=new s4(this._location.bucket,t);return new r(this._service,n)}_throwIfRoot(t){if(this._location.path==="")throw Zko(t)}};function f01(r,t){r._throwIfRoot("getBytes");let n=n01(r.storage,r._location,t);return r.storage.makeRequestWithTokens(n,d01).then(i=>t!==void 0?i.slice(0,t):i)}function h01(r,t,n){return r._throwIfRoot("uploadBytesResumable"),new HRt(r,new a$e(t),n)}function g01(r){let t={prefixes:[],items:[]};return sGc(r,t).then(()=>t)}async function sGc(r,t,n){let o=await aGc(r,{pageToken:n});t.prefixes.push(...o.prefixes),t.items.push(...o.items),o.nextPageToken!=null&&await sGc(r,t,o.nextPageToken)}function aGc(r,t){t!=null&&typeof t.maxResults=="number"&&Wko("options.maxResults",1,1e3,t.maxResults);let n=t||{},i=r01(r.storage,r._location,"/",n.pageToken,n.maxResults);return r.storage.makeRequestWithTokens(i,AX)}function A01(r){r._throwIfRoot("getMetadata");let t=nGc(r.storage,r._location,MEr());return r.storage.makeRequestWithTokens(t,AX)}function m01(r,t){r._throwIfRoot("updateMetadata");let n=o01(r.storage,r._location,t,MEr());return r.storage.makeRequestWithTokens(n,AX)}function y01(r){r._throwIfRoot("getDownloadURL");let t=i01(r.storage,r._location,MEr());return r.storage.makeRequestWithTokens(t,AX).then(n=>{if(n===null)throw Id1();return n})}function b01(r){r._throwIfRoot("deleteObject");let t=s01(r.storage,r._location);return r.storage.makeRequestWithTokens(t,AX)}function uGc(r,t){let n=Vd1(r._location.path,t),i=new s4(r._location.bucket,n);return new c$e(r.storage,i)}function E01(r){return/^[A-Za-z]+:\/\//.test(r)}function C01(r,t){return new c$e(r,t)}function cGc(r,t){if(r instanceof VRt){let n=r;if(n._bucket==null)throw Td1();let i=new c$e(n,n._bucket);return t!=null?cGc(i,t):i}else return t!==void 0?uGc(r,t):r}function S01(r,t){if(t&&E01(t)){if(r instanceof VRt)return C01(r,t);throw FNe("To use ref(service, url), the first argument must be a Storage instance.")}else return cGc(r,t)}function jjc(r,t){let n=t?.[Vjc];return n==null?null:s4.makeFromBucketSpec(n,r)}function v01(r,t,n,i={}){r.host=`${t}:${n}`,r._protocol="http";let{mockUserToken:o}=i;o&&(r._overrideAuthToken=typeof o=="string"?o:k0r(o,r.app.options.projectId))}var VRt=class{constructor(t,n,i,o,s){this.app=t,this._authProvider=n,this._appCheckProvider=i,this._url=o,this._firebaseVersion=s,this._bucket=null,this._host=Hjc,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=hd1,this._maxUploadRetryTime=gd1,this._requests=new Set,o!=null?this._bucket=s4.makeFromBucketSpec(o,this._host):this._bucket=jjc(this._host,this.app.options)}get host(){return this._host}set host(t){this._host=t,this._url!=null?this._bucket=s4.makeFromBucketSpec(this._url,t):this._bucket=jjc(t,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(t){Wko("time",0,Number.POSITIVE_INFINITY,t),this._maxUploadRetryTime=t}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(t){Wko("time",0,Number.POSITIVE_INFINITY,t),this._maxOperationRetryTime=t}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let t=this._authProvider.getImmediate({optional:!0});if(t){let n=await t.getToken();if(n!==null)return n.accessToken}return null}async _getAppCheckToken(){let t=this._appCheckProvider.getImmediate({optional:!0});return t?(await t.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(t=>t.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(t){return new c$e(this,t)}_makeRequest(t,n,i,o,s=!0){if(this._deleted)return new Vko(Jjc());{let a=Ld1(t,this._appId,i,o,n,this._firebaseVersion,s);return this._requests.add(a),a.getPromise().then(()=>this._requests.delete(a),()=>this._requests.delete(a)),a}}async makeRequestWithTokens(t,n){let[i,o]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(t,n,i,o).getPromise()}},T01="@firebase/storage",_01="0.12.3";var I01="storage";function lGc(r,t){return r=ja(r),f01(r,t)}function PEr(r,t,n){return r=ja(r),h01(r,t,n)}function pGc(r){return r=ja(r),A01(r)}function dGc(r,t){return r=ja(r),m01(r,t)}function fGc(r,t){return r=ja(r),aGc(r,t)}function hGc(r){return r=ja(r),g01(r)}function gGc(r){return r=ja(r),y01(r)}function AGc(r){return r=ja(r),b01(r)}function KRt(r,t){return r=ja(r),S01(r,t)}function mGc(r,t){return uGc(r,t)}function yGc(r,t,n,i={}){v01(r,t,n,i)}function R01(r,{instanceIdentifier:t}){let n=r.getProvider("app").getImmediate(),i=r.getProvider("auth-internal"),o=r.getProvider("app-check-internal");return new VRt(n,i,o,t,hL)}function O01(){zP(new km(I01,R01,"PUBLIC").setMultipleInstances(!0)),vv(T01,_01)}O01();var p$e=class{constructor(t,n,i){this._delegate=t,this.task=n,this.ref=i}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}};var NEr=class{constructor(t,n){this._delegate=t,this._ref=n,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new p$e(this._delegate.snapshot,this,this._ref)}then(t,n){return this._delegate.then(i=>{if(t)return t(new p$e(i,this,this._ref))},n)}on(t,n,i,o){let s;return n&&(typeof n=="function"?s=a=>n(new p$e(a,this,this._ref)):s={next:n.next?a=>n.next(new p$e(a,this,this._ref)):void 0,complete:n.complete||void 0,error:n.error||void 0}),this._delegate.on(t,s,i||void 0,o||void 0)}},DEr=class{constructor(t,n){this._delegate=t,this._service=n}get prefixes(){return this._delegate.prefixes.map(t=>new UNe(t,this._service))}get items(){return this._delegate.items.map(t=>new UNe(t,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}};var UNe=class r{constructor(t,n){this._delegate=t,this.storage=n}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(t){let n=mGc(this._delegate,t);return new r(n,this.storage)}get root(){return new r(this._delegate.root,this.storage)}get parent(){let t=this._delegate.parent;return t==null?null:new r(t,this.storage)}put(t,n){return this._throwIfRoot("put"),new NEr(PEr(this._delegate,t,n),this)}putString(t,n=DL.RAW,i){this._throwIfRoot("putString");let o=t9o(n,t),s=Object.assign({},i);return s.contentType==null&&o.contentType!=null&&(s.contentType=o.contentType),new NEr(new HRt(this._delegate,new a$e(o.data,!0),s),this)}listAll(){return hGc(this._delegate).then(t=>new DEr(t,this.storage))}list(t){return fGc(this._delegate,t||void 0).then(n=>new DEr(n,this.storage))}getMetadata(){return pGc(this._delegate)}updateMetadata(t){return dGc(this._delegate,t)}getDownloadURL(){return gGc(this._delegate)}delete(){return this._throwIfRoot("delete"),AGc(this._delegate)}_throwIfRoot(t){if(this._delegate._location.path==="")throw Zko(t)}};var BEr=class{constructor(t,n){this.app=t,this._delegate=n}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(t){if(bGc(t))throw FNe("ref() expected a child path but got a URL, use refFromURL instead.");return new UNe(KRt(this._delegate,t),this)}refFromURL(t){if(!bGc(t))throw FNe("refFromURL() expected a full URL but got a child path, use ref() instead.");try{s4.makeFromUrl(t,this._delegate.host)}catch{throw FNe("refFromUrl() expected a valid full URL but got an invalid one.")}return new UNe(KRt(this._delegate,t),this)}setMaxUploadRetryTime(t){this._delegate.maxUploadRetryTime=t}setMaxOperationRetryTime(t){this._delegate.maxOperationRetryTime=t}useEmulator(t,n,i={}){yGc(this._delegate,t,n,i)}};function bGc(r){return/^[A-Za-z]+:\/\//.test(r)}var w01="@firebase/storage-compat",M01="0.3.6";var x01="storage-compat";function P01(r,{instanceIdentifier:t}){let n=r.getProvider("app-compat").getImmediate(),i=r.getProvider("storage").getImmediate({identifier:t});return new BEr(n,i)}function N01(r){let t={TaskState:UM,TaskEvent:oGc,StringFormat:DL,Storage:BEr,Reference:UNe};r.INTERNAL.registerComponent(new km(x01,P01,"PUBLIC").setServiceProps(t).setMultipleInstances(!0)),r.registerVersion(w01,M01)}N01(Gh);var BB2=yt(xNe(),1);var D01="firebase",B01="10.10.0";Gh.registerVersion(D01,B01,"app-compat");var EGc,o9o=new WeakMap,L01=()=>{},k01=class vbe{constructor(t){this.subscribers=[],this.settlement=null,this[EGc]="Unpromise",t instanceof Promise?this.promise=t:this.promise=new Promise(t),this.promise.then(n=>{let{subscribers:i}=this;this.subscribers=null,this.settlement={status:"fulfilled",value:n},i?.forEach(({resolve:o})=>{o(n)})}).catch(n=>{let{subscribers:i}=this;this.subscribers=null,this.settlement={status:"rejected",reason:n},i?.forEach(({reject:o})=>{o(n)})})}subscribe(){let t,n,{settlement:i}=this;if(i===null){if(this.subscribers===null)throw new Error("Unpromise settled but still has subscribers");let o=q01();this.subscribers=F01(this.subscribers,o),t=o.promise,n=()=>{this.subscribers!==null&&(this.subscribers=z01(this.subscribers,o))}}else{let{status:o}=i;o==="fulfilled"?t=Promise.resolve(i.value):t=Promise.reject(i.reason),n=L01}return Object.assign(t,{unsubscribe:n})}then(t,n){let i=this.subscribe(),{unsubscribe:o}=i;return Object.assign(i.then(t,n),{unsubscribe:o})}catch(t){let n=this.subscribe(),{unsubscribe:i}=n;return Object.assign(n.catch(t),{unsubscribe:i})}finally(t){let n=this.subscribe(),{unsubscribe:i}=n;return Object.assign(n.finally(t),{unsubscribe:i})}static proxy(t){let n=vbe.getSubscribablePromise(t);return typeof n<"u"?n:vbe.createSubscribablePromise(t)}static createSubscribablePromise(t){let n=new vbe(t);return o9o.set(t,n),o9o.set(n,n),n}static getSubscribablePromise(t){return o9o.get(t)}static resolve(t){return vbe.proxy(t).subscribe()}static async any(t){let n=t.map(vbe.resolve);try{return await Promise.any(n)}finally{n.forEach(({unsubscribe:i})=>{i()})}}static async race(t){let n=t.map(vbe.resolve);try{return await Promise.race(n)}finally{n.forEach(({unsubscribe:i})=>{i()})}}static async raceSingletons(t){let n=t.map(i=>vbe.proxy(i).then(()=>[i]));try{return await Promise.race(n)}finally{for(let i of n)i.unsubscribe()}}};EGc=Symbol.toStringTag;var LEr=k01;function q01(){let r,t;return{promise:new Promise((n,i)=>{r=n,t=i}),resolve:r,reject:t}}function F01(r,t){return[...r,t]}function U01(r,t){return[...r.slice(0,t),...r.slice(t+1)]}function z01(r,t){let n=r.indexOf(t);return n!==-1?U01(r,n):r}var zNe=class extends nt{};var JR=async(r,t,n)=>{let i=Q01(r),o=i.promise.then(()=>{throw new zNe(t)});return await LEr.race([n,o]).finally(i.cancel)},Q01=r=>{let t=TR(),n=setTimeout(t.resolve,r),i=()=>clearTimeout(n);return{promise:t.promise,cancel:i}};var YB2=global.setImmediate??setTimeout;var ZG=(()=>{let r=o=>{if(typeof window<"u"){let s=window[o];if(typeof s=="string"&&s)return s}return process.env[o]},t=r("FIREBASE_AUTH_EMULATOR_HOST"),n=r("FIRESTORE_EMULATOR_HOST"),i=r("FIREBASE_STORAGE_EMULATOR_HOST");if(!!t!=!!n||!!t!=!!i||!!n!=!!i)throw new Error(`Inconsistent Firebase emulator use! All three emulators must be used, or none! auth=${t} firestore=${n} storage=${i}`);return t&&n&&i?{auth:t.startsWith("http")?t:`http://${t}`,firestore:n,storage:i}:null})();var j01=Pb({auth:ld(),firestore:ld(),storage:ld()}),CGc=Mr("FirebaseEmulatorInfo",j01);var YRt=Je("FIREBASE"),G01=(r,t)=>{let n;if(ZG)n=ZG;else if("emulatorInfo"in r.options)n=CGc.assert(r.options.emulatorInfo);else return!1;Hg().isTest&&(t=!1),YRt.info(`Using Firebase Auth emulator at ${n.auth}`),typeof window<"u"?LNe(oEr(r),n.auth):r.auth().useEmulator(n.auth),YRt.info(`Using Firestore emulator at ${n.firestore} over ${t?"https":"http"}`);let[i,o]=n.firestore.split(":");r.firestore().useEmulator(i,parseInt(o)),t&&r.firestore()._delegate._setSettings({...r.firestore()._delegate._getSettings(),ssl:!0}),YRt.info(`Using Firebase Storage emulator at ${n.storage} over ${t?"https":"http"}`);let[s,a]=n.storage.split(":");return r.storage().useEmulator(s,parseInt(a)),t&&(r.storage()._delegate._protocol="https"),!0},H01="[DEFAULT]";var SGc=async(r,t)=>{Gh.apps.find(n=>n.name===(t??H01))||await V01(r,t)};async function V01(r,t){let n=Gh.initializeApp(r,t);if(!G01(n,!i3())&&!i3()&&ixe(!1,"proxyFirestore")){let i=await vGc(r);YRt.info(`Using Firestore proxy host: ${i}`),n.firestore().settings({host:i})}}var vGc=r=>{if(r.emulatorInfo)return`http://${r.emulatorInfo.firestore}`;let t=new URL(sQe());return pd(t.protocol==="https:"&&(t.port==="443"||t.port==="")&&t.pathname==="/",`Unable to specify a firestore proxy host for backend URL ${t}. Only HTTPS with no port and no path is supported.`,"FIREBASE"),`${t.hostname}/firestore`};var W01=Gh;var TGc=()=>W01;var _Gc=r=>oQe()?Promise.resolve():r.delete().catch(t=>{YRt.error(`Error deleting firebase instance: ${t}`)});var kEr=r=>{let t=ep(r);return Object.values(t).forEach(n=>{n.id=n.id.toString(),n.steps=n.steps.map(i=>i.toString())}),t};var qEr=async(r,t)=>{let i=[],o;for(;;){let s=await r.nodes.select({limit:1e3,startingFrom:o,orderBy:[]},{ignoreDataTransformErrors:!!t});if(i=i.concat(s),s.length<1e3)break;o=s[s.length-1].id}return Lpo(i.map(s=>[s.id,{operation:jLc(s)}]))},IGc=async r=>{let t=await r.subgraphs.select();return kEr(X1e(t,"id"))},RGc=async r=>{let t=await r.jobs.select();return X1e(t,"id")},s9o=async r=>{let t=await r.macros.select();return X1e(t,"id")},OGc=async(r,t)=>{let n=await r.nodeTypes.select(void 0,{ignoreDataTransformErrors:!!t});return X1e(n,"id")},wGc=async(r,t)=>{let n=await r.workspaceUsers.select();return{[t]:X1e(n,"id")}},MGc=async r=>{let t=await r.installedPackages.select();return X1e(t,"id")},xGc=async r=>{let t=await r.fetch();return{locations:qIt(t),defaultStorageMapping:t.defaultStorageMapping}};var a9o=Je("FIREBASE"),cL2=Je("GIT"),PGc=Je("WORKSPACES");var d$e=r=>({...NGc({},{},{},{},lNe(r),r),defaultStorageMapping:null,locations:{},installedPackages:{}}),FEr=r=>NGc({},{},{},{},{},r),NGc=(r,t,n,i,o,s)=>({steps:r,folders:t,jobs:n,macros:i,stepTypes:o,platformKind:s}),UEr=(r,t,n,i,o)=>{let s="[getAllWorkspaceDataFromRepository]",u={orgID:t.id,workspaceID:r,...o};return cf(async()=>Ah(s,u,"WORKSPACES",async()=>{let c="getAllWorkspaceDataFromRepository()";n.logMemorySnapshot(u,`${s} Before workspace data loading`,c);let l=t.workspace(r),d=await xGc(l),[f,h,A,E,v,T,w]=await Promise.all([IGc(l),RGc(l),s9o(l),wGc(l,r),MGc(l),qEr(l,i),OGc(l,i)]),N={folders:f,jobs:h,macros:A,stepTypes:w,userConnections:E,locations:d.locations,installedPackages:v,steps:T};return n.logMemorySnapshot(u,`${s} Workspace data loading completed`,c),n.cleanup(),PGc.infoContext(u,`${s} Loaded workspace data - Steps: ${Object.keys(N.steps).length}, Step types: ${Object.keys(N.stepTypes).length}, Users: ${Object.keys(N.userConnections||{}).length}`),N},"info"),3,a9o,u,{retryStrategy:{name:"nowait"},logOnRetry:`${s} retrying`,logOnFailure:`${s} failed, exhausted allotted retry attempts`})},QNe=async(r,t,n)=>{let{steps:i,...o}=await UEr(r,t,n);return{steps:Hce(i),...o}};var DGc=async(r,t,n,i)=>{let o=r.id,s=NPe(o,n,t);(i?.connectionKind==="snowflake"||i?.connectionKind===void 0)&&hh("CONNECTION",!!i&&BGc(i),{orgID:o,userID:t},"is valid user connection data on save"),a9o.appContext({orgID:o,userID:t,workspaceID:n},`Modifying user connection for user ${t} / team ${o} / workspace ${n}`,i);let a=$3o.parse({id:t,version:1,...r3(i,["createdAt","updatedAt","createdBy","updatedBy","id"])});try{await r.workspace(n).workspaceUser(t).save(a)}catch(u){if(u instanceof Du){a9o.infoContext({orgID:o,userID:t,workspaceID:n},"Failed to save workspace user entity. Creating one instead.",a,u),await r.workspace(n).workspaceUsers.createEntity(a);return}throw u}try{if(s3t.getInstance().isInitialized()&&!await r.workspace(n).isDevEnv()){let u=A_c(a);await s3t.getInstance().updateEnvironmentCredentials(n,u)}}catch(u){PGc.errorContext(s,"Issue with updating Scheduled Job credentials",u)}};var LGc=Je("CONNECTION"),Y01=TM("UserConnectionType",dAc),J01=(r,t)=>$g({snowflake:()=>tf1(t),databricks:()=>ef1(t),fabric:()=>Z01(t),bigquery:()=>X01(t)},r,"CreateDefaultUserConnection"),$01=(r,t)=>({connectionType:r,connectionDetails:{userID:t,clientEmail:""},connectionKind:"bigquery"}),X01=r=>$01("ServiceAccount",r),Z01=(r,t="oauth")=>({connectionKind:"fabric",connectionType:t,connectionDetails:{userID:r,connectionString:""}}),ef1=r=>({connectionType:"Cloud",connectionDetails:{userID:r,path:""},connectionKind:"databricks"}),tf1=r=>rf1("Cloud",r,"",""),rf1=(r,t,n,i)=>({connectionType:r,connectionDetails:{user:n,role:i,userID:t,warehouse:""},connectionKind:"snowflake"});var BGc=r=>Y01.is(r),mle=async(r,t)=>{try{let n=await r.fetch({retryOptions:{attempts:3,tags:["[GetUserConnectionInfoByEnvironment]"],waitSeconds:60}}),i=_We(n.connectionKind,n,{snowflake:o=>({connectionType:o.connectionType,connectionDetails:{user:o.connectionDetails?.user??"",userID:o.connectionDetails?.userID??"",role:o.connectionDetails?.role,warehouse:o.connectionDetails?.warehouse}}),databricks:o=>({connectionKind:"databricks",connectionType:o.connectionType,connectionDetails:{path:o.connectionDetails?.path??"",userID:o.connectionDetails?.userID??""}}),fabric:o=>({connectionKind:"fabric",connectionType:"oauth",connectionDetails:{connectionString:o.connectionDetails?.connectionString,userID:o.connectionDetails?.userID??""}}),bigquery:o=>({connectionKind:"bigquery",connectionType:o.connectionType,connectionDetails:{userID:o.connectionDetails?.userID??"",clientEmail:o.connectionDetails?.clientEmail??""}})},"GetUserConnectionInfoByEnvironment");return LGc.infoContext(t,"User Connection found,","kind:",i.connectionKind??"snowflake","type:",i.connectionType),i}catch(n){throw LGc.errorContext(t,"Error getting user connection info",n),n instanceof Du?new Vi("Invalid Connection Information, environment or connection does not exist. Please check that the environmentID is valid, and contains a valid connection.",`environmentID: ${t.workspaceID}: ${n.detail||n.message}`):n}},Tbe=async(r,t)=>{try{await r.fetch()}catch(n){if(n instanceof Du){let{id:i,parent:{id:o,parent:s}}=r,a=Lme(t,{snowflake:p=>p.snowflakeAuthType,databricks:p=>p.databricksAuthType,fabric:p=>p.fabricAuthType,bigquery:p=>p.bigQueryAuthType},"writeBasicUserConnectionIfNoneExists");if(a==="WorkspaceUserDefault")throw new nt("Unexpected connection type 'WorkspaceUserDefault'");let u={...J01(t.platformKind??"snowflake",i),...a&&{connectionType:a}};await DGc(s,i,o,u)}else throw n}};var u9o=r=>typeof r=="object"&&r instanceof Error&&"code"in r&&(typeof r.code=="string"||typeof r.code=="number")&&"name"in r&&typeof r.name=="string",kGc=r=>u9o(r)&&(r.name==="NetworkError"||r.code===401001);var yX=class extends Mme{constructor(t,n,i){super(t,n,i)}},zEr=class extends DA{constructor(n){super("Could not identify the initial warehouse - possibly invalid credentials or warehouse");this.warehouse=n}warehouse;statusCode(){return 400}toTRunError(){let n=this.warehouse?`Tried to set a warehouse of ${this.warehouse}`:"Did not set a warehouse";return{error:{errorString:this.message,errorDetail:`${n} and snowflake did not indicate a warehouse was used, but it should have`}}}},yle=class extends nt{constructor(n){let i="Snowflake execution error",o;typeof n=="object"&&n instanceof Error&&(i=n.message||i,o=n.stack);super(i);this.coalesceCause=n;this.originalStack=o}coalesceCause;originalStack;statusCode(){switch(this.getSnowflakeErrorCode()){case"390189":case"390100":return 401;case"000604":return 499;case"001003":case"002040":default:return 422}}isCancel(){return this.getSnowflakeErrorCode()==="000604"}getSnowflakeErrorCode(){try{return this.coalesceCause.code??null}catch{return null}}getErrorDetail=()=>{if(this.coalesceCause.name==="OperationFailedError")try{let n=this.coalesceCause.data;if(n)return`name=${this.coalesceCause.name}, code=${this.coalesceCause.code}, data=${JSON.stringify(n)}`}catch{}if(this.coalesceCause.name==="NetworkError")try{let n=this.coalesceCause.coalesceCause;if(n&&n.message)return`name=${this.coalesceCause.name}, code=${this.coalesceCause.code}, cause=${n.message}`}catch{}try{return`name=${this.coalesceCause.name}, code=${this.coalesceCause.code}`}catch{}return""};getErrorData=()=>this.getSnowflakeErrorCode()==="390189"?{errorString:"Role not found or is invalid",errorDetail:this.coalesceCause.message}:{errorString:this.message,errorDetail:this.getErrorDetail()};toTRunError(){return{error:this.getErrorData()}}},cF=class extends yle{constructor(n,i,o,s,a){super(n);this.options=i;this.requestID=o;this.queryID=s;this.warehouse=a}options;requestID;queryID;warehouse};var bX=class extends nt{constructor(n,i){let{errorString:o,errorDetail:s}=aa(i).error;super(o,s);this.query=n;this.coalesceCause=i}query;coalesceCause;isCancel(){return(this.getDatabricksErrorCause()?.includes("The session was closed or has expired")||this.getDatabricksErrorCause()?.includes("canceled"))??!1}getDatabricksErrorCause(){return this.message??null}statusCode(){return this.isCancel()?499:422}},eH=class extends Mme{constructor(t,n,i){super(t,n,i)}};var if1=Je("STEPS");var c9o=(r,t,n)=>{let i={},o=new Set([t]),s=0,a=new Set,u=new Set([t]);try{for(;u.size>0;){s=s+1,a=u,u=new Set;for(let p of a){o.add(p);let c=n==="predecessors"?r.predecessors(p):r.successors(p);if(c)for(let l of c)i[s]||(i[s]=new Set),!o.has(l)&&(i[s].add(l),u.add(l))}}}catch(p){throw if1.error(`getSuccessorsOrPredecessorsWithLevels threw an error when getting ${n} for step: ${t}. error:
|
|
9600
9600
|
|
|
9601
9601
|
`,p),p}return i};var tHc=yt(d9o(),1),q3=(r,t,n={})=>(GEr(t),!n.nocomment&&t.charAt(0)==="#"?!1:new f$e(t,n).match(r));var df1=/^\*+([^+@!?\*\[\(]*)$/,ff1=r=>t=>!t.startsWith(".")&&t.endsWith(r),hf1=r=>t=>t.endsWith(r),gf1=r=>(r=r.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(r)),Af1=r=>(r=r.toLowerCase(),t=>t.toLowerCase().endsWith(r)),mf1=/^\*+\.\*+$/,yf1=r=>!r.startsWith(".")&&r.includes("."),bf1=r=>r!=="."&&r!==".."&&r.includes("."),Ef1=/^\.\*+$/,Cf1=r=>r!=="."&&r!==".."&&r.startsWith("."),Sf1=/^\*+$/,vf1=r=>r.length!==0&&!r.startsWith("."),Tf1=r=>r.length!==0&&r!=="."&&r!=="..",_f1=/^\?+([^+@!?\*\[\(]*)?$/,If1=([r,t=""])=>{let n=ZGc([r]);return t?(t=t.toLowerCase(),i=>n(i)&&i.toLowerCase().endsWith(t)):n},Rf1=([r,t=""])=>{let n=eHc([r]);return t?(t=t.toLowerCase(),i=>n(i)&&i.toLowerCase().endsWith(t)):n},Of1=([r,t=""])=>{let n=eHc([r]);return t?i=>n(i)&&i.endsWith(t):n},wf1=([r,t=""])=>{let n=ZGc([r]);return t?i=>n(i)&&i.endsWith(t):n},ZGc=([r])=>{let t=r.length;return n=>n.length===t&&!n.startsWith(".")},eHc=([r])=>{let t=r.length;return n=>n.length===t&&n!=="."&&n!==".."},Mf1=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",jEr=Mf1==="win32",h9o=jEr?{sep:"\\"}:{sep:"/"},xf1=h9o.sep;q3.sep=xf1;var lF=Symbol("globstar **");q3.GLOBSTAR=lF;var $Gc={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},g9o="[^/]",f9o=g9o+"*?",Pf1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Nf1="(?:(?!(?:\\/|^)\\.).)*?",rHc=r=>r.split("").reduce((t,n)=>(t[n]=!0,t),{}),XGc=rHc("().*{}+?[]^$\\!"),Df1=rHc("[.("),Bf1=(r,t={})=>n=>q3(n,r,t);q3.filter=Bf1;var _be=(r,t={})=>Object.assign({},r,t),Lf1=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return q3;let t=q3;return Object.assign((i,o,s={})=>t(i,o,_be(r,s)),{Minimatch:class extends t.Minimatch{constructor(o,s={}){super(o,_be(r,s))}static defaults(o){return t.defaults(_be(r,o)).Minimatch}},filter:(i,o={})=>t.filter(i,_be(r,o)),defaults:i=>t.defaults(_be(r,i)),makeRe:(i,o={})=>t.makeRe(i,_be(r,o)),braceExpand:(i,o={})=>t.braceExpand(i,_be(r,o)),match:(i,o,s={})=>t.match(i,o,_be(r,s)),sep:t.sep,GLOBSTAR:lF})};q3.defaults=Lf1;var nHc=(r,t={})=>(GEr(r),t.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,tHc.default)(r));q3.braceExpand=nHc;var kf1=1024*64,GEr=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>kf1)throw new TypeError("pattern is too long")},QEr=Symbol("subparse"),qf1=(r,t={})=>new f$e(r,t).makeRe();q3.makeRe=qf1;var A9o=(r,t,n={})=>{let i=new f$e(t,n);return r=r.filter(o=>i.match(o)),i.options.nonull&&!r.length&&r.push(t),r};q3.match=A9o;var Ff1=r=>r.replace(/\\(.)/g,"$1"),Uf1=r=>r.replace(/\\([^-\]])/g,"$1"),zf1=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qf1=r=>r.replace(/[[\]\\]/g,"\\$&"),f$e=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;regexp;constructor(t,n={}){GEr(t),n=n||{},this.options=n,this.pattern=t,this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.globSet=[],this.globParts=[],this.set=[],this.make()}debug(...t){}make(){let t=this.pattern,n=this.options;if(!n.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=this.braceExpand(),n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(s=>this.slashSplit(s));if(this.options.noglobstar)this.globParts=i;else{for(let s of i){let a;do{a=!1;for(let u=0;u<s.length-1;u++)s[u]==="*"&&s[u-1]==="**"&&(s[u]="**",s[u-1]="*",a=!0)}while(a)}this.globParts=i.map(s=>(s=s.reduce((a,u)=>{let p=a[a.length-1];return u==="**"&&p==="**"?a:u===".."&&p&&p!==".."&&p!=="."&&p!=="**"?(a.pop(),a):(a.push(u),a)},[]),s.length===0?[""]:s))}this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,a,u)=>s.map(p=>this.parse(p)));if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),jEr)for(let s=0;s<this.set.length;s++){let a=this.set[s];a[0]===""&&a[1]===""&&this.globParts[s][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?")}this.debug(this.pattern,this.set)}parseNegate(){if(this.nonegate)return;let t=this.pattern,n=!1,i=0;for(let o=0;o<t.length&&t.charAt(o)==="!";o++)n=!n,i++;i&&(this.pattern=t.slice(i)),this.negate=n}matchOne(t,n,i=!1){let o=this.options;if(jEr){let A=t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),E=n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]);if(A&&E){let v=t[3],T=n[3];v.toLowerCase()===T.toLowerCase()&&(t[3]=T)}else if(E&&typeof t[0]=="string"){let v=n[3],T=t[0];v.toLowerCase()===T.toLowerCase()&&(n[3]=T,n=n.slice(3))}else if(A&&typeof n[0]=="string"){let v=t[3];v.toLowerCase()===n[0].toLowerCase()&&(n[0]=v,t=t.slice(3))}}this.debug("matchOne",this,{file:t,pattern:n}),this.debug("matchOne",t.length,n.length);for(var s=0,a=0,u=t.length,p=n.length;s<u&&a<p;s++,a++){this.debug("matchOne loop");var c=n[a],l=t[s];if(this.debug(n,c,l),c===!1)return!1;if(c===lF){this.debug("GLOBSTAR",[n,c,l]);var d=s,f=a+1;if(f===p){for(this.debug("** at the end");s<u;s++)if(t[s]==="."||t[s]===".."||!o.dot&&t[s].charAt(0)===".")return!1;return!0}for(;d<u;){var h=t[d];if(this.debug(`
|
|
9602
9602
|
globstar while`,t,d,n,f,h),this.matchOne(t.slice(d),n.slice(f),i))return this.debug("globstar found match!",d,u,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",t,d,n,f);break}this.debug("globstar swallow a segment, and continue"),d++}return!!(i&&(this.debug(`
|
|
9603
9603
|
>>> no match, partial?`,t,d,n,f),d===u))}let A;if(typeof c=="string"?(A=l===c,this.debug("string match",c,l,A)):(A=c.test(l),this.debug("pattern match",c,l,A)),!A)return!1}if(s===u&&a===p)return!0;if(s===u)return i;if(a===p)return s===u-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return nHc(this.pattern,this.options)}parse(t,n){GEr(t);let i=this.options;if(t==="**")if(i.noglobstar)t="*";else return lF;if(t==="")return"";let o,s=null;n!==QEr&&((o=t.match(Sf1))?s=i.dot?Tf1:vf1:(o=t.match(df1))?s=(i.nocase?i.dot?Af1:gf1:i.dot?hf1:ff1)(o[1]):(o=t.match(_f1))?s=(i.nocase?i.dot?Rf1:If1:i.dot?Of1:wf1)(o):(o=t.match(mf1))?s=i.dot?bf1:yf1:(o=t.match(Ef1))&&(s=Cf1));let a="",u=!1,p=!1,c=[],l=[],d=!1,f=!1,h=-1,A=-1,E,v,T,w=t.charAt(0)===".",N=i.dot||w,k=()=>w?"":N?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",L=V=>V.charAt(0)==="."?"":i.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",q=()=>{if(d){switch(d){case"*":a+=f9o,u=!0;break;case"?":a+=g9o,u=!0;break;default:a+="\\"+d;break}this.debug("clearStateChar %j %j",d,a),d=!1}};for(let V=0,W;V<t.length&&(W=t.charAt(V));V++){if(this.debug("%s %s %s %j",t,V,a,W),p){if(W==="/")return!1;XGc[W]&&(a+="\\"),a+=W,p=!1;continue}switch(W){case"/":return!1;case"\\":if(f&&t.charAt(V+1)==="-"){a+=W;continue}q(),p=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",t,V,a,W),f){this.debug(" in class"),W==="!"&&V===A+1&&(W="^"),a+=W;continue}this.debug("call clearStateChar %j",d),q(),d=W,i.noext&&q();continue;case"(":{if(f){a+="(";continue}if(!d){a+="\\(";continue}let F={type:d,start:V-1,reStart:a.length,open:$Gc[d].open,close:$Gc[d].close};this.debug(this.pattern," ",F),c.push(F),a+=F.open,F.start===0&&F.type!=="!"&&(w=!0,a+=L(t.slice(V+1))),this.debug("plType %j %j",d,a),d=!1;continue}case")":{let F=c[c.length-1];if(f||!F){a+="\\)";continue}c.pop(),q(),u=!0,v=F,a+=v.close,v.type==="!"&&l.push(Object.assign(v,{reEnd:a.length}));continue}case"|":{let F=c[c.length-1];if(f||!F){a+="\\|";continue}q(),a+="|",F.start===0&&F.type!=="!"&&(w=!0,a+=L(t.slice(V+1)));continue}case"[":if(q(),f){a+="\\"+W;continue}f=!0,A=V,h=a.length,a+=W;continue;case"]":if(V===A+1||!f){a+="\\"+W;continue}E=t.substring(A+1,V);try{RegExp("["+Qf1(Uf1(E))+"]"),a+=W}catch{a=a.substring(0,h)+"(?:$.)"}u=!0,f=!1;continue;default:q(),XGc[W]&&!(W==="^"&&f)&&(a+="\\"),a+=W;break}}for(f&&(E=t.slice(A+1),T=this.parse(E,QEr),a=a.substring(0,h)+"\\["+T[0],u=u||T[1]),v=c.pop();v;v=c.pop()){let V;V=a.slice(v.reStart+v.open.length),this.debug(this.pattern,"setting tail",a,v),V=V.replace(/((?:\\{2}){0,64})(\\?)\|/g,(F,J,Y)=>(Y||(Y="\\"),J+J+Y+"|")),this.debug(`tail=%j
|
|
9604
|
-
%s`,V,V,v,a);let W=v.type==="*"?f9o:v.type==="?"?g9o:"\\"+v.type;u=!0,a=a.slice(0,v.reStart)+W+"\\("+V}q(),p&&(a+="\\\\");let G=Df1[a.charAt(0)];for(let V=l.length-1;V>-1;V--){let W=l[V],F=a.slice(0,W.reStart),J=a.slice(W.reStart,W.reEnd-8),Y=a.slice(W.reEnd),z=a.slice(W.reEnd-8,W.reEnd)+Y,X=F.split(")").length,Z=F.split("(").length-X,re=Y;for(let ee=0;ee<Z;ee++)re=re.replace(/\)[+*?]?/,"");Y=re;let oe=Y===""&&n!==QEr?"(?:$|\\/)":"";a=F+J+Y+oe+z}if(a!==""&&u&&(a="(?=.)"+a),G&&(a=k()+a),n===QEr)return[a,u];if(i.nocase&&!u&&!i.nocaseMagicOnly&&(u=t.toUpperCase()!==t.toLowerCase()),!u)return Ff1(t);let H=i.nocase?"i":"";try{let V=s?{_glob:t,_src:a,test:s}:{_glob:t,_src:a};return Object.assign(new RegExp("^"+a+"$",H),V)}catch(V){return this.debug("invalid regexp",V),new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let n=this.options,i=n.noglobstar?f9o:n.dot?Pf1:Nf1,o=n.nocase?"i":"",s=t.map(a=>{let u=a.map(p=>typeof p=="string"?zf1(p):p===lF?lF:p._src);return u.forEach((p,c)=>{let l=u[c+1],d=u[c-1];p!==lF||d===lF||(d===void 0?l!==void 0&&l!==lF?u[c+1]="(?:\\/|"+i+"\\/)?"+l:u[c]=i:l===void 0?u[c-1]=d+"(?:\\/|"+i+")?":l!==lF&&(u[c-1]=d+"(?:\\/|\\/"+i+"\\/)"+l,u[c+1]=lF))}),u.filter(p=>p!==lF).join("/")}).join("|");s="^(?:"+s+")$",this.negate&&(s="^(?!"+s+").*$");try{this.regexp=new RegExp(s,o)}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):jEr&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,n=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&n)return!0;let i=this.options;h9o.sep!=="/"&&(t=t.split(h9o.sep).join("/"));let o=this.slashSplit(t);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let a=o[o.length-1];if(!a)for(let u=o.length-2;!a&&u>=0;u--)a=o[u];for(let u=0;u<s.length;u++){let p=s[u],c=o;if(i.matchBase&&p.length===1&&(c=[a]),this.matchOne(c,p,n))return i.flipNegate?!0:!this.negate}return i.flipNegate?!1:this.negate}static defaults(t){return q3.defaults(t).Minimatch}};q3.Minimatch=f$e;var oHc=2,sHc=1,aHc=3,uHc=2,cHc=8,lHc=5,pHc=6,dHc=new RegExp(/([\+]?){([\s\S]+)}([\+](?![\+]))?\s*/g),fHc=new RegExp(/((\w+):\s*((?:["])((([^\"\+\r\n\[/\\]+))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),hHc=new RegExp(/((\w+):\s*(((?:["])(((?:[^"]|"")*))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),gHc=new RegExp(/((?:[^\+\ \r\n\[\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\s*/g),iHc="",h$e=(r,t)=>{if(t==="*")return r.some(o=>o!=null&&String(o).length>0);let n=r.map(o=>o!=null?String(o).replace(/\//g,iHc):""),i=t.replace(/\//g,iHc);return!!A9o(n,i).length};var g$e=Je("SEARCH"),XL2=B.object({include:B.string(),exclude:B.string(),enabled:B.boolean()}),AHc={name:{MatchFunction:h$e,MatchList:r=>[r.operation.name]},location:{MatchFunction:h$e,MatchList:r=>[r.operation.locationName]},nodeType:{MatchFunction:h$e,MatchList:r=>[r.operation.sqlType]},subgraph:{MatchFunction:h$e,MatchList:r=>[r?.id?.toString(),r.name]},nodeID:{MatchFunction:h$e,MatchList:r=>[r]}},mHc=r=>{let t=[];return r.forEach((n,i)=>{if(n==="+{"||n==="{"||n==="}"||n==="}+")return;let o=n,s=n.split(""),a=s[s.length-1],u=s[0];a!=="}"&&a!=="+"&&(o=o+r[i+1]),u!=="{"&&u!=="+"&&(o=r[i-1]+o),t.push(o)}),t},yHc=(r,t,n,i=!1)=>{let{steps:o,graphInformation:s,allSubgraphs:a,allStepTypesYAML:u}=n,p={},c=i3()?Date.now():performance.now(),l=r;l||(l=t);let d=l.split(/(\}\+?)\s*(or|OR|\|\|)\s*(\+?\{)/).filter(A=>!(A==="OR"||A==="or"||A==="||")),f=mHc(d);f.length||(f=[t]),g$e.debug("got unions",f,"searchStringTouse",l,"defaultSearchString",t,"steps",o),f.forEach(A=>{let E=A.split(/(\}\+?)\s*(and|AND|\,)\s*(\+?\{)/).filter(k=>!(k==="AND"||k==="and"||k===",")),v=mHc(E),T=[];v.forEach(k=>{let L={};g$e.debug("Got intersection:",k);let q=[...k.matchAll(dHc)];if(g$e.debug("Got matches:",k,q),!q[0])return;let G=q[0][oHc],H={prefix:q[0][sHc]||"",postfix:q[0][aHc]||""};if(G.indexOf(":")>-1){let F=i?hHc:fHc,J=[...G.trim().matchAll(F)],Y=i?pHc:lHc;J.forEach(z=>{let X=z[uHc],Z=z[cHc]||z[Y];H[X]=Z})}else{let J=[...G.trim().matchAll(gHc)][0];J&&(H.name=J[0])}_M(H);let V=H;g$e.debug("Got groups ",k,V);let W=new Set;if(V.subgraph?Object.values(a).forEach(F=>{let J=AHc.subgraph,Y=J.MatchList(F);if(J.MatchFunction(Y,V.subgraph)){let{steps:X}=F;X.forEach(Z=>{W.add(Z.toString())})}else return}):W=new Set(Object.keys(o)),V.nodeType){let{nodeType:F}=V;if(!u[F]){let J=F;Object.entries(u).forEach(([Y,z])=>{z.name===F&&(J=Y)}),V.nodeType=J}}Object.keys(o).forEach(F=>{if(!V){g$e.emerg("got an unexpected undefined value for match",l,V,k);return}let J=W.has(F);if(Object.entries(V).forEach(([Y,z])=>{let X=o[F];if(Y==="nodeID"&&(X=F),Y==="subgraph"){J=W.has(F);return}let Z=AHc[Y];if(Z){let re=Z.MatchList(X).filter(oe=>oe!=null);J=J&&Z.MatchFunction(re,z)}}),J){if(L[F]=!0,V.prefix&&s){let Y=c9o(s,F,"predecessors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}if(V.postfix&&s){let Y=c9o(s,F,"successors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}}}),T.push(L)}),T.length||T.push({});let w={};Object.keys(o).forEach(k=>{w[k]=!0});let N=T.reduce((k,L)=>Object.fromEntries($gc(k,L).map(q=>[q,!0])),w);p={...p,...N}});let h=i3()?Date.now():performance.now();return g$e.debug("Time that search took: ",h-c),p};var HEr=(r,t,n,i=!1)=>{let o=yHc(`${r}`,"{ * }",n,i),s=yHc(`${t}`,"!*",n,i),a=o;return Object.keys(s).forEach(u=>{delete a[u]}),{stepsResult:a}};var bHc=(r,t,n,i)=>{let o=[];return t.forEach(s=>{let a=i[s];if(a){let{name:u}=a,p=`{ subgraph: "${u}" }`;o.push(p)}}),r.forEach(s=>{let a=n[s];if(a){let{locationName:u,name:p}=a.operation,c=`{ location: "${u}" name: "${p}" }`;o.push(c)}}),o};var Gf1=Je("JOBS");var EHc=r=>!r?.hasOwnProperty("includeSelector")||!r?.hasOwnProperty("version"),m9o=(r,t,n)=>{let{steps:i,subgraphs:o,...s}=r,a={...s};if(a.hasOwnProperty("version")||(a.version=c$),a.hasOwnProperty("includeSelector"))return a;a.includeSelector="",a.excludeSelector="";let u=new Set(i),p=new Set(o),d=bHc([...u],[...p].map(f=>`${f}`),n,t).map(f=>`+${f}`).join(" OR ");return a.includeSelector=d,Gf1.info("Upgrading job v1 to v2",r,a),a};var CHc=(r,t)=>{let{jobs:n,folders:i,steps:o}=r,s=n[t];return m9o(s,i,o)};var ak2=Je("PACKAGES_BACKEND");var SHc=(r,t,n)=>{let i=L6o(t)??"",o=r?.config?.entities?.nodeTypes[i];return o||(n.error(`No config found for node type ${t}`),{isDisabled:!1,defaultStorageLocation:null})};var VEr=(r,t={})=>Object.values(r).map(n=>Hf1(n)).reduce((n,i)=>{for(let[o,s]of Object.entries(i))n[o]=s;return n},t),Hf1=r=>Object.fromEntries(Object.entries(r?.contents?.nodeTypes??{}).map(([t,n])=>{let{id:i,nodeType:o}=Vf1(r.alias,t,r,n);return[i,o]})),Vf1=(r,t,n,i)=>{let o=Tmr(r,t),{isDisabled:s,defaultStorageLocation:a}=SHc(n,o,Je("PACKAGES")),u={...ep(i),id:o,isDisabled:s};return u.metadata.defaultStorageLocation=a,{id:o,nodeType:u}};var Ho=yt(Mq());var Wf1=Ho.Record({type:Ho.Unknown,name:Ho.String}),vHc=Ho.Record({locationName:Ho.String,nodeName:Ho.String}),THc=Ho.Record({sql:Ho.String,success:Ho.Boolean,rows:Ho.Array(Ho.Unknown),fields:Ho.Array(Wf1),error:Ho.Union(Ho.Null,jdr).optional(),startTime:Ho.Unknown,endTime:Ho.Unknown,status:Ho.String,name:Ho.String,isRunning:Ho.Boolean,exportedRefs:Ho.Array(vHc),invalidExportedRefs:Ho.Array(vHc),queryResultSequence:Ho.Optional(Ho.Unknown),type:Ho.Union(Ho.Literal("sql"),Ho.Literal("sqlTest")).optional(),warehouse:Ho.String.nullable().optional(),queryID:Ho.String.nullable().optional()}),y9o=Ho.Record({name:Ho.String,queryResults:Ho.Array(THc),isRunning:Ho.Boolean,renderQueryResults:Ho.Optional(THc)}),yk2=Ho.Record({runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,name:Ho.String,queryResultSequence:y9o,runState:Ho.String}),Kf1=Ho.Record({dataResult:Ho.Unknown,name:Ho.String,queryResultSequence:y9o,runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,runState:Ho.String,stepRunState:pWe(Y3o)}),_Hc=TM("RunResultFirestoreValidator",Kf1),Yf1=Ho.Record({nodeID:Ho.String,queryResultSequence:y9o,runState:Ho.String,hasTestFailures:Ho.Boolean.optional()}),Jf1=Ho.Record({runResults:Ho.Record({runStartTime:Ho.Unknown,runEndTime:Ho.Unknown,runFailureReason:Ho.Optional(Ho.String),runType:Ho.String,runStatus:Ho.String,runResults:Ho.Array(Yf1),runID:Ho.Number,environmentID:Ho.String,snowflakeAccount:Ho.String.optional(),snowflakeWarehouse:Ho.String.optional(),jobID:Ho.Number.optional(),hasFailedTest:Ho.Boolean.optional(),runTimeParameters:Ho.Unknown.nullable(),includeNodesSelector:Ho.String.optional(),excludeNodesSelector:Ho.String.optional()})}),WEr=TM("TRunOutput",Jf1);var Ck2=pWe(K3o);var Xf1=["deploy","refresh","rerun","plan"],Sk2=[...Xf1,"devRun"];var jNe=class{constructor(t,n,i,o){this.allNodes=t;this.renderResults=n;this.extraRefs=i;this.logContext=o;this.phasedRefUsage=n.map("phased ref usage",s=>s.map(a=>a.runDetails.ref_usage))}allNodes;renderResults;extraRefs;logContext;phasedRefUsage;buildPhase(t,n){let i="[DependencyBuilder.buildPhase()]",o=n.keys(),s=Object.keys(this.extraRefs),a=[...new Set([...o,...s])];if(Je("PIPELINE").appContext(this.logContext,i,"Nodes present in both current-phase data AND extra non-phased (views & advanced deploy) data:",Fpo([...o],s)),this.noDependenciesPhases.includes(t))return Object.fromEntries(a.map(u=>[u,[]]));{let u=this.getNodeRefsInPhase(t,a),p=new cNe(Nb(this.allNodes,a));return fv(u,(c,l)=>{let{nodeIDsToAdd:d}=JYe(c,p);return[...new Set(d)].filter(f=>f!==l)})}}build(){return Object.fromEntries([...this.phasedRefUsage.entries()].map(([t,n])=>[t,this.buildPhase(t,n)]))}};var xk2=Je("DEBUG");var KEr=r=>{typeof r.stepCounter=="number"&&(r.stepCounter=`${r.stepCounter}`),typeof r.columnCounter=="number"&&(r.columnCounter=`${r.columnCounter}`)};var Ibe=new Date("1980-01-01T00:00:00.000Z"),Vs=(r,t,n)=>{let i=`${r}Entity`;return n||(n=la(t)),{standard:Mr(i,n),strict:Mr(`${i} (strict)`,t)}};var IHc=r=>{if(Array.isArray(r))for(let t=r.length-1;t>=0;t--)r[t]===void 0&&r.splice(t,1);if(r&&typeof r=="object")for(let t in r)r.hasOwnProperty(t)&&r[t]===void 0&&delete r[t];return[r,!1]},Zf1=(r,t)=>{if(r&&typeof r=="object"){let n=r;if(n.toDate&&(!isNaN(n.seconds)&&!isNaN(n.nanoseconds)||!isNaN(n._seconds)&&!isNaN(n._nanoseconds))){let i=n.toDate();return i.getTime()===Bce.SENTINEL_DATE&&Ml().emerg(`Repository server timestamp sentinel value found in stored data at path ${t}`),[i,!0]}}return[r,!1]},RHc=(r,t)=>r instanceof Q4e?[t.getDeleteSentinel(),!0]:r instanceof Date&&r.getTime()===Bce.SENTINEL_DATE?[t.getServerTimestampSentinel(),!0]:[r,!1],GNe=(r,t,n)=>{let[i,o]=t(n,r);if(!o&&typeof i=="object"){if(Array.isArray(i))return i.map(s=>GNe(r,t,s));for(let s in i)i.hasOwnProperty(s)&&(i[s]=GNe(r,t,i[s]))}return i},$Rt=class{fromStorage(t,n,i,o,s){try{return this.transformFromStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} from storage: ${a}`),a}return i}toStorage(t,n,i,o,s){try{return this.transformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} to storage ${a}`),a}return i}mergeToStorage(t,n,i,o,s){try{return this.mergeTransformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error merge transforming repository entity ${n} to storage ${a}`),a}return i}},b9o=class extends $Rt{constructor(n=!1){super();this.preserveID=n}preserveID;transformFromStorage(n,i,o){return"id"in o?o.id!=n&&(Ml().error(`'id' property does not match doc id on doc at path ${i}; doc id: ${n}, value.id: ${o.id}`),o.id=n):o.id=n,"createdAt"in o||(o.createdAt=Ibe),"updatedAt"in o||(o.updatedAt=Ibe),GNe(i,Zf1,o)}transformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}mergeTransformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}},E9o=class extends $Rt{constructor(n){super();this.validators=n}validators;transformFromStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}transformToStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}mergeTransformToStorage(n,i,o,s,a){return o}getValidatorOptions(n,i,o=500){let s={...i,statusCode:o};return s.errorMessage||(s.errorMessage=a=>`Found ${a.failures.length} validation failure(s) for ${this.validators.standard.name} ${n}`),s}},qu=(r,t,n)=>{let i=[new b9o(n),new E9o(r)];return t&&i.unshift(t),new C9o(...i)},C9o=class{transforms;constructor(...t){this.transforms=t}fromStorage(t,n,i,o,s){return this.transforms.reduce((a,u)=>u.fromStorage(t,n,a,o,s),i)}toStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.toStorage(t,n,a,o,s),i)}mergeToStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.mergeToStorage(t,n,a,o,s),i)}},F3=class extends $Rt{transformToStorage(t,n,i){return i}mergeTransformToStorage(t,n,i){return i}};var OHc=r=>!!r&&typeof r=="object"&&!Array.isArray(r),A$e=r=>OHc(r)&&!(r instanceof Date)&&!(r instanceof RegExp),tH=r=>{if(typeof r=="string")return r;if(OHc(r)&&r.constructor&&typeof r.constructor.name=="string")return`[class ${r.constructor.name}]`;if(r instanceof Date)return`[date ${r.toISOString()}]`;if(r instanceof RegExp)return`[regexp ${r.toString()}]`;if(typeof r=="function")return`[function ${r.name}]`;try{return JSON.stringify(r)}catch{return"Error: could not stringify unknown value"}},S9o=r=>r==null,XRt=(r,t,n,i)=>{t.filter((o,s)=>A$e(o)?!0:(n.logError(`Invalid ${r} item detected at index ${s}: ${tH(o)}`),n.logPatch(`Removed invalid ${r} item at index ${s}`),!1)).forEach(i)},pF=(r,t,n)=>{r[t]=n},Rbe=(r,t)=>{delete r[t]},T9o=(r,t,n)=>{let i=new v9o(r,Je("FIREBASE"),t),{logError:o,logPatch:s,report:a}=i,u=()=>(a(),n);if(!A$e(n))return u();let p=n;if([["locationName",!p.locationName&&typeof p.locationName!="string"||typeof p.locationName!="string"],["description",typeof p.description!="string"]].forEach(([c,l])=>{l&&(s(`Set non-string property ${c} from ${tH(p[c])} to ""`),pF(p,c,""))}),["dependencies","isDataVault","locationID"].forEach(c=>{c in p&&(s(`Removed deprecated field ${c}`),Rbe(p,c))}),p.type==="sql")s("-- data.type is sql --"),eh1(r,p,i);else if(p.type==="sourceInput")s("-- data.type is sourceInput --"),th1(r,p,i);else return o(`Data type is of invalid type ${tH(p.type)}`),u();return p.version!==o$&&(s(`Set version ${tH(p.version)} to ${o$}`),pF(p,"version",o$)),u()},eh1=(r,t,n)=>{let{logError:i,logPatch:o}=n;if(t.isMultisource===void 0&&(o("Set missing isMultisource to false"),pF(t,"isMultisource",!1)),A$e(t.metadata)){let s=t.metadata;if(s.appliedNodeTests===null&&(o("Set metadata.appliedNodeTests from null to []"),pF(s,"appliedNodeTests",[])),!Array.isArray(s.sourceMapping)||!s.sourceMapping.length){o("Set non-array or empty metadata.sourceMapping to [ basicMapping ]");let a;typeof t.name=="string"?a=t.name:(o("Data has no name value, setting sourceMapping.name to empty string"),a=""),pF(s,"sourceMapping",[{name:a,join:{joinCondition:""},dependencies:[],noLinkRefs:[],aliases:{}}])}else XRt("sourceMapping",s.sourceMapping,n,(a,u)=>{let p=a;if(typeof p.join=="string"){let c={joinCondition:""};o(`Setting invalid string value metadata.sourceMapping[${u}].join to object: ${tH(c)}`),pF(p,"join",c)}if(p.name===void 0){let c=p.join?.name??"";o(`Set missing metadata.sourceMapping[${u}].name to "${c}"`),pF(p,"name",c),c||i(`metadata.sourceMapping[${u}].name is an empty string`)}Array.isArray(p.dependencies)&&XRt("sourceMapping dependency",p.dependencies,n,(c,l)=>{let d=c;for(let f of["locationName","nodeName"])S9o(d[f])&&(o(`Set metadata.sourceMapping[${u}].dependencies[${l}].${f} from ${tH(d[f])} to ""`),pF(d,f,""))})});wHc(r,s.columns,n)}if(t.config&&typeof t.config=="object")for(let[s,a]of Object.entries(t.config))a===null&&(o(`Removing null config property "${s}"`),Rbe(t.config,s))},th1=(r,t,n)=>{let{logPatch:i,logError:o}=n;if(t.dataset!==void 0&&(i("Removed deprecated v0 property dataset"),Rbe(t,"dataset")),t.table!==void 0&&(t.table!==t.name&&o(`source data properties 'table' and 'name' are different for source node ${r}, table: ${t.table}, name: ${t.name}`),i("Removed deprecated v0 property table"),Rbe(t,"table")),A$e(t.metadata)){let s=t.metadata;Array.isArray(s.columns)&&(s.columns.length&&wHc(r,s.columns,n),Object.keys(s).length>1&&(i(`Removed deprecated metadata properties, keeping only columns. Was: ${tH(s)}`),pF(t,"metadata",{columns:s.columns})))}},wHc=(r,t,n)=>{let{logPatch:i}=n;Array.isArray(t)&&XRt("column",t,n,(o,s)=>{let a=o;if(["ghostRecordValue","descendedFrom","hashColumns","columnsForHash"].forEach(c=>{a.hasOwnProperty(c)&&(i(`Removed deprecated property '${c}' from metadata.columns[${s}]`),Rbe(a,c))}),A$e(a.hashDetails)){let c=a.hashDetails;c.hashType&&(i(`Removed deprecated property 'hashType' from metadata.columns[${s}].hashDetails`),Rbe(c,"hashType")),c.hubHashes&&(i(`Removed deprecated property 'hubHashes' from metadata.columns[${s}].hashDetails`),Rbe(c,"hubHashes"))}[["appliedColumnTests",a.appliedColumnTests===null],["config",a.config===null],["hashDetails",typeof a.hashDetails=="string"]].forEach(([c,l])=>{l&&(i(`Deleted metadata.columns[${s}].${c} with invalid value ${tH(a[c])}`),Rbe(a,c))}),[["dataType",typeof a.dataType!="string"],["transform",a.transform===null]].forEach(([c,l])=>{l&&(i(`Set ${c} from ${tH(a[c])} to "" in metadata.columns[${s}]`),pF(a,c,""))});let u=a.hashedColumns;if(Array.isArray(u))for(let c of u)KEr(c);let p=a.columnReference;if(A$e(p)){KEr(p);let c=p;S9o(c.stepCounter)&&(i(`Set metadata.columns[${s}].columnReference.stepCounter from ${tH(c.stepCounter)} to ${r}`),pF(c,"stepCounter",r))}Array.isArray(a.sourceColumnReferences)&&XRt("sourceColumnReference",a.sourceColumnReferences,n,(c,l)=>{let d=c;Array.isArray(d.columnReferences)&&XRt("columnReference",d.columnReferences,n,(f,h)=>{KEr(f);let A=f;S9o(A.stepCounter)&&(i(`Set invalid metadata.columns[${s}].sourceColumnReferences[${l}].columnReferences[${h}].stepCounter to "" from ${tH(r)}`),pF(A,"stepCounter",""))})})})},v9o=class{constructor(t,n,i){this.id=t;this.logger=n;this.path=i}id;logger;path;patchMessages=[];errorMessages=[];logPatch=t=>{this.patchMessages.push(t)};logError=t=>{this.errorMessages.push(t)};reportErrors=()=>{this.errorMessages.length&&this.logger.error(`Error patching node data with id ${this.id} at path ${this.path}`,this.errorMessages)};reportPatches=()=>{this.patchMessages.length&&this.logger.debug(`Patched node data with id ${this.id} at path ${this.path}`,this.patchMessages)};report=()=>{this.reportErrors(),this.reportPatches()}},YEr=class extends F3{transformFromStorage(t,n,i){return T9o(t,n,i)}};var b92=Je("FIREBASE");var E92=Je("STEPS"),C92=Je("METADATA_OPERATIONS");var PHc=(r,t)=>t[r].runState==="running";var NHc=r=>(Bm("STEPS",!!r,`Error converting API refs: argument apiRefLinks is ${r}.`),r.map(t=>({locationName:t.location_name,nodeName:t.node_name})));var DHc=r=>r?.deployEnabled??!0,_9o=r=>({nodeName:r,columns:new Set});var MHc=(r,t)=>r?r.every((n,i)=>n.deref()===t[i]):!1,xHc={},BHc=(r,t)=>{let n={};return sNe(r,(i,o)=>{let s=xHc[i],a=t[i];if(!a)throw new nt(`Dependency/ref data for node ID "${i}" was not found`,`Dependency/ref data for node ID "${i}" not found in "GetNodesWithMissingColumnDependencies" (known IDs: ${JSON.stringify(t)})`);let{dependencies:u,noLinkDependencies:p}=a,c=o.operation.metadata.columns,d=s?.nodeData.deref()===o,f=MHc(s?.dependencies,u),h=MHc(s?.noLinkDependencies,p);if(d&&f&&h&&s){s.result&&(n[i]=s.result);return}let A=new Set,E=new Set,v=new Set;c.forEach(w=>{w.sourceColumnReferences?.forEach(N=>{N.transform.trim().length||N.columnReferences?.forEach(k=>{let{stepCounter:L,columnCounter:q}=k;if(L==="0"||q==="0"||A.has(L))return;E.has(L)&&v.add(w.name);let G=r[L];if(G){let{locationName:H,name:V}=G.operation,W=u.some(J=>J.locationName===H&&J.nodeName===V),F=p.some(J=>J.locationName===H&&J.nodeName===V);W||F?A.add(L):(E.add(L),n[i]||(n[i]=_9o(o.operation.name)),v.add(w.name))}})})});let T=v.size>0?{columns:v,nodeName:o.operation.name}:void 0;T&&(n[i]=T),xHc[i]={dependencies:u.map(w=>new WeakRef(w)),noLinkDependencies:p.map(w=>new WeakRef(w)),nodeData:new WeakRef(o),result:T}}),n};var Obe=class extends jNe{noDependenciesPhases=["deletedTable"];getNodeRefsInPhase(t,n){return Object.fromEntries(n.map(i=>{let o,s=this.extraRefs[i];s?o=[s]:o=this.phasedRefUsage.get(t,i);let a=o.map(({ref:u,ref_no_link:p})=>NHc([...u,...p]));return[i,[].concat(...a)]}))}};var m$e=class extends jNe{noDependenciesPhases=[];getNodeRefsInPhase(t,n){let i=Nb(this.allNodes,...n);return fv(i,o=>{if(Zye(o.operation))return[];let{sourceMapping:s}=o.operation.metadata;if(!s?.length)return[];let a=s.map(({dependencies:u})=>u);return[].concat(...a)})}};var ZRt=async(r,t)=>{let{attempts:n,tags:i,waitSeconds:o}=t,s=Ml().child({retryOptions:{maxAttempts:n,waitSeconds:o},tags:["[withRetries]",...i]});kE(n>=2,`Retry attempts value must be at least '2', but was '${n}'`,s);try{let a=await r();return s.debug("Operation succeeded without retrying"),a}catch(a){s.error(`Operation initial attempt failed; retrying. Error: ${a}`);let u,p=n-1;do{p--,await new Promise(c=>setTimeout(c,o*(n-p)*1e3));try{let c=await r();return s.info(`Operation succeeded on retry (attempt ${n-p})`),c}catch(c){s.error(`Operation failed on retry (attempt ${n-p}). Error: ${c}`),u=c}}while(p);throw s.error("Exhausted all retry attempts; exiting"),u}};var BL=yt(Mq()),oh1=BL.String,sh1=BL.Record({locationName:BL.String,database:BL.String,schema:BL.String}),U92=BL.Dictionary(sh1,oh1);var z92=BL.Record({seconds:BL.Number,nanoseconds:BL.Number});var ah1="Making metadata updates",LHc="Deleting metadata for source input";function y$e(r,t){let n=[];for(let i of r){let o=i.compiledSQL?tJe(i.compiledSQL):[];if(o.length===0)t&&n.push({name:t,sql:"",type:"sql",continueOnFailure:!1,parsedStage:null});else for(let s of o)n.push({name:s.name,sql:s.code,type:s.type,continueOnFailure:s.continueOnFailure,parsedStage:s})}return n}function JEr(r,t){return r==="deletedTable"&&t?LHc:ah1}var rH=class extends nt{constructor(n,i){super(i,`Failed node ${n}: ${i}`);this.nodeID=n}nodeID};var lOt=yt(Mq()),oA1=yt(v$e()),F72=(0,lOt.Record)({version:lOt.String,hash:lOt.String}),sA1=()=>{let r="7.40.0-aa-dev.45.h16af1ae6d5b0.dirty",t="16af1ae6d5b00b37857f21ef5957306875c0eb1b";return r&&t?{version:r,hash:t}:null},Dv=sA1();var wbe=class extends nt{constructor(n){super(`Run ${n} canceled by user`);this.runID=n}runID},T$e=class extends nt{constructor(n){super('Test failed with "continue on failure" set to false');this.result=n}result};var PWc=(r,t,n)=>{switch(r){case"skipped":return"Skipped";case"error":return"Error";case"complete":switch(n){case"create":return t?"Validated":"Created";case"run":return t?"Validated":"DataLoaded";default:return"None"}default:return"None"}},NWc=r=>typeof r=="object"&&r instanceof T$e,YNe=r=>typeof r=="object"&&(r instanceof BA||r instanceof wbe),pOt=r=>typeof r=="object"&&r instanceof cF&&r.isCancel(),dOt=r=>typeof r=="object"&&r instanceof bX&&r.isCancel(),K9o=r=>YNe(r)||pOt(r)||dOt(r);var DWc=5e5,BWc=500,Mbe=class r{constructor(t,n,i,o,s){this.state=t;this.repository=n;this.logContext=i;this.operationType=o;this.analyticsCollector=s}state;repository;logContext;operationType;stepsInitialized=null;runResults={};flusher=null;wasCanceled=!1;nodeStageIndexTracker=new Map;analyticsCollector;get teamID(){return this.logContext.orgID}get runID(){return this.logContext.runID}get envID(){return this.logContext.workspaceID}GetLogContext=t=>({...this.logContext,nodeID:t});async runIsCanceled(){if(!this.repository)return!1;if(this.wasCanceled)return!0;try{let t=!!(await this.getRepositoryForRun().fetch({pendingWritesTimeoutMs:100})).runDetails.canceled;return t&&(this.wasCanceled=!0),t}catch(t){if(LE(t)){if(t instanceof zNe)return!1;if(t instanceof Du)return!1}throw t}}async throwIfRunCanceled(){if(await this.runIsCanceled())throw new wbe(this.runID)}updateNodeLocalRunResult({stepID:t,isPreview:n,runExecutionSequenceID:i},o){let s=this.runResults[t];s?(s.runState=o,s.queryResultSequence.isRunning=o==="running",s.stepRunState=this.getStepRunState(o,n),i!==void 0&&(s.runExecutionSequenceID=i),(o==="canceled"||o==="skipped"||o==="error")&&s.queryResultSequence.queryResults.forEach(a=>{!a.isRunning&&a.status==="Queued"&&(a.status="Canceled")})):this.Logger.errorContext(this.GetLogContext(t),"EventHandler updateNodeLocalRunResult: missing expected local run result for node",t)}getBulkSkipHandler=()=>async t=>{if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let[o,s]of Object.entries(t))if(this.runResults[o]){let a=i.get(o);this.updateNodeLocalRunResult({stepID:o,isPreview:!1,runExecutionSequenceID:s},"skipped");let u={...r.truncateRunResult(this.runResults[o]),version:2};await n.save(a,u)}await n.commit()};getCancelNodeHandler=()=>async t=>{try{if(!this.repository)return;if(this.runResults[t]){this.updateNodeLocalRunResult({stepID:t,isPreview:!1},"canceled");let i=this.getRepositoryForRun().runResults.get(t),o={...r.truncateRunResult(this.runResults[t]),version:2};await i.save(o)}else this.Logger.errorContext(this.GetLogContext(t),"EventHandler getCancelNodeHandler: missing expected local run result for node",t)}catch(n){this.Logger.errorContext(this.logContext,`Error canceling node ${t}`,n)}};async repositoryUpdateRunStatus({expectedStatus:t,newStatus:n}){if(!this.repository)return;let i=this.getRepositoryForRun();try{let o=await i.fetch();hh("RUNNER_BACKEND",t===o.runStatus,this.logContext,`EventHandler.repositoryUpdateRunStatus found unexpected run status - expected: ${t} / actual: ${o.runStatus}`)}catch(o){this.Logger.alertContext(this.logContext,"Error fetching runInfo",o)}await i.merge({runStatus:n})}async repositoryStampExecutorInfo(t){if(this.repository)try{await this.getRepositoryForRun().merge({platform:t,...Dv?{softwareVersion:Dv.version}:{}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryStampExecutorInfo] Error stamping executor info. Cannot update run document version/platform.",n)}}async repositoryUpdateRenderingProgress(t){if(this.repository)try{await this.getRepositoryForRun().merge({renderingProgress:{totalNodes:t.totalNodes,completedNodes:t.completedNodes}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryUpdateRenderingProgress] Error updating rendering progress. Cannot update run document renderingProgress.",n)}}getRepositoryRunsCollection(){if(!this.repository)throw new nt("No repository to get runs collection for!");let t=this.repository.orgs.get(this.logContext.orgID);return this.runLevel==="orgRuns"?t.runs:t.devRuns}getRepositoryForRun(){return this.getRepositoryRunsCollection().get(this.runID)}formatError=(t,n=null,i=null,o=!1)=>{let s=ua(t.error).error,a="";return t.error&&typeof t.error=="object"&&!(t.error instanceof Error)&&"runDetails"in t.error&&typeof t.error.runDetails=="object"&&(a=t.error?.runDetails?.compiledSQL??""),t.templateString&&(a=t.templateString),{success:!1,error:{errorString:s.errorString??"",errorDetail:s.errorDetail??""},rows:[],fields:[],name:"",exportedRefs:[],invalidExportedRefs:[],status:o?"Canceled":"Failure",sql:a??"",startTime:t.startTime,endTime:new Date,isRunning:!1,type:"sql",queryID:n,warehouse:i}};populateRunResults(t,n){let i="[EventHandler.populateRunResults()]",o=t.length+1;for(let s of t){let u=g1(s,this.state.nodes,`${i} state.nodes`).operation.name;this.runResults[s]={name:u,runExecutionSequenceID:o,dataResult:null,runState:n,stepRunState:"None",queryResultSequence:{name:u,queryResults:[],isRunning:!1},runResultVersion:2}}}async bulkSetRunResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)throw new nt(`Run result for node ${o} does not exist for run ${this.runID}`);let a={...s,name:s.queryResultSequence.name,runExecutionSequenceID:s.runExecutionSequenceID,version:2},u=i.get(o);await n.save(u,a)}await n.commit()}async initializeRunResults(t,n="queued"){this.stepsInitialized=[...t],this.populateRunResults(t,n),await this.bulkSetRunResults(t)}setFlusher(t){this.flusher=t,t.startTimer()}async disposeFlusher(){await this.flusher?.stopAndFlush()}async populatePlaceholderStages(t,n){let i=new Set,o=new Set(t.keys());for(let s of n){if(!o.has(s))continue;let a=t.getPhaseItems(s);for(let[u,p]of a.entries()){let c=g1(u,this.runResults,"populateQueuedStages: this.runResults"),l=this.state.nodes[u],d=l?$P(l,void 0):!1,f=y$e(p,this.getNameForStageWithoutSQL(s,d));for(let h of f)c.queryResultSequence.queryResults.push(this.createQueuedStage(h));f.length>0&&!i.has(u)&&(i.add(u),this.nodeStageIndexTracker.set(u,0))}}await this.bulkSetQueuedStageResults(i)}createQueuedStage({name:t,sql:n,type:i}){return{name:t,status:"Queued",success:!0,sql:n,rows:[],fields:[],startTime:new Date,endTime:new Date,isRunning:!1,exportedRefs:[],invalidExportedRefs:[],type:i}}async bulkSetQueuedStageResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)continue;let a=i.get(o);await n.save(a,r.buildRunResultEntitySave(s))}await n.commit()}formatErrorToResult(t,n){let i=null,o=null;return typeof t.error=="object"&&(i=t.error.queryID||null,o=t.error.warehouse||null),{...this.formatError(t,i,o,n),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}ensureHasQueryResult(t){if(hh("DEPLOY",!!t.queryResult,this.GetLogContext(t.stepID),"query result should always be returned for stage execution"),!t.queryResult)throw new Error("Got an empty query result for stage execution")}updateStageResultAtTrackedIndex=(t,n)=>{let o=g1(t,this.runResults,"[EventHandler.setLastQueryResult()]").queryResultSequence.queryResults,s=this.getCurrentStageIndex(t);if(s<0||s>=o.length)throw this.Logger.errorContext(this.GetLogContext(t),"[EventHandler.setLastQueryResult] stage index out of bounds",{targetIndex:s,queryResultsLength:o.length,resultName:n.name}),new nt(`Stage index ${s} out of bounds (length: ${o.length}) for node ${t}`);o[s]=n};async dispatchQueryFailure(t,n){let i=this.formatErrorToResult(t,n);return this.Logger.errorContext(this.GetLogContext(t.stepID),"failed to execute run sql",n?"- canceled":"- errored",t.error,"stack: ",t.error.stack||"<none found>"),this.updateStageResultAtTrackedIndex(t.stepID,i),{error:i.error}}getSingleStepData(t,n){let i=this.state.nodes[n];if(i)return i;let o=`(${this.runTypeName}) EventHandler: Could not get step data for step: ${n}`;throw this.Logger.errorContext(this.GetLogContext(n),o,n),new nt(o)}getUnrunSteps(){let t={},n=this.state.nodes,i=this.runResults;if(n&&this.stepsInitialized)for(let o of this.stepsInitialized){let s=i[o];if(s){let{runState:a}=s;(a==="waiting"||a==="queued")&&(n[o]?t[o]=0:this.Logger.alertContext(this.logContext,"Node ID from initialization not found in steps data",o))}else this.Logger.alertContext(this.logContext,"Node ID from initialization not found in run results",o)}return t}getStepContext=(t,n,i,o)=>{let s=this.getSingleStepData(t,n),{locationName:a}=s.operation,{database:u}=this.state.mappings[a]?.mappingDefinitions[this.state.currentWorkspace]??{},p=$P(s,void 0),c=s.operation.name;return{startTime:new Date,stepID:n,stepName:c,runExecutionSequenceID:i,phase:t,isPreview:o,isSource:p,database:u??""}};convertIQueryToCompletedQueryResult(t){return{...t,startTime:n4o(t.startTime),endTime:n4o(t.endTime)}}getCurrentStageIndex(t){let n=this.nodeStageIndexTracker.get(t);if(n===void 0)throw new nt(`[EventHandler.getCurrentStageIndex] Node ${t} not in stage tracker. Was populateQueuedStages called for this node?`);return n}advanceToNextStage(t){let n=this.getCurrentStageIndex(t);this.nodeStageIndexTracker.set(t,n+1)}getQueryResultForUpdateSuccess(t){return{...this.convertIQueryToCompletedQueryResult(t.queryResult),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}getStepRunState(t,n){return PWc(t,n,this.operationType)}async updateRunResult(t){if(!this.repository)return;let n=this.runResults[t];if(!n)throw new nt(`[EventHandler.updateRunResult()] run result for node ${t} does not exist for run ${this.runID}`);if(this.flusher)this.flusher.markDirty(t);else{let i=r.buildRunResultEntitySave(n);this.Logger.debugContext(this.GetLogContext(t),"updating run result",i),await this.getRepositoryForRun().runResults.get(t).save(i)}}isFinalRunForStep(t){return!0}async beforePhaseExecution(t,n){}async afterPhaseExecution(t){}async beforeStepExecution(t){this.runResults[t.stepID]&&(this.runResults[t.stepID].runExecutionSequenceID=t.runExecutionSequenceID),this.updateNodeLocalRunResult(t,"running"),await this.updateRunResult(t.stepID)}async afterFinalRunSuccessForNode(t){return Promise.resolve()}async afterStepExecutionSuccess(t){this.isFinalRunForStep(t)?(this.updateNodeLocalRunResult(t,"complete"),await this.afterFinalRunSuccessForNode(t)):this.updateNodeLocalRunResult(t,"waiting"),await this.updateRunResult(t.stepID)}async afterStepExecutionFailure(t){let n=await this.isCoalesceInitiatedCancel(t.error);this.markUnexecutedStagesAsCanceled(t.stepID),this.updateNodeLocalRunResult(t,n?"canceled":"error");try{this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID)}catch(i){this.Logger.emergContext(this.GetLogContext(t.stepID),`Error in firebaseUpdateStepResult for stepCounter:${t.stepID}:`,i)}}markUnexecutedStagesAsCanceled(t){let n=this.runResults[t];if(n)for(let i of n.queryResultSequence.queryResults)"status"in i&&i.status==="Queued"&&(i.status="Canceled")}sanityCheckContext(t){if(!t.stageType)throw this.Logger.emergContext(this.logContext,`No stage type on this ${this.runTypeName}!`,t),new Error(`Internal critical error: no stage type on this ${this.runTypeName}!`)}async beforeStageExecution(t){this.sanityCheckContext(t);let n=this.runResults[t.stepID];if(n){let i=n.queryResultSequence.queryResults,o=this.getCurrentStageIndex(t.stepID),s=i[o];if(!s||!("status"in s)||s.status!=="Queued"){let a=s&&"status"in s?s.status:"no-status";throw new nt(`[EventHandler.beforeStageExecution] Expected queued placeholder at index ${o} for node ${t.stepID}, but found: ${s?`status=${a}`:"undefined"}`)}s.status="Running",s.startTime=new Date,s.endTime=s.startTime,await this.updateRunResult(t.stepID)}}async updateRunWithHeartbeat(t){await this.getRepositoryForRun().updateHeartbeat(t)}async afterStageExecutionSuccess(t){let n="[EventHandler.afterStageExecutionSuccess()]";if(this.sanityCheckContext(t),!t.queryResult){let i="Got an empty query result for stage execution - query result should always be returned!";throw this.Logger.alertContext(this.GetLogContext(t.stepID),n,i),new nt(i)}if(t.stageExecutionStartTime&&t.stageExecutionEndTime){let i=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,i,!0,t.stageExecutionStartTime)}if(DIt(t.queryResult)&&!t.queryResult.success){await this.updateRunWithHeartbeat({hasTestFailures:!0});let i=this.runResults[t.stepID];i&&(i.hasTestFailures=!0)}this.updateStageResultAtTrackedIndex(t.stepID,this.getQueryResultForUpdateSuccess(t)),await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID)}async afterStageExecutionFailure(t){if(this.sanityCheckContext(t),t.stageExecutionStartTime&&t.stageExecutionEndTime){let o=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,o,!1,t.stageExecutionStartTime)}let n=await this.isCoalesceInitiatedCancel(t.error),i=await this.dispatchQueryFailure(t,n);throw this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID),n?t.error:i}async isCoalesceInitiatedCancel(t){return YNe(t)?!0:pOt(t)?this.runIsCanceled():dOt(t)?this.runIsCanceled():!1}static truncateQueryResult(t,n=DWc,i=BWc){let o=t.sql,s=t.rows,a,u;if(o){let p=new TextEncoder,c=new TextDecoder("utf8"),l=p.encode(o);if(l.length>n){let d=c.decode(l.slice(0,n));d.slice(-1)==="\uFFFD"&&(d=d.slice(0,-1)),a=`${d}...data truncated`}}return s?.length>i&&(u=s.slice(0,i),u.push({values:[`${s.length-i} rows truncated`]})),a||u?{...t,sql:a??o,rows:u??s}:t}static buildRunResultEntitySave(t){return{...r.truncateRunResult(t),name:t.queryResultSequence.name,runExecutionSequenceID:t.runExecutionSequenceID,version:2}}static truncateRunResult(t){let n=(t.dataResult?.sql?1:0)+(t.queryResultSequence?.renderQueryResults?.sql?1:0)+(t.queryResultSequence?.queryResults?.length??0),i=(t.dataResult?.rows?.length?1:0)+(t.queryResultSequence?.renderQueryResults?.rows?.length?1:0)+(t.queryResultSequence?.queryResults?.reduce((p,c)=>p+c?.rows?.length?1:0,0)??0);if(n===0&&i===0)return t;let o=Math.trunc(DWc/n)-100,s=BWc/(i??1),a={...t};t.dataResult?.sql&&(a.dataResult=r.truncateQueryResult(t.dataResult,o,s)??null);let u=t.queryResultSequence;return u&&(a.queryResultSequence={...u,queryResults:u.queryResults?.map(p=>r.truncateQueryResult(p,o,s))},u.renderQueryResults&&(a.queryResultSequence.renderQueryResults=r.truncateQueryResult(u.renderQueryResults,o,s))),a}};var fOt=class extends Mbe{constructor(n,i,o,s,a){super(n,i,o,"create",a);this.phasedNodeData=s}phasedNodeData;getNameForStageWithoutSQL=(n,i)=>JEr(n,i);getNodeDataForUpdate=n=>{let i=this.getSingleStepData(n.phase,n.stepID),o=i.operation.locationName,s=Zq(this.state.mappings,this.envID),a=this.GetLogContext(n.stepID),u;try{let p=s?.[o]?.database??i.operation.database,c=s?.[o]?.schema??i.operation.schema;return u={...i.operation,metadata:{...i.operation.metadata,columns:i.operation.metadata.columns.map(l=>({...l}))},database:p,schema:c,version:1,id:n.stepID,deployEnabled:!0},this.Logger.infoContext(a,"newStepData:",u,"stepCounter:",n.stepID),cAc("(Logging Only) Compare locations from context and workspace",a,()=>{let l=Zq(this.state.mappings||{},this.state.currentWorkspace);hh("DEPLOY",$1e(l[o],s[o]),a,`Location data for location ${o} for node ${i.operation.name} with id ${n.stepID} differs between data from context and data from workspace.`,"locationsFromWorkspace:",l,"locationsFromContext:",s)}),u}catch(p){let c=u?u.name:i.operation.name,l=`Error attempting to update the database/schema on deployed nodeID ${n.stepID}: ${c}`;throw this.Logger.emergContext(a,l,"locations:",s,"error:",p),new rH(n.stepID,l)}};async updateEnvironmentNodeMetadata(n){if(!this.repository)return;let i=this.repository.org(this.teamID).workspace(+this.envID).nodes.get(n.stepID);if(n.phase==="deletedTable")n.stepID in this.phasedNodeData.addedTable||await i.delete();else{let o=this.getNodeDataForUpdate(n);await i.save(o)}}isFinalRunForStep(n){let i=[];return n.phase==="deletedTable"&&(i.push(this.phasedNodeData.alteredTable),i.push(this.phasedNodeData.addedTable)),n.phase==="alteredTable"&&i.push(this.phasedNodeData.addedTable),!i.some(o=>n.stepID in o)}async afterFinalRunSuccessForNode(n){try{await this.updateEnvironmentNodeMetadata(n)}catch(i){let o=this.GetLogContext(n.stepID);this.Logger.errorContext(o,"Error updating node metadata -- nodeID:",n.stepID,"error:",i);let s=sWe(i),a="unknown location";try{a=this.getSingleStepData(n.phase,n.stepID).operation.locationName}catch(u){this.Logger.errorContext(o,`Error getting location name for node ${n.stepName} (${n.stepID}):`,u)}throw new rH(n.stepID,`Failed to update node metadata for ${n.stepName} (${a}): ${s}`)}}};var LWc=(r,t)=>{let n=new Set(t);return n.delete(r),Array.from(n)},u2r=async(r,t,n)=>{if(!t)throw new nt(`Cannot get deploy run info since workspace ${r} has no currently running jobs`);if(t.length)return(await n.selectInBatches("id","in",t,[["runType","==","deploy"],["runStatus","==","running"]]))[0]};var c2r="No SQL to execute";var hOt=class extends Mbe{constructor(t,n,i,o){super(t,n,i,"run",o)}async initializeRunResults(t){await super.initializeRunResults(t,"waiting")}getNameForStageWithoutSQL=()=>c2r};var l2r=class{constructor(t,n,i,o,s,a,u){this.repository=t;this.getRunRepository=n;this.buildEntitySave=i;this.runResults=o;this.logger=s;this.logContext=a;this.flushIntervalMs=u?.flushIntervalMs??3e3,this.flushThreshold=u?.flushThreshold??50}repository;getRunRepository;buildEntitySave;runResults;logger;logContext;dirtyNodes=new Set;timer=null;activeFlush=null;flushedDuringBatch=new Set;flushIntervalMs;flushThreshold;totalFlushes=0;totalNodeWrites=0;totalImmediateWrites=0;timerFlushes=0;thresholdFlushes=0;slowCommits=0;tag="[RunResultFlusher]";markDirty(t){this.dirtyNodes.add(t),this.dirtyNodes.size>=this.flushThreshold&&this.flush("threshold").catch(n=>{this.logger.errorContext(this.logContext,`${this.tag} threshold-triggered flush error`,n)})}async flush(t="dispose"){if(this.activeFlush||this.dirtyNodes.size===0){this.logger.debugContext(this.logContext,`${this.tag} flush skipped (activeFlush=${!!this.activeFlush}, dirtySetEmpty=${this.dirtyNodes.size===0}, trigger=${t})`);return}let n=new Set(this.dirtyNodes);this.dirtyNodes.clear(),this.activeFlush=this.doFlush(n,t);try{await this.activeFlush}finally{this.activeFlush=null}}async doFlush(t,n){try{let i=this.repository.batch();for(let a of t){let u=this.runResults[a];if(!u){this.logger.warnContext(this.logContext,`${this.tag} node ${a} no longer has a run result, skipping write`);continue}let p=this.buildEntitySave(u),c=this.getRunRepository().runResults.get(a);await i.save(c,p)}let o=Date.now();await i.commit();let s=Date.now()-o;if(this.flushedDuringBatch.size>0){let a=this.getRunRepository().runResults;for(let u of this.flushedDuringBatch)if(t.has(u)){let p=this.runResults[u];p&&await a.get(u).save(this.buildEntitySave(p))}this.flushedDuringBatch.clear()}this.totalFlushes++,this.totalNodeWrites+=t.size,n==="timer"&&this.timerFlushes++,n==="threshold"&&this.thresholdFlushes++,s>=2e3&&(this.slowCommits++,this.logger.warnContext(this.logContext,`${this.tag} slow commit: ${s}ms for ${t.size} nodes (possible write stream pressure)`)),this.logger.debugContext(this.logContext,`${this.tag} flushed ${t.size} run results in ${s}ms (${n}, threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}catch(i){for(let o of t)this.dirtyNodes.add(o);throw this.logger.errorContext(this.logContext,`${this.tag} flush failed, ${t.size} nodes re-queued`,i),i}}async flushOne(t){this.dirtyNodes.delete(t);let n=this.runResults[t];if(!n){this.logger.warnContext(this.logContext,`${this.tag} node ${t} no longer has a run result, skipping write (flushOne)`);return}this.activeFlush&&this.flushedDuringBatch.add(t);let i=this.buildEntitySave(n);await this.getRunRepository().runResults.get(t).save(i),this.totalImmediateWrites++}startTimer(){this.timer||(this.timer=setInterval(()=>{this.flush("timer").catch(t=>{this.logger.errorContext(this.logContext,`${this.tag} timer-triggered flush error`,t)})},this.flushIntervalMs))}async stopAndFlush(){this.timer&&(clearInterval(this.timer),this.timer=null);try{if(this.activeFlush)try{await this.activeFlush}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error waiting for in-flight flush (stopAndFlush)`,t)}this.logger.infoContext(this.logContext,`${this.tag} draining remaining dirty nodes (stopAndFlush)`),await this.flush("dispose")}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error stopping and flushing (stopAndFlush)`,t)}finally{this.logger.infoContext(this.logContext,`${this.tag} done \u2014 ${this.totalFlushes} flushes (${this.thresholdFlushes} threshold, ${this.timerFlushes} timer, ${this.slowCommits} slow), ${this.totalNodeWrites} batched writes, ${this.totalImmediateWrites} immediate writes (threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}}};var p2r=class extends fOt{constructor(t,n,i,o,s){super(t,n,i,o,s)}get Logger(){return Je("DEPLOY")}get runTypeName(){return"Deploy"}get runLevel(){return"orgRuns"}},d2r=class extends hOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Refresh"}get runLevel(){return"orgRuns"}afterStepExecutionSuccess=async t=>{await super.afterStepExecutionSuccess(t),this.repository&&super.isFinalRunForStep(t)&&!t.isSource&&await this.repository.org(this.logContext.orgID).workspace(this.logContext.workspaceID).nodeLastRefreshed(t.stepID).save({lastRefreshed:new Date().toISOString()})};getQueryResultForUpdateSuccess=t=>({...super.getQueryResultForUpdateSuccess(t),type:t.stageType});async dispatchQueryFailure(t,n){if(NWc(t.error)){let i=t.error,o=this.getCurrentStageIndex(t.stepID);t.stepID in this.runResults&&(this.runResults[t.stepID].queryResultSequence.queryResults[o]=this.convertIQueryToCompletedQueryResult(i.result));let s=this.runResults[t.stepID];return s&&(s.hasTestFailures=!0),await this.updateRunWithHeartbeat({hasTestFailures:!0}),{error:{errorString:t.error.message,errorDetail:t.error.message}}}else return super.dispatchQueryFailure(t,n)}},f2r=class extends fOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}},h2r=class extends hOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}};var JNe=["deletedTable","alteredTable","addedTable"],$Ne=["refresh"];var g2r=`{%- macro get_value_by_column_attribute(column_attribute, value="name") -%}
|
|
9604
|
+
%s`,V,V,v,a);let W=v.type==="*"?f9o:v.type==="?"?g9o:"\\"+v.type;u=!0,a=a.slice(0,v.reStart)+W+"\\("+V}q(),p&&(a+="\\\\");let G=Df1[a.charAt(0)];for(let V=l.length-1;V>-1;V--){let W=l[V],F=a.slice(0,W.reStart),J=a.slice(W.reStart,W.reEnd-8),Y=a.slice(W.reEnd),z=a.slice(W.reEnd-8,W.reEnd)+Y,X=F.split(")").length,Z=F.split("(").length-X,re=Y;for(let ee=0;ee<Z;ee++)re=re.replace(/\)[+*?]?/,"");Y=re;let oe=Y===""&&n!==QEr?"(?:$|\\/)":"";a=F+J+Y+oe+z}if(a!==""&&u&&(a="(?=.)"+a),G&&(a=k()+a),n===QEr)return[a,u];if(i.nocase&&!u&&!i.nocaseMagicOnly&&(u=t.toUpperCase()!==t.toLowerCase()),!u)return Ff1(t);let H=i.nocase?"i":"";try{let V=s?{_glob:t,_src:a,test:s}:{_glob:t,_src:a};return Object.assign(new RegExp("^"+a+"$",H),V)}catch(V){return this.debug("invalid regexp",V),new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let n=this.options,i=n.noglobstar?f9o:n.dot?Pf1:Nf1,o=n.nocase?"i":"",s=t.map(a=>{let u=a.map(p=>typeof p=="string"?zf1(p):p===lF?lF:p._src);return u.forEach((p,c)=>{let l=u[c+1],d=u[c-1];p!==lF||d===lF||(d===void 0?l!==void 0&&l!==lF?u[c+1]="(?:\\/|"+i+"\\/)?"+l:u[c]=i:l===void 0?u[c-1]=d+"(?:\\/|"+i+")?":l!==lF&&(u[c-1]=d+"(?:\\/|\\/"+i+"\\/)"+l,u[c+1]=lF))}),u.filter(p=>p!==lF).join("/")}).join("|");s="^(?:"+s+")$",this.negate&&(s="^(?!"+s+").*$");try{this.regexp=new RegExp(s,o)}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):jEr&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,n=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&n)return!0;let i=this.options;h9o.sep!=="/"&&(t=t.split(h9o.sep).join("/"));let o=this.slashSplit(t);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let a=o[o.length-1];if(!a)for(let u=o.length-2;!a&&u>=0;u--)a=o[u];for(let u=0;u<s.length;u++){let p=s[u],c=o;if(i.matchBase&&p.length===1&&(c=[a]),this.matchOne(c,p,n))return i.flipNegate?!0:!this.negate}return i.flipNegate?!1:this.negate}static defaults(t){return q3.defaults(t).Minimatch}};q3.Minimatch=f$e;var oHc=2,sHc=1,aHc=3,uHc=2,cHc=8,lHc=5,pHc=6,dHc=new RegExp(/([\+]?){([\s\S]+)}([\+](?![\+]))?\s*/g),fHc=new RegExp(/((\w+):\s*((?:["])((([^\"\+\r\n\[/\\]+))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),hHc=new RegExp(/((\w+):\s*(((?:["])(((?:[^"]|"")*))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),gHc=new RegExp(/((?:[^\+\ \r\n\[\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\s*/g),iHc="",h$e=(r,t)=>{if(t==="*")return r.some(o=>o!=null&&String(o).length>0);let n=r.map(o=>o!=null?String(o).replace(/\//g,iHc):""),i=t.replace(/\//g,iHc);return!!A9o(n,i).length};var g$e=Je("SEARCH"),XL2=B.object({include:B.string(),exclude:B.string(),enabled:B.boolean()}),AHc={name:{MatchFunction:h$e,MatchList:r=>[r.operation.name]},location:{MatchFunction:h$e,MatchList:r=>[r.operation.locationName]},nodeType:{MatchFunction:h$e,MatchList:r=>[r.operation.sqlType]},subgraph:{MatchFunction:h$e,MatchList:r=>[r?.id?.toString(),r.name]},nodeID:{MatchFunction:h$e,MatchList:r=>[r]}},mHc=r=>{let t=[];return r.forEach((n,i)=>{if(n==="+{"||n==="{"||n==="}"||n==="}+")return;let o=n,s=n.split(""),a=s[s.length-1],u=s[0];a!=="}"&&a!=="+"&&(o=o+r[i+1]),u!=="{"&&u!=="+"&&(o=r[i-1]+o),t.push(o)}),t},yHc=(r,t,n,i=!1)=>{let{steps:o,graphInformation:s,allSubgraphs:a,allStepTypesYAML:u}=n,p={},c=i3()?Date.now():performance.now(),l=r;l||(l=t);let d=l.split(/(\}\+?)\s*(or|OR|\|\|)\s*(\+?\{)/).filter(A=>!(A==="OR"||A==="or"||A==="||")),f=mHc(d);f.length||(f=[t]),g$e.debug("got unions",f,"searchStringTouse",l,"defaultSearchString",t,"steps",o),f.forEach(A=>{let E=A.split(/(\}\+?)\s*(and|AND|\,)\s*(\+?\{)/).filter(k=>!(k==="AND"||k==="and"||k===",")),v=mHc(E),T=[];v.forEach(k=>{let L={};g$e.debug("Got intersection:",k);let q=[...k.matchAll(dHc)];if(g$e.debug("Got matches:",k,q),!q[0])return;let G=q[0][oHc],H={prefix:q[0][sHc]||"",postfix:q[0][aHc]||""};if(G.indexOf(":")>-1){let F=i?hHc:fHc,J=[...G.trim().matchAll(F)],Y=i?pHc:lHc;J.forEach(z=>{let X=z[uHc],Z=z[cHc]||z[Y];H[X]=Z})}else{let J=[...G.trim().matchAll(gHc)][0];J&&(H.name=J[0])}_M(H);let V=H;g$e.debug("Got groups ",k,V);let W=new Set;if(V.subgraph?Object.values(a).forEach(F=>{let J=AHc.subgraph,Y=J.MatchList(F);if(J.MatchFunction(Y,V.subgraph)){let{steps:X}=F;X.forEach(Z=>{W.add(Z.toString())})}else return}):W=new Set(Object.keys(o)),V.nodeType){let{nodeType:F}=V;if(!u[F]){let J=F;Object.entries(u).forEach(([Y,z])=>{z.name===F&&(J=Y)}),V.nodeType=J}}Object.keys(o).forEach(F=>{if(!V){g$e.emerg("got an unexpected undefined value for match",l,V,k);return}let J=W.has(F);if(Object.entries(V).forEach(([Y,z])=>{let X=o[F];if(Y==="nodeID"&&(X=F),Y==="subgraph"){J=W.has(F);return}let Z=AHc[Y];if(Z){let re=Z.MatchList(X).filter(oe=>oe!=null);J=J&&Z.MatchFunction(re,z)}}),J){if(L[F]=!0,V.prefix&&s){let Y=c9o(s,F,"predecessors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}if(V.postfix&&s){let Y=c9o(s,F,"successors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}}}),T.push(L)}),T.length||T.push({});let w={};Object.keys(o).forEach(k=>{w[k]=!0});let N=T.reduce((k,L)=>Object.fromEntries($gc(k,L).map(q=>[q,!0])),w);p={...p,...N}});let h=i3()?Date.now():performance.now();return g$e.debug("Time that search took: ",h-c),p};var HEr=(r,t,n,i=!1)=>{let o=yHc(`${r}`,"{ * }",n,i),s=yHc(`${t}`,"!*",n,i),a=o;return Object.keys(s).forEach(u=>{delete a[u]}),{stepsResult:a}};var bHc=(r,t,n,i)=>{let o=[];return t.forEach(s=>{let a=i[s];if(a){let{name:u}=a,p=`{ subgraph: "${u}" }`;o.push(p)}}),r.forEach(s=>{let a=n[s];if(a){let{locationName:u,name:p}=a.operation,c=`{ location: "${u}" name: "${p}" }`;o.push(c)}}),o};var Gf1=Je("JOBS");var EHc=r=>!r?.hasOwnProperty("includeSelector")||!r?.hasOwnProperty("version"),m9o=(r,t,n)=>{let{steps:i,subgraphs:o,...s}=r,a={...s};if(a.hasOwnProperty("version")||(a.version=c$),a.hasOwnProperty("includeSelector"))return a;a.includeSelector="",a.excludeSelector="";let u=new Set(i),p=new Set(o),d=bHc([...u],[...p].map(f=>`${f}`),n,t).map(f=>`+${f}`).join(" OR ");return a.includeSelector=d,Gf1.info("Upgrading job v1 to v2",r,a),a};var CHc=(r,t)=>{let{jobs:n,folders:i,steps:o}=r,s=n[t];return m9o(s,i,o)};var ak2=Je("PACKAGES_BACKEND");var SHc=(r,t,n)=>{let i=L6o(t)??"",o=r?.config?.entities?.nodeTypes[i];return o||(n.error(`No config found for node type ${t}`),{isDisabled:!1,defaultStorageLocation:null})};var VEr=(r,t={})=>Object.values(r).map(n=>Hf1(n)).reduce((n,i)=>{for(let[o,s]of Object.entries(i))n[o]=s;return n},t),Hf1=r=>Object.fromEntries(Object.entries(r?.contents?.nodeTypes??{}).map(([t,n])=>{let{id:i,nodeType:o}=Vf1(r.alias,t,r,n);return[i,o]})),Vf1=(r,t,n,i)=>{let o=Tmr(r,t),{isDisabled:s,defaultStorageLocation:a}=SHc(n,o,Je("PACKAGES")),u={...ep(i),id:o,isDisabled:s};return u.metadata.defaultStorageLocation=a,{id:o,nodeType:u}};var Ho=yt(Mq());var Wf1=Ho.Record({type:Ho.Unknown,name:Ho.String}),vHc=Ho.Record({locationName:Ho.String,nodeName:Ho.String}),THc=Ho.Record({sql:Ho.String,success:Ho.Boolean,rows:Ho.Array(Ho.Unknown),fields:Ho.Array(Wf1),error:Ho.Union(Ho.Null,jdr).optional(),startTime:Ho.Unknown,endTime:Ho.Unknown,status:Ho.String,name:Ho.String,isRunning:Ho.Boolean,exportedRefs:Ho.Array(vHc),invalidExportedRefs:Ho.Array(vHc),queryResultSequence:Ho.Optional(Ho.Unknown),type:Ho.Union(Ho.Literal("sql"),Ho.Literal("sqlTest")).optional(),warehouse:Ho.String.nullable().optional(),queryID:Ho.String.nullable().optional()}),y9o=Ho.Record({name:Ho.String,queryResults:Ho.Array(THc),isRunning:Ho.Boolean,renderQueryResults:Ho.Optional(THc)}),yk2=Ho.Record({runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,name:Ho.String,queryResultSequence:y9o,runState:Ho.String}),Kf1=Ho.Record({dataResult:Ho.Unknown,name:Ho.String,queryResultSequence:y9o,runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,runState:Ho.String,stepRunState:pWe(Y3o)}),_Hc=TM("RunResultFirestoreValidator",Kf1),Yf1=Ho.Record({nodeID:Ho.String,queryResultSequence:y9o,runState:Ho.String,hasTestFailures:Ho.Boolean.optional()}),Jf1=Ho.Record({runResults:Ho.Record({runStartTime:Ho.Unknown,runEndTime:Ho.Unknown,runFailureReason:Ho.Optional(Ho.String),runType:Ho.String,runStatus:Ho.String,runResults:Ho.Array(Yf1),runID:Ho.Number,environmentID:Ho.String,snowflakeAccount:Ho.String.optional(),snowflakeWarehouse:Ho.String.optional(),jobID:Ho.Number.optional(),hasFailedTest:Ho.Boolean.optional(),runTimeParameters:Ho.Unknown.nullable(),includeNodesSelector:Ho.String.optional(),excludeNodesSelector:Ho.String.optional()})}),WEr=TM("TRunOutput",Jf1);var Ck2=pWe(K3o);var Xf1=["deploy","refresh","rerun","plan"],Sk2=[...Xf1,"devRun"];var jNe=class{constructor(t,n,i,o){this.allNodes=t;this.renderResults=n;this.extraRefs=i;this.logContext=o;this.phasedRefUsage=n.map("phased ref usage",s=>s.map(a=>a.runDetails.ref_usage))}allNodes;renderResults;extraRefs;logContext;phasedRefUsage;buildPhase(t,n){let i="[DependencyBuilder.buildPhase()]",o=n.keys(),s=Object.keys(this.extraRefs),a=[...new Set([...o,...s])];if(Je("PIPELINE").appContext(this.logContext,i,"Nodes present in both current-phase data AND extra non-phased (views & advanced deploy) data:",Fpo([...o],s)),this.noDependenciesPhases.includes(t))return Object.fromEntries(a.map(u=>[u,[]]));{let u=this.getNodeRefsInPhase(t,a),p=new cNe(Nb(this.allNodes,a));return fv(u,(c,l)=>{let{nodeIDsToAdd:d}=JYe(c,p);return[...new Set(d)].filter(f=>f!==l)})}}build(){return Object.fromEntries([...this.phasedRefUsage.entries()].map(([t,n])=>[t,this.buildPhase(t,n)]))}};var xk2=Je("DEBUG");var KEr=r=>{typeof r.stepCounter=="number"&&(r.stepCounter=`${r.stepCounter}`),typeof r.columnCounter=="number"&&(r.columnCounter=`${r.columnCounter}`)};var Ibe=new Date("1980-01-01T00:00:00.000Z"),Vs=(r,t,n)=>{let i=`${r}Entity`;return n||(n=la(t)),{standard:Mr(i,n),strict:Mr(`${i} (strict)`,t)}};var IHc=r=>{if(Array.isArray(r))for(let t=r.length-1;t>=0;t--)r[t]===void 0&&r.splice(t,1);if(r&&typeof r=="object")for(let t in r)r.hasOwnProperty(t)&&r[t]===void 0&&delete r[t];return[r,!1]},Zf1=(r,t)=>{if(r&&typeof r=="object"){let n=r;if(n.toDate&&(!isNaN(n.seconds)&&!isNaN(n.nanoseconds)||!isNaN(n._seconds)&&!isNaN(n._nanoseconds))){let i=n.toDate();return i.getTime()===Bce.SENTINEL_DATE&&Ml().emerg(`Repository server timestamp sentinel value found in stored data at path ${t}`),[i,!0]}}return[r,!1]},RHc=(r,t)=>r instanceof Q4e?[t.getDeleteSentinel(),!0]:r instanceof Date&&r.getTime()===Bce.SENTINEL_DATE?[t.getServerTimestampSentinel(),!0]:[r,!1],GNe=(r,t,n)=>{let[i,o]=t(n,r);if(!o&&typeof i=="object"){if(Array.isArray(i))return i.map(s=>GNe(r,t,s));for(let s in i)i.hasOwnProperty(s)&&(i[s]=GNe(r,t,i[s]))}return i},$Rt=class{fromStorage(t,n,i,o,s){try{return this.transformFromStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} from storage: ${a}`),a}return i}toStorage(t,n,i,o,s){try{return this.transformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} to storage ${a}`),a}return i}mergeToStorage(t,n,i,o,s){try{return this.mergeTransformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error merge transforming repository entity ${n} to storage ${a}`),a}return i}},b9o=class extends $Rt{constructor(n=!1){super();this.preserveID=n}preserveID;transformFromStorage(n,i,o){return"id"in o?o.id!=n&&(Ml().error(`'id' property does not match doc id on doc at path ${i}; doc id: ${n}, value.id: ${o.id}`),o.id=n):o.id=n,"createdAt"in o||(o.createdAt=Ibe),"updatedAt"in o||(o.updatedAt=Ibe),GNe(i,Zf1,o)}transformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}mergeTransformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}},E9o=class extends $Rt{constructor(n){super();this.validators=n}validators;transformFromStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}transformToStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}mergeTransformToStorage(n,i,o,s,a){return o}getValidatorOptions(n,i,o=500){let s={...i,statusCode:o};return s.errorMessage||(s.errorMessage=a=>`Found ${a.failures.length} validation failure(s) for ${this.validators.standard.name} ${n}`),s}},qu=(r,t,n)=>{let i=[new b9o(n),new E9o(r)];return t&&i.unshift(t),new C9o(...i)},C9o=class{transforms;constructor(...t){this.transforms=t}fromStorage(t,n,i,o,s){return this.transforms.reduce((a,u)=>u.fromStorage(t,n,a,o,s),i)}toStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.toStorage(t,n,a,o,s),i)}mergeToStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.mergeToStorage(t,n,a,o,s),i)}},F3=class extends $Rt{transformToStorage(t,n,i){return i}mergeTransformToStorage(t,n,i){return i}};var OHc=r=>!!r&&typeof r=="object"&&!Array.isArray(r),A$e=r=>OHc(r)&&!(r instanceof Date)&&!(r instanceof RegExp),tH=r=>{if(typeof r=="string")return r;if(OHc(r)&&r.constructor&&typeof r.constructor.name=="string")return`[class ${r.constructor.name}]`;if(r instanceof Date)return`[date ${r.toISOString()}]`;if(r instanceof RegExp)return`[regexp ${r.toString()}]`;if(typeof r=="function")return`[function ${r.name}]`;try{return JSON.stringify(r)}catch{return"Error: could not stringify unknown value"}},S9o=r=>r==null,XRt=(r,t,n,i)=>{t.filter((o,s)=>A$e(o)?!0:(n.logError(`Invalid ${r} item detected at index ${s}: ${tH(o)}`),n.logPatch(`Removed invalid ${r} item at index ${s}`),!1)).forEach(i)},pF=(r,t,n)=>{r[t]=n},Rbe=(r,t)=>{delete r[t]},T9o=(r,t,n)=>{let i=new v9o(r,Je("FIREBASE"),t),{logError:o,logPatch:s,report:a}=i,u=()=>(a(),n);if(!A$e(n))return u();let p=n;if([["locationName",!p.locationName&&typeof p.locationName!="string"||typeof p.locationName!="string"],["description",typeof p.description!="string"]].forEach(([c,l])=>{l&&(s(`Set non-string property ${c} from ${tH(p[c])} to ""`),pF(p,c,""))}),["dependencies","isDataVault","locationID"].forEach(c=>{c in p&&(s(`Removed deprecated field ${c}`),Rbe(p,c))}),p.type==="sql")s("-- data.type is sql --"),eh1(r,p,i);else if(p.type==="sourceInput")s("-- data.type is sourceInput --"),th1(r,p,i);else return o(`Data type is of invalid type ${tH(p.type)}`),u();return p.version!==o$&&(s(`Set version ${tH(p.version)} to ${o$}`),pF(p,"version",o$)),u()},eh1=(r,t,n)=>{let{logError:i,logPatch:o}=n;if(t.isMultisource===void 0&&(o("Set missing isMultisource to false"),pF(t,"isMultisource",!1)),A$e(t.metadata)){let s=t.metadata;if(s.appliedNodeTests===null&&(o("Set metadata.appliedNodeTests from null to []"),pF(s,"appliedNodeTests",[])),!Array.isArray(s.sourceMapping)||!s.sourceMapping.length){o("Set non-array or empty metadata.sourceMapping to [ basicMapping ]");let a;typeof t.name=="string"?a=t.name:(o("Data has no name value, setting sourceMapping.name to empty string"),a=""),pF(s,"sourceMapping",[{name:a,join:{joinCondition:""},dependencies:[],noLinkRefs:[],aliases:{}}])}else XRt("sourceMapping",s.sourceMapping,n,(a,u)=>{let p=a;if(typeof p.join=="string"){let c={joinCondition:""};o(`Setting invalid string value metadata.sourceMapping[${u}].join to object: ${tH(c)}`),pF(p,"join",c)}if(p.name===void 0){let c=p.join?.name??"";o(`Set missing metadata.sourceMapping[${u}].name to "${c}"`),pF(p,"name",c),c||i(`metadata.sourceMapping[${u}].name is an empty string`)}Array.isArray(p.dependencies)&&XRt("sourceMapping dependency",p.dependencies,n,(c,l)=>{let d=c;for(let f of["locationName","nodeName"])S9o(d[f])&&(o(`Set metadata.sourceMapping[${u}].dependencies[${l}].${f} from ${tH(d[f])} to ""`),pF(d,f,""))})});wHc(r,s.columns,n)}if(t.config&&typeof t.config=="object")for(let[s,a]of Object.entries(t.config))a===null&&(o(`Removing null config property "${s}"`),Rbe(t.config,s))},th1=(r,t,n)=>{let{logPatch:i,logError:o}=n;if(t.dataset!==void 0&&(i("Removed deprecated v0 property dataset"),Rbe(t,"dataset")),t.table!==void 0&&(t.table!==t.name&&o(`source data properties 'table' and 'name' are different for source node ${r}, table: ${t.table}, name: ${t.name}`),i("Removed deprecated v0 property table"),Rbe(t,"table")),A$e(t.metadata)){let s=t.metadata;Array.isArray(s.columns)&&(s.columns.length&&wHc(r,s.columns,n),Object.keys(s).length>1&&(i(`Removed deprecated metadata properties, keeping only columns. Was: ${tH(s)}`),pF(t,"metadata",{columns:s.columns})))}},wHc=(r,t,n)=>{let{logPatch:i}=n;Array.isArray(t)&&XRt("column",t,n,(o,s)=>{let a=o;if(["ghostRecordValue","descendedFrom","hashColumns","columnsForHash"].forEach(c=>{a.hasOwnProperty(c)&&(i(`Removed deprecated property '${c}' from metadata.columns[${s}]`),Rbe(a,c))}),A$e(a.hashDetails)){let c=a.hashDetails;c.hashType&&(i(`Removed deprecated property 'hashType' from metadata.columns[${s}].hashDetails`),Rbe(c,"hashType")),c.hubHashes&&(i(`Removed deprecated property 'hubHashes' from metadata.columns[${s}].hashDetails`),Rbe(c,"hubHashes"))}[["appliedColumnTests",a.appliedColumnTests===null],["config",a.config===null],["hashDetails",typeof a.hashDetails=="string"]].forEach(([c,l])=>{l&&(i(`Deleted metadata.columns[${s}].${c} with invalid value ${tH(a[c])}`),Rbe(a,c))}),[["dataType",typeof a.dataType!="string"],["transform",a.transform===null]].forEach(([c,l])=>{l&&(i(`Set ${c} from ${tH(a[c])} to "" in metadata.columns[${s}]`),pF(a,c,""))});let u=a.hashedColumns;if(Array.isArray(u))for(let c of u)KEr(c);let p=a.columnReference;if(A$e(p)){KEr(p);let c=p;S9o(c.stepCounter)&&(i(`Set metadata.columns[${s}].columnReference.stepCounter from ${tH(c.stepCounter)} to ${r}`),pF(c,"stepCounter",r))}Array.isArray(a.sourceColumnReferences)&&XRt("sourceColumnReference",a.sourceColumnReferences,n,(c,l)=>{let d=c;Array.isArray(d.columnReferences)&&XRt("columnReference",d.columnReferences,n,(f,h)=>{KEr(f);let A=f;S9o(A.stepCounter)&&(i(`Set invalid metadata.columns[${s}].sourceColumnReferences[${l}].columnReferences[${h}].stepCounter to "" from ${tH(r)}`),pF(A,"stepCounter",""))})})})},v9o=class{constructor(t,n,i){this.id=t;this.logger=n;this.path=i}id;logger;path;patchMessages=[];errorMessages=[];logPatch=t=>{this.patchMessages.push(t)};logError=t=>{this.errorMessages.push(t)};reportErrors=()=>{this.errorMessages.length&&this.logger.error(`Error patching node data with id ${this.id} at path ${this.path}`,this.errorMessages)};reportPatches=()=>{this.patchMessages.length&&this.logger.debug(`Patched node data with id ${this.id} at path ${this.path}`,this.patchMessages)};report=()=>{this.reportErrors(),this.reportPatches()}},YEr=class extends F3{transformFromStorage(t,n,i){return T9o(t,n,i)}};var b92=Je("FIREBASE");var E92=Je("STEPS"),C92=Je("METADATA_OPERATIONS");var PHc=(r,t)=>t[r].runState==="running";var NHc=r=>(Bm("STEPS",!!r,`Error converting API refs: argument apiRefLinks is ${r}.`),r.map(t=>({locationName:t.location_name,nodeName:t.node_name})));var DHc=r=>r?.deployEnabled??!0,_9o=r=>({nodeName:r,columns:new Set});var MHc=(r,t)=>r?r.every((n,i)=>n.deref()===t[i]):!1,xHc={},BHc=(r,t)=>{let n={};return sNe(r,(i,o)=>{let s=xHc[i],a=t[i];if(!a)throw new nt(`Dependency/ref data for node ID "${i}" was not found`,`Dependency/ref data for node ID "${i}" not found in "GetNodesWithMissingColumnDependencies" (known IDs: ${JSON.stringify(t)})`);let{dependencies:u,noLinkDependencies:p}=a,c=o.operation.metadata.columns,d=s?.nodeData.deref()===o,f=MHc(s?.dependencies,u),h=MHc(s?.noLinkDependencies,p);if(d&&f&&h&&s){s.result&&(n[i]=s.result);return}let A=new Set,E=new Set,v=new Set;c.forEach(w=>{w.sourceColumnReferences?.forEach(N=>{N.transform.trim().length||N.columnReferences?.forEach(k=>{let{stepCounter:L,columnCounter:q}=k;if(L==="0"||q==="0"||A.has(L))return;E.has(L)&&v.add(w.name);let G=r[L];if(G){let{locationName:H,name:V}=G.operation,W=u.some(J=>J.locationName===H&&J.nodeName===V),F=p.some(J=>J.locationName===H&&J.nodeName===V);W||F?A.add(L):(E.add(L),n[i]||(n[i]=_9o(o.operation.name)),v.add(w.name))}})})});let T=v.size>0?{columns:v,nodeName:o.operation.name}:void 0;T&&(n[i]=T),xHc[i]={dependencies:u.map(w=>new WeakRef(w)),noLinkDependencies:p.map(w=>new WeakRef(w)),nodeData:new WeakRef(o),result:T}}),n};var Obe=class extends jNe{noDependenciesPhases=["deletedTable"];getNodeRefsInPhase(t,n){return Object.fromEntries(n.map(i=>{let o,s=this.extraRefs[i];s?o=[s]:o=this.phasedRefUsage.get(t,i);let a=o.map(({ref:u,ref_no_link:p})=>NHc([...u,...p]));return[i,[].concat(...a)]}))}};var m$e=class extends jNe{noDependenciesPhases=[];getNodeRefsInPhase(t,n){let i=Nb(this.allNodes,...n);return fv(i,o=>{if(Zye(o.operation))return[];let{sourceMapping:s}=o.operation.metadata;if(!s?.length)return[];let a=s.map(({dependencies:u})=>u);return[].concat(...a)})}};var ZRt=async(r,t)=>{let{attempts:n,tags:i,waitSeconds:o}=t,s=Ml().child({retryOptions:{maxAttempts:n,waitSeconds:o},tags:["[withRetries]",...i]});kE(n>=2,`Retry attempts value must be at least '2', but was '${n}'`,s);try{let a=await r();return s.debug("Operation succeeded without retrying"),a}catch(a){s.error(`Operation initial attempt failed; retrying. Error: ${a}`);let u,p=n-1;do{p--,await new Promise(c=>setTimeout(c,o*(n-p)*1e3));try{let c=await r();return s.info(`Operation succeeded on retry (attempt ${n-p})`),c}catch(c){s.error(`Operation failed on retry (attempt ${n-p}). Error: ${c}`),u=c}}while(p);throw s.error("Exhausted all retry attempts; exiting"),u}};var BL=yt(Mq()),oh1=BL.String,sh1=BL.Record({locationName:BL.String,database:BL.String,schema:BL.String}),U92=BL.Dictionary(sh1,oh1);var z92=BL.Record({seconds:BL.Number,nanoseconds:BL.Number});var ah1="Making metadata updates",LHc="Deleting metadata for source input";function y$e(r,t){let n=[];for(let i of r){let o=i.compiledSQL?tJe(i.compiledSQL):[];if(o.length===0)t&&n.push({name:t,sql:"",type:"sql",continueOnFailure:!1,parsedStage:null});else for(let s of o)n.push({name:s.name,sql:s.code,type:s.type,continueOnFailure:s.continueOnFailure,parsedStage:s})}return n}function JEr(r,t){return r==="deletedTable"&&t?LHc:ah1}var rH=class extends nt{constructor(n,i){super(i,`Failed node ${n}: ${i}`);this.nodeID=n}nodeID};var lOt=yt(Mq()),oA1=yt(v$e()),F72=(0,lOt.Record)({version:lOt.String,hash:lOt.String}),sA1=()=>{let r="7.40.0-aa-dev.42.h7d6bba96702c.dirty",t="7d6bba96702c14b60f0ad37e604318fee408831a";return r&&t?{version:r,hash:t}:null},Dv=sA1();var wbe=class extends nt{constructor(n){super(`Run ${n} canceled by user`);this.runID=n}runID},T$e=class extends nt{constructor(n){super('Test failed with "continue on failure" set to false');this.result=n}result};var PWc=(r,t,n)=>{switch(r){case"skipped":return"Skipped";case"error":return"Error";case"complete":switch(n){case"create":return t?"Validated":"Created";case"run":return t?"Validated":"DataLoaded";default:return"None"}default:return"None"}},NWc=r=>typeof r=="object"&&r instanceof T$e,YNe=r=>typeof r=="object"&&(r instanceof BA||r instanceof wbe),pOt=r=>typeof r=="object"&&r instanceof cF&&r.isCancel(),dOt=r=>typeof r=="object"&&r instanceof bX&&r.isCancel(),K9o=r=>YNe(r)||pOt(r)||dOt(r);var DWc=5e5,BWc=500,Mbe=class r{constructor(t,n,i,o,s){this.state=t;this.repository=n;this.logContext=i;this.operationType=o;this.analyticsCollector=s}state;repository;logContext;operationType;stepsInitialized=null;runResults={};flusher=null;wasCanceled=!1;nodeStageIndexTracker=new Map;analyticsCollector;get teamID(){return this.logContext.orgID}get runID(){return this.logContext.runID}get envID(){return this.logContext.workspaceID}GetLogContext=t=>({...this.logContext,nodeID:t});async runIsCanceled(){if(!this.repository)return!1;if(this.wasCanceled)return!0;try{let t=!!(await this.getRepositoryForRun().fetch({pendingWritesTimeoutMs:100})).runDetails.canceled;return t&&(this.wasCanceled=!0),t}catch(t){if(LE(t)){if(t instanceof zNe)return!1;if(t instanceof Du)return!1}throw t}}async throwIfRunCanceled(){if(await this.runIsCanceled())throw new wbe(this.runID)}updateNodeLocalRunResult({stepID:t,isPreview:n,runExecutionSequenceID:i},o){let s=this.runResults[t];s?(s.runState=o,s.queryResultSequence.isRunning=o==="running",s.stepRunState=this.getStepRunState(o,n),i!==void 0&&(s.runExecutionSequenceID=i),(o==="canceled"||o==="skipped"||o==="error")&&s.queryResultSequence.queryResults.forEach(a=>{!a.isRunning&&a.status==="Queued"&&(a.status="Canceled")})):this.Logger.errorContext(this.GetLogContext(t),"EventHandler updateNodeLocalRunResult: missing expected local run result for node",t)}getBulkSkipHandler=()=>async t=>{if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let[o,s]of Object.entries(t))if(this.runResults[o]){let a=i.get(o);this.updateNodeLocalRunResult({stepID:o,isPreview:!1,runExecutionSequenceID:s},"skipped");let u={...r.truncateRunResult(this.runResults[o]),version:2};await n.save(a,u)}await n.commit()};getCancelNodeHandler=()=>async t=>{try{if(!this.repository)return;if(this.runResults[t]){this.updateNodeLocalRunResult({stepID:t,isPreview:!1},"canceled");let i=this.getRepositoryForRun().runResults.get(t),o={...r.truncateRunResult(this.runResults[t]),version:2};await i.save(o)}else this.Logger.errorContext(this.GetLogContext(t),"EventHandler getCancelNodeHandler: missing expected local run result for node",t)}catch(n){this.Logger.errorContext(this.logContext,`Error canceling node ${t}`,n)}};async repositoryUpdateRunStatus({expectedStatus:t,newStatus:n}){if(!this.repository)return;let i=this.getRepositoryForRun();try{let o=await i.fetch();hh("RUNNER_BACKEND",t===o.runStatus,this.logContext,`EventHandler.repositoryUpdateRunStatus found unexpected run status - expected: ${t} / actual: ${o.runStatus}`)}catch(o){this.Logger.alertContext(this.logContext,"Error fetching runInfo",o)}await i.merge({runStatus:n})}async repositoryStampExecutorInfo(t){if(this.repository)try{await this.getRepositoryForRun().merge({platform:t,...Dv?{softwareVersion:Dv.version}:{}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryStampExecutorInfo] Error stamping executor info. Cannot update run document version/platform.",n)}}async repositoryUpdateRenderingProgress(t){if(this.repository)try{await this.getRepositoryForRun().merge({renderingProgress:{totalNodes:t.totalNodes,completedNodes:t.completedNodes}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryUpdateRenderingProgress] Error updating rendering progress. Cannot update run document renderingProgress.",n)}}getRepositoryRunsCollection(){if(!this.repository)throw new nt("No repository to get runs collection for!");let t=this.repository.orgs.get(this.logContext.orgID);return this.runLevel==="orgRuns"?t.runs:t.devRuns}getRepositoryForRun(){return this.getRepositoryRunsCollection().get(this.runID)}formatError=(t,n=null,i=null,o=!1)=>{let s=aa(t.error).error,a="";return t.error&&typeof t.error=="object"&&!(t.error instanceof Error)&&"runDetails"in t.error&&typeof t.error.runDetails=="object"&&(a=t.error?.runDetails?.compiledSQL??""),t.templateString&&(a=t.templateString),{success:!1,error:{errorString:s.errorString??"",errorDetail:s.errorDetail??""},rows:[],fields:[],name:"",exportedRefs:[],invalidExportedRefs:[],status:o?"Canceled":"Failure",sql:a??"",startTime:t.startTime,endTime:new Date,isRunning:!1,type:"sql",queryID:n,warehouse:i}};populateRunResults(t,n){let i="[EventHandler.populateRunResults()]",o=t.length+1;for(let s of t){let u=g1(s,this.state.nodes,`${i} state.nodes`).operation.name;this.runResults[s]={name:u,runExecutionSequenceID:o,dataResult:null,runState:n,stepRunState:"None",queryResultSequence:{name:u,queryResults:[],isRunning:!1},runResultVersion:2}}}async bulkSetRunResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)throw new nt(`Run result for node ${o} does not exist for run ${this.runID}`);let a={...s,name:s.queryResultSequence.name,runExecutionSequenceID:s.runExecutionSequenceID,version:2},u=i.get(o);await n.save(u,a)}await n.commit()}async initializeRunResults(t,n="queued"){this.stepsInitialized=[...t],this.populateRunResults(t,n),await this.bulkSetRunResults(t)}setFlusher(t){this.flusher=t,t.startTimer()}async disposeFlusher(){await this.flusher?.stopAndFlush()}async populatePlaceholderStages(t,n){let i=new Set,o=new Set(t.keys());for(let s of n){if(!o.has(s))continue;let a=t.getPhaseItems(s);for(let[u,p]of a.entries()){let c=g1(u,this.runResults,"populateQueuedStages: this.runResults"),l=this.state.nodes[u],d=l?$P(l,void 0):!1,f=y$e(p,this.getNameForStageWithoutSQL(s,d));for(let h of f)c.queryResultSequence.queryResults.push(this.createQueuedStage(h));f.length>0&&!i.has(u)&&(i.add(u),this.nodeStageIndexTracker.set(u,0))}}await this.bulkSetQueuedStageResults(i)}createQueuedStage({name:t,sql:n,type:i}){return{name:t,status:"Queued",success:!0,sql:n,rows:[],fields:[],startTime:new Date,endTime:new Date,isRunning:!1,exportedRefs:[],invalidExportedRefs:[],type:i}}async bulkSetQueuedStageResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)continue;let a=i.get(o);await n.save(a,r.buildRunResultEntitySave(s))}await n.commit()}formatErrorToResult(t,n){let i=null,o=null;return typeof t.error=="object"&&(i=t.error.queryID||null,o=t.error.warehouse||null),{...this.formatError(t,i,o,n),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}ensureHasQueryResult(t){if(hh("DEPLOY",!!t.queryResult,this.GetLogContext(t.stepID),"query result should always be returned for stage execution"),!t.queryResult)throw new Error("Got an empty query result for stage execution")}updateStageResultAtTrackedIndex=(t,n)=>{let o=g1(t,this.runResults,"[EventHandler.setLastQueryResult()]").queryResultSequence.queryResults,s=this.getCurrentStageIndex(t);if(s<0||s>=o.length)throw this.Logger.errorContext(this.GetLogContext(t),"[EventHandler.setLastQueryResult] stage index out of bounds",{targetIndex:s,queryResultsLength:o.length,resultName:n.name}),new nt(`Stage index ${s} out of bounds (length: ${o.length}) for node ${t}`);o[s]=n};async dispatchQueryFailure(t,n){let i=this.formatErrorToResult(t,n);return this.Logger.errorContext(this.GetLogContext(t.stepID),"failed to execute run sql",n?"- canceled":"- errored",t.error,"stack: ",t.error.stack||"<none found>"),this.updateStageResultAtTrackedIndex(t.stepID,i),{error:i.error}}getSingleStepData(t,n){let i=this.state.nodes[n];if(i)return i;let o=`(${this.runTypeName}) EventHandler: Could not get step data for step: ${n}`;throw this.Logger.errorContext(this.GetLogContext(n),o,n),new nt(o)}getUnrunSteps(){let t={},n=this.state.nodes,i=this.runResults;if(n&&this.stepsInitialized)for(let o of this.stepsInitialized){let s=i[o];if(s){let{runState:a}=s;(a==="waiting"||a==="queued")&&(n[o]?t[o]=0:this.Logger.alertContext(this.logContext,"Node ID from initialization not found in steps data",o))}else this.Logger.alertContext(this.logContext,"Node ID from initialization not found in run results",o)}return t}getStepContext=(t,n,i,o)=>{let s=this.getSingleStepData(t,n),{locationName:a}=s.operation,{database:u}=this.state.mappings[a]?.mappingDefinitions[this.state.currentWorkspace]??{},p=$P(s,void 0),c=s.operation.name;return{startTime:new Date,stepID:n,stepName:c,runExecutionSequenceID:i,phase:t,isPreview:o,isSource:p,database:u??""}};convertIQueryToCompletedQueryResult(t){return{...t,startTime:n4o(t.startTime),endTime:n4o(t.endTime)}}getCurrentStageIndex(t){let n=this.nodeStageIndexTracker.get(t);if(n===void 0)throw new nt(`[EventHandler.getCurrentStageIndex] Node ${t} not in stage tracker. Was populateQueuedStages called for this node?`);return n}advanceToNextStage(t){let n=this.getCurrentStageIndex(t);this.nodeStageIndexTracker.set(t,n+1)}getQueryResultForUpdateSuccess(t){return{...this.convertIQueryToCompletedQueryResult(t.queryResult),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}getStepRunState(t,n){return PWc(t,n,this.operationType)}async updateRunResult(t){if(!this.repository)return;let n=this.runResults[t];if(!n)throw new nt(`[EventHandler.updateRunResult()] run result for node ${t} does not exist for run ${this.runID}`);if(this.flusher)this.flusher.markDirty(t);else{let i=r.buildRunResultEntitySave(n);this.Logger.debugContext(this.GetLogContext(t),"updating run result",i),await this.getRepositoryForRun().runResults.get(t).save(i)}}isFinalRunForStep(t){return!0}async beforePhaseExecution(t,n){}async afterPhaseExecution(t){}async beforeStepExecution(t){this.runResults[t.stepID]&&(this.runResults[t.stepID].runExecutionSequenceID=t.runExecutionSequenceID),this.updateNodeLocalRunResult(t,"running"),await this.updateRunResult(t.stepID)}async afterFinalRunSuccessForNode(t){return Promise.resolve()}async afterStepExecutionSuccess(t){this.isFinalRunForStep(t)?(this.updateNodeLocalRunResult(t,"complete"),await this.afterFinalRunSuccessForNode(t)):this.updateNodeLocalRunResult(t,"waiting"),await this.updateRunResult(t.stepID)}async afterStepExecutionFailure(t){let n=await this.isCoalesceInitiatedCancel(t.error);this.markUnexecutedStagesAsCanceled(t.stepID),this.updateNodeLocalRunResult(t,n?"canceled":"error");try{this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID)}catch(i){this.Logger.emergContext(this.GetLogContext(t.stepID),`Error in firebaseUpdateStepResult for stepCounter:${t.stepID}:`,i)}}markUnexecutedStagesAsCanceled(t){let n=this.runResults[t];if(n)for(let i of n.queryResultSequence.queryResults)"status"in i&&i.status==="Queued"&&(i.status="Canceled")}sanityCheckContext(t){if(!t.stageType)throw this.Logger.emergContext(this.logContext,`No stage type on this ${this.runTypeName}!`,t),new Error(`Internal critical error: no stage type on this ${this.runTypeName}!`)}async beforeStageExecution(t){this.sanityCheckContext(t);let n=this.runResults[t.stepID];if(n){let i=n.queryResultSequence.queryResults,o=this.getCurrentStageIndex(t.stepID),s=i[o];if(!s||!("status"in s)||s.status!=="Queued"){let a=s&&"status"in s?s.status:"no-status";throw new nt(`[EventHandler.beforeStageExecution] Expected queued placeholder at index ${o} for node ${t.stepID}, but found: ${s?`status=${a}`:"undefined"}`)}s.status="Running",s.startTime=new Date,s.endTime=s.startTime,await this.updateRunResult(t.stepID)}}async updateRunWithHeartbeat(t){await this.getRepositoryForRun().updateHeartbeat(t)}async afterStageExecutionSuccess(t){let n="[EventHandler.afterStageExecutionSuccess()]";if(this.sanityCheckContext(t),!t.queryResult){let i="Got an empty query result for stage execution - query result should always be returned!";throw this.Logger.alertContext(this.GetLogContext(t.stepID),n,i),new nt(i)}if(t.stageExecutionStartTime&&t.stageExecutionEndTime){let i=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,i,!0,t.stageExecutionStartTime)}if(DIt(t.queryResult)&&!t.queryResult.success){await this.updateRunWithHeartbeat({hasTestFailures:!0});let i=this.runResults[t.stepID];i&&(i.hasTestFailures=!0)}this.updateStageResultAtTrackedIndex(t.stepID,this.getQueryResultForUpdateSuccess(t)),await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID)}async afterStageExecutionFailure(t){if(this.sanityCheckContext(t),t.stageExecutionStartTime&&t.stageExecutionEndTime){let o=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,o,!1,t.stageExecutionStartTime)}let n=await this.isCoalesceInitiatedCancel(t.error),i=await this.dispatchQueryFailure(t,n);throw this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID),n?t.error:i}async isCoalesceInitiatedCancel(t){return YNe(t)?!0:pOt(t)?this.runIsCanceled():dOt(t)?this.runIsCanceled():!1}static truncateQueryResult(t,n=DWc,i=BWc){let o=t.sql,s=t.rows,a,u;if(o){let p=new TextEncoder,c=new TextDecoder("utf8"),l=p.encode(o);if(l.length>n){let d=c.decode(l.slice(0,n));d.slice(-1)==="\uFFFD"&&(d=d.slice(0,-1)),a=`${d}...data truncated`}}return s?.length>i&&(u=s.slice(0,i),u.push({values:[`${s.length-i} rows truncated`]})),a||u?{...t,sql:a??o,rows:u??s}:t}static buildRunResultEntitySave(t){return{...r.truncateRunResult(t),name:t.queryResultSequence.name,runExecutionSequenceID:t.runExecutionSequenceID,version:2}}static truncateRunResult(t){let n=(t.dataResult?.sql?1:0)+(t.queryResultSequence?.renderQueryResults?.sql?1:0)+(t.queryResultSequence?.queryResults?.length??0),i=(t.dataResult?.rows?.length?1:0)+(t.queryResultSequence?.renderQueryResults?.rows?.length?1:0)+(t.queryResultSequence?.queryResults?.reduce((p,c)=>p+c?.rows?.length?1:0,0)??0);if(n===0&&i===0)return t;let o=Math.trunc(DWc/n)-100,s=BWc/(i??1),a={...t};t.dataResult?.sql&&(a.dataResult=r.truncateQueryResult(t.dataResult,o,s)??null);let u=t.queryResultSequence;return u&&(a.queryResultSequence={...u,queryResults:u.queryResults?.map(p=>r.truncateQueryResult(p,o,s))},u.renderQueryResults&&(a.queryResultSequence.renderQueryResults=r.truncateQueryResult(u.renderQueryResults,o,s))),a}};var fOt=class extends Mbe{constructor(n,i,o,s,a){super(n,i,o,"create",a);this.phasedNodeData=s}phasedNodeData;getNameForStageWithoutSQL=(n,i)=>JEr(n,i);getNodeDataForUpdate=n=>{let i=this.getSingleStepData(n.phase,n.stepID),o=i.operation.locationName,s=Zq(this.state.mappings,this.envID),a=this.GetLogContext(n.stepID),u;try{let p=s?.[o]?.database??i.operation.database,c=s?.[o]?.schema??i.operation.schema;return u={...i.operation,metadata:{...i.operation.metadata,columns:i.operation.metadata.columns.map(l=>({...l}))},database:p,schema:c,version:1,id:n.stepID,deployEnabled:!0},this.Logger.infoContext(a,"newStepData:",u,"stepCounter:",n.stepID),cAc("(Logging Only) Compare locations from context and workspace",a,()=>{let l=Zq(this.state.mappings||{},this.state.currentWorkspace);hh("DEPLOY",$1e(l[o],s[o]),a,`Location data for location ${o} for node ${i.operation.name} with id ${n.stepID} differs between data from context and data from workspace.`,"locationsFromWorkspace:",l,"locationsFromContext:",s)}),u}catch(p){let c=u?u.name:i.operation.name,l=`Error attempting to update the database/schema on deployed nodeID ${n.stepID}: ${c}`;throw this.Logger.emergContext(a,l,"locations:",s,"error:",p),new rH(n.stepID,l)}};async updateEnvironmentNodeMetadata(n){if(!this.repository)return;let i=this.repository.org(this.teamID).workspace(+this.envID).nodes.get(n.stepID);if(n.phase==="deletedTable")n.stepID in this.phasedNodeData.addedTable||await i.delete();else{let o=this.getNodeDataForUpdate(n);await i.save(o)}}isFinalRunForStep(n){let i=[];return n.phase==="deletedTable"&&(i.push(this.phasedNodeData.alteredTable),i.push(this.phasedNodeData.addedTable)),n.phase==="alteredTable"&&i.push(this.phasedNodeData.addedTable),!i.some(o=>n.stepID in o)}async afterFinalRunSuccessForNode(n){try{await this.updateEnvironmentNodeMetadata(n)}catch(i){let o=this.GetLogContext(n.stepID);this.Logger.errorContext(o,"Error updating node metadata -- nodeID:",n.stepID,"error:",i);let s=sWe(i),a="unknown location";try{a=this.getSingleStepData(n.phase,n.stepID).operation.locationName}catch(u){this.Logger.errorContext(o,`Error getting location name for node ${n.stepName} (${n.stepID}):`,u)}throw new rH(n.stepID,`Failed to update node metadata for ${n.stepName} (${a}): ${s}`)}}};var LWc=(r,t)=>{let n=new Set(t);return n.delete(r),Array.from(n)},u2r=async(r,t,n)=>{if(!t)throw new nt(`Cannot get deploy run info since workspace ${r} has no currently running jobs`);if(t.length)return(await n.selectInBatches("id","in",t,[["runType","==","deploy"],["runStatus","==","running"]]))[0]};var c2r="No SQL to execute";var hOt=class extends Mbe{constructor(t,n,i,o){super(t,n,i,"run",o)}async initializeRunResults(t){await super.initializeRunResults(t,"waiting")}getNameForStageWithoutSQL=()=>c2r};var l2r=class{constructor(t,n,i,o,s,a,u){this.repository=t;this.getRunRepository=n;this.buildEntitySave=i;this.runResults=o;this.logger=s;this.logContext=a;this.flushIntervalMs=u?.flushIntervalMs??3e3,this.flushThreshold=u?.flushThreshold??50}repository;getRunRepository;buildEntitySave;runResults;logger;logContext;dirtyNodes=new Set;timer=null;activeFlush=null;flushedDuringBatch=new Set;flushIntervalMs;flushThreshold;totalFlushes=0;totalNodeWrites=0;totalImmediateWrites=0;timerFlushes=0;thresholdFlushes=0;slowCommits=0;tag="[RunResultFlusher]";markDirty(t){this.dirtyNodes.add(t),this.dirtyNodes.size>=this.flushThreshold&&this.flush("threshold").catch(n=>{this.logger.errorContext(this.logContext,`${this.tag} threshold-triggered flush error`,n)})}async flush(t="dispose"){if(this.activeFlush||this.dirtyNodes.size===0){this.logger.debugContext(this.logContext,`${this.tag} flush skipped (activeFlush=${!!this.activeFlush}, dirtySetEmpty=${this.dirtyNodes.size===0}, trigger=${t})`);return}let n=new Set(this.dirtyNodes);this.dirtyNodes.clear(),this.activeFlush=this.doFlush(n,t);try{await this.activeFlush}finally{this.activeFlush=null}}async doFlush(t,n){try{let i=this.repository.batch();for(let a of t){let u=this.runResults[a];if(!u){this.logger.warnContext(this.logContext,`${this.tag} node ${a} no longer has a run result, skipping write`);continue}let p=this.buildEntitySave(u),c=this.getRunRepository().runResults.get(a);await i.save(c,p)}let o=Date.now();await i.commit();let s=Date.now()-o;if(this.flushedDuringBatch.size>0){let a=this.getRunRepository().runResults;for(let u of this.flushedDuringBatch)if(t.has(u)){let p=this.runResults[u];p&&await a.get(u).save(this.buildEntitySave(p))}this.flushedDuringBatch.clear()}this.totalFlushes++,this.totalNodeWrites+=t.size,n==="timer"&&this.timerFlushes++,n==="threshold"&&this.thresholdFlushes++,s>=2e3&&(this.slowCommits++,this.logger.warnContext(this.logContext,`${this.tag} slow commit: ${s}ms for ${t.size} nodes (possible write stream pressure)`)),this.logger.debugContext(this.logContext,`${this.tag} flushed ${t.size} run results in ${s}ms (${n}, threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}catch(i){for(let o of t)this.dirtyNodes.add(o);throw this.logger.errorContext(this.logContext,`${this.tag} flush failed, ${t.size} nodes re-queued`,i),i}}async flushOne(t){this.dirtyNodes.delete(t);let n=this.runResults[t];if(!n){this.logger.warnContext(this.logContext,`${this.tag} node ${t} no longer has a run result, skipping write (flushOne)`);return}this.activeFlush&&this.flushedDuringBatch.add(t);let i=this.buildEntitySave(n);await this.getRunRepository().runResults.get(t).save(i),this.totalImmediateWrites++}startTimer(){this.timer||(this.timer=setInterval(()=>{this.flush("timer").catch(t=>{this.logger.errorContext(this.logContext,`${this.tag} timer-triggered flush error`,t)})},this.flushIntervalMs))}async stopAndFlush(){this.timer&&(clearInterval(this.timer),this.timer=null);try{if(this.activeFlush)try{await this.activeFlush}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error waiting for in-flight flush (stopAndFlush)`,t)}this.logger.infoContext(this.logContext,`${this.tag} draining remaining dirty nodes (stopAndFlush)`),await this.flush("dispose")}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error stopping and flushing (stopAndFlush)`,t)}finally{this.logger.infoContext(this.logContext,`${this.tag} done \u2014 ${this.totalFlushes} flushes (${this.thresholdFlushes} threshold, ${this.timerFlushes} timer, ${this.slowCommits} slow), ${this.totalNodeWrites} batched writes, ${this.totalImmediateWrites} immediate writes (threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}}};var p2r=class extends fOt{constructor(t,n,i,o,s){super(t,n,i,o,s)}get Logger(){return Je("DEPLOY")}get runTypeName(){return"Deploy"}get runLevel(){return"orgRuns"}},d2r=class extends hOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Refresh"}get runLevel(){return"orgRuns"}afterStepExecutionSuccess=async t=>{await super.afterStepExecutionSuccess(t),this.repository&&super.isFinalRunForStep(t)&&!t.isSource&&await this.repository.org(this.logContext.orgID).workspace(this.logContext.workspaceID).nodeLastRefreshed(t.stepID).save({lastRefreshed:new Date().toISOString()})};getQueryResultForUpdateSuccess=t=>({...super.getQueryResultForUpdateSuccess(t),type:t.stageType});async dispatchQueryFailure(t,n){if(NWc(t.error)){let i=t.error,o=this.getCurrentStageIndex(t.stepID);t.stepID in this.runResults&&(this.runResults[t.stepID].queryResultSequence.queryResults[o]=this.convertIQueryToCompletedQueryResult(i.result));let s=this.runResults[t.stepID];return s&&(s.hasTestFailures=!0),await this.updateRunWithHeartbeat({hasTestFailures:!0}),{error:{errorString:t.error.message,errorDetail:t.error.message}}}else return super.dispatchQueryFailure(t,n)}},f2r=class extends fOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}},h2r=class extends hOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}};var JNe=["deletedTable","alteredTable","addedTable"],$Ne=["refresh"];var g2r=`{%- macro get_value_by_column_attribute(column_attribute, value="name") -%}
|
|
9605
9605
|
{%- set filtered_columns_by_attribute = columns | selectattr(column_attribute) | list -%}
|
|
9606
9606
|
{%- if filtered_columns_by_attribute | length > 0 -%}
|
|
9607
9607
|
{{- (filtered_columns_by_attribute | first)[value] -}}
|
|
@@ -10044,11 +10044,11 @@ ${yOt("End rendering context","")}`;super(n,o);this.context=i}context};var y2r=r
|
|
|
10044
10044
|
`+"Encountered the following error when rendering a column value containing template syntax:";return S2r(t,i,d,n,f,u,{runTimeParameters:a,detailedError:l?A:void 0},c)},S2r=async(r,t,n,i,o,s,a,u)=>{if(!r.render)throw oKc.debug("RenderTemplate: bad renderer"),new nt("bad renderer");let{formatSQL:p,renderDepth:c,runTimeParameters:l}=a,d=m2r(_G(s)),f={id:mu(),templateString:t,dependencies:o,templateVars:{nodeMetadata:i,runTimeParameters:l},globalMacros:d+n,...typeof c=="number"&&{renderDepth:c},...typeof s=="string"&&{renderPlatformKind:s}},{runDetails:h}=await Ah("RenderTemplate",u,"RUNNER_BACKEND",async()=>{let A=await r.render(f);if(aWe(A)){oKc.errorContext(u,"RenderTemplate: template rendering error in render result; node metadata:",i,"template string:",t);let{message:E}=yg(A.error),v=a.detailedError?.length?a.detailedError+" ":"";throw new Pbe(v+E,{templateString:t,macrosString:n,nodeID:u.nodeID,parameters:l})}else return p&&(A.runDetails.compiledSQL=C2r(A.runDetails.compiledSQL,u)),A});return h};var n7o=class{constructor(t){this.name=t}name;inner=new Map;get=t=>{let n=this.inner.get(t);if(!n)throw new _It("node",t,this.inner.keys(),this.name);return n};set=(t,n)=>{this.inner.set(t,n)};keys=()=>this.inner.keys();values=()=>this.inner.values();entries=()=>this.inner.entries();toRecord=()=>Object.fromEntries(this.inner)},Nbe=class r{constructor(t,n){this.name=t;for(let i of n)this.phases.has(i)||this.phases.set(i,new n7o(this.name))}name;phases=new Map;getPhaseItems=t=>{let n=this.phases.get(t);if(!n)throw new i7o(t,Array.from(this.phases.keys()),this.name);return n};get=(t,n)=>this.getPhaseItems(t).get(n);set=(t,n,i)=>{this.getPhaseItems(t).set(n,i)};map=(t,n)=>{let i=new r(t,this.keys());for(let[o,s]of this.entries())for(let[a,u]of s.entries())i.set(o,a,n(u,a,o));return i};keys=()=>this.phases.keys();entries=()=>this.phases.entries();getAllNodeIDs=()=>{let t=new Set;for(let n of this.phases.values())for(let i of n.keys())t.add(i);return t};toRecord(){return Object.fromEntries([...this.phases.entries()].map(([t,n])=>[t,n.toRecord()]))}static fromRecord(t,n){let i=new r(t,Object.keys(n));for(let[o,s]of Object.entries(n))for(let[a,u]of Object.entries(s))i.set(o,a,u);return i}},i7o=class extends nt{constructor(n,i,o){super(`Phase name "${n}" not found`,`expected one of ${i.join(" | ")} in ${o}`);this.phaseName=n;this.options=i;this.source=o}phaseName;options;source};var QM=class extends nt{failedNodeIDs;skippedNodeIDs;status;nodeErrors;constructor(t,n,i,o="run",s=new Map){let a=t.length?`${t.length} ${t.length===1?"node":"nodes"} failed to ${o}`:void 0,u=n.length?`${n.length} ${n.length===1?"node was":"nodes were"} skipped`:void 0,p=a&&u?`${a}; ${u}`:a||u||`Failed to ${o}`,c=s.size?[...s.entries()].map(([l,d])=>`${l}: ${d.message}`).join(`
|
|
10045
10045
|
`):`Failed: [${t.join(", ")}]
|
|
10046
10046
|
Skipped: [${n.join(", ")}]`;super(p,c),this.failedNodeIDs=new Set(t),this.skippedNodeIDs=new Set(n),this.status=i,this.nodeErrors=s}};var O$e=class{status=new Map;constructor(t){for(let n of t)this.status.set(n,"pending")}has=t=>this.status.has(t);get=t=>this.status.get(t);set=(t,n)=>this.status.set(t,n);asMap=()=>this.status;getNodesMatchingStatus=t=>{let n=[];for(let[i,o]of this.status.entries())o===t&&n.push(i);return n};get failures(){return this.getNodesMatchingStatus("failed")}get skips(){return this.getNodesMatchingStatus("skipped")}get pending(){return this.getNodesMatchingStatus("pending")}};var Dbe=class extends QM{constructor(n,i,o,s){let a=new Map;for(let[u,{renderFailure:p}]of s.entries())a.set(u,p);super(n,i,o,"render",a);this.errors=s}errors;makeRenderFailures(){let n={};for(let[i,{detailedNodeName:o,renderFailure:s}]of this.errors.entries())n[i]={id:i,detailedNodeName:o,message:s.message,context:s.context};return n}};var v2r=class extends Nbe{toEdits(){return this.map("phased node edits",t=>t.map(({runDetails:{compiledSQL:n},templateParams:{description:i,templateString:o}})=>({compiledSQL:n,...i!==void 0&&{description:i},...o!==void 0&&{templateString:o}})))}};var T2r=class{constructor(t,n,i){this.allNodeIDs=i;this.statusMap=new O$e(i),this.renderResults=new v2r(t,n)}allNodeIDs;errors=new Map;nodesInPhases=new Map;nodesInPhasesHandled=new Map;rendersInPhases=new Map;rendersInPhasesHandled=new Map;nodesCompleted=0;rendersCompleted=0;totalNodes=0;totalRenders=0;statusMap;renderResults;setPhase(t,n,i){this.nodesInPhases.set(t,n),this.totalNodes+=n,this.nodesInPhasesHandled.set(t,0),this.rendersInPhases.set(t,i),this.totalRenders+=i,this.rendersInPhasesHandled.set(t,0)}markNodeHandled=(t,n)=>(this.nodesInPhasesHandled.set(t,(this.nodesInPhasesHandled.get(t)||0)+1),this.rendersInPhasesHandled.set(t,(this.rendersInPhasesHandled.get(t)||0)+n),this.nodesCompleted++,this.rendersCompleted+=n,{nodesInPhases:this.nodesInPhases,nodesInPhasesHandled:new Map(this.nodesInPhasesHandled),rendersInPhases:this.rendersInPhases,rendersInPhasesHandled:new Map(this.rendersInPhasesHandled),nodesCompleted:this.nodesCompleted,rendersCompleted:this.rendersCompleted});markStatusFromResult=(t,n,i,o)=>{if(this.markNodeHandled(t,i.length),LE(o)){this.statusMap.set(n,"failed");let{nodeMetadata:{destinationName:s,operationName:a}}=i[0];this.errors.set(n,{detailedNodeName:`${a} (${s})`,renderFailure:o})}else this.statusMap.get(n)!=="failed"&&this.statusMap.set(n,"succeeded"),this.renderResults.set(t,n,o)}};var w$e=class{constructor(t,n,i,o,s,a,u,p,c,l=null){this.renderer=t;this.platformKind=n;this.logContext=i;this.nodesInRun=o;this.runtimeParameters=s;this.allMacros=a;this.installedPackages=u;this.refLookup=p;this.memoryMonitor=c;this.multisourceIndexLookup=l}renderer;platformKind;logContext;nodesInRun;runtimeParameters;allMacros;installedPackages;refLookup;memoryMonitor;multisourceIndexLookup;get Logger(){return Je("RUNNER")}getAllNodeIDs(){return this.nodesInRun}async renderOneNode(t,n){return uAc(n,async i=>{let o=new Date,{macrosString:s,nodeMetadata:a,packages:u,templateString:p,...c}=i,l=await S2r(this.renderer,p,s,a,u,this.platformKind,{...c,detailedError:""},{...this.logContext,nodeID:t});return{renderStartTime:o,renderEndTime:new Date,runDetails:l,templateParams:i}})}createAllRenderPlans(t){let n=`(${this.getName()}) RunRenderer.createAllRenderPlans()`,i=`[${n}]`;return this.memoryMonitor.measureOperationSync(this.logContext,`${i} Before bulk metadata hydration for render plans for ${this.nodesInRun.size} nodes`,`${i} Bulk metadata hydration completed for render plans for ${this.nodesInRun.size} nodes`,n,()=>{let o=0,s=new Nbe(this.getName(),this.phases());for(let a of this.phases())for(let[u,p]of this.allNodeTemplateParamsForPhase(a,t))s.set(a,u,p),o++,o%500===0&&o>0&&this.memoryMonitor.logMemorySnapshot(this.logContext,i+`[phase: ${a}] Processed ${o} node render plans`,n);return s})}getRenderStatus=t=>{let n=t.getAllNodeIDs(),i=new T2r(`${this.getName()} results`,this.phases(),[...n]);for(let[o,s]of t.entries()){let a=0,u=0;for(let p of s.values())u++,a+=p.length;i.setPhase(o,u,a)}return i};calculateProgressUpdateFrequency(t){return Math.max(1,Math.ceil(t/100))}async renderAllNodes(t,n){let i=`[RunRenderer.renderAllNodes() - ${this.getName()}]`;this.Logger.infoContext(this.logContext,i,"Creating the render plan");let o=this.createAllRenderPlans(t);this.Logger.debugContext(this.logContext,i,"Gathering initial metrics");let s=this.getRenderStatus(o),a=Array.from(s.rendersInPhases.entries()).map(([f,h])=>`${f}: ${h}`).join(", ");this.Logger.infoContext(this.logContext,i,"Starting rendering process; performing",s.totalRenders,"renders across phases -",a);let u=performance.now(),p=this.calculateProgressUpdateFrequency(s.totalNodes);n&&await n({totalNodes:s.totalNodes,completedNodes:0});let c=[],l=`(${this.getName()}) RunRenderer.renderAllNodes()`;await this.memoryMonitor.measureOperationAsync(this.logContext,`${i} Before rendering process initialization`,`${i} After render all nodes completed`,l,async()=>{for(let[h,A]of o.entries()){this.memoryMonitor.logMemorySnapshot(this.logContext,`${i} Processing ${h} phase`,l);let E=0;for(let[v,T]of A.entries())c.push(async()=>{E%500===0&&E>0&&this.memoryMonitor.logMemorySnapshot(this.logContext,`${i} [${h} phase] Processed ${E} nodes`,l);let w;try{w=await this.renderOneNode(v,T)}catch(N){if(LE(N)&&N instanceof Pbe)w=N;else{let k=yg(N);w=new Pbe(k.message,{templateString:T[0].templateString,macrosString:T[0].macrosString,nodeID:v,parameters:T[0].runTimeParameters})}}s.markStatusFromResult(h,v,T,w),n&&s.nodesCompleted%p===0&&await n({totalNodes:s.totalNodes,completedNodes:s.nodesCompleted})}),E++}await dce(c,this.renderer.size),this.memoryMonitor.logMemorySnapshot(this.logContext,i+`After completing ${c.length} renders`,l),this.memoryMonitor.cleanup();let f=Array.from(s.rendersInPhasesHandled.entries()).map(([h,A])=>`${h}: ${A}`).join(", ");this.Logger.infoContext(this.logContext,i,"Completed rendering process in",i4o(u),"seconds; performed",s.rendersCompleted,"renders across phases -",f)}),n&&s.nodesCompleted%p!==0&&await n({totalNodes:s.totalNodes,completedNodes:s.nodesCompleted});let d=s.statusMap.failures;if(d.length)throw new Dbe(d,s.statusMap.skips,s.statusMap.asMap(),s.errors);return s.renderResults}};var ROt=class extends w$e{constructor(n,i,o,s,a,u,p,c,l,d){super(n,i,o,s,a,u,p,c,d);this.dividedStepDataWithWorkspaceEdits=l;this.allMacrosString=Sle(i,this.allMacros)}dividedStepDataWithWorkspaceEdits;allMacrosString;phases(){return JNe}allNodeTemplateParamsForPhase(n,i){return Object.entries(this.dividedStepDataWithWorkspaceEdits[n]).map(([o,s])=>{let{nodeMetadata:a,workspaceEdits:u,operation:{sqlType:p}}=s,c=aAc(u,({dataForNodeMetadata:l,description:d,sql:f})=>{let{macrosString:h,packages:A}=c4(this.platformKind,this.allMacrosString,f,this.installedPackages,i[p]||null,this.logContext);return{description:d,formatSQL:!1,macrosString:h,nodeMetadata:{...a,...l,parameters:a.parameters??{}},packages:A,runTimeParameters:this.runtimeParameters,templateString:f}});return[o,c]})}};var OOt=class extends w$e{constructor(n,i,o,s,a,u,p,c,l,d,f,h=null){super(n,i,o,s,a,u,p,d,f,h);this.allNodes=c;this.mappings=l}allNodes;mappings;phases(){return $Ne}allNodeTemplateParamsForPhase(n,i){let o="[SinglePhaseRunRenderer.allNodeTemplateParamsForPhase()]";return[...this.nodesInRun].map(s=>{let a={...this.logContext,nodeID:s},{operation:u}=g1(s,this.allNodes,`${o} allNodes`),{locationName:p,name:c,sqlType:l}=u,d=jR(l,i,`${o} stepTypesParsed`),f=NIt(i,l,"run"),h=$$(d,"nodeMetadataSpec")?.config??null;if(h){let L=ykc(u,h);if(L){let q=`"${c}" config options missing required fields: ${L.join(`
|
|
10047
|
-
`)}`;throw this.Logger.errorContext(a,q),wq(q,"Required attributes missing. Please check your config.")}}let A=Zq(this.mappings,a.workspaceID),{database:E,schema:v}=A[p]??{};this.Logger.debugContext(a,`node ${c} will use location ${p} during refresh: ${E}.${v}`);let T=Sle(this.platformKind,this.allMacros),w={operationName:c,destinationName:p,mapping:A},k={formatSQL:!1,nodeMetadata:{...Mv(u,s,this.allNodes,i,A,this.runtimeParameters,this.refLookup,a,this.platformKind,{throwOnMissingSource:!0,sourceIndex:this.multisourceIndexLookup?.[s]}),...w},runTimeParameters:this.runtimeParameters,templateString:f,...c4(this.platformKind,T,f,this.installedPackages,d,a)};return[s,[k]]})}};var _2r=class extends ROt{getName(){return"Deploy"}},I2r=class extends OOt{getName(){return"Refresh"}},R2r=class extends ROt{getName(){return"Dev Run (operation type 'create')"}},O2r=class extends OOt{getName(){return"Dev Run (operation type 'run')"}};i3()||(self.YAML=Hgr);var WU2=Je("RUNNER");var Cm1=r=>({user:r.user,accountName:r.accountName,accessUrl:r.accessUrl,database:r.database,destinationSchema:r.destinationSchema,warehouse:r.warehouse,role:r.role,orgID:r.orgID,environmentID:r.environmentID,authenticator:r.authenticator,kind:"snowflake"}),Sm1=r=>r3(r,"token"),vm1=r=>r3(r,"credentials"),Tm1=r=>r3(r,"serviceAccountKey","clientID","secret","refreshToken"),wOt=r=>fL(r,{snowflake:t=>JSON.stringify(Cm1(t)),databricks:t=>JSON.stringify(Sm1(t)),fabric:t=>JSON.stringify(vm1(t)),bigquery:t=>JSON.stringify(Tm1(t))});var w2r=()=>({sql:"",success:!0,rows:[],fields:[],error:null,startTime:new Date,endTime:new Date,name:"dummy",isRunning:!1,exportedRefs:[],invalidExportedRefs:[],queryResultSequence:null,status:"Success",type:"sql",queryID:null,warehouse:null});var sKc=(r,t)=>{let n=r?.columns.map(i=>({Name:i.columnName,DataType:""}));return{runDetails:{compiledSQL:t,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:null,warehouse:null},data:{columns:n,rows:r.rows,status:r.status}}},M2r=(r,t)=>({runDetails:{compiledSQL:t,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:null,warehouse:null},data:{columns:[],rows:r.rows,status:"Success"}}),aKc=(r,t)=>{let n=(r.columns??[]).map(i=>({Name:i.name??"",DataType:i.type??""}));return{runDetails:{compiledSQL:t,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:null,warehouse:null},data:{columns:n,rows:r.rows,status:r.status}}};var _m1={bigquery:{maxQueries:5,windowMs:10050},snowflake:null,databricks:null,fabric:null};function uKc(r){return _m1[r]??null}var o7o=class extends nt{constructor(n,i){let o={...ua(n),queryID:i};super(o.error.errorString,o.error.errorDetail);this.queryID=i;this.converted=o,this.cause=n}queryID;converted;toTRunError(){return this.converted}},M$e=class{constructor(t,n,i,o){this.logContext=t;this.nodeEdits=n;this.jobName=i;this.isPreview=o}logContext;nodeEdits;jobName;isPreview;async handleQuery(t){let{exec:n,template:i}=t,o=new Date;this.Logger.infoContext(this.logContext,"BaseStepExecutor RunSQL: marking startTime",o,"for SQL",i);try{this.Logger.infoContext(this.logContext,"[BaseStepExecutor.handleQuery]: Calling TimedSQLExecution with template",i.substring(0,100)+"...");let s=await s_c(i,n,this.logContext);return this.Logger.infoContext(this.logContext,"[BaseStepExecutor.handleQuery]: TimedSQLExecution completed"),s}catch(s){this.Logger.errorContext(this.logContext,"BaseStepExecutor RunSQL error:",Ome(s)?"TRunError":"other error",s);let a=s,u=null;throw K9o(s)?s:(typeof s=="object"&&s instanceof cF&&(u=s.queryID||null,a=s.coalesceCause),this.Logger.errorContext(this.logContext,"Got failure on template execution",a),new o7o(a,u))}}async executeStage(t,n,i,o){let s=`[BaseStepExecutor.executeStage()] [${n.context.stepID} | ${n.context.stageName}]:`;this.Logger.infoContext(this.logContext,s,"Called at",new Date);let a=null,u=null;await t.throwIfRunCanceled();try{await t.beforeStageExecution(n.context),await this.setQueryTag(t,n.context,i),a=new Date,this.Logger.infoContext(this.logContext,s,"Starting stage execution; marking stageExecutionStartTime at",a);let p=await this.executeStageWithoutEvents(n,i,o),c=p.sql.length>100?p.sql.substring(0,100)+"...":p.sql;this.Logger.infoContext(this.logContext,s,`Query result completed -- total rows: ${p.rows.length} | SQL (truncated): ${c}`),this.Logger.debugContext(this.logContext,s,"Truncated query result:",{...p,sql:p.sql.length>1e3?p.sql.substring(0,1e3)+"...":p.sql,rows:p.rows?`[${p.rows.length} rows]`:void 0}),u=new Date,this.Logger.infoContext({...this.logContext,queryMetrics:{rows:p.rows.length,sql:p.sql.length,id:p.queryID}},s,"Finished stage execution (success); marking stageExecutionEndTime at",u),Bm("RUNNER",!p||p.hasOwnProperty("sql"),"query Result checked in executeStage has sql "),await t.afterStageExecutionSuccess({...n.context,queryResult:p,stageExecutionStartTime:a,stageExecutionEndTime:u})}catch(p){throw a&&!u&&(u=new Date),this.Logger.errorContext(this.logContext,s,"Failure during stage execution; marking stageExecutionEndTime at",u),await t.afterStageExecutionFailure({...n.context,error:p,stageExecutionStartTime:a,stageExecutionEndTime:u}),p}finally{await this.unsetQueryTag(i)}}getJobID(){return null}async setQueryTag(t,n,i){let o=null;try{o=t.getSingleStepData(n.phase,n.stepID).operation.locationName}catch(u){this.Logger.errorContext(this.logContext,"Error getting storage location for step",n.stepID,":",u)}let s={runType:this.runTypeName,runID:this.logContext.runID.toString(),jobID:this.getJobID(),jobName:this.jobName,storageLocation:o,nodeID:n.stepID,nodeName:n.stepName,stageName:n.stageName},a={coalesce:tAc(s)};await i.setQueryTag(JSON.stringify(a,void 0,1))}async unsetQueryTag(t){await t.setQueryTag(null)}async executeStep(t,n,i,o){if(PHc(n.stepID,t.runResults))throw new rH(n.stepID,"Nodes are already running!");try{await t.beforeStepExecution(n);let s=uKc(o.name),a=this.getStepStages(n);if(s&&a.length>=s.maxQueries){let u=[];for(;a.length>0;){let c=a.splice(0,s.maxQueries);u.push(c)}let p=`[BaseStepExecutor.executeStep()] [${n.stepID}]:`;this.Logger.infoContext(this.logContext,p,`Number of stages exceeds platform query limits, executing node ${n.stepID} in ${u.length} groups of ${s.maxQueries}...`);for(let c of u){let l=Date.now();for(let A of c)await this.executeStage(t,A,i,o);let d=Date.now()-l,f=d<s.windowMs,h=c.length===s.maxQueries;if(f&&h){let A=s.windowMs-d;this.Logger.infoContext(this.logContext,p,`${c.length} queries executed in ${d}ms. Waiting a remaining ${A}ms before proceeding...`),await new Promise(E=>setTimeout(E,A))}}}else for(let u of a)await this.executeStage(t,u,i,o);await t.afterStepExecutionSuccess(n),this.stepSuccessLog(t,n)}catch(s){let a={...n,error:s};if(await t.afterStepExecutionFailure(a),this.stepFailedLog(t,a),s instanceof rH||K9o(s))throw s;let u=sWe(s),p="unknown location";try{p=t.getSingleStepData(n.phase,n.stepID).operation.locationName}catch{}throw new rH(n.stepID,`${n.stepName} (${p}): ${u}`)}}stepSuccessLog(t,n){}stepFailedLog(t,n){this.Logger.errorContext(t.GetLogContext(n.stepID),`Step execution failed (${this.runTypeName} stepExecutor, runID ${t.runID}):`,n.error)}};var MOt=class{constructor(t){this.context=t}context},xOt=class extends MOt{},x2r=class{constructor(t,n){this.context=t;this.stage=n}context;stage};var POt=class extends M$e{constructor(t,n,i,o=!1){super(t,n,i,o)}async executeStageWithoutEvents(t,n,i){if(t.stage===null)return{...w2r(),name:"",startTime:t.context.startTime,status:"Success"};{let s={template:i.getTemplateString(t.stage.code,this.isPreview,!1),exec:a=>i.usingConnection(n).getSQLQueryResult({sql:a,options:{database:t.context.database}})};return this.handleQuery(s)}}getStepStages(t){return y$e(this.nodeEdits,JEr(t.phase,t.isSource)).map(i=>{let o={...t,stageName:i.name,database:t.database,stageType:i.type,continueOnFailure:i.continueOnFailure,templateString:i.sql};return new x2r(o,i.parsedStage)})}};var NOt=class extends M$e{constructor(t,n,i,o){super(t,n,i,o)}IsFailedTestResult=t=>!this.isPreview&&DIt(t)&&Mkc(t);async executeStageWithoutEvents(t,n,i){if(t instanceof xOt)return{...w2r(),name:t.context.stageName,startTime:t.context.startTime};let{stageName:o,stageType:s,templateString:a,database:u,continueOnFailure:p}=t.context,l={template:i.getTemplateString(a,this.isPreview,wkc(s)),exec:h=>i.usingConnection(n).getSQLQueryResult({sql:h,options:{database:u}})},f={...await this.handleQuery(l),name:o,type:s};if(this.IsFailedTestResult(f)){let h=p===!1,A=h?E6o.failCOF:E6o.fail;if(f.success=!1,f.error=u3o(A,A),h)throw new T$e(f)}return f}getStepStages(t){return y$e(this.nodeEdits,c2r).map(i=>{let o={...t,stageName:i.name,stageType:i.type,continueOnFailure:i.continueOnFailure,templateString:i.sql,phase:"refresh"};if(!o.stageType)throw new rH(t.stepID,"In getStepStages, no stage type on stage?!");return i.type==="sql"&&!i.sql.trim()?new xOt(o):new MOt(o)})}};var P2r=class extends POt{get runTypeName(){return"Deploy"}get Logger(){return Je("DEPLOY")}},N2r=class extends NOt{constructor(n,i,o,s){super(n,i,o,!1);this.jobID=s}jobID;get runTypeName(){return"Refresh"}getJobID(){return this.jobID}get Logger(){return Je("RUNNER")}},D2r=class extends POt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}},B2r=class extends NOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}};var Bbe=class extends nt{constructor(n,i,o){super(`Cycle found at node ${n} -> ${i}. Potential members: ${[...o].join(", ")}`);this.nodeID=n;this.dependencyID=i;this.potentialMembers=o}nodeID;dependencyID;potentialMembers;withNamesAndLocations(n){let i=o=>{let s,a;try{({operation:{name:s,locationName:a}}=g1(o,n,"[GraphCycleError]"))}catch{s=`<unknown name - ID '${o}'>`,a="<unknown location>"}return`${s} (${a})`};return this.message=`Circular dependency found between ${i(this.nodeID)} and ${i(this.dependencyID)}. Circular dependency includes ${[...this.potentialMembers].map(o=>i(o)).join(", ")}. Review JOIN conditions and use ref_no_link where appropriate.`,this}statusCode(){return 400}},cKc=(r,t,n,i)=>`Expected ${i} node ${r} to be in ${n} state, but state=${t}`;var lKc=r=>{let t=new Map;for(let[n,i]of Object.entries(r)){let o=new Set(i);t.set(n,o)}return t},pKc=r=>{let t=new Map;for(let[n,i]of r.entries())for(let o of i){let s=t.get(o);s?s.add(n):t.set(o,new Set([n]))}return t},L2r=r=>{let t=new Set,n=new Map,i=o=>{n.set(o,!0),t.add(o);for(let s of r[o])if(!n.get(s))i(s);else if(t.has(s))throw new Bbe(o,s,t);t.delete(o)};for(let o in r)n.set(o,!1);for(let o in r)n.get(o)||i(o)},DOt=r=>({failedNodeIDs:new Set,skippedNodeIDs:new Set,status:r});var k2r=class r{constructor(t,n,i){this.nodes=t;this.requirements=n;this.requiredBy=i}nodes;requirements;requiredBy;getDependents=t=>this.requiredBy.get(t)||new Set;getDependencies=t=>this.requirements.get(t)||new Set;static create(t,n){L2r(t);let i=lKc(t),o=pKc(i);return new r(new Set(n),i,o)}};var q2r=class{constructor(t,n,i,o,s,a){this.runID=t;this.repository=n;this.connectionManager=i;this.logger=o;this.logContext=s;this.nodeStatusCancelledHandler=a}runID;repository;connectionManager;logger;logContext;nodeStatusCancelledHandler;cancelWatch=()=>{};canceled_=!1;async start(){this.logger.infoContext(this.logContext,"Start watching for run cancellation for runID",this.runID);let{promise:t,cancelWatch:n}=Im1(this.repository);this.cancelWatch=n;try{await t,this.logger.infoContext(this.logContext,"Run cancellation for runID",this.runID,"detected"),this.canceled_=!0;let i=parseInt(process.env.COALESCE_JOB_TIMEOUT_MS)||900*1e3,o=this.connectionManager.cancel();if(!oQe()&&i3()&&i!==0){let s=!1;this.logger.infoContext(this.logContext,"Waiting",i,"milliseconds for cancellation to complete");let a=setTimeout(()=>{s||this.logger.errorContext(this.logContext,"Graceful cancellation timed out. Exiting in 2 seconds..."),setTimeout(()=>{process.exit(1)},2e3)},i);await o,this.logger.infoContext(this.logContext,"Cancellation completed successfully within the timeout."),Hg().isTest&&clearTimeout(a),s=!0}else await o}catch(i){this.logger.errorContext(this.logContext,"Run cancellation for runID",this.runID,"error",i)}finally{this.logger.infoContext(this.logContext,"Completed processing run cancellation for runID",this.runID)}}stop(){this.logger.infoContext(this.logContext,"Stop watching for run cancellation for runID",this.runID),this.cancelWatch()}get canceled(){return this.canceled_}async handleCanceledNode(t){await this.nodeStatusCancelledHandler(t)}},Im1=r=>{let{promise:t,resolve:n}=TR(),i=r.listen(o=>{(o.type==="added"||o.type==="modified")&&o.value.runDetails?.canceled&&(i(),n())});return{cancelWatch:i,promise:t}};var F2r=class{inner;constructor(){this.inner=new Map}addExecution=(t,n,i)=>{if(this.inner.has(t))return!1;let o=i.catch(n).catch(()=>{}).then(()=>t);return this.inner.set(t,o),!0};allCompleted=async()=>{for(;this.inner.size>0;){let t=await LEr.race([...this.inner.values()]);this.inner.delete(t)}}};var U2r=class{constructor(t,n,i,o,s,a,u){this.stepExecutor=t;this.graph=n;this.logContext=i;this.logger=o;this.skipHandler=s;this.semaphoreCap=a;this.cancellationHandler=u;this.executionSemaphore=new aL(this.semaphoreCap),this.runExecutionSequenceID=0,this.stateMutex=new oce,this.inFlightPromises=new F2r,this.status=new O$e(n.nodes),this.nodeErrors=new Map}stepExecutor;graph;logContext;logger;skipHandler;semaphoreCap;cancellationHandler;status;executionSemaphore;stateMutex;runExecutionSequenceID;inFlightPromises;nodeErrors;dependenciesAreSatisfied=t=>{for(let n of this.graph.getDependencies(t))switch(this.status.get(n)){case"pending":case"scheduled":case"failed":case"skipped":return!1;case void 0:if(!this.dependenciesAreSatisfied(n))return!1}return!0};handleDependentsOnSuccess=(t,n)=>{let i={...this.logContext,nodeID:t},o=[...this.graph.getDependents(t)].sort();this.logger.debugContext(i,"Examining dependent steps",o);for(let s of o)n.has(s)||(n.add(s),this.status.get(s)==="pending"?this.dependenciesAreSatisfied(s)?(this.logger.debugContext(i,"Scheduling dependent step",s),this.scheduleStep(s)):this.logger.debugContext(i,"Dependent step",s,"has unsatisfied dependencies"):this.status.get(s)===void 0?(this.logger.debugContext(i,"Dependent step",s,"is not part of this run, so checking its dependents too"),this.handleDependentsOnSuccess(s,n)):this.logger.debugContext(i,"Dependent step",s,"is not pending"))};handleDependentsOnFailure=async t=>{let n=this.graph.getDependents(t),i={...this.logContext,nodeID:t},o={};for(;n.size>0;){let a=n.values().next().value;n.delete(a);let u=this.status.get(a);if(u==="skipped"||u==="failed"){this.logger.debugContext(i,"Already skipped dependent step",a);continue}else if(u===void 0){this.logger.debugContext(i,"Dependent step",a,"was not scheduled, processing dependents");for(let p of this.graph.getDependents(a)||[])n.add(p)}else{this.status.set(a,"skipped"),this.logger.debugContext(i,"Skipping dependent step",a),o[a]=this.nextRunID();for(let p of this.graph.getDependents(a)||[])n.add(p)}}await this.skipHandler(o)};handlePendingNodesOnCancel=async()=>{let t={};for(let n of this.pending)this.status.set(n,"skipped"),t[n]=this.nextRunID();await this.skipHandler(t)};preSkip=async t=>{await this.stateMutex.runExclusive(async()=>{for(let n of t)this.status.has(n)&&this.stateTransition(n,"pending","skipped"),await this.handleDependentsOnFailure(n)})};stateTransition=(t,n,i)=>{let o=this.status.get(t);hh("RUNNER",o===n,this.logContext,cKc(t,o,n,i)),this.status.set(t,i)};markCompleted=async(t,n)=>{let i={...this.logContext,nodeID:t};switch(n){case"success":this.logger.debugContext(i,"Step succeeded"),this.stateTransition(t,"scheduled","succeeded"),this.handleDependentsOnSuccess(t,new Set);break;case"error":this.logger.debugContext(i,"Step failed"),this.stateTransition(t,"scheduled","failed"),await this.handleDependentsOnFailure(t);break;case"canceled":this.logger.debugContext(i,"Run canceled"),this.stateTransition(t,"scheduled","failed"),await this.cancellationHandler?.handleCanceledNode(t),await this.handlePendingNodesOnCancel();break;default:this.logger.errorContext(i,`Unexpected graphRunStatus ${n}`);break}};finishStepExecution=async(t,n)=>{await this.stateMutex.runExclusive(async()=>{await this.markCompleted(t,n)})};getStepExecutionPromise=async(t,n)=>{await this.executionSemaphore.runExclusive(async()=>{let i="success";try{this.logger.infoContext(this.logContext,`step:${t} starting to run in GraphExecutor`),await this.stepExecutor(t,n),this.logger.infoContext(this.logContext,`step:${t} finished executing in GraphExecutor`)}catch(o){let s=p=>{this.logger.infoContext(this.logContext,`GraphExecutor for step ${t} finished with error due to expected ${p}`,o instanceof Error?o.message:o)},a=p=>{this.logger.errorContext(this.logContext,`GraphExecutor for step ${t} finished with error due to unexpected ${p}`,o instanceof Error?o.message:o,o instanceof Error?o.stack:"[no stack trace]")},u=(p,c)=>{c||this.cancellationHandler&&this.cancellationHandler.canceled?(s(p),i="canceled"):(a(p),i="error")};if(YNe(o)?u("run cancellation",!0):pOt(o)||dOt(o)?u("query cancellation",!1):(a("issue"),i="error"),i==="error"){let p=o instanceof nt?o:new nt(o instanceof Error?o.message:String(o));this.nodeErrors.set(t,p)}}this.logger.infoContext(this.logContext,`step:${t} updating workspace status in GraphExecutor`),await this.finishStepExecution(t,i),this.logger.infoContext(this.logContext,`step:${t} finished running in GraphExecutor, outstanding:${this.currentlyRunning()-1}`)})};nextRunID=()=>this.runExecutionSequenceID++;get hasFailures(){return this.failures.length>0}get failures(){return this.status.failures}get skips(){return this.status.skips}get pending(){return this.status.pending}currentlyRunning=()=>this.semaphoreCap-this.executionSemaphore.getValue();internalErrorHandler=t=>{this.logger.emergContext(this.logContext,"Internal failure in graph executor!",t,t.stack)};scheduleStep=t=>{this.stateTransition(t,"pending","scheduled");let n=this.nextRunID(),i=this.getStepExecutionPromise(t,n);this.inFlightPromises.addExecution(t,this.internalErrorHandler,i)||this.logger.warnContext(this.logContext,`Promise for step ${t} was already in the tracker!`)};beginRun=async()=>{let t=[];if(await this.stateMutex.runExclusive(async()=>{for(let n of this.graph.nodes)this.status.get(n)!=="skipped"&&this.dependenciesAreSatisfied(n)&&(t.push(n),this.scheduleStep(n))}),t.length===0)throw this.logger.errorContext(this.logContext,"Could not prepare graph for running, all nodes had unfulfilled requirements!"),new Error("Could not prepare graph for running, all nodes had unfulfilled requirements!");this.logger.infoContext(this.logContext,`Scheduled ${t.length} initial nodes!`)};waitForCompletion=async()=>{await this.inFlightPromises.allCompleted();let t=this.failures,n=this.skips;if([...t,...n].sort().length>0){let o=new QM(t,n,this.status.asMap(),"execute",this.nodeErrors);throw this.logger.infoContext(this.logContext,o.message),o}else return this.logger.infoContext(this.logContext,"all complete for run (PlayTaskThunk)"),DOt(this.status.asMap())};async runGraph(){if(!this.graph.nodes.size)return this.logger.infoContext(this.logContext,"Got an empty graph, so no requirements to fulfill!"),DOt(this.status.asMap());this.cancellationHandler&&this.cancellationHandler.start();try{return await this.beginRun(),await this.waitForCompletion()}finally{this.cancellationHandler&&this.cancellationHandler.stop()}}};var x$e=class{constructor(t,n,i,o,s){this.logContext=t;this.phasedNodeEdits=n;this.phasedDependencies=i;this.jobName=o;this.isPreview=s;this.phasedNodeExecutors=n.map(`${this.getName()} stepExecutors`,(a,u)=>this.createExecutorForID(a,u))}logContext;phasedNodeEdits;phasedDependencies;jobName;isPreview;phasedNodeExecutors;get Logger(){return Je("RUNNER")}runPhase=async(t,n,i,o,s)=>{let a=`[CoalesceRun.runPhase() | '${this.getName()}' - phase '${t}']`,{measure:u,printSummary:p}=Bf(a,this.logContext),c=Array.from(this.phasedNodeExecutors.getPhaseItems(t).keys());if(this.Logger.appContext(this.logContext,a,`Nodes in phase: ${c.length}`,`
|
|
10047
|
+
`)}`;throw this.Logger.errorContext(a,q),wq(q,"Required attributes missing. Please check your config.")}}let A=Zq(this.mappings,a.workspaceID),{database:E,schema:v}=A[p]??{};this.Logger.debugContext(a,`node ${c} will use location ${p} during refresh: ${E}.${v}`);let T=Sle(this.platformKind,this.allMacros),w={operationName:c,destinationName:p,mapping:A},k={formatSQL:!1,nodeMetadata:{...Mv(u,s,this.allNodes,i,A,this.runtimeParameters,this.refLookup,a,this.platformKind,{throwOnMissingSource:!0,sourceIndex:this.multisourceIndexLookup?.[s]}),...w},runTimeParameters:this.runtimeParameters,templateString:f,...c4(this.platformKind,T,f,this.installedPackages,d,a)};return[s,[k]]})}};var _2r=class extends ROt{getName(){return"Deploy"}},I2r=class extends OOt{getName(){return"Refresh"}},R2r=class extends ROt{getName(){return"Dev Run (operation type 'create')"}},O2r=class extends OOt{getName(){return"Dev Run (operation type 'run')"}};i3()||(self.YAML=Hgr);var WU2=Je("RUNNER");var Cm1=r=>({user:r.user,accountName:r.accountName,accessUrl:r.accessUrl,database:r.database,destinationSchema:r.destinationSchema,warehouse:r.warehouse,role:r.role,orgID:r.orgID,environmentID:r.environmentID,authenticator:r.authenticator,kind:"snowflake"}),Sm1=r=>r3(r,"token"),vm1=r=>r3(r,"credentials"),Tm1=r=>r3(r,"serviceAccountKey","clientID","secret","refreshToken"),wOt=r=>fL(r,{snowflake:t=>JSON.stringify(Cm1(t)),databricks:t=>JSON.stringify(Sm1(t)),fabric:t=>JSON.stringify(vm1(t)),bigquery:t=>JSON.stringify(Tm1(t))});var w2r=()=>({sql:"",success:!0,rows:[],fields:[],error:null,startTime:new Date,endTime:new Date,name:"dummy",isRunning:!1,exportedRefs:[],invalidExportedRefs:[],queryResultSequence:null,status:"Success",type:"sql",queryID:null,warehouse:null});var sKc=(r,t)=>{let n=r?.columns.map(i=>({Name:i.columnName,DataType:""}));return{runDetails:{compiledSQL:t,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:null,warehouse:null},data:{columns:n,rows:r.rows,status:r.status}}},M2r=(r,t)=>({runDetails:{compiledSQL:t,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:null,warehouse:null},data:{columns:[],rows:r.rows,status:"Success"}}),aKc=(r,t)=>{let n=(r.columns??[]).map(i=>({Name:i.name??"",DataType:i.type??""}));return{runDetails:{compiledSQL:t,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:null,warehouse:null},data:{columns:n,rows:r.rows,status:r.status}}};var _m1={bigquery:{maxQueries:5,windowMs:10050},snowflake:null,databricks:null,fabric:null};function uKc(r){return _m1[r]??null}var o7o=class extends nt{constructor(n,i){let o={...aa(n),queryID:i};super(o.error.errorString,o.error.errorDetail);this.queryID=i;this.converted=o,this.cause=n}queryID;converted;toTRunError(){return this.converted}},M$e=class{constructor(t,n,i,o){this.logContext=t;this.nodeEdits=n;this.jobName=i;this.isPreview=o}logContext;nodeEdits;jobName;isPreview;async handleQuery(t){let{exec:n,template:i}=t,o=new Date;this.Logger.infoContext(this.logContext,"BaseStepExecutor RunSQL: marking startTime",o,"for SQL",i);try{this.Logger.infoContext(this.logContext,"[BaseStepExecutor.handleQuery]: Calling TimedSQLExecution with template",i.substring(0,100)+"...");let s=await s_c(i,n,this.logContext);return this.Logger.infoContext(this.logContext,"[BaseStepExecutor.handleQuery]: TimedSQLExecution completed"),s}catch(s){this.Logger.errorContext(this.logContext,"BaseStepExecutor RunSQL error:",Ome(s)?"TRunError":"other error",s);let a=s,u=null;throw K9o(s)?s:(typeof s=="object"&&s instanceof cF&&(u=s.queryID||null,a=s.coalesceCause),this.Logger.errorContext(this.logContext,"Got failure on template execution",a),new o7o(a,u))}}async executeStage(t,n,i,o){let s=`[BaseStepExecutor.executeStage()] [${n.context.stepID} | ${n.context.stageName}]:`;this.Logger.infoContext(this.logContext,s,"Called at",new Date);let a=null,u=null;await t.throwIfRunCanceled();try{await t.beforeStageExecution(n.context),await this.setQueryTag(t,n.context,i),a=new Date,this.Logger.infoContext(this.logContext,s,"Starting stage execution; marking stageExecutionStartTime at",a);let p=await this.executeStageWithoutEvents(n,i,o),c=p.sql.length>100?p.sql.substring(0,100)+"...":p.sql;this.Logger.infoContext(this.logContext,s,`Query result completed -- total rows: ${p.rows.length} | SQL (truncated): ${c}`),this.Logger.debugContext(this.logContext,s,"Truncated query result:",{...p,sql:p.sql.length>1e3?p.sql.substring(0,1e3)+"...":p.sql,rows:p.rows?`[${p.rows.length} rows]`:void 0}),u=new Date,this.Logger.infoContext({...this.logContext,queryMetrics:{rows:p.rows.length,sql:p.sql.length,id:p.queryID}},s,"Finished stage execution (success); marking stageExecutionEndTime at",u),Bm("RUNNER",!p||p.hasOwnProperty("sql"),"query Result checked in executeStage has sql "),await t.afterStageExecutionSuccess({...n.context,queryResult:p,stageExecutionStartTime:a,stageExecutionEndTime:u})}catch(p){throw a&&!u&&(u=new Date),this.Logger.errorContext(this.logContext,s,"Failure during stage execution; marking stageExecutionEndTime at",u),await t.afterStageExecutionFailure({...n.context,error:p,stageExecutionStartTime:a,stageExecutionEndTime:u}),p}finally{await this.unsetQueryTag(i)}}getJobID(){return null}async setQueryTag(t,n,i){let o=null;try{o=t.getSingleStepData(n.phase,n.stepID).operation.locationName}catch(u){this.Logger.errorContext(this.logContext,"Error getting storage location for step",n.stepID,":",u)}let s={runType:this.runTypeName,runID:this.logContext.runID.toString(),jobID:this.getJobID(),jobName:this.jobName,storageLocation:o,nodeID:n.stepID,nodeName:n.stepName,stageName:n.stageName},a={coalesce:tAc(s)};await i.setQueryTag(JSON.stringify(a,void 0,1))}async unsetQueryTag(t){await t.setQueryTag(null)}async executeStep(t,n,i,o){if(PHc(n.stepID,t.runResults))throw new rH(n.stepID,"Nodes are already running!");try{await t.beforeStepExecution(n);let s=uKc(o.name),a=this.getStepStages(n);if(s&&a.length>=s.maxQueries){let u=[];for(;a.length>0;){let c=a.splice(0,s.maxQueries);u.push(c)}let p=`[BaseStepExecutor.executeStep()] [${n.stepID}]:`;this.Logger.infoContext(this.logContext,p,`Number of stages exceeds platform query limits, executing node ${n.stepID} in ${u.length} groups of ${s.maxQueries}...`);for(let c of u){let l=Date.now();for(let A of c)await this.executeStage(t,A,i,o);let d=Date.now()-l,f=d<s.windowMs,h=c.length===s.maxQueries;if(f&&h){let A=s.windowMs-d;this.Logger.infoContext(this.logContext,p,`${c.length} queries executed in ${d}ms. Waiting a remaining ${A}ms before proceeding...`),await new Promise(E=>setTimeout(E,A))}}}else for(let u of a)await this.executeStage(t,u,i,o);await t.afterStepExecutionSuccess(n),this.stepSuccessLog(t,n)}catch(s){let a={...n,error:s};if(await t.afterStepExecutionFailure(a),this.stepFailedLog(t,a),s instanceof rH||K9o(s))throw s;let u=sWe(s),p="unknown location";try{p=t.getSingleStepData(n.phase,n.stepID).operation.locationName}catch{}throw new rH(n.stepID,`${n.stepName} (${p}): ${u}`)}}stepSuccessLog(t,n){}stepFailedLog(t,n){this.Logger.errorContext(t.GetLogContext(n.stepID),`Step execution failed (${this.runTypeName} stepExecutor, runID ${t.runID}):`,n.error)}};var MOt=class{constructor(t){this.context=t}context},xOt=class extends MOt{},x2r=class{constructor(t,n){this.context=t;this.stage=n}context;stage};var POt=class extends M$e{constructor(t,n,i,o=!1){super(t,n,i,o)}async executeStageWithoutEvents(t,n,i){if(t.stage===null)return{...w2r(),name:"",startTime:t.context.startTime,status:"Success"};{let s={template:i.getTemplateString(t.stage.code,this.isPreview,!1),exec:a=>i.usingConnection(n).getSQLQueryResult({sql:a,options:{database:t.context.database}})};return this.handleQuery(s)}}getStepStages(t){return y$e(this.nodeEdits,JEr(t.phase,t.isSource)).map(i=>{let o={...t,stageName:i.name,database:t.database,stageType:i.type,continueOnFailure:i.continueOnFailure,templateString:i.sql};return new x2r(o,i.parsedStage)})}};var NOt=class extends M$e{constructor(t,n,i,o){super(t,n,i,o)}IsFailedTestResult=t=>!this.isPreview&&DIt(t)&&Mkc(t);async executeStageWithoutEvents(t,n,i){if(t instanceof xOt)return{...w2r(),name:t.context.stageName,startTime:t.context.startTime};let{stageName:o,stageType:s,templateString:a,database:u,continueOnFailure:p}=t.context,l={template:i.getTemplateString(a,this.isPreview,wkc(s)),exec:h=>i.usingConnection(n).getSQLQueryResult({sql:h,options:{database:u}})},f={...await this.handleQuery(l),name:o,type:s};if(this.IsFailedTestResult(f)){let h=p===!1,A=h?E6o.failCOF:E6o.fail;if(f.success=!1,f.error=u3o(A,A),h)throw new T$e(f)}return f}getStepStages(t){return y$e(this.nodeEdits,c2r).map(i=>{let o={...t,stageName:i.name,stageType:i.type,continueOnFailure:i.continueOnFailure,templateString:i.sql,phase:"refresh"};if(!o.stageType)throw new rH(t.stepID,"In getStepStages, no stage type on stage?!");return i.type==="sql"&&!i.sql.trim()?new xOt(o):new MOt(o)})}};var P2r=class extends POt{get runTypeName(){return"Deploy"}get Logger(){return Je("DEPLOY")}},N2r=class extends NOt{constructor(n,i,o,s){super(n,i,o,!1);this.jobID=s}jobID;get runTypeName(){return"Refresh"}getJobID(){return this.jobID}get Logger(){return Je("RUNNER")}},D2r=class extends POt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}},B2r=class extends NOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}};var Bbe=class extends nt{constructor(n,i,o){super(`Cycle found at node ${n} -> ${i}. Potential members: ${[...o].join(", ")}`);this.nodeID=n;this.dependencyID=i;this.potentialMembers=o}nodeID;dependencyID;potentialMembers;withNamesAndLocations(n){let i=o=>{let s,a;try{({operation:{name:s,locationName:a}}=g1(o,n,"[GraphCycleError]"))}catch{s=`<unknown name - ID '${o}'>`,a="<unknown location>"}return`${s} (${a})`};return this.message=`Circular dependency found between ${i(this.nodeID)} and ${i(this.dependencyID)}. Circular dependency includes ${[...this.potentialMembers].map(o=>i(o)).join(", ")}. Review JOIN conditions and use ref_no_link where appropriate.`,this}statusCode(){return 400}},cKc=(r,t,n,i)=>`Expected ${i} node ${r} to be in ${n} state, but state=${t}`;var lKc=r=>{let t=new Map;for(let[n,i]of Object.entries(r)){let o=new Set(i);t.set(n,o)}return t},pKc=r=>{let t=new Map;for(let[n,i]of r.entries())for(let o of i){let s=t.get(o);s?s.add(n):t.set(o,new Set([n]))}return t},L2r=r=>{let t=new Set,n=new Map,i=o=>{n.set(o,!0),t.add(o);for(let s of r[o])if(!n.get(s))i(s);else if(t.has(s))throw new Bbe(o,s,t);t.delete(o)};for(let o in r)n.set(o,!1);for(let o in r)n.get(o)||i(o)},DOt=r=>({failedNodeIDs:new Set,skippedNodeIDs:new Set,status:r});var k2r=class r{constructor(t,n,i){this.nodes=t;this.requirements=n;this.requiredBy=i}nodes;requirements;requiredBy;getDependents=t=>this.requiredBy.get(t)||new Set;getDependencies=t=>this.requirements.get(t)||new Set;static create(t,n){L2r(t);let i=lKc(t),o=pKc(i);return new r(new Set(n),i,o)}};var q2r=class{constructor(t,n,i,o,s,a){this.runID=t;this.repository=n;this.connectionManager=i;this.logger=o;this.logContext=s;this.nodeStatusCancelledHandler=a}runID;repository;connectionManager;logger;logContext;nodeStatusCancelledHandler;cancelWatch=()=>{};canceled_=!1;async start(){this.logger.infoContext(this.logContext,"Start watching for run cancellation for runID",this.runID);let{promise:t,cancelWatch:n}=Im1(this.repository);this.cancelWatch=n;try{await t,this.logger.infoContext(this.logContext,"Run cancellation for runID",this.runID,"detected"),this.canceled_=!0;let i=parseInt(process.env.COALESCE_JOB_TIMEOUT_MS)||900*1e3,o=this.connectionManager.cancel();if(!oQe()&&i3()&&i!==0){let s=!1;this.logger.infoContext(this.logContext,"Waiting",i,"milliseconds for cancellation to complete");let a=setTimeout(()=>{s||this.logger.errorContext(this.logContext,"Graceful cancellation timed out. Exiting in 2 seconds..."),setTimeout(()=>{process.exit(1)},2e3)},i);await o,this.logger.infoContext(this.logContext,"Cancellation completed successfully within the timeout."),Hg().isTest&&clearTimeout(a),s=!0}else await o}catch(i){this.logger.errorContext(this.logContext,"Run cancellation for runID",this.runID,"error",i)}finally{this.logger.infoContext(this.logContext,"Completed processing run cancellation for runID",this.runID)}}stop(){this.logger.infoContext(this.logContext,"Stop watching for run cancellation for runID",this.runID),this.cancelWatch()}get canceled(){return this.canceled_}async handleCanceledNode(t){await this.nodeStatusCancelledHandler(t)}},Im1=r=>{let{promise:t,resolve:n}=TR(),i=r.listen(o=>{(o.type==="added"||o.type==="modified")&&o.value.runDetails?.canceled&&(i(),n())});return{cancelWatch:i,promise:t}};var F2r=class{inner;constructor(){this.inner=new Map}addExecution=(t,n,i)=>{if(this.inner.has(t))return!1;let o=i.catch(n).catch(()=>{}).then(()=>t);return this.inner.set(t,o),!0};allCompleted=async()=>{for(;this.inner.size>0;){let t=await LEr.race([...this.inner.values()]);this.inner.delete(t)}}};var U2r=class{constructor(t,n,i,o,s,a,u){this.stepExecutor=t;this.graph=n;this.logContext=i;this.logger=o;this.skipHandler=s;this.semaphoreCap=a;this.cancellationHandler=u;this.executionSemaphore=new aL(this.semaphoreCap),this.runExecutionSequenceID=0,this.stateMutex=new oce,this.inFlightPromises=new F2r,this.status=new O$e(n.nodes),this.nodeErrors=new Map}stepExecutor;graph;logContext;logger;skipHandler;semaphoreCap;cancellationHandler;status;executionSemaphore;stateMutex;runExecutionSequenceID;inFlightPromises;nodeErrors;dependenciesAreSatisfied=t=>{for(let n of this.graph.getDependencies(t))switch(this.status.get(n)){case"pending":case"scheduled":case"failed":case"skipped":return!1;case void 0:if(!this.dependenciesAreSatisfied(n))return!1}return!0};handleDependentsOnSuccess=(t,n)=>{let i={...this.logContext,nodeID:t},o=[...this.graph.getDependents(t)].sort();this.logger.debugContext(i,"Examining dependent steps",o);for(let s of o)n.has(s)||(n.add(s),this.status.get(s)==="pending"?this.dependenciesAreSatisfied(s)?(this.logger.debugContext(i,"Scheduling dependent step",s),this.scheduleStep(s)):this.logger.debugContext(i,"Dependent step",s,"has unsatisfied dependencies"):this.status.get(s)===void 0?(this.logger.debugContext(i,"Dependent step",s,"is not part of this run, so checking its dependents too"),this.handleDependentsOnSuccess(s,n)):this.logger.debugContext(i,"Dependent step",s,"is not pending"))};handleDependentsOnFailure=async t=>{let n=this.graph.getDependents(t),i={...this.logContext,nodeID:t},o={};for(;n.size>0;){let a=n.values().next().value;n.delete(a);let u=this.status.get(a);if(u==="skipped"||u==="failed"){this.logger.debugContext(i,"Already skipped dependent step",a);continue}else if(u===void 0){this.logger.debugContext(i,"Dependent step",a,"was not scheduled, processing dependents");for(let p of this.graph.getDependents(a)||[])n.add(p)}else{this.status.set(a,"skipped"),this.logger.debugContext(i,"Skipping dependent step",a),o[a]=this.nextRunID();for(let p of this.graph.getDependents(a)||[])n.add(p)}}await this.skipHandler(o)};handlePendingNodesOnCancel=async()=>{let t={};for(let n of this.pending)this.status.set(n,"skipped"),t[n]=this.nextRunID();await this.skipHandler(t)};preSkip=async t=>{await this.stateMutex.runExclusive(async()=>{for(let n of t)this.status.has(n)&&this.stateTransition(n,"pending","skipped"),await this.handleDependentsOnFailure(n)})};stateTransition=(t,n,i)=>{let o=this.status.get(t);hh("RUNNER",o===n,this.logContext,cKc(t,o,n,i)),this.status.set(t,i)};markCompleted=async(t,n)=>{let i={...this.logContext,nodeID:t};switch(n){case"success":this.logger.debugContext(i,"Step succeeded"),this.stateTransition(t,"scheduled","succeeded"),this.handleDependentsOnSuccess(t,new Set);break;case"error":this.logger.debugContext(i,"Step failed"),this.stateTransition(t,"scheduled","failed"),await this.handleDependentsOnFailure(t);break;case"canceled":this.logger.debugContext(i,"Run canceled"),this.stateTransition(t,"scheduled","failed"),await this.cancellationHandler?.handleCanceledNode(t),await this.handlePendingNodesOnCancel();break;default:this.logger.errorContext(i,`Unexpected graphRunStatus ${n}`);break}};finishStepExecution=async(t,n)=>{await this.stateMutex.runExclusive(async()=>{await this.markCompleted(t,n)})};getStepExecutionPromise=async(t,n)=>{await this.executionSemaphore.runExclusive(async()=>{let i="success";try{this.logger.infoContext(this.logContext,`step:${t} starting to run in GraphExecutor`),await this.stepExecutor(t,n),this.logger.infoContext(this.logContext,`step:${t} finished executing in GraphExecutor`)}catch(o){let s=p=>{this.logger.infoContext(this.logContext,`GraphExecutor for step ${t} finished with error due to expected ${p}`,o instanceof Error?o.message:o)},a=p=>{this.logger.errorContext(this.logContext,`GraphExecutor for step ${t} finished with error due to unexpected ${p}`,o instanceof Error?o.message:o,o instanceof Error?o.stack:"[no stack trace]")},u=(p,c)=>{c||this.cancellationHandler&&this.cancellationHandler.canceled?(s(p),i="canceled"):(a(p),i="error")};if(YNe(o)?u("run cancellation",!0):pOt(o)||dOt(o)?u("query cancellation",!1):(a("issue"),i="error"),i==="error"){let p=o instanceof nt?o:new nt(o instanceof Error?o.message:String(o));this.nodeErrors.set(t,p)}}this.logger.infoContext(this.logContext,`step:${t} updating workspace status in GraphExecutor`),await this.finishStepExecution(t,i),this.logger.infoContext(this.logContext,`step:${t} finished running in GraphExecutor, outstanding:${this.currentlyRunning()-1}`)})};nextRunID=()=>this.runExecutionSequenceID++;get hasFailures(){return this.failures.length>0}get failures(){return this.status.failures}get skips(){return this.status.skips}get pending(){return this.status.pending}currentlyRunning=()=>this.semaphoreCap-this.executionSemaphore.getValue();internalErrorHandler=t=>{this.logger.emergContext(this.logContext,"Internal failure in graph executor!",t,t.stack)};scheduleStep=t=>{this.stateTransition(t,"pending","scheduled");let n=this.nextRunID(),i=this.getStepExecutionPromise(t,n);this.inFlightPromises.addExecution(t,this.internalErrorHandler,i)||this.logger.warnContext(this.logContext,`Promise for step ${t} was already in the tracker!`)};beginRun=async()=>{let t=[];if(await this.stateMutex.runExclusive(async()=>{for(let n of this.graph.nodes)this.status.get(n)!=="skipped"&&this.dependenciesAreSatisfied(n)&&(t.push(n),this.scheduleStep(n))}),t.length===0)throw this.logger.errorContext(this.logContext,"Could not prepare graph for running, all nodes had unfulfilled requirements!"),new Error("Could not prepare graph for running, all nodes had unfulfilled requirements!");this.logger.infoContext(this.logContext,`Scheduled ${t.length} initial nodes!`)};waitForCompletion=async()=>{await this.inFlightPromises.allCompleted();let t=this.failures,n=this.skips;if([...t,...n].sort().length>0){let o=new QM(t,n,this.status.asMap(),"execute",this.nodeErrors);throw this.logger.infoContext(this.logContext,o.message),o}else return this.logger.infoContext(this.logContext,"all complete for run (PlayTaskThunk)"),DOt(this.status.asMap())};async runGraph(){if(!this.graph.nodes.size)return this.logger.infoContext(this.logContext,"Got an empty graph, so no requirements to fulfill!"),DOt(this.status.asMap());this.cancellationHandler&&this.cancellationHandler.start();try{return await this.beginRun(),await this.waitForCompletion()}finally{this.cancellationHandler&&this.cancellationHandler.stop()}}};var x$e=class{constructor(t,n,i,o,s){this.logContext=t;this.phasedNodeEdits=n;this.phasedDependencies=i;this.jobName=o;this.isPreview=s;this.phasedNodeExecutors=n.map(`${this.getName()} stepExecutors`,(a,u)=>this.createExecutorForID(a,u))}logContext;phasedNodeEdits;phasedDependencies;jobName;isPreview;phasedNodeExecutors;get Logger(){return Je("RUNNER")}runPhase=async(t,n,i,o,s)=>{let a=`[CoalesceRun.runPhase() | '${this.getName()}' - phase '${t}']`,{measure:u,printSummary:p}=Bf(a,this.logContext),c=Array.from(this.phasedNodeExecutors.getPhaseItems(t).keys());if(this.Logger.appContext(this.logContext,a,`Nodes in phase: ${c.length}`,`
|
|
10048
10048
|
`,c),await n.beforePhaseExecution(t,c),!c.length){this.Logger.appContext(this.logContext,a,"Empty graph; skipping execution");let h=DOt(new Map);return await n.afterPhaseExecution(t),h}this.Logger.appContext(this.logContext,a,"Building graph");let l;try{l=k2r.create(this.phasedDependencies[t],c)}catch(h){throw h instanceof Bbe?h.withNamesAndLocations(n.state.nodes):h}let d;n.repository&&(d=new q2r(this.logContext.runID,n.getRepositoryForRun(),i,this.Logger,this.logContext,n.getCancelNodeHandler())),this.Logger.appContext(this.logContext,a,"Creating graph executor");let f=new U2r(this.getGraphStepExecutor(t,n,i,s),l,this.logContext,this.Logger,n.getBulkSkipHandler(),i.maximumConnections,d);o.size&&(this.Logger.appContext(this.logContext,a,"Skipping nodes with upstream failures:",[...o]),await f.preSkip(o));try{this.Logger.appContext(this.logContext,a,"Running graph");let h=await u("run graph",()=>f.runGraph());return await n.afterPhaseExecution(t),h}catch(h){throw await n.afterPhaseExecution(t),h}finally{p()}};getGraphStepExecutor(t,n,i,o){return async(s,a)=>{let u=this.phasedNodeExecutors.get(t,s),p=n.getStepContext(t,s,a,this.isPreview);await i.withConnection(async c=>{await u.executeStep(n,p,c,o)})}}runAll=async(t,n,i)=>{let o=`[CoalesceRun.runAll() | '${this.getName()}']`,{measure:s,printSummary:a}=Bf(o,this.logContext),u=new Set,p=new Map;for(let c of this.phases){let l;try{l=await s(`run phase '${c}'`,()=>this.runPhase(c,t,n,u,i))}catch(d){if(this.Logger.appContext(this.logContext,o,`Error running phase ${c}`,d),d instanceof QM)l=d;else throw d}this.Logger.appContext(this.logContext,o,`Phase '${c}' completed with the following node failures:`,l.failedNodeIDs);for(let d of l.failedNodeIDs)u.add(d);p.set(c,l)}a(),this.handlePhaseResults(p)}};var P$e=class extends nt{constructor(n,i,o,s){let a=n.size+i.size+o.size,u=`${a} ${a===1?"node":"nodes"} failed during deploy`,p=`delete phase - ${n.size?[...n]:"none"}; alter phase - ${i.size?[...i]:"none"}; add phase - ${o.size?[...o]:"none"}`,c=s?.size?`
|
|
10049
10049
|
`+[...s.entries()].map(([l,d])=>`${l}: ${d.message}`).join(`
|
|
10050
10050
|
`):"";super(u,p+c);this.deleteFailures=n;this.alterFailures=i;this.addFailures=o;this.nodeErrors=s}deleteFailures;alterFailures;addFailures;nodeErrors};var BOt=class extends x$e{constructor(t,n,i,o,s=!1){super(t,n,i,o,s)}get phases(){return JNe}handlePhaseResults(t){if(Array.from(t.values()).filter(n=>n.failedNodeIDs.size>0).length){let n=new Map;for(let i of t.values())if(i instanceof QM)for(let[o,s]of i.nodeErrors)n.set(o,s);throw new P$e(t.get("deletedTable").failedNodeIDs,t.get("alteredTable").failedNodeIDs,t.get("addedTable").failedNodeIDs,n)}}};var LOt=class extends x$e{constructor(t,n,i,o,s=!1){super(t,n,i,o,s)}get phases(){return $Ne}handlePhaseResults(t){let n=t.get("refresh");if(n.failedNodeIDs.size){let i=n instanceof QM?n.nodeErrors:void 0;throw new QM([...n.failedNodeIDs],[...n.skippedNodeIDs],n.status,"run",i)}}};var z2r=class extends BOt{constructor(t,n,i,o){super(t,n,i,o)}getName(){return"Deploy"}createExecutorForID(t,n){return new P2r({...this.logContext,nodeID:n},t,this.jobName)}},Q2r=class extends LOt{constructor(n,i,o,s,a){super(n,i,o,s);this.jobID=a}jobID;getName(){return"Refresh"}createExecutorForID(n,i){return new N2r({...this.logContext,nodeID:i},n,this.jobName,this.jobID)}},j2r=class extends BOt{getName(){return"Dev Run (operation type 'create')"}createExecutorForID(t,n){return new D2r({...this.logContext,nodeID:n},t,this.jobName,this.isPreview)}},G2r=class extends LOt{getName(){return"Dev Run (operation type 'run')"}createExecutorForID(t,n){return new B2r({...this.logContext,nodeID:n},t,this.jobName,this.isPreview)}};var dKc={name:"runDeploy",phaseOrder:JNe,getEventHandler:(r,t,n,i,o)=>new p2r(r,t,n,i.runDetails.phasedNodeEdits,o),getRenderer:()=>{throw new nt("Rendering in pipeline is incompatible with deploy requests")},getDependencyBuilder:(r,t,n,i)=>new Obe(r,t,n,i),getRun:(r,t,n,i)=>new z2r(r,t,n,i)},fKc={name:"runRefresh",phaseOrder:$Ne,getEventHandler:(r,t,n,i,o)=>new d2r(r,t,n,o),getRenderer:(r,t,n,i,o,s,a)=>new I2r(t,n,i,o,a.runTimeParameters||{},r.macros,r.installedPackages,r.nodes,r.mappings,r.refLinkLookup,s),getDependencyBuilder:(r,t,n,i)=>new m$e(r,t,n,i),getRun:(r,t,n,i,o)=>new Q2r(r,t,n,i,o.runDetails.jobID?.toString()??null)},hKc={name:"runDevCreate",phaseOrder:JNe,getEventHandler:(r,t,n,i,o)=>new f2r(r,t,n,i.runDetails.dividedStepDataWithWorkspaceEdits,o),getRenderer:(r,t,n,i,o,s,a)=>new R2r(t,n,i,o,a.runTimeParameters||{},r.macros,r.installedPackages,r.refLinkLookup,a.runDetails.dividedStepDataWithWorkspaceEdits,s),getDependencyBuilder:(r,t,n,i)=>new Obe(r,t,n,i),getRun:(r,t,n,i,o)=>new j2r(r,t,n,i,o.runDetails.isPreview)},gKc={name:"runDevRun",phaseOrder:$Ne,getEventHandler:(r,t,n,i,o)=>new h2r(r,t,n,o),getRenderer:(r,t,n,i,o,s,a)=>new O2r(t,n,i,o,a.runTimeParameters||{},r.macros,r.installedPackages,r.nodes,r.mappings,r.refLinkLookup,s,a.runDetails.multisourceIndexLookup),getDependencyBuilder:(r,t,n,i)=>new m$e(r,t,n,i),getRun:(r,t,n,i,o)=>new G2r(r,t,n,i,o.runDetails.isPreview)};function N$e(r){let t=!1,n=[];for(let i=0;i<r.length;i++){let o=r.charAt(i);switch(o){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(o),t=!1;break;default:t&&(t=!1,o=o.toUpperCase()),n.push(o);break}}return n.join("")}var Rm1=new Set(["constructor","toString","toJSON","valueOf"]);function D$e(r){return Rm1.has(r)?r+"$":r}function mKc(){let r=0,t=0;for(let i=0;i<28;i+=7){let o=this.buf[this.pos++];if(r|=(o&127)<<i,(o&128)==0)return this.assertBounds(),[r,t]}let n=this.buf[this.pos++];if(r|=(n&15)<<28,t=(n&112)>>4,(n&128)==0)return this.assertBounds(),[r,t];for(let i=3;i<=31;i+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<i,(o&128)==0)return this.assertBounds(),[r,t]}throw new Error("invalid varint")}var H2r=4294967296;function s7o(r){let t=r[0]==="-";t&&(r=r.slice(1));let n=1e6,i=0,o=0;function s(a,u){let p=Number(r.slice(a,u));o*=n,i=i*n+p,i>=H2r&&(o=o+(i/H2r|0),i=i%H2r)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?bKc(i,o):u7o(i,o)}function yKc(r,t){let n=u7o(r,t),i=n.hi&2147483648;i&&(n=bKc(n.lo,n.hi));let o=a7o(n.lo,n.hi);return i?"-"+o:o}function a7o(r,t){if({lo:r,hi:t}=Om1(r,t),t<=2097151)return String(H2r*t+r);let n=r&16777215,i=(r>>>24|t<<8)&16777215,o=t>>16&65535,s=n+i*6777216+o*6710656,a=i+o*8147497,u=o*2,p=1e7;return s>=p&&(a+=Math.floor(s/p),s%=p),a>=p&&(u+=Math.floor(a/p),a%=p),u.toString()+AKc(a)+AKc(s)}function Om1(r,t){return{lo:r>>>0,hi:t>>>0}}function u7o(r,t){return{lo:r|0,hi:t|0}}function bKc(r,t){return t=~t,r?r=~r+1:t+=1,u7o(r,t)}var AKc=r=>{let t=String(r);return"0000000".slice(t.length)+t};function c7o(r,t){if(r>=0){for(;r>127;)t.push(r&127|128),r=r>>>7;t.push(r)}else{for(let n=0;n<9;n++)t.push(r&127|128),r=r>>7;t.push(1)}}function EKc(){let r=this.buf[this.pos++],t=r&127;if((r&128)==0)return this.assertBounds(),t;if(r=this.buf[this.pos++],t|=(r&127)<<7,(r&128)==0)return this.assertBounds(),t;if(r=this.buf[this.pos++],t|=(r&127)<<14,(r&128)==0)return this.assertBounds(),t;if(r=this.buf[this.pos++],t|=(r&127)<<21,(r&128)==0)return this.assertBounds(),t;r=this.buf[this.pos++],t|=(r&15)<<28;for(let n=5;(r&128)!==0&&n<10;n++)r=this.buf[this.pos++];if((r&128)!=0)throw new Error("invalid varint");return this.assertBounds(),t>>>0}var rC=wm1();function wm1(){let r=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof r.getBigInt64=="function"&&typeof r.getBigUint64=="function"&&typeof r.setBigInt64=="function"&&typeof r.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),o=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(a){let u=typeof a=="bigint"?a:BigInt(a);if(u>i||u<n)throw new Error(`invalid int64: ${a}`);return u},uParse(a){let u=typeof a=="bigint"?a:BigInt(a);if(u>s||u<o)throw new Error(`invalid uint64: ${a}`);return u},enc(a){return r.setBigInt64(0,this.parse(a),!0),{lo:r.getInt32(0,!0),hi:r.getInt32(4,!0)}},uEnc(a){return r.setBigInt64(0,this.uParse(a),!0),{lo:r.getInt32(0,!0),hi:r.getInt32(4,!0)}},dec(a,u){return r.setInt32(0,a,!0),r.setInt32(4,u,!0),r.getBigInt64(0,!0)},uDec(a,u){return r.setInt32(0,a,!0),r.setInt32(4,u,!0),r.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),CKc(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),SKc(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),CKc(n),s7o(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),SKc(n),s7o(n)},dec(n,i){return yKc(n,i)},uDec(n,i){return a7o(n,i)}}}function CKc(r){if(!/^-?[0-9]+$/.test(r))throw new Error("invalid int64: "+r)}function SKc(r){if(!/^[0-9]+$/.test(r))throw new Error("invalid uint64: "+r)}var Mn;(function(r){r[r.DOUBLE=1]="DOUBLE",r[r.FLOAT=2]="FLOAT",r[r.INT64=3]="INT64",r[r.UINT64=4]="UINT64",r[r.INT32=5]="INT32",r[r.FIXED64=6]="FIXED64",r[r.FIXED32=7]="FIXED32",r[r.BOOL=8]="BOOL",r[r.STRING=9]="STRING",r[r.BYTES=12]="BYTES",r[r.UINT32=13]="UINT32",r[r.SFIXED32=15]="SFIXED32",r[r.SFIXED64=16]="SFIXED64",r[r.SINT32=17]="SINT32",r[r.SINT64=18]="SINT64"})(Mn||(Mn={}));function vle(r,t){switch(r){case Mn.STRING:return"";case Mn.BOOL:return!1;case Mn.DOUBLE:case Mn.FLOAT:return 0;case Mn.INT64:case Mn.UINT64:case Mn.SFIXED64:case Mn.FIXED64:case Mn.SINT64:return t?"0":rC.zero;case Mn.BYTES:return new Uint8Array(0);default:return 0}}function vKc(r,t){switch(r){case Mn.BOOL:return t===!1;case Mn.STRING:return t==="";case Mn.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var TKc=2,oH=Symbol.for("reflect unsafe local");function V2r(r,t){let n=r[t.localName].case;return n===void 0?n:t.fields.find(i=>i.localName===n)}function _Kc(r,t){let n=t.localName;if(t.oneof)return r[t.oneof.localName].case===n;if(t.presence!=TKc)return r[n]!==void 0&&Object.prototype.hasOwnProperty.call(r,n);switch(t.fieldKind){case"list":return r[n].length>0;case"map":return Object.keys(r[n]).length>0;case"scalar":return!vKc(t.scalar,r[n]);case"enum":return r[n]!==t.enum.values[0].number}throw new Error("message field with implicit presence")}function rDe(r,t){return Object.prototype.hasOwnProperty.call(r,t)&&r[t]!==void 0}function W2r(r,t){if(t.oneof){let n=r[t.oneof.localName];return n.case===t.localName?n.value:void 0}return r[t.localName]}function K2r(r,t,n){t.oneof?r[t.oneof.localName]={case:t.localName,value:n}:r[t.localName]=n}function IKc(r,t){let n=t.localName;if(t.oneof){let i=t.oneof.localName;r[i].case===n&&(r[i]={case:void 0})}else if(t.presence!=TKc)delete r[n];else switch(t.fieldKind){case"map":r[n]={};break;case"list":r[n]=[];break;case"enum":r[n]=t.enum.values[0].number;break;case"scalar":r[n]=vle(t.scalar,t.longAsString);break}}function kOt(r){for(let t of r.field)rDe(t,"jsonName")||(t.jsonName=N$e(t.name));r.nestedType.forEach(kOt)}function RKc(r,t){let n=r.values.find(i=>i.name===t);if(!n)throw new Error(`cannot parse ${r} default value: ${t}`);return n.number}function OKc(r,t){switch(r){case Mn.STRING:return t;case Mn.BYTES:{let n=Mm1(t);if(n===!1)throw new Error(`cannot parse ${Mn[r]} default value: ${t}`);return n}case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:return rC.parse(t);case Mn.UINT64:case Mn.FIXED64:return rC.uParse(t);case Mn.DOUBLE:case Mn.FLOAT:switch(t){case"inf":return Number.POSITIVE_INFINITY;case"-inf":return Number.NEGATIVE_INFINITY;case"nan":return Number.NaN;default:return parseFloat(t)}case Mn.BOOL:return t==="true";case Mn.INT32:case Mn.UINT32:case Mn.SINT32:case Mn.FIXED32:case Mn.SFIXED32:return parseInt(t,10)}}function Mm1(r){let t=[],n={tail:r,c:"",next(){return this.tail.length==0?!1:(this.c=this.tail[0],this.tail=this.tail.substring(1),!0)},take(i){if(this.tail.length>=i){let o=this.tail.substring(0,i);return this.tail=this.tail.substring(i),o}return!1}};for(;n.next();)switch(n.c){case"\\":if(n.next())switch(n.c){case"\\":t.push(n.c.charCodeAt(0));break;case"b":t.push(8);break;case"f":t.push(12);break;case"n":t.push(10);break;case"r":t.push(13);break;case"t":t.push(9);break;case"v":t.push(11);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let i=n.c,o=n.take(2);if(o===!1)return!1;let s=parseInt(i+o,8);if(Number.isNaN(s))return!1;t.push(s);break}case"x":{let i=n.c,o=n.take(2);if(o===!1)return!1;let s=parseInt(i+o,16);if(Number.isNaN(s))return!1;t.push(s);break}case"u":{let i=n.c,o=n.take(4);if(o===!1)return!1;let s=parseInt(i+o,16);if(Number.isNaN(s))return!1;let a=new Uint8Array(4);new DataView(a.buffer).setInt32(0,s,!0),t.push(a[0],a[1],a[2],a[3]);break}case"U":{let i=n.c,o=n.take(8);if(o===!1)return!1;let s=rC.uEnc(i+o),a=new Uint8Array(8),u=new DataView(a.buffer);u.setInt32(0,s.lo,!0),u.setInt32(4,s.hi,!0),t.push(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]);break}}break;default:t.push(n.c.charCodeAt(0))}return new Uint8Array(t)}function*Y2r(r){switch(r.kind){case"file":for(let t of r.messages)yield t,yield*Y2r(t);yield*r.enums,yield*r.services,yield*r.extensions;break;case"message":for(let t of r.nestedMessages)yield t,yield*Y2r(t);yield*r.nestedEnums,yield*r.nestedExtensions;break}}function J2r(...r){let t=xm1();if(!r.length)return t;if("$typeName"in r[0]&&r[0].$typeName=="google.protobuf.FileDescriptorSet"){for(let n of r[0].file)PKc(n,t);return t}if("$typeName"in r[0]){let s=function(a){let u=[];for(let p of a.dependency){if(t.getFile(p)!=null||o.has(p))continue;let c=i(p);if(!c)throw new Error(`Unable to resolve ${p}, imported by ${a.name}`);"kind"in c?t.addFile(c,!1,!0):(o.add(c.name),u.push(c))}return u.concat(...u.map(s))},n=r[0],i=r[1],o=new Set;for(let a of[n,...s(n)].reverse())PKc(a,t)}else for(let n of r)for(let i of n.files)t.addFile(i);return t}function xm1(){let r=new Map,t=new Map,n=new Map;return{kind:"registry",types:r,extendees:t,[Symbol.iterator](){return r.values()},get files(){return n.values()},addFile(i,o,s){if(n.set(i.proto.name,i),!o)for(let a of Y2r(i))this.add(a);if(s)for(let a of i.dependencies)this.addFile(a,o,s)},add(i){if(i.kind=="extension"){let o=t.get(i.extendee.typeName);o||t.set(i.extendee.typeName,o=new Map),o.set(i.number,i)}r.set(i.typeName,i)},get(i){return r.get(i)},getFile(i){return n.get(i)},getMessage(i){let o=r.get(i);return o?.kind=="message"?o:void 0},getEnum(i){let o=r.get(i);return o?.kind=="enum"?o:void 0},getExtension(i){let o=r.get(i);return o?.kind=="extension"?o:void 0},getExtensionFor(i,o){var s;return(s=t.get(i.typeName))===null||s===void 0?void 0:s.get(o)},getService(i){let o=r.get(i);return o?.kind=="service"?o:void 0}}}var Pm1=998,Nm1=999,Dm1=9999,Bm1=9,FOt=10,qOt=11,Lm1=12,wKc=14,h7o=3,km1=2,MKc=1,qm1=0,l7o=1,xKc=2,Fm1=3,Um1=1,zm1=2,Qm1=1,jm1=2;var Gm1=1001,DKc={998:{fieldPresence:1,enumType:2,repeatedFieldEncoding:2,utf8Validation:3,messageEncoding:1,jsonFormat:2,enforceNamingStyle:2,defaultSymbolVisibility:1},999:{fieldPresence:2,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1e3:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1001:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:1,defaultSymbolVisibility:2}};function PKc(r,t){var n,i;let o={kind:"file",proto:r,deprecated:(i=(n=r.options)===null||n===void 0?void 0:n.deprecated)!==null&&i!==void 0?i:!1,edition:Km1(r),name:r.name.replace(/\.proto$/,""),dependencies:Ym1(r,t),enums:[],messages:[],extensions:[],services:[],toString(){return`file ${r.name}`}},s=new Map,a={get(u){return s.get(u)},add(u){var p;sH(((p=u.proto.options)===null||p===void 0?void 0:p.mapEntry)===!0),s.set(u.typeName,u)}};for(let u of r.enumType)BKc(u,o,void 0,t);for(let u of r.messageType)LKc(u,o,void 0,t,a);for(let u of r.service)Hm1(u,o,t);p7o(o,t);for(let u of s.values())d7o(u,t,a);for(let u of o.messages)d7o(u,t,a),p7o(u,t);t.addFile(o,!0)}function p7o(r,t){switch(r.kind){case"file":for(let n of r.proto.extension){let i=f7o(n,r,t);r.extensions.push(i),t.add(i)}break;case"message":for(let n of r.proto.extension){let i=f7o(n,r,t);r.nestedExtensions.push(i),t.add(i)}for(let n of r.nestedMessages)p7o(n,t);break}}function d7o(r,t,n){let i=r.proto.oneofDecl.map(s=>Wm1(s,r)),o=new Set;for(let s of r.proto.field){let a=Xm1(s,i),u=f7o(s,r,t,a,n);r.fields.push(u),r.field[u.localName]=u,a===void 0?r.members.push(u):(a.fields.push(u),o.has(a)||(o.add(a),r.members.push(a)))}for(let s of i.filter(a=>o.has(a)))r.oneofs.push(s);for(let s of r.nestedMessages)d7o(s,t,n)}function BKc(r,t,n,i){var o,s,a,u,p;let c=Jm1(r.name,r.value),l={kind:"enum",proto:r,deprecated:(s=(o=r.options)===null||o===void 0?void 0:o.deprecated)!==null&&s!==void 0?s:!1,file:t,parent:n,open:!0,name:r.name,typeName:$2r(r,n,t),value:{},values:[],sharedPrefix:c,toString(){return`enum ${this.typeName}`}};l.open=ry1(l),i.add(l);for(let d of r.value){let f=d.name;l.values.push(l.value[d.number]={kind:"enum_value",proto:d,deprecated:(u=(a=d.options)===null||a===void 0?void 0:a.deprecated)!==null&&u!==void 0?u:!1,parent:l,name:f,localName:D$e(c==null?f:f.substring(c.length)),number:d.number,toString(){return`enum value ${l.typeName}.${f}`}})}((p=n?.nestedEnums)!==null&&p!==void 0?p:t.enums).push(l)}function LKc(r,t,n,i,o){var s,a,u,p;let c={kind:"message",proto:r,deprecated:(a=(s=r.options)===null||s===void 0?void 0:s.deprecated)!==null&&a!==void 0?a:!1,file:t,parent:n,name:r.name,typeName:$2r(r,n,t),fields:[],field:{},oneofs:[],members:[],nestedEnums:[],nestedMessages:[],nestedExtensions:[],toString(){return`message ${this.typeName}`}};((u=r.options)===null||u===void 0?void 0:u.mapEntry)===!0?o.add(c):(((p=n?.nestedMessages)!==null&&p!==void 0?p:t.messages).push(c),i.add(c));for(let l of r.enumType)BKc(l,t,c,i);for(let l of r.nestedType)LKc(l,t,c,i,o)}function Hm1(r,t,n){var i,o;let s={kind:"service",proto:r,deprecated:(o=(i=r.options)===null||i===void 0?void 0:i.deprecated)!==null&&o!==void 0?o:!1,file:t,name:r.name,typeName:$2r(r,void 0,t),methods:[],method:{},toString(){return`service ${this.typeName}`}};t.services.push(s),n.add(s);for(let a of r.method){let u=Vm1(a,s,n);s.methods.push(u),s.method[u.localName]=u}}function Vm1(r,t,n){var i,o,s,a;let u;r.clientStreaming&&r.serverStreaming?u="bidi_streaming":r.clientStreaming?u="client_streaming":r.serverStreaming?u="server_streaming":u="unary";let p=n.getMessage(Tle(r.inputType)),c=n.getMessage(Tle(r.outputType));sH(p,`invalid MethodDescriptorProto: input_type ${r.inputType} not found`),sH(c,`invalid MethodDescriptorProto: output_type ${r.inputType} not found`);let l=r.name;return{kind:"rpc",proto:r,deprecated:(o=(i=r.options)===null||i===void 0?void 0:i.deprecated)!==null&&o!==void 0?o:!1,parent:t,name:l,localName:D$e(l.length?D$e(l[0].toLowerCase()+l.substring(1)):l),methodKind:u,input:p,output:c,idempotency:(a=(s=r.options)===null||s===void 0?void 0:s.idempotencyLevel)!==null&&a!==void 0?a:qm1,toString(){return`rpc ${t.typeName}.${l}`}}}function Wm1(r,t){return{kind:"oneof",proto:r,deprecated:!1,parent:t,fields:[],name:r.name,localName:D$e(N$e(r.name)),toString(){return`oneof ${t.typeName}.${this.name}`}}}function f7o(r,t,n,i,o){var s,a,u;let p=o===void 0,c={kind:"field",proto:r,deprecated:(a=(s=r.options)===null||s===void 0?void 0:s.deprecated)!==null&&a!==void 0?a:!1,name:r.name,number:r.number,scalar:void 0,message:void 0,enum:void 0,presence:Zm1(r,i,p,t),utf8Validation:ny1(r,t),listKind:void 0,mapKind:void 0,mapKey:void 0,delimitedEncoding:void 0,packed:void 0,longAsString:!1,getDefaultValue:void 0};if(p){let h=t.kind=="file"?t:t.file,A=t.kind=="file"?void 0:t,E=$2r(r,A,h);c.kind="extension",c.file=h,c.parent=A,c.oneof=void 0,c.typeName=E,c.jsonName=`[${E}]`,c.toString=()=>`extension ${E}`;let v=n.getMessage(Tle(r.extendee));sH(v,`invalid FieldDescriptorProto: extendee ${r.extendee} not found`),c.extendee=v}else{let h=t;sH(h.kind=="message"),c.parent=h,c.oneof=i,c.localName=i?N$e(r.name):D$e(N$e(r.name)),c.jsonName=r.jsonName,c.toString=()=>`field ${h.typeName}.${r.name}`}let l=r.label,d=r.type,f=(u=r.options)===null||u===void 0?void 0:u.jstype;if(l===h7o){let h=d==qOt?o?.get(Tle(r.typeName)):void 0;if(h){c.fieldKind="map";let{key:A,value:E}=ty1(h);return c.mapKey=A.scalar,c.mapKind=E.fieldKind,c.message=E.message,c.delimitedEncoding=!1,c.enum=E.enum,c.scalar=E.scalar,c}switch(c.fieldKind="list",d){case qOt:case FOt:c.listKind="message",c.message=n.getMessage(Tle(r.typeName)),sH(c.message),c.delimitedEncoding=NKc(r,t);break;case wKc:c.listKind="enum",c.enum=n.getEnum(Tle(r.typeName)),sH(c.enum);break;default:c.listKind="scalar",c.scalar=d,c.longAsString=f==MKc;break}return c.packed=ey1(r,t),c}switch(d){case qOt:case FOt:c.fieldKind="message",c.message=n.getMessage(Tle(r.typeName)),sH(c.message,`invalid FieldDescriptorProto: type_name ${r.typeName} not found`),c.delimitedEncoding=NKc(r,t),c.getDefaultValue=()=>{};break;case wKc:{let h=n.getEnum(Tle(r.typeName));sH(h!==void 0,`invalid FieldDescriptorProto: type_name ${r.typeName} not found`),c.fieldKind="enum",c.enum=n.getEnum(Tle(r.typeName)),c.getDefaultValue=()=>rDe(r,"defaultValue")?RKc(h,r.defaultValue):void 0;break}default:{c.fieldKind="scalar",c.scalar=d,c.longAsString=f==MKc,c.getDefaultValue=()=>rDe(r,"defaultValue")?OKc(d,r.defaultValue):void 0;break}}return c}function Km1(r){switch(r.syntax){case"":case"proto2":return Pm1;case"proto3":return Nm1;case"editions":if(r.edition===Dm1)return Gm1;if(r.edition in DKc)return r.edition;throw new Error(`${r.name}: unsupported edition`);default:throw new Error(`${r.name}: unsupported syntax "${r.syntax}"`)}}function Ym1(r,t){return r.dependency.map(n=>{let i=t.getFile(n);if(!i)throw new Error(`Cannot find ${n}, imported by ${r.name}`);return i})}function Jm1(r,t){let n=$m1(r)+"_";for(let i of t){if(!i.name.toLowerCase().startsWith(n))return;let o=i.name.substring(n.length);if(o.length==0||/^\d/.test(o))return}return n}function $m1(r){return(r.substring(0,1)+r.substring(1).replace(/[A-Z]/g,t=>"_"+t)).toLowerCase()}function $2r(r,t,n){let i;return t?i=`${t.typeName}.${r.name}`:n.proto.package.length>0?i=`${n.proto.package}.${r.name}`:i=`${r.name}`,i}function Tle(r){return r.startsWith(".")?r.substring(1):r}function Xm1(r,t){if(!rDe(r,"oneofIndex")||r.proto3Optional)return;let n=t[r.oneofIndex];return sH(n,`invalid FieldDescriptorProto: oneof #${r.oneofIndex} for field #${r.number} not found`),n}function Zm1(r,t,n,i){if(r.label==km1)return Fm1;if(r.label==h7o)return xKc;if(t||r.proto3Optional||n)return l7o;let o=nDe("fieldPresence",{proto:r,parent:i});return o==xKc&&(r.type==qOt||r.type==FOt)?l7o:o}function ey1(r,t){if(r.label!=h7o)return!1;switch(r.type){case Bm1:case Lm1:case FOt:case qOt:return!1}let n=r.options;return n&&rDe(n,"packed")?n.packed:Um1==nDe("repeatedFieldEncoding",{proto:r,parent:t})}function ty1(r){let t=r.fields.find(i=>i.number===1),n=r.fields.find(i=>i.number===2);return sH(t&&t.fieldKind=="scalar"&&t.scalar!=Mn.BYTES&&t.scalar!=Mn.FLOAT&&t.scalar!=Mn.DOUBLE&&n&&n.fieldKind!="list"&&n.fieldKind!="map"),{key:t,value:n}}function ry1(r){var t;return Qm1==nDe("enumType",{proto:r.proto,parent:(t=r.parent)!==null&&t!==void 0?t:r.file})}function NKc(r,t){return r.type==FOt?!0:zm1==nDe("messageEncoding",{proto:r,parent:t})}function ny1(r,t){return jm1==nDe("utf8Validation",{proto:r,parent:t})}function nDe(r,t){var n,i;let o=(n=t.proto.options)===null||n===void 0?void 0:n.features;if(o){let s=o[r];if(s!=0)return s}if("kind"in t){if(t.kind=="message")return nDe(r,(i=t.parent)!==null&&i!==void 0?i:t.file);let s=DKc[t.edition];if(!s)throw new Error(`feature default for edition ${t.edition} not found`);return s[r]}return nDe(r,t.parent)}function sH(r,t){if(!r)throw new Error(t)}function kKc(r){let t=iy1(r);return t.messageType.forEach(kOt),J2r(t,()=>{}).getFile(t.name)}function iy1(r){return Object.assign(Object.create({syntax:"",edition:0}),Object.assign(Object.assign({$typeName:"google.protobuf.FileDescriptorProto",dependency:[],publicDependency:[],weakDependency:[],optionDependency:[],service:[],extension:[]},r),{messageType:r.messageType.map(qKc),enumType:r.enumType.map(FKc)}))}function qKc(r){var t,n,i,o,s,a,u,p;return Object.assign(Object.create({visibility:0}),{$typeName:"google.protobuf.DescriptorProto",name:r.name,field:(n=(t=r.field)===null||t===void 0?void 0:t.map(oy1))!==null&&n!==void 0?n:[],extension:[],nestedType:(o=(i=r.nestedType)===null||i===void 0?void 0:i.map(qKc))!==null&&o!==void 0?o:[],enumType:(a=(s=r.enumType)===null||s===void 0?void 0:s.map(FKc))!==null&&a!==void 0?a:[],extensionRange:(p=(u=r.extensionRange)===null||u===void 0?void 0:u.map(l=>Object.assign({$typeName:"google.protobuf.DescriptorProto.ExtensionRange"},l)))!==null&&p!==void 0?p:[],oneofDecl:[],reservedRange:[],reservedName:[]})}function oy1(r){return Object.assign(Object.create({label:1,typeName:"",extendee:"",defaultValue:"",oneofIndex:0,jsonName:"",proto3Optional:!1}),Object.assign(Object.assign({$typeName:"google.protobuf.FieldDescriptorProto"},r),{options:r.options?sy1(r.options):void 0}))}function sy1(r){var t,n,i;return Object.assign(Object.create({ctype:0,packed:!1,jstype:0,lazy:!1,unverifiedLazy:!1,deprecated:!1,weak:!1,debugRedact:!1,retention:0}),Object.assign(Object.assign({$typeName:"google.protobuf.FieldOptions"},r),{targets:(t=r.targets)!==null&&t!==void 0?t:[],editionDefaults:(i=(n=r.editionDefaults)===null||n===void 0?void 0:n.map(s=>Object.assign({$typeName:"google.protobuf.FieldOptions.EditionDefault"},s)))!==null&&i!==void 0?i:[],uninterpretedOption:[]}))}function FKc(r){return Object.assign(Object.create({visibility:0}),{$typeName:"google.protobuf.EnumDescriptorProto",name:r.name,reservedName:[],reservedRange:[],value:r.value.map(n=>Object.assign({$typeName:"google.protobuf.EnumValueDescriptorProto"},n))})}function zKc(r){let t=uy1(),n=r.length*3/4;r[r.length-2]=="="?n-=2:r[r.length-1]=="="&&(n-=1);let i=new Uint8Array(n),o=0,s=0,a,u=0;for(let p=0;p<r.length;p++){if(a=t[r.charCodeAt(p)],a===void 0)switch(r[p]){case"=":s=0;case`
|
|
10051
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string")}switch(s){case 0:u=a,s=1;break;case 1:i[o++]=u<<2|(a&48)>>4,u=a,s=2;break;case 2:i[o++]=(u&15)<<4|(a&60)>>2,u=a,s=3;break;case 3:i[o++]=(u&3)<<6|a,s=0;break}}if(s==1)throw Error("invalid base64 string");return i.subarray(0,o)}var X2r,UKc,B$e;function ay1(r){return X2r||(X2r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),UKc=X2r.slice(0,-2).concat("-","_")),r=="url"?UKc:X2r}function uy1(){if(!B$e){B$e=[];let r=ay1("std");for(let t=0;t<r.length;t++)B$e[r[t].charCodeAt(0)]=t;B$e[45]=r.indexOf("+"),B$e[95]=r.indexOf("/")}return B$e}function UOt(r,t){return r!==null&&typeof r=="object"&&"$typeName"in r&&typeof r.$typeName=="string"?t===void 0?!0:t.typeName===r.$typeName:!1}var EX=class extends Error{constructor(t,n,i="FieldValueInvalidError"){super(n),this.name=i,this.field=()=>t}};function CX(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function zOt(r,t){var n,i,o,s;if(CX(r)&&oH in r&&"add"in r&&"field"in r&&typeof r.field=="function"){if(t!==void 0){let a=t,u=r.field();return a.listKind==u.listKind&&a.scalar===u.scalar&&((n=a.message)===null||n===void 0?void 0:n.typeName)===((i=u.message)===null||i===void 0?void 0:i.typeName)&&((o=a.enum)===null||o===void 0?void 0:o.typeName)===((s=u.enum)===null||s===void 0?void 0:s.typeName)}return!0}return!1}function QOt(r,t){var n,i,o,s;if(CX(r)&&oH in r&&"has"in r&&"field"in r&&typeof r.field=="function"){if(t!==void 0){let a=t,u=r.field();return a.mapKey===u.mapKey&&a.mapKind==u.mapKind&&a.scalar===u.scalar&&((n=a.message)===null||n===void 0?void 0:n.typeName)===((i=u.message)===null||i===void 0?void 0:i.typeName)&&((o=a.enum)===null||o===void 0?void 0:o.typeName)===((s=u.enum)===null||s===void 0?void 0:s.typeName)}return!0}return!1}function jOt(r,t){return CX(r)&&oH in r&&"desc"in r&&CX(r.desc)&&r.desc.kind==="message"&&(t===void 0||r.desc.typeName==t.typeName)}var g7o=Symbol.for("@bufbuild/protobuf/text-encoding");function Z2r(){if(globalThis[g7o]==null){let r=new globalThis.TextEncoder,t=new globalThis.TextDecoder,n;globalThis[g7o]={encodeUtf8(i){return r.encode(i)},decodeUtf8(i,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(i)):t.decode(i)},checkUtf8(i){try{return encodeURIComponent(i),!0}catch{return!1}}}}return globalThis[g7o]}var hF;(function(r){r[r.Varint=0]="Varint",r[r.Bit64=1]="Bit64",r[r.LengthDelimited=2]="LengthDelimited",r[r.StartGroup=3]="StartGroup",r[r.EndGroup=4]="EndGroup",r[r.Bit32=5]="Bit32"})(hF||(hF={}));var QKc=34028234663852886e22,jKc=-34028234663852886e22,GKc=4294967295,HKc=2147483647,VKc=-2147483648;var eCr=class{constructor(t,n=Z2r().decodeUtf8){this.decodeUtf8=n,this.varint64=mKc,this.uint32=EKc,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}tag(){let t=this.pos,n=this.uint32(),i=this.pos-t;if(i>5||i==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,s=n&7;if(o<=0||s>5)throw new Error("illegal tag: field no "+o+" wire type "+s);return[o,s]}skip(t,n){let i=this.pos;switch(t){case hF.Varint:for(;this.buf[this.pos++]&128;);break;case hF.Bit64:this.pos+=4;case hF.Bit32:this.pos+=4;break;case hF.LengthDelimited:let o=this.uint32();this.pos+=o;break;case hF.StartGroup:for(;;){let[s,a]=this.tag();if(a===hF.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(a,s)}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return rC.dec(...this.varint64())}uint64(){return rC.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),i=-(t&1);return t=(t>>>1|(n&1)<<31)^i,n=n>>>1^i,rC.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return rC.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return rC.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(t){return this.decodeUtf8(this.bytes(),t)}};function WKc(r,t){let n=r.fieldKind=="list"?zOt(t,r):r.fieldKind=="map"?QOt(t,r):m7o(r,t);if(n===!0)return;let i;switch(r.fieldKind){case"list":i=`expected ${$Kc(r)}, got ${rCr(t)}`;break;case"map":i=`expected ${XKc(r)}, got ${rCr(t)}`;break;default:i=tCr(r,t,n)}return new EX(r,i)}function A7o(r,t,n){let i=m7o(r,n);if(i!==!0)return new EX(r,`list item #${t+1}: ${tCr(r,n,i)}`)}function KKc(r,t,n){let i=YKc(t,r.mapKey);if(i!==!0)return new EX(r,`invalid map key: ${tCr({scalar:r.mapKey},t,i)}`);let o=m7o(r,n);if(o!==!0)return new EX(r,`map entry ${rCr(t)}: ${tCr(r,n,o)}`)}function m7o(r,t){return r.scalar!==void 0?YKc(t,r.scalar):r.enum!==void 0?r.enum.open?Number.isInteger(t):r.enum.values.some(n=>n.number===t):jOt(t,r.message)}function YKc(r,t){switch(t){case Mn.DOUBLE:return typeof r=="number";case Mn.FLOAT:return typeof r!="number"?!1:Number.isNaN(r)||!Number.isFinite(r)?!0:r>QKc||r<jKc?`${r.toFixed()} out of range`:!0;case Mn.INT32:case Mn.SFIXED32:case Mn.SINT32:return typeof r!="number"||!Number.isInteger(r)?!1:r>HKc||r<VKc?`${r.toFixed()} out of range`:!0;case Mn.FIXED32:case Mn.UINT32:return typeof r!="number"||!Number.isInteger(r)?!1:r>GKc||r<0?`${r.toFixed()} out of range`:!0;case Mn.BOOL:return typeof r=="boolean";case Mn.STRING:return typeof r!="string"?!1:Z2r().checkUtf8(r)||"invalid UTF8";case Mn.BYTES:return r instanceof Uint8Array;case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:if(typeof r=="bigint"||typeof r=="number"||typeof r=="string"&&r.length>0)try{return rC.parse(r),!0}catch{return`${r} out of range`}return!1;case Mn.FIXED64:case Mn.UINT64:if(typeof r=="bigint"||typeof r=="number"||typeof r=="string"&&r.length>0)try{return rC.uParse(r),!0}catch{return`${r} out of range`}return!1}}function tCr(r,t,n){return n=typeof n=="string"?`: ${n}`:`, got ${rCr(t)}`,r.scalar!==void 0?`expected ${cy1(r.scalar)}`+n:r.enum!==void 0?`expected ${r.enum.toString()}`+n:`expected ${JKc(r.message)}`+n}function rCr(r){switch(typeof r){case"object":return r===null?"null":r instanceof Uint8Array?`Uint8Array(${r.length})`:Array.isArray(r)?`Array(${r.length})`:zOt(r)?$Kc(r.field()):QOt(r)?XKc(r.field()):jOt(r)?JKc(r.desc):UOt(r)?`message ${r.$typeName}`:"object";case"string":return r.length>30?"string":`"${r.split('"').join('\\"')}"`;case"boolean":return String(r);case"number":return String(r);case"bigint":return String(r)+"n";default:return typeof r}}function JKc(r){return`ReflectMessage (${r.typeName})`}function $Kc(r){switch(r.listKind){case"message":return`ReflectList (${r.message.toString()})`;case"enum":return`ReflectList (${r.enum.toString()})`;case"scalar":return`ReflectList (${Mn[r.scalar]})`}}function XKc(r){switch(r.mapKind){case"message":return`ReflectMap (${Mn[r.mapKey]}, ${r.message.toString()})`;case"enum":return`ReflectMap (${Mn[r.mapKey]}, ${r.enum.toString()})`;case"scalar":return`ReflectMap (${Mn[r.mapKey]}, ${Mn[r.scalar]})`}}function cy1(r){switch(r){case Mn.STRING:return"string";case Mn.BOOL:return"boolean";case Mn.INT64:case Mn.SINT64:case Mn.SFIXED64:return"bigint (int64)";case Mn.UINT64:case Mn.FIXED64:return"bigint (uint64)";case Mn.BYTES:return"Uint8Array";case Mn.DOUBLE:return"number (float64)";case Mn.FLOAT:return"number (float32)";case Mn.FIXED32:case Mn.UINT32:return"number (uint32)";case Mn.INT32:case Mn.SFIXED32:case Mn.SINT32:return"number (int32)"}}function ZKc(r){return eYc(r.$typeName)}function nCr(r){let t=r.fields[0];return eYc(r.typeName)&&t!==void 0&&t.fieldKind=="scalar"&&t.name=="value"&&t.number==1}function eYc(r){return r.startsWith("google.protobuf.")&&["DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue"].includes(r.substring(16))}var ly1=999,py1=998,iCr=2;function b7o(r,t){if(UOt(t,r))return t;let n=Ay1(r);return t!==void 0&&dy1(r,n,t),n}function dy1(r,t,n){for(let i of r.members){let o=n[i.localName];if(o==null)continue;let s;if(i.kind=="oneof"){let a=V2r(n,i);if(!a)continue;s=a,o=W2r(n,a)}else s=i;switch(s.fieldKind){case"message":o=E7o(s,o);break;case"scalar":o=nYc(s,o);break;case"list":o=hy1(s,o);break;case"map":o=fy1(s,o);break}K2r(t,s,o)}return t}function nYc(r,t){return r.scalar==Mn.BYTES?C7o(t):t}function fy1(r,t){if(CX(t)){if(r.scalar==Mn.BYTES)return tYc(t,C7o);if(r.mapKind=="message")return tYc(t,n=>E7o(r,n))}return t}function hy1(r,t){if(Array.isArray(t)){if(r.scalar==Mn.BYTES)return t.map(C7o);if(r.listKind=="message")return t.map(n=>E7o(r,n))}return t}function E7o(r,t){if(r.fieldKind=="message"&&!r.oneof&&nCr(r.message))return nYc(r.message.fields[0],t);if(CX(t)){if(r.message.typeName=="google.protobuf.Struct"&&r.parent.typeName!=="google.protobuf.Value")return t;if(!UOt(t,r.message))return b7o(r.message,t)}return t}function C7o(r){return Array.isArray(r)?new Uint8Array(r):r}function tYc(r,t){let n={};for(let i of Object.entries(r))n[i[0]]=t(i[1]);return n}var gy1=Symbol(),rYc=new WeakMap;function Ay1(r){let t;if(my1(r)){let n=rYc.get(r),i,o;if(n)({prototype:i,members:o}=n);else{i={},o=new Set;for(let s of r.members)s.kind!="oneof"&&(s.fieldKind!="scalar"&&s.fieldKind!="enum"||s.presence!=iCr&&(o.add(s),i[s.localName]=y7o(s)));rYc.set(r,{prototype:i,members:o})}t=Object.create(i),t.$typeName=r.typeName;for(let s of r.members)o.has(s)||s.kind=="field"&&(s.fieldKind=="message"||(s.fieldKind=="scalar"||s.fieldKind=="enum")&&s.presence!=iCr)||(t[s.localName]=y7o(s))}else{t={$typeName:r.typeName};for(let n of r.members)(n.kind=="oneof"||n.presence==iCr)&&(t[n.localName]=y7o(n))}return t}function my1(r){switch(r.file.edition){case ly1:return!1;case py1:return!0;default:return r.fields.some(t=>t.presence!=iCr&&t.fieldKind!="message"&&!t.oneof)}}function y7o(r){if(r.kind=="oneof")return{case:void 0};if(r.fieldKind=="list")return[];if(r.fieldKind=="map")return{};if(r.fieldKind=="message")return gy1;let t=r.getDefaultValue();return t!==void 0?r.fieldKind=="scalar"&&r.longAsString?t.toString():t:r.fieldKind=="scalar"?vle(r.scalar,r.longAsString):r.enum.values[0].number}function aCr(r,t,n=!0){return new sCr(r,t,n)}var iYc=new WeakMap,sCr=class{get sortedFields(){let t=iYc.get(this.desc);if(t)return t;let n=this.desc.fields.concat().sort((i,o)=>i.number-o.number);return iYc.set(this.desc,n),n}constructor(t,n,i=!0){this.lists=new Map,this.maps=new Map,this.check=i,this.desc=t,this.message=this[oH]=n??b7o(t),this.fields=t.fields,this.oneofs=t.oneofs,this.members=t.members}findNumber(t){return this._fieldsByNumber||(this._fieldsByNumber=new Map(this.desc.fields.map(n=>[n.number,n]))),this._fieldsByNumber.get(t)}oneofCase(t){return GOt(this.message,t),V2r(this.message,t)}isSet(t){return GOt(this.message,t),_Kc(this.message,t)}clear(t){GOt(this.message,t),IKc(this.message,t)}get(t){GOt(this.message,t);let n=W2r(this.message,t);switch(t.fieldKind){case"list":let i=this.lists.get(t);return(!i||i[oH]!==n)&&this.lists.set(t,i=new T7o(t,n,this.check)),i;case"map":let o=this.maps.get(t);return(!o||o[oH]!==n)&&this.maps.set(t,o=new _7o(t,n,this.check)),o;case"message":return R7o(t,n,this.check);case"scalar":return n===void 0?vle(t.scalar,!1):O7o(t,n);case"enum":return n??t.enum.values[0].number}}set(t,n){if(GOt(this.message,t),this.check){let o=WKc(t,n);if(o)throw o}let i;t.fieldKind=="message"?i=I7o(t,n):QOt(n)||zOt(n)?i=n[oH]:i=w7o(t,n),K2r(this.message,t,i)}getUnknown(){return this.message.$unknown}setUnknown(t){this.message.$unknown=t}};function GOt(r,t){if(t.parent.typeName!==r.$typeName)throw new EX(t,`cannot use ${t.toString()} with message ${r.$typeName}`,"ForeignFieldError")}var T7o=class{field(){return this._field}get size(){return this._arr.length}constructor(t,n,i){this._field=t,this._arr=this[oH]=n,this.check=i}get(t){let n=this._arr[t];return n===void 0?void 0:S7o(this._field,n,this.check)}set(t,n){if(t<0||t>=this._arr.length)throw new EX(this._field,`list item #${t+1}: out of range`);if(this.check){let i=A7o(this._field,t,n);if(i)throw i}this._arr[t]=oYc(this._field,n)}add(t){if(this.check){let n=A7o(this._field,this._arr.length,t);if(n)throw n}this._arr.push(oYc(this._field,t))}clear(){this._arr.splice(0,this._arr.length)}[Symbol.iterator](){return this.values()}keys(){return this._arr.keys()}*values(){for(let t of this._arr)yield S7o(this._field,t,this.check)}*entries(){for(let t=0;t<this._arr.length;t++)yield[t,S7o(this._field,this._arr[t],this.check)]}};var _7o=class{constructor(t,n,i=!0){this.obj=this[oH]=n??{},this.check=i,this._field=t}field(){return this._field}set(t,n){if(this.check){let i=KKc(this._field,t,n);if(i)throw i}return this.obj[oCr(t)]=yy1(this._field,n),this}delete(t){let n=oCr(t),i=Object.prototype.hasOwnProperty.call(this.obj,n);return i&&delete this.obj[n],i}clear(){for(let t of Object.keys(this.obj))delete this.obj[t]}get(t){let n=this.obj[oCr(t)];return n!==void 0&&(n=v7o(this._field,n,this.check)),n}has(t){return Object.prototype.hasOwnProperty.call(this.obj,oCr(t))}*keys(){for(let t of Object.keys(this.obj))yield sYc(t,this._field.mapKey)}*entries(){for(let t of Object.entries(this.obj))yield[sYc(t[0],this._field.mapKey),v7o(this._field,t[1],this.check)]}[Symbol.iterator](){return this.entries()}get size(){return Object.keys(this.obj).length}*values(){for(let t of Object.values(this.obj))yield v7o(this._field,t,this.check)}forEach(t,n){for(let i of this.entries())t.call(n,i[1],i[0],this)}};function I7o(r,t){return jOt(t)?ZKc(t.message)&&!r.oneof&&r.fieldKind=="message"?t.message.value:t.desc.typeName=="google.protobuf.Struct"&&r.parent.typeName!="google.protobuf.Value"?uYc(t.message):t.message:t}function R7o(r,t,n){return t!==void 0&&(nCr(r.message)&&!r.oneof&&r.fieldKind=="message"?t={$typeName:r.message.typeName,value:O7o(r.message.fields[0],t)}:r.message.typeName=="google.protobuf.Struct"&&r.parent.typeName!="google.protobuf.Value"&&CX(t)&&(t=aYc(t))),new sCr(r.message,t,n)}function oYc(r,t){return r.listKind=="message"?I7o(r,t):w7o(r,t)}function S7o(r,t,n){return r.listKind=="message"?R7o(r,t,n):O7o(r,t)}function yy1(r,t){return r.mapKind=="message"?I7o(r,t):w7o(r,t)}function v7o(r,t,n){return r.mapKind=="message"?R7o(r,t,n):t}function oCr(r){return typeof r=="string"||typeof r=="number"?r:String(r)}function sYc(r,t){switch(t){case Mn.STRING:return r;case Mn.INT32:case Mn.FIXED32:case Mn.UINT32:case Mn.SFIXED32:case Mn.SINT32:{let n=Number.parseInt(r);if(Number.isFinite(n))return n;break}case Mn.BOOL:switch(r){case"true":return!0;case"false":return!1}break;case Mn.UINT64:case Mn.FIXED64:try{return rC.uParse(r)}catch{}break;default:try{return rC.parse(r)}catch{}break}return r}function O7o(r,t){switch(r.scalar){case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:"longAsString"in r&&r.longAsString&&typeof t=="string"&&(t=rC.parse(t));break;case Mn.FIXED64:case Mn.UINT64:"longAsString"in r&&r.longAsString&&typeof t=="string"&&(t=rC.uParse(t));break}return t}function w7o(r,t){switch(r.scalar){case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:"longAsString"in r&&r.longAsString?t=String(t):(typeof t=="string"||typeof t=="number")&&(t=rC.parse(t));break;case Mn.FIXED64:case Mn.UINT64:"longAsString"in r&&r.longAsString?t=String(t):(typeof t=="string"||typeof t=="number")&&(t=rC.uParse(t));break}return t}function aYc(r){let t={$typeName:"google.protobuf.Struct",fields:{}};if(CX(r))for(let[n,i]of Object.entries(r))t.fields[n]=lYc(i);return t}function uYc(r){let t={};for(let[n,i]of Object.entries(r.fields))t[n]=cYc(i);return t}function cYc(r){switch(r.kind.case){case"structValue":return uYc(r.kind.value);case"listValue":return r.kind.value.values.map(cYc);case"nullValue":case void 0:return null;default:return r.kind.value}}function lYc(r){let t={$typeName:"google.protobuf.Value",kind:{case:void 0}};switch(typeof r){case"number":t.kind={case:"numberValue",value:r};break;case"string":t.kind={case:"stringValue",value:r};break;case"boolean":t.kind={case:"boolValue",value:r};break;case"object":if(r===null)t.kind={case:"nullValue",value:0};else if(Array.isArray(r)){let n={$typeName:"google.protobuf.ListValue",values:[]};if(Array.isArray(r))for(let i of r)n.values.push(lYc(i));t.kind={case:"listValue",value:n}}else t.kind={case:"structValue",value:aYc(r)};break}return t}function HOt(r,t,...n){return n.reduce((i,o)=>i.nestedMessages[o],r.messages[t])}var M7o=kKc({name:"google/protobuf/descriptor.proto",package:"google.protobuf",messageType:[{name:"FileDescriptorSet",field:[{name:"file",number:1,type:11,label:3,typeName:".google.protobuf.FileDescriptorProto"}],extensionRange:[{start:536e6,end:536000001}]},{name:"FileDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"package",number:2,type:9,label:1},{name:"dependency",number:3,type:9,label:3},{name:"public_dependency",number:10,type:5,label:3},{name:"weak_dependency",number:11,type:5,label:3},{name:"option_dependency",number:15,type:9,label:3},{name:"message_type",number:4,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:5,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"service",number:6,type:11,label:3,typeName:".google.protobuf.ServiceDescriptorProto"},{name:"extension",number:7,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FileOptions"},{name:"source_code_info",number:9,type:11,label:1,typeName:".google.protobuf.SourceCodeInfo"},{name:"syntax",number:12,type:9,label:1},{name:"edition",number:14,type:14,label:1,typeName:".google.protobuf.Edition"}]},{name:"DescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"field",number:2,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"extension",number:6,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"nested_type",number:3,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"extension_range",number:5,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ExtensionRange"},{name:"oneof_decl",number:8,type:11,label:3,typeName:".google.protobuf.OneofDescriptorProto"},{name:"options",number:7,type:11,label:1,typeName:".google.protobuf.MessageOptions"},{name:"reserved_range",number:9,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ReservedRange"},{name:"reserved_name",number:10,type:9,label:3},{name:"visibility",number:11,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"ExtensionRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ExtensionRangeOptions"}]},{name:"ReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"ExtensionRangeOptions",field:[{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"},{name:"declaration",number:2,type:11,label:3,typeName:".google.protobuf.ExtensionRangeOptions.Declaration",options:{retention:2}},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"verification",number:3,type:14,label:1,typeName:".google.protobuf.ExtensionRangeOptions.VerificationState",defaultValue:"UNVERIFIED",options:{retention:2}}],nestedType:[{name:"Declaration",field:[{name:"number",number:1,type:5,label:1},{name:"full_name",number:2,type:9,label:1},{name:"type",number:3,type:9,label:1},{name:"reserved",number:5,type:8,label:1},{name:"repeated",number:6,type:8,label:1}]}],enumType:[{name:"VerificationState",value:[{name:"DECLARATION",number:0},{name:"UNVERIFIED",number:1}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:3,type:5,label:1},{name:"label",number:4,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Label"},{name:"type",number:5,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Type"},{name:"type_name",number:6,type:9,label:1},{name:"extendee",number:2,type:9,label:1},{name:"default_value",number:7,type:9,label:1},{name:"oneof_index",number:9,type:5,label:1},{name:"json_name",number:10,type:9,label:1},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FieldOptions"},{name:"proto3_optional",number:17,type:8,label:1}],enumType:[{name:"Type",value:[{name:"TYPE_DOUBLE",number:1},{name:"TYPE_FLOAT",number:2},{name:"TYPE_INT64",number:3},{name:"TYPE_UINT64",number:4},{name:"TYPE_INT32",number:5},{name:"TYPE_FIXED64",number:6},{name:"TYPE_FIXED32",number:7},{name:"TYPE_BOOL",number:8},{name:"TYPE_STRING",number:9},{name:"TYPE_GROUP",number:10},{name:"TYPE_MESSAGE",number:11},{name:"TYPE_BYTES",number:12},{name:"TYPE_UINT32",number:13},{name:"TYPE_ENUM",number:14},{name:"TYPE_SFIXED32",number:15},{name:"TYPE_SFIXED64",number:16},{name:"TYPE_SINT32",number:17},{name:"TYPE_SINT64",number:18}]},{name:"Label",value:[{name:"LABEL_OPTIONAL",number:1},{name:"LABEL_REPEATED",number:3},{name:"LABEL_REQUIRED",number:2}]}]},{name:"OneofDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"options",number:2,type:11,label:1,typeName:".google.protobuf.OneofOptions"}]},{name:"EnumDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"value",number:2,type:11,label:3,typeName:".google.protobuf.EnumValueDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumOptions"},{name:"reserved_range",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto.EnumReservedRange"},{name:"reserved_name",number:5,type:9,label:3},{name:"visibility",number:6,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"EnumReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"EnumValueDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumValueOptions"}]},{name:"ServiceDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"method",number:2,type:11,label:3,typeName:".google.protobuf.MethodDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ServiceOptions"}]},{name:"MethodDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"input_type",number:2,type:9,label:1},{name:"output_type",number:3,type:9,label:1},{name:"options",number:4,type:11,label:1,typeName:".google.protobuf.MethodOptions"},{name:"client_streaming",number:5,type:8,label:1,defaultValue:"false"},{name:"server_streaming",number:6,type:8,label:1,defaultValue:"false"}]},{name:"FileOptions",field:[{name:"java_package",number:1,type:9,label:1},{name:"java_outer_classname",number:8,type:9,label:1},{name:"java_multiple_files",number:10,type:8,label:1,defaultValue:"false",options:{}},{name:"java_generate_equals_and_hash",number:20,type:8,label:1,options:{deprecated:!0}},{name:"java_string_check_utf8",number:27,type:8,label:1,defaultValue:"false"},{name:"optimize_for",number:9,type:14,label:1,typeName:".google.protobuf.FileOptions.OptimizeMode",defaultValue:"SPEED"},{name:"go_package",number:11,type:9,label:1},{name:"cc_generic_services",number:16,type:8,label:1,defaultValue:"false"},{name:"java_generic_services",number:17,type:8,label:1,defaultValue:"false"},{name:"py_generic_services",number:18,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:23,type:8,label:1,defaultValue:"false"},{name:"cc_enable_arenas",number:31,type:8,label:1,defaultValue:"true"},{name:"objc_class_prefix",number:36,type:9,label:1},{name:"csharp_namespace",number:37,type:9,label:1},{name:"swift_prefix",number:39,type:9,label:1},{name:"php_class_prefix",number:40,type:9,label:1},{name:"php_namespace",number:41,type:9,label:1},{name:"php_metadata_namespace",number:44,type:9,label:1},{name:"ruby_package",number:45,type:9,label:1},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"OptimizeMode",value:[{name:"SPEED",number:1},{name:"CODE_SIZE",number:2},{name:"LITE_RUNTIME",number:3}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"MessageOptions",field:[{name:"message_set_wire_format",number:1,type:8,label:1,defaultValue:"false"},{name:"no_standard_descriptor_accessor",number:2,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"map_entry",number:7,type:8,label:1},{name:"deprecated_legacy_json_field_conflicts",number:11,type:8,label:1,options:{deprecated:!0}},{name:"features",number:12,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldOptions",field:[{name:"ctype",number:1,type:14,label:1,typeName:".google.protobuf.FieldOptions.CType",defaultValue:"STRING"},{name:"packed",number:2,type:8,label:1},{name:"jstype",number:6,type:14,label:1,typeName:".google.protobuf.FieldOptions.JSType",defaultValue:"JS_NORMAL"},{name:"lazy",number:5,type:8,label:1,defaultValue:"false"},{name:"unverified_lazy",number:15,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"weak",number:10,type:8,label:1,defaultValue:"false",options:{deprecated:!0}},{name:"debug_redact",number:16,type:8,label:1,defaultValue:"false"},{name:"retention",number:17,type:14,label:1,typeName:".google.protobuf.FieldOptions.OptionRetention"},{name:"targets",number:19,type:14,label:3,typeName:".google.protobuf.FieldOptions.OptionTargetType"},{name:"edition_defaults",number:20,type:11,label:3,typeName:".google.protobuf.FieldOptions.EditionDefault"},{name:"features",number:21,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"feature_support",number:22,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],nestedType:[{name:"EditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"value",number:2,type:9,label:1}]},{name:"FeatureSupport",field:[{name:"edition_introduced",number:1,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"edition_deprecated",number:2,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"deprecation_warning",number:3,type:9,label:1},{name:"edition_removed",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"removal_error",number:5,type:9,label:1}]}],enumType:[{name:"CType",value:[{name:"STRING",number:0},{name:"CORD",number:1},{name:"STRING_PIECE",number:2}]},{name:"JSType",value:[{name:"JS_NORMAL",number:0},{name:"JS_STRING",number:1},{name:"JS_NUMBER",number:2}]},{name:"OptionRetention",value:[{name:"RETENTION_UNKNOWN",number:0},{name:"RETENTION_RUNTIME",number:1},{name:"RETENTION_SOURCE",number:2}]},{name:"OptionTargetType",value:[{name:"TARGET_TYPE_UNKNOWN",number:0},{name:"TARGET_TYPE_FILE",number:1},{name:"TARGET_TYPE_EXTENSION_RANGE",number:2},{name:"TARGET_TYPE_MESSAGE",number:3},{name:"TARGET_TYPE_FIELD",number:4},{name:"TARGET_TYPE_ONEOF",number:5},{name:"TARGET_TYPE_ENUM",number:6},{name:"TARGET_TYPE_ENUM_ENTRY",number:7},{name:"TARGET_TYPE_SERVICE",number:8},{name:"TARGET_TYPE_METHOD",number:9}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"OneofOptions",field:[{name:"features",number:1,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumOptions",field:[{name:"allow_alias",number:2,type:8,label:1},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"deprecated_legacy_json_field_conflicts",number:6,type:8,label:1,options:{deprecated:!0}},{name:"features",number:7,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumValueOptions",field:[{name:"deprecated",number:1,type:8,label:1,defaultValue:"false"},{name:"features",number:2,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"debug_redact",number:3,type:8,label:1,defaultValue:"false"},{name:"feature_support",number:4,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"ServiceOptions",field:[{name:"features",number:34,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"MethodOptions",field:[{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"idempotency_level",number:34,type:14,label:1,typeName:".google.protobuf.MethodOptions.IdempotencyLevel",defaultValue:"IDEMPOTENCY_UNKNOWN"},{name:"features",number:35,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"IdempotencyLevel",value:[{name:"IDEMPOTENCY_UNKNOWN",number:0},{name:"NO_SIDE_EFFECTS",number:1},{name:"IDEMPOTENT",number:2}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"UninterpretedOption",field:[{name:"name",number:2,type:11,label:3,typeName:".google.protobuf.UninterpretedOption.NamePart"},{name:"identifier_value",number:3,type:9,label:1},{name:"positive_int_value",number:4,type:4,label:1},{name:"negative_int_value",number:5,type:3,label:1},{name:"double_value",number:6,type:1,label:1},{name:"string_value",number:7,type:12,label:1},{name:"aggregate_value",number:8,type:9,label:1}],nestedType:[{name:"NamePart",field:[{name:"name_part",number:1,type:9,label:2},{name:"is_extension",number:2,type:8,label:2}]}]},{name:"FeatureSet",field:[{name:"field_presence",number:1,type:14,label:1,typeName:".google.protobuf.FeatureSet.FieldPresence",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPLICIT",edition:900},{value:"IMPLICIT",edition:999},{value:"EXPLICIT",edition:1e3}]}},{name:"enum_type",number:2,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnumType",options:{retention:1,targets:[6,1],editionDefaults:[{value:"CLOSED",edition:900},{value:"OPEN",edition:999}]}},{name:"repeated_field_encoding",number:3,type:14,label:1,typeName:".google.protobuf.FeatureSet.RepeatedFieldEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPANDED",edition:900},{value:"PACKED",edition:999}]}},{name:"utf8_validation",number:4,type:14,label:1,typeName:".google.protobuf.FeatureSet.Utf8Validation",options:{retention:1,targets:[4,1],editionDefaults:[{value:"NONE",edition:900},{value:"VERIFY",edition:999}]}},{name:"message_encoding",number:5,type:14,label:1,typeName:".google.protobuf.FeatureSet.MessageEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"LENGTH_PREFIXED",edition:900}]}},{name:"json_format",number:6,type:14,label:1,typeName:".google.protobuf.FeatureSet.JsonFormat",options:{retention:1,targets:[3,6,1],editionDefaults:[{value:"LEGACY_BEST_EFFORT",edition:900},{value:"ALLOW",edition:999}]}},{name:"enforce_naming_style",number:7,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnforceNamingStyle",options:{retention:2,targets:[1,2,3,4,5,6,7,8,9],editionDefaults:[{value:"STYLE_LEGACY",edition:900},{value:"STYLE2024",edition:1001}]}},{name:"default_symbol_visibility",number:8,type:14,label:1,typeName:".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility",options:{retention:2,targets:[1],editionDefaults:[{value:"EXPORT_ALL",edition:900},{value:"EXPORT_TOP_LEVEL",edition:1001}]}}],nestedType:[{name:"VisibilityFeature",enumType:[{name:"DefaultSymbolVisibility",value:[{name:"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",number:0},{name:"EXPORT_ALL",number:1},{name:"EXPORT_TOP_LEVEL",number:2},{name:"LOCAL_ALL",number:3},{name:"STRICT",number:4}]}]}],enumType:[{name:"FieldPresence",value:[{name:"FIELD_PRESENCE_UNKNOWN",number:0},{name:"EXPLICIT",number:1},{name:"IMPLICIT",number:2},{name:"LEGACY_REQUIRED",number:3}]},{name:"EnumType",value:[{name:"ENUM_TYPE_UNKNOWN",number:0},{name:"OPEN",number:1},{name:"CLOSED",number:2}]},{name:"RepeatedFieldEncoding",value:[{name:"REPEATED_FIELD_ENCODING_UNKNOWN",number:0},{name:"PACKED",number:1},{name:"EXPANDED",number:2}]},{name:"Utf8Validation",value:[{name:"UTF8_VALIDATION_UNKNOWN",number:0},{name:"VERIFY",number:2},{name:"NONE",number:3}]},{name:"MessageEncoding",value:[{name:"MESSAGE_ENCODING_UNKNOWN",number:0},{name:"LENGTH_PREFIXED",number:1},{name:"DELIMITED",number:2}]},{name:"JsonFormat",value:[{name:"JSON_FORMAT_UNKNOWN",number:0},{name:"ALLOW",number:1},{name:"LEGACY_BEST_EFFORT",number:2}]},{name:"EnforceNamingStyle",value:[{name:"ENFORCE_NAMING_STYLE_UNKNOWN",number:0},{name:"STYLE2024",number:1},{name:"STYLE_LEGACY",number:2}]}],extensionRange:[{start:1e3,end:9995},{start:9995,end:1e4},{start:1e4,end:10001}]},{name:"FeatureSetDefaults",field:[{name:"defaults",number:1,type:11,label:3,typeName:".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"},{name:"minimum_edition",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"maximum_edition",number:5,type:14,label:1,typeName:".google.protobuf.Edition"}],nestedType:[{name:"FeatureSetEditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"overridable_features",number:4,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"fixed_features",number:5,type:11,label:1,typeName:".google.protobuf.FeatureSet"}]}]},{name:"SourceCodeInfo",field:[{name:"location",number:1,type:11,label:3,typeName:".google.protobuf.SourceCodeInfo.Location"}],nestedType:[{name:"Location",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"span",number:2,type:5,label:3,options:{packed:!0}},{name:"leading_comments",number:3,type:9,label:1},{name:"trailing_comments",number:4,type:9,label:1},{name:"leading_detached_comments",number:6,type:9,label:3}]}],extensionRange:[{start:536e6,end:536000001}]},{name:"GeneratedCodeInfo",field:[{name:"annotation",number:1,type:11,label:3,typeName:".google.protobuf.GeneratedCodeInfo.Annotation"}],nestedType:[{name:"Annotation",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"source_file",number:2,type:9,label:1},{name:"begin",number:3,type:5,label:1},{name:"end",number:4,type:5,label:1},{name:"semantic",number:5,type:14,label:1,typeName:".google.protobuf.GeneratedCodeInfo.Annotation.Semantic"}],enumType:[{name:"Semantic",value:[{name:"NONE",number:0},{name:"SET",number:1},{name:"ALIAS",number:2}]}]}]}],enumType:[{name:"Edition",value:[{name:"EDITION_UNKNOWN",number:0},{name:"EDITION_LEGACY",number:900},{name:"EDITION_PROTO2",number:998},{name:"EDITION_PROTO3",number:999},{name:"EDITION_2023",number:1e3},{name:"EDITION_2024",number:1001},{name:"EDITION_UNSTABLE",number:9999},{name:"EDITION_1_TEST_ONLY",number:1},{name:"EDITION_2_TEST_ONLY",number:2},{name:"EDITION_99997_TEST_ONLY",number:99997},{name:"EDITION_99998_TEST_ONLY",number:99998},{name:"EDITION_99999_TEST_ONLY",number:99999},{name:"EDITION_MAX",number:2147483647}]},{name:"SymbolVisibility",value:[{name:"VISIBILITY_UNSET",number:0},{name:"VISIBILITY_LOCAL",number:1},{name:"VISIBILITY_EXPORT",number:2}]}]});var xYc=HOt(M7o,1);var pYc;(function(r){r[r.DECLARATION=0]="DECLARATION",r[r.UNVERIFIED=1]="UNVERIFIED"})(pYc||(pYc={}));var dYc;(function(r){r[r.DOUBLE=1]="DOUBLE",r[r.FLOAT=2]="FLOAT",r[r.INT64=3]="INT64",r[r.UINT64=4]="UINT64",r[r.INT32=5]="INT32",r[r.FIXED64=6]="FIXED64",r[r.FIXED32=7]="FIXED32",r[r.BOOL=8]="BOOL",r[r.STRING=9]="STRING",r[r.GROUP=10]="GROUP",r[r.MESSAGE=11]="MESSAGE",r[r.BYTES=12]="BYTES",r[r.UINT32=13]="UINT32",r[r.ENUM=14]="ENUM",r[r.SFIXED32=15]="SFIXED32",r[r.SFIXED64=16]="SFIXED64",r[r.SINT32=17]="SINT32",r[r.SINT64=18]="SINT64"})(dYc||(dYc={}));var fYc;(function(r){r[r.OPTIONAL=1]="OPTIONAL",r[r.REPEATED=3]="REPEATED",r[r.REQUIRED=2]="REQUIRED"})(fYc||(fYc={}));var hYc;(function(r){r[r.SPEED=1]="SPEED",r[r.CODE_SIZE=2]="CODE_SIZE",r[r.LITE_RUNTIME=3]="LITE_RUNTIME"})(hYc||(hYc={}));var gYc;(function(r){r[r.STRING=0]="STRING",r[r.CORD=1]="CORD",r[r.STRING_PIECE=2]="STRING_PIECE"})(gYc||(gYc={}));var AYc;(function(r){r[r.JS_NORMAL=0]="JS_NORMAL",r[r.JS_STRING=1]="JS_STRING",r[r.JS_NUMBER=2]="JS_NUMBER"})(AYc||(AYc={}));var mYc;(function(r){r[r.RETENTION_UNKNOWN=0]="RETENTION_UNKNOWN",r[r.RETENTION_RUNTIME=1]="RETENTION_RUNTIME",r[r.RETENTION_SOURCE=2]="RETENTION_SOURCE"})(mYc||(mYc={}));var yYc;(function(r){r[r.TARGET_TYPE_UNKNOWN=0]="TARGET_TYPE_UNKNOWN",r[r.TARGET_TYPE_FILE=1]="TARGET_TYPE_FILE",r[r.TARGET_TYPE_EXTENSION_RANGE=2]="TARGET_TYPE_EXTENSION_RANGE",r[r.TARGET_TYPE_MESSAGE=3]="TARGET_TYPE_MESSAGE",r[r.TARGET_TYPE_FIELD=4]="TARGET_TYPE_FIELD",r[r.TARGET_TYPE_ONEOF=5]="TARGET_TYPE_ONEOF",r[r.TARGET_TYPE_ENUM=6]="TARGET_TYPE_ENUM",r[r.TARGET_TYPE_ENUM_ENTRY=7]="TARGET_TYPE_ENUM_ENTRY",r[r.TARGET_TYPE_SERVICE=8]="TARGET_TYPE_SERVICE",r[r.TARGET_TYPE_METHOD=9]="TARGET_TYPE_METHOD"})(yYc||(yYc={}));var bYc;(function(r){r[r.IDEMPOTENCY_UNKNOWN=0]="IDEMPOTENCY_UNKNOWN",r[r.NO_SIDE_EFFECTS=1]="NO_SIDE_EFFECTS",r[r.IDEMPOTENT=2]="IDEMPOTENT"})(bYc||(bYc={}));var EYc;(function(r){r[r.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0]="DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",r[r.EXPORT_ALL=1]="EXPORT_ALL",r[r.EXPORT_TOP_LEVEL=2]="EXPORT_TOP_LEVEL",r[r.LOCAL_ALL=3]="LOCAL_ALL",r[r.STRICT=4]="STRICT"})(EYc||(EYc={}));var CYc;(function(r){r[r.FIELD_PRESENCE_UNKNOWN=0]="FIELD_PRESENCE_UNKNOWN",r[r.EXPLICIT=1]="EXPLICIT",r[r.IMPLICIT=2]="IMPLICIT",r[r.LEGACY_REQUIRED=3]="LEGACY_REQUIRED"})(CYc||(CYc={}));var SYc;(function(r){r[r.ENUM_TYPE_UNKNOWN=0]="ENUM_TYPE_UNKNOWN",r[r.OPEN=1]="OPEN",r[r.CLOSED=2]="CLOSED"})(SYc||(SYc={}));var vYc;(function(r){r[r.REPEATED_FIELD_ENCODING_UNKNOWN=0]="REPEATED_FIELD_ENCODING_UNKNOWN",r[r.PACKED=1]="PACKED",r[r.EXPANDED=2]="EXPANDED"})(vYc||(vYc={}));var TYc;(function(r){r[r.UTF8_VALIDATION_UNKNOWN=0]="UTF8_VALIDATION_UNKNOWN",r[r.VERIFY=2]="VERIFY",r[r.NONE=3]="NONE"})(TYc||(TYc={}));var _Yc;(function(r){r[r.MESSAGE_ENCODING_UNKNOWN=0]="MESSAGE_ENCODING_UNKNOWN",r[r.LENGTH_PREFIXED=1]="LENGTH_PREFIXED",r[r.DELIMITED=2]="DELIMITED"})(_Yc||(_Yc={}));var IYc;(function(r){r[r.JSON_FORMAT_UNKNOWN=0]="JSON_FORMAT_UNKNOWN",r[r.ALLOW=1]="ALLOW",r[r.LEGACY_BEST_EFFORT=2]="LEGACY_BEST_EFFORT"})(IYc||(IYc={}));var RYc;(function(r){r[r.ENFORCE_NAMING_STYLE_UNKNOWN=0]="ENFORCE_NAMING_STYLE_UNKNOWN",r[r.STYLE2024=1]="STYLE2024",r[r.STYLE_LEGACY=2]="STYLE_LEGACY"})(RYc||(RYc={}));var OYc;(function(r){r[r.NONE=0]="NONE",r[r.SET=1]="SET",r[r.ALIAS=2]="ALIAS"})(OYc||(OYc={}));var wYc;(function(r){r[r.EDITION_UNKNOWN=0]="EDITION_UNKNOWN",r[r.EDITION_LEGACY=900]="EDITION_LEGACY",r[r.EDITION_PROTO2=998]="EDITION_PROTO2",r[r.EDITION_PROTO3=999]="EDITION_PROTO3",r[r.EDITION_2023=1e3]="EDITION_2023",r[r.EDITION_2024=1001]="EDITION_2024",r[r.EDITION_UNSTABLE=9999]="EDITION_UNSTABLE",r[r.EDITION_1_TEST_ONLY=1]="EDITION_1_TEST_ONLY",r[r.EDITION_2_TEST_ONLY=2]="EDITION_2_TEST_ONLY",r[r.EDITION_99997_TEST_ONLY=99997]="EDITION_99997_TEST_ONLY",r[r.EDITION_99998_TEST_ONLY=99998]="EDITION_99998_TEST_ONLY",r[r.EDITION_99999_TEST_ONLY=99999]="EDITION_99999_TEST_ONLY",r[r.EDITION_MAX=2147483647]="EDITION_MAX"})(wYc||(wYc={}));var MYc;(function(r){r[r.VISIBILITY_UNSET=0]="VISIBILITY_UNSET",r[r.VISIBILITY_LOCAL=1]="VISIBILITY_LOCAL",r[r.VISIBILITY_EXPORT=2]="VISIBILITY_EXPORT"})(MYc||(MYc={}));var PYc={readUnknownFields:!0};function by1(r){return r?Object.assign(Object.assign({},PYc),r):PYc}function NYc(r,t,n){let i=aCr(r,void 0,!1);return DYc(i,new eCr(t),by1(n),!1,t.byteLength),i.message}function DYc(r,t,n,i,o){var s;let a=i?t.len:t.pos+o,u,p,c=(s=r.getUnknown())!==null&&s!==void 0?s:[];for(;t.pos<a&&([u,p]=t.tag(),!(i&&p==hF.EndGroup));){let l=r.findNumber(u);if(!l){let d=t.skip(p,u);n.readUnknownFields&&c.push({no:u,wireType:p,data:d});continue}Ey1(r,t,l,p,n)}if(i&&(p!=hF.EndGroup||u!==o))throw new Error("invalid end group tag");c.length>0&&r.setUnknown(c)}function Ey1(r,t,n,i,o){var s;switch(n.fieldKind){case"scalar":r.set(n,L$e(t,n.scalar,n.utf8Validation));break;case"enum":let a=L$e(t,Mn.INT32);if(n.enum.open)r.set(n,a);else if(n.enum.values.some(p=>p.number===a))r.set(n,a);else if(o.readUnknownFields){let p=[];c7o(a,p);let c=(s=r.getUnknown())!==null&&s!==void 0?s:[];c.push({no:n.number,wireType:i,data:new Uint8Array(p)}),r.setUnknown(c)}break;case"message":r.set(n,x7o(t,o,n,r.get(n)));break;case"list":Sy1(t,i,r.get(n),o);break;case"map":Cy1(t,r.get(n),o);break}}function Cy1(r,t,n){let i=t.field(),o,s,a=r.uint32(),u=r.pos+a;for(;r.pos<u;){let[p]=r.tag();switch(p){case 1:o=L$e(r,i.mapKey,i.utf8Validation);break;case 2:switch(i.mapKind){case"scalar":s=L$e(r,i.scalar,i.utf8Validation);break;case"enum":s=r.int32();break;case"message":s=x7o(r,n,i);break}break}}if(o===void 0&&(o=vle(i.mapKey,!1)),s===void 0)switch(i.mapKind){case"scalar":s=vle(i.scalar,!1);break;case"enum":s=i.enum.values[0].number;break;case"message":s=aCr(i.message,void 0,!1);break}t.set(o,s)}function Sy1(r,t,n,i){var o;let s=n.field();if(s.listKind==="message"){n.add(x7o(r,i,s));return}let a=(o=s.scalar)!==null&&o!==void 0?o:Mn.INT32;if(!(t==hF.LengthDelimited&&a!=Mn.STRING&&a!=Mn.BYTES)){n.add(L$e(r,a,s.utf8Validation));return}let p=r.uint32()+r.pos;for(;r.pos<p;)n.add(L$e(r,a,s.utf8Validation))}function x7o(r,t,n,i){let o=n.delimitedEncoding,s=i??aCr(n.message,void 0,!1);return DYc(s,r,t,o,o?n.number:r.uint32()),s}function L$e(r,t,n=!1){switch(t){case Mn.STRING:return r.string(n);case Mn.BOOL:return r.bool();case Mn.DOUBLE:return r.double();case Mn.FLOAT:return r.float();case Mn.INT32:return r.int32();case Mn.INT64:return r.int64();case Mn.UINT64:return r.uint64();case Mn.FIXED64:return r.fixed64();case Mn.BYTES:return r.bytes();case Mn.FIXED32:return r.fixed32();case Mn.SFIXED32:return r.sfixed32();case Mn.SFIXED64:return r.sfixed64();case Mn.SINT64:return r.sint64();case Mn.UINT32:return r.uint32();case Mn.SINT32:return r.sint32()}}function SX(r,t){var n;let i=NYc(xYc,zKc(r));return i.messageType.forEach(kOt),i.dependency=(n=t?.map(s=>s.proto.name))!==null&&n!==void 0?n:[],J2r(i,s=>t?.find(a=>a.proto.name===s)).getFile(i.name)}var BYc=SX("Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvE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cHJlZGVmaW5lZBIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlvbnMYiAkgASgLMh0uYnVmLnZhbGlkYXRlLlByZWRlZmluZWRSdWxlc1IKcHJlZGVmaW5lZEJuChJidWlsZC5idWYudmFsaWRhdGVCDVZhbGlkYXRlUHJvdG9QAVpHYnVmLmJ1aWxkL2dlbi9nby9idWZidWlsZC9wcm90b3ZhbGlkYXRlL3Byb3RvY29sYnVmZmVycy9nby9idWYvdmFsaWRhdGU",[M7o,LYc,kYc,BYc]);var P7o=SX("Cipjb2FsZXNjZS9ldmVudHMvdHJhbnNmb3JtL2pvYi92MS9qb2IucHJvdG8SIGNvYWxlc2NlLmV2ZW50cy50cmFuc2Zvcm0uam9iLnYxInwKDEpvYkNvbXBsZXRlZBIXCgZqb2JfaWQYASABKAlCB7pIBHICEAESHAoLZHVyYXRpb25fbXMYAiABKANCB7pIBCICKAASHgoNcm93c19hZmZlY3RlZBgDIAEoA0IHukgEIgIoABIVCg10YXJnZXRfdGFibGVzGAQgAygJIlcKCUpvYkZhaWxlZBIXCgZqb2JfaWQYASABKAlCB7pIBHICEAESGwoKZXJyb3JfY29kZRgCIAEoCUIHukgEcgIQARIUCgxmYWlsZWRfbm9kZXMYAyADKAliBnByb3RvMw",[qYc]),N7o=HOt(P7o,0),D7o=HOt(P7o,1);var GO1=yt(Ftl(),1);var HO1=yt(ztl(),1);var iK2=1440*60;var Xvr=class{constructor(t){this.logOptions=t;this.startTime=performance.now()}logOptions;phases=new Map;queries=[];startTime;startPhase(t){this.phases.set(t,{startTime:performance.now()})}endPhase(t){let n=this.phases.get(t);n&&!n.endTime&&(n.endTime=performance.now()),n||this.logOptions?.logger.errorContext(this.logOptions.context,"AnalyticsCollector.endPhase",`Phase ${t} not found`)}getPhaseDuration(t){let n=this.phases.get(t);if(n&&n.endTime){if(typeof n.startTime!="number"){this.logOptions?.logger.errorContext(this.logOptions.context,"AnalyticsCollector.getPhaseDuration",`Phase ${t} has an end time but start time was type of ${typeof n.startTime} - this should never happen`);return}return Math.round(n.endTime-n.startTime)}}addQueryTiming(t,n,i,o,s){this.queries.push({nodeId:t,stageName:n,durationMs:Math.round(i),success:o,executedAt:s})}getTotalDuration(){return Math.round(performance.now()-this.startTime)}getTotalQueryDuration(){return this.queries.reduce((t,n)=>t+n.durationMs,0)}stripUndefined(t){return Object.fromEntries(Object.entries(t).filter(([n,i])=>i!==void 0))}getQueryCount(){return this.queries.length}getQueries(){return this.queries}},Zvr=class extends Xvr{toPlanAnalytics(t){return{createdAt:new Date,workspaceID:t,totalDurationMs:this.getTotalDuration(),phases:this.stripUndefined({presyncDurationMs:this.getPhaseDuration("presync"),contextUploadDurationMs:this.getPhaseDuration("store plan context"),jinjaRenderingDurationMs:this.getPhaseDuration("render nodes"),schemasDurationMs:this.getPhaseDuration("schemas"),nodeEditsDurationMs:this.getPhaseDuration("node edits"),buildDependenciesDurationMs:this.getPhaseDuration("build dependencies & edits")})}}},eTr=class extends Xvr{toRunAnalyticsDocs(t,n){let i={runType:n,totalDurationMs:this.getTotalDuration(),createdAt:new Date,...this.stripUndefined({planID:t,totalQueryExecutionDurationMs:this.getTotalQueryDuration(),queryCount:this.getQueries().length})},o=this.stripUndefined({beforeRunDurationMs:this.getPhaseDuration("beforeRun"),afterRunDurationMs:this.getPhaseDuration("afterRun"),pipelineExecutionDurationMs:this.getPhaseDuration("pipeline execution"),initializeStepsDurationMs:this.getPhaseDuration("initializeSteps"),runExecutionDurationMs:this.getPhaseDuration("runExecution")}),s;if(n==="refresh"||n==="devRun"){let u=this.getPhaseDuration("rendering all nodes"),p=this.getPhaseDuration("building dependencies"),c;(u!==void 0||p!==void 0)&&(c=(u??0)+(p??0)),s=this.stripUndefined({renderingDurationMs:u,dependencyBuildingDurationMs:p,totalPlanDurationMs:c})}let a=this.getQueries().map(u=>({nodeId:u.nodeId,stageName:u.stageName,durationMs:u.durationMs,success:u.success,executedAt:u.executedAt}));return{summary:i,runPhases:o,planPhases:s,queries:a}}};var pK2=B.object({}).partial().passthrough(),VO1=B.object({orgID:B.string(),planID:B.string()}).partial().passthrough(),lf=B.object({error:B.object({errorString:B.string()})}),Qtl=B.object({environmentID:B.string(),nodeID:B.string(),hash:B.string(),ref:B.string()}).passthrough(),WO1=B.object({renderedRefs:B.array(Qtl)}).passthrough(),KO1=B.object({renderedRefs:B.array(Qtl)}).passthrough(),dK2=B.string(),iQo=B.object({workspaceID:B.string(),status:B.enum(["Waiting","Deploying","Refreshing","Failed Deploy"]),currentlyRunningJobs:B.array(B.number()),currentlyRunningDevJobs:B.array(B.number())}).passthrough(),tMt=B.object({status:B.array(iQo)}).partial().passthrough(),YO1=B.object({workspaceID:B.string(),deployStatus:B.enum(["waiting","failed"]).describe("Optional initial deploy status for the workspace. Used to seed the correct state when auto-creating from an existing Firestore workspace.").optional()}).passthrough(),JO1=B.object({workspaceID:B.string(),runID:B.string(),runType:B.enum(["deploy","refresh","dev"]),createdAt:B.string().datetime({offset:!0})}).passthrough(),$O1=B.object({workspaceRuns:B.array(JO1)}).passthrough(),XO1=B.object({runID:B.string().describe("The run ID to use when submitting an event for an existing run ID - ignored for `start_*` events and required for `complete_*/fail_*/cancel_*` events").optional(),workspaceID:B.string(),event:B.enum(["start_deploy","start_refresh","start_dev","complete_deploy","complete_refresh","complete_dev","fail_deploy","fail_refresh","fail_dev","cancel_refresh","force_start_deploy","force_start_refresh"])}).passthrough(),fK2=B.object({workspaceID:B.string()}).passthrough(),ZO1=B.object({reset:B.boolean().describe("Whether a stuck workspace was actually reset to Waiting"),reason:B.enum(["not_transitional","runs_present"]).describe("When reset is false, why no action was taken").optional(),status:B.array(iQo)}).passthrough(),ew1=B.object({workspaceID:B.string(),runID:B.string(),runType:B.enum(["deploy","refresh","dev"]).describe("Run type of the row to evict. Required to disambiguate dev vs deploy/refresh rows, which use separate run-ID counters and can share a numeric runID within a workspace.")}).passthrough(),tw1=B.object({evicted:B.boolean().describe("true if a workspace_runs row was deleted; false if no matching row existed (idempotent no-op)"),status:B.array(iQo)}).passthrough(),rw1=B.object({orgID:B.string().describe("Optional org override (requires superuser)").optional(),workspaceID:B.string(),status:B.enum(["Waiting","Deploying","Refreshing","Failed Deploy"]).describe("One of Waiting, Deploying, Refreshing, Failed Deploy")}).passthrough();var jtl=vgr([{method:"post",path:"/v1/evict_workspace_run",alias:"evictWorkspaceRun",description:"Reconciliation eviction (cleanup tool). Deletes a workspace_runs row whose run firestore no longer tracks as running, without attributing success or failure to the run. Clears only an unbacked transitional (running) status to waiting; preserves a failed deploy_status and any dimension still backed by a remaining run. Locked + idempotent server-side - no-op if the row is already gone. Scoped to the auth-context org. Used by the cleanup tool.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:ew1}],response:tw1,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/plan",alias:"createPlan",description:"Create a plan",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:B.object({}).partial().passthrough()}],response:VO1,errors:[{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/rendered_refs",alias:"getRenderedRefs",description:"Get rendered refs",requestFormat:"json",parameters:[{name:"environmentID",type:"Query",schema:B.string().describe("Environment to check for cached rendered refs")}],response:WO1,errors:[{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/rendered_refs",alias:"postRenderedRefs",description:"Post rendered refs",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:KO1}],response:B.string(),errors:[{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/reset_stuck_workspace_status",alias:"resetStuckWorkspaceStatus",description:"Conditionally reset a workspace stuck in a transitional state (Deploying/Refreshing) with zero workspace_runs rows back to Waiting. Locked and conditional server-side - no-ops if the workspace is not actually stuck. Scoped to the auth-context org. Used by the cleanup tool.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:B.object({workspaceID:B.string()}).passthrough()}],response:ZO1,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/stuck_workspace_statuses",alias:"listStuckWorkspaceStatuses",description:"List workspaces stuck in a transitional state (Deploying/Refreshing) with zero workspace_runs rows for the auth-context org. Detected via a single postgres join. Used by the cleanup tool to find workspaces needing a reset.",requestFormat:"json",response:tMt,errors:[{status:403,description:"Forbidden",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/support_workspace_status",alias:"setWorkspaceStatus",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:rw1}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/workspace_run_event",alias:"postWorkspaceRunEvent",description:"Post a workspace run event and return the resulting workspace_run_status - no state is persisted; status is computed and returned",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:XO1}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/workspace_run_status",alias:"listWorkspaceStatuses",description:"Get run status for workspaces",requestFormat:"json",parameters:[{name:"workspaceID",type:"Query",schema:B.string().describe("Workspace ID").optional()}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/workspace_run_status",alias:"createWorkspaceStatus",description:"Create a workspace status row",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:YO1}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:409,description:"Conflict",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"delete",path:"/v1/workspace_run_status",alias:"deleteWorkspaceStatus",description:"Delete a workspace status row and its associated workspace runs",requestFormat:"json",parameters:[{name:"workspaceID",type:"Query",schema:B.string().describe("Workspace ID")}],response:B.void(),errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/workspace_runs",alias:"listWorkspaceRunsForOrg",description:"List all workspace_runs rows for the auth-context org. Used by the cleanup tool to detect orphaned postgres rows that no longer correspond to a live Firestore Run doc.",requestFormat:"json",response:$O1,errors:[{status:403,description:"Forbidden",schema:lf},{status:500,description:"Internal Error",schema:lf}]}]),hK2=new gYe(jtl);function Gtl(r,t){return new gYe(r,jtl,t)}var vDe=r=>{try{if(!r&&!Xc.isInitialized)throw Je("COMMON").fatal("Deploy service client requires authentication! Provide explicit token or ensure ClientAuthService is initialized"),new nt("Deploy service client cannot be created without authentication");let t=jEt(),n=Gtl(`${t}/api/deploy`);return n.use(z4e({getToken:r?async()=>r:Xc.resolveAuthToken})),n}catch(t){throw t instanceof rue?(Je("COMMON").error("Deploy Service configuration error",t.diagnostics),new nt("Unable to connect to Coalesce Deploy Service. Please check your configuration and ensure you are properly authenticated.")):t}};var kle=Je("SERVICE_WORKSPACE_STATUS"),nw1=(r,t)=>r==="deploy"?t?"force_start_deploy":"start_deploy":r==="refresh"?t?"force_start_refresh":"start_refresh":"start_dev",iw1=(r,t)=>r==="deploy"?t?"complete_deploy":"fail_deploy":r==="refresh"?t?"complete_refresh":"fail_refresh":t?"complete_dev":"fail_dev",Htl=r=>({retryStrategy:{name:"backoff",base:1},checkError:t=>{if(!N1(t)||t.response&&t.response.status<500)return t},logOnRetry:`${r} retrying after transient failure`,retryLogLevel:"info",logOnFailure:`${r} failed, request never resolved after maximum allowed retries.`}),ow1=async(r,t,n,i)=>{let o="[ensureWorkspaceStatus]";try{await r.createWorkspaceStatus({workspaceID:t,deployStatus:i}),kle.infoContext(n,o,"ensured workspace status (created)",{workspaceID:t,initialDeployStatus:i})}catch(s){if(sw1(s)){kle.infoContext(n,o,"The workspace was already migrated to the deploy service and was not (re)created - continuing",s);return}throw s}},Vtl=async(r,t,n,i,o,s,a)=>{let u=`[postWorkspaceStartEvent][ws=${r}][run=${t}]`,p={...o,workspaceID:Number(r),runID:Number(t)};kle.infoContext(p,u,"getting deploy service client.",s?"with auth token":"without auth token");let c=vDe(s),l=nw1(n,i),d=a?a==="Failed Deploy"?"failed":"waiting":void 0;await cf(async()=>{await ow1(c,r,p,d),kle.infoContext(p,u,"posting start event...",{event:l,runID:t}),await c.postWorkspaceRunEvent({workspaceID:r,event:l,runID:t}),kle.infoContext(p,u,"posted start event",{event:l,runID:t})},3,kle,p,Htl(u))},tTr=async(r,t,n,i,o,s)=>{let a=`[postWorkspaceTerminalEvent][ws=${n}][run=${i}]`,u={...o,workspaceID:Number(n),runID:Number(i)},p=iw1(r,t),c=vDe(s),d=(await cf(async()=>(kle.infoContext(u,a,`posting terminal event ${p}...`),c.postWorkspaceRunEvent({workspaceID:n,event:p,runID:i})),3,kle,u,Htl(a))).status?.[0];if(!d)throw new nt(`Posted terminal event ${p} but deploy service returned no workspace run status.`);return kle.infoContext(u,a,`posted terminal event ${p}! Workspace run status: ${JSON.stringify(d)}`),d.status},sw1=r=>N1(r)&&(r.response?.status===409||r.status===409);var rTr=(r,t)=>{if(!r)return r;let n=Object.create(Object.getPrototypeOf(r));return Object.assign(n,r),t&&Object.assign(n,t),n},aw1=["run","runs","devRun","devRuns"],uw1=["createEntity","save","delete","recursiveDelete","merge","fetchAndMerge","mergeMetadata"],DX=class r{providers;flaggedRepositoryParent;_spiedProperties=new Map;constructor(t,n,i,o,s){return this.providers=n,this.flaggedRepositoryParent=t,new Proxy(this,{defineProperty:(a,u,p)=>{if("value"in p){let c=p.value;typeof c=="function"&&(typeof c.mockRestore=="function"||c._isMockFunction===!0)?a._spiedProperties.set(u,c):a._spiedProperties.delete(u)}return!0},getOwnPropertyDescriptor:(a,u)=>{if(u==="flaggedRepositoryParent"||u==="providers"||u==="_spiedProperties")return Reflect.getOwnPropertyDescriptor(a,u);let p=t[u];return p!==void 0?{configurable:!0,enumerable:!0,writable:!0,value:a._spiedProperties.get(u)??p}:Reflect.getOwnPropertyDescriptor(a,u)},get:(a,u)=>{if(a._spiedProperties.has(u))return a._spiedProperties.get(u);if(u==="flaggedRepositoryParent")return t;if(u==="providers")return n;if(aw1.includes(u))return this.providers.firebase[u];if(u==="batch"&&t.id==="root")return s;let{providerId:p,shouldMutateBoth:c}=o(u,i);if(!(p in this.providers))throw new nt("[FLAGGED_REPOSITORY] Attempted to access a flagged repository implementation that is not configured.",`Provider ID: ${p}`);let l=a.providers[p]?.[u];if(l instanceof Lce){let d=Object.fromEntries(Object.entries(this.providers).map(([f,h])=>[f,h?.[u]]));return new r(l,d,{...i},o,s)}return typeof l=="function"?(...d)=>{let f=t?.[u],h=l,A=this.providers.firebase?.[u],E=this.providers.service?.[u],v=f||h,T={};if(c&&u==="createEntity"){let X=t.generateID?.(d[0]);T.generateID=()=>X}let w=rTr(t,T),N=rTr(a.providers[p],T),k=rTr(this.providers.firebase,T),L=rTr(this.providers.service,T),q=f?.bind(w),G=h?.bind(N),H=A?.bind(k),V=E?.bind(L),F=(q||G)?.(...d);if(F instanceof Promise&&(F=new Promise((X,Z)=>{let re=F,oe=[re];uw1.includes(u)&&c&&(v===A?oe.push(V?.(...d)):oe.push(H?.(...d))),Promise.allSettled(oe).then(()=>{re.then(X).catch(Z)}).catch(()=>{console.error("Promise allSettled failed unexpectedly")})})),!(F instanceof Lce))return F;let J=Object.fromEntries(Object.entries(this.providers).map(([X,Z])=>[X,Z?.[u]?.bind(Z)?.(...d)])),Y=i.orgId;u==="org"&&(Y=d[0]),u==="get"&&t.id==="orgs"&&(Y=d[0]);let z=u==="get"?F:G?.(...d);return new r(z,J,{...i,orgId:Y},o,s)}:t[u]}})}},Wtl=(r,t,n,i)=>new DX(r,t,{},n,i),jXe=r=>{if(r instanceof DX){let t=r.providers.firebase;if(!t)Je("COMMON").error("[getFirestoreProvider] FlaggedRepository has no firebase provider configured. Cannot extract firestore provider for direct access. Defaulting to the parent repository instead.");else return t}return r};var pEe=class extends nt{constructor(n,i,o,s){super(`Unable to secure workspace ${n} for ${o} - cannot start a ${o} when workspace is in state ${i}`,s);this.workspaceName=n;this.workspaceStatus=i;this.runType=o}workspaceName;workspaceStatus;runType};var Ktl=(r,t)=>r?"Deploying":t?"Refreshing":"Waiting",nTr=(r,t,n,i,o)=>{let{status:s,currentlyRunningDevJobs:a,currentlyRunningJobs:u}=i,p=n.type,c=p==="devRun"?a:u,l=`Workspace ${i.name??r}`;if(!c)throw new nt(`Could not find corresponding workspace runs for run ${t} of type ${p}`);if(Zdr.includes(s))throw new nt(`Unable to release run from workspace in state ${s}`,`${l} is in state ${s}, context=${JSON.stringify(o)}.`);s==="Waiting"&&Je("SECURE_RUN_AND_WORKSPACE").warnContext(o,`${l} is in unexpected state ${s}`);let d=LWc(t,c);if(Je("SECURE_RUN_AND_WORKSPACE").infoContext(o,"getWorkspaceTerminalRunUpdate:",{workspace:l,workspaceStatus:s,completedRunID:t,currentlyRunningDevJobs:a,currentlyRunningJobs:u,remainingActiveRuns:d,...n}),p==="deploy"){let f=c.length>1;return{remainingActiveRuns:d,newStatus:n.deployFailed?"Failed Deploy":Ktl(!1,f)}}else if(p==="refresh"){let f=n.hasActiveDeployRun?d.length>1:!!d.length;return{remainingActiveRuns:d,newStatus:s==="Failed Deploy"?s:Ktl(n.hasActiveDeployRun,f)}}else return{remainingActiveRuns:d}},oQo=(r,t,n,i)=>{let{name:o,status:s,devEnv:a}=r;if(Je("SECURE_RUN_AND_WORKSPACE").infoContext(i,"checkRunCanStart: workspace status",{workspaceName:o,workspaceStatus:s,runType:t}),Zdr.includes(s))throw new pEe(o,s,t,`Cannot start any run when workspace is in state ${s}`);if(a&&t==="deploy")throw new pEe(o,s,t,"Cannot start a deploy for a development workspace");let u=()=>new pEe(o,s,t);if(n&&Je("SECURE_RUN_AND_WORKSPACE").infoContext(i,`checkRunCanStart: ${t} run passed with option to ignore workspace status; ignoring some default status checks`),t==="deploy"&&(s==="Deploying"||s==="Refreshing"&&!n)||t==="refresh"&&(s==="Deploying"||s==="Failed Deploy"&&!n))throw u()};var sQo=async(r,t,n)=>{if(!!(await(t==="run"?n.run(r):n.devRun(r)).fetch()).runDetails?.canceled)throw new wbe(r)};var cw1=3,Ytl=r=>r instanceof P$e||r instanceof QM,Jtl=r=>{let t=Ytl(r)?r.nodeErrors:void 0;if(Ytl(r)){let n=`${r.message}.`;if(t?.size){let i=[...t.values()].slice(0,cw1),o=i.map(u=>u.message).join("; "),s=t.size-i.length,a=s>0?` (+${s} more)`:"";return`${n} ${o}${a}`}return`${n} Check the failed nodes for details.`}return ua(r).error.errorString},$tl=r=>r instanceof Dbe?{errorCode:"render_failed",failedNodes:[...r.failedNodeIDs]}:r instanceof QM?{errorCode:"node_execution_failed",failedNodes:[...r.failedNodeIDs]}:r instanceof Mme?{errorCode:"warehouse_auth_failed",failedNodes:[]}:{errorCode:"run_error",failedNodes:[]};var Ztl=Je("PIPELINE"),Xtl=Je("RUN_TRANSACTION"),aQo=Je("SECURE_RUN_AND_WORKSPACE"),uQo=async(r,t,n,i,o)=>async(s,a,u)=>{s&&u&&Ztl.emergContext(o,"Unexpected error registered for a successful run",u);let p={runStatus:"completed"};if(!s){let{runDetails:l,runFailureReason:d}=await i[r](n).fetch(),f=l.canceled||!1;p.runStatus=f?"canceled":"failed",d||(p.runStatus==="canceled"?p.runFailureReason=`Run #${n} canceled by user.`:p.runFailureReason=`Run #${n} has failed. ${Jtl(u)}`)}return pw1(()=>i.releaseWorkspaceStatusAndEndRun(t,n,r,a,p),r,t,n,o)},lw1="does not match the required base version",pw1=async(r,t,n,i,o)=>{let s="terminalRunUpdatesWithRetries:";try{let u=await cf(()=>cf(r,10,Xtl,o,{checkError:p=>oWe(ua(p,!0),lw1)?!1:p,retryStrategy:{name:"backoff",base:2},logOnFailure:"ran out of attempts due to transaction contention",logOnRetry:"[runUpdatesWithRetries][inner retry] retrying release workspace (transaction contention)"}),3,Xtl,o,{logOnFailure:"ran out of attempts and failed to release workspace",logOnRetry:"[runUpdatesWithRetries][outer retry] retrying release workspace"});aQo.appContext(o,s,`successfully set workspace ${n} state to ${u} after ${t} ${i}`)}catch(a){aQo.errorContext(o,s,`failed to update workspace ${n} state for ${t} ${i}}`,a)}},rMt=async(r,t,n,i,o,s)=>{let a="[cleanUpRunAndWorkspaceOnFailedJob]";if(t==="plan"){aQo.alertContext(o,a,`plan job ${r} wants to clean up, but there's nothing to clean up`);return}let u=TG(r,`Unable to parse runID: ${r}`),p=t==="deploy",c=t==="rerun"?"refresh":t,l=n.runs.get(u);if(!l)throw new Du(`Run repository for run ${r} not found in org ${n.id}`);let d=await l.fetch();if(!d)throw new Du(`Run data for run ${r} not found in org ${n.id}`);let f=d.runDetails.environmentID;if(!f)throw new nt(`Workspace ID not found in runDetails for run ${r}`);let h=async()=>{let v=await n.workspace(+f).fetch(),T=c==="refresh"?await u2r(v.name,v.currentlyRunningJobs,n.runs):void 0;return nTr(+f,u,{type:c,deployFailed:p,hasActiveDeployRun:!!T},v,o)},A=await uQo("run",+f,u,n,o),E=async()=>{try{await tTr(c,!1,f.toString(),u.toString(),o,s??bc().authToken)}catch(v){Ztl.errorContext(o,a,"Failed to post terminal event to deploy service. This could result in orphaned workspace_runs row until the cleanup tool's next run.",v)}};await Promise.all([A(!1,h,i),E()])};var TDe=B.object({oldName:B.string(),oldLocation:B.string()}),dw1=B.object({nullable:B.boolean().optional(),dataType:B.string().optional(),description:B.string().optional(),name:B.string()}),fw1=B.object({name:B.string(),dataType:B.string(),nullable:B.boolean(),description:B.string(),defaultValue:B.string().optional()}),cQo=TDe.extend({addedColumns:B.array(fw1)}),lQo=TDe.extend({alteredColumns:B.array(dw1)}),hw1=B.object({name:B.string()}),pQo=TDe.extend({deletedColumns:B.array(hw1)}),dQo=TDe.extend({oldColumn:Pq,newColumn:Pq}),erl=[TDe,pQo,lQo,cQo,dQo],fY2=B.union(erl),gw1=[...erl,o0r,B.object({})],hY2=B.union(gw1);var h5="select 1 as coalesce_test",trl="SELECT name FROM sys.databases;";var dEe=T3o.merge(bmr),rrl=T3o.merge(I6o),Aw1=B.object({templateString:B.string(),macrosString:B.string(),runTimeParameters:Xvt.optional(),packages:w3o,renderDepth:B.number().optional(),formatSQL:B.boolean().optional(),nodeMetadata:B.union([dEe.strict(),rrl.strict()]),description:B.string().optional(),detailedError:B.string().optional()}).strict(),SY2=Mr("RenderNodeParams",Aw1),mw1=B.union([dEe.merge(TDe),dEe.merge(pQo),dEe.merge(lQo),dEe.merge(cQo),dEe.merge(dQo),dEe.merge(o0r),dEe.merge(B.object({})),rrl]),vY2=Mr("RenderDeployNodeMetadata",mw1);var fQo=r=>"fromWorkspaceData"in r&&r.version===2&&"phasedDependencies"in r&&"phasedNodeEdits"in r,yw1=r=>r.environmentID!==void 0&&!bw1(r)&&!fQo(r),bw1=r=>r.operationType!==void 0,nrl=r=>{if(!r?.runType||!r?.runDetails)throw new Error("Run info has invalid run type or run details!");let t=r.runType==="refresh";if(t&&!yw1(r.runDetails))throw new Error(`Refresh run ${r.id||r.reRunID} info has invalid run details!`);return t},irl=r=>!!r.reRunID;var GXe=(r,t)=>{let{jobID:n}=r;return n?`Refreshed Job - ${t[n]?.name||n}`:r.includeNodesSelector||r.excludeNodesSelector?"Refreshed an ad hoc Job":"Refreshed all Nodes"},orl=r=>{if(r.runType==="deploy"){let t=r.runDetails.deployCommitMessage?.substring(0,256)||"N/A",n=r.runDetails.deployCommit?.substring(0,8)||"N/A";return`Commit - ${t} (sha: ${n})`}else return r.runType==="refresh"?r.runDetails.refreshDescription?.substring(0,256)||"Refresh":r.runType==="devRun"?`Dev run (environment ${r.runDetails.environmentID})`:"N/A"};var fEe=Je("PIPELINE"),srl=async(r,t)=>{let{connectionManager:n,featureFlags:i,logContext:o,nodesInRun:s,platform:a,renderer:u,repository:p,runInfo:c,memoryMonitor:l,...d}=t,f=orl(c),h=`[runPipeline (${r.name} / job name '${f}']`;fEe.appContext(o,h,"creating event handler");let A=r.getEventHandler(d,p,o,c,t.analyticsCollector);t.analyticsCollector.startPhase("initializeSteps"),await A.initializeRunResults([...s]),t.analyticsCollector.endPhase("initializeSteps"),await A.repositoryStampExecutorInfo(a.name);let E,v;if(c.runType==="deploy")pd(fQo(c.runDetails),`${h} Malformed deploy run details!`,"PIPELINE",o,`version=${c.runDetails.version} / planID=${c.runDetails.planID}`,c.runDetails),E=c.runDetails.phasedDependencies,v=Nbe.fromRecord("phased node edits",c.runDetails.phasedNodeEdits),await A.repositoryUpdateRunStatus({expectedStatus:"initializing",newStatus:"running"});else{fEe.appContext(o,h,"rendering all nodes"),await A.repositoryUpdateRunStatus({expectedStatus:"initializing",newStatus:"rendering"});let w=r.getRenderer(d,u,a.name,o,s,l,c),N=G=>A.repositoryUpdateRenderingProgress(G);t.analyticsCollector.startPhase("rendering all nodes");let k;try{k=await w.renderAllNodes(d.stepTypesParsed,N)}catch(G){if(G instanceof Dbe)try{let H=Fmc.assert(G.makeRenderFailures(),{logArea:"PIPELINE",logContext:o}),V=A.getRepositoryForRun(),W=V.renderFailures,F=V.parent.parent.batch();for(let[J,Y]of Object.entries(H)){let z=W.get(J);await F.save(z,Y)}await F.commit(),fEe.infoContext(o,h,`Successfully wrote render failures to database for run ${c.id}`),await V.merge({hasRenderFailures:!0})}catch(H){fEe.errorContext(o,h,"Failed to write render failures to database",H)}throw G}t.analyticsCollector.endPhase("rendering all nodes"),v=k.toEdits(),fEe.appContext(o,h,"building dependencies");let L={};t.analyticsCollector.startPhase("building dependencies"),E=r.getDependencyBuilder(d.nodes,k,L,o).build(),t.analyticsCollector.endPhase("building dependencies"),await A.repositoryUpdateRunStatus({expectedStatus:"rendering",newStatus:"running"})}t.analyticsCollector.startPhase("populateQueuedStages"),await A.populatePlaceholderStages(v,r.phaseOrder),t.analyticsCollector.endPhase("populateQueuedStages");let T=new l2r(p,()=>A.getRepositoryForRun(),Mbe.buildRunResultEntitySave,A.runResults,fEe,o);A.setFlusher(T),fEe.infoContext(o,h,"executing run");try{let w=r.getRun(o,v,E,f,c);t.analyticsCollector.startPhase("runExecution"),await w.runAll(A,n,a)}finally{await A.disposeFlusher()}return t.analyticsCollector.endPhase("runExecution"),fEe.infoContext(o,h,"finished executing run"),{eventHandler:A}};var hQo=Je("PIPELINE"),Ew1=1e4,Cw1=r=>({retryStrategy:{name:"backoff",base:1},checkError:t=>!N1(t)||t.response&&t.response.status<500?t:void 0,logOnRetry:`${r} retrying after transient failure`,retryLogLevel:"info",logOnFailure:`${r} failed, request never resolved after maximum allowed retries`}),gQo=async(r,t,n,i)=>{let o=`[publishEventViaScheduler][${r}]`,s=`${QEt()}/api/v1/events/publish`;try{await cf(async()=>{let a=n??(Xc.isInitialized?await Xc.resolveAuthToken():void 0);return hQo.infoContext(i,o,"publishing via scheduler relay"),dc.post(s,{type:r,payload:t},{timeout:Ew1,headers:a?{Authorization:`Bearer ${a}`}:{}})},3,hQo,i,Cw1(o))}catch(a){hQo.errorContext(i,o,"failed to publish via scheduler relay",a)}};var Sw1=Je("RUNNER_BACKEND"),arl=(r,t,n,i)=>{Sw1.appContext(i,"[createCoalesceRunRequirements]","Creating run requirements");let s=r.steps;if(n)for(let[p,{operation:c}]of Object.entries(n))p in s||(s[p]={operation:c});let a=r?.installedPackages||{},u=VEr(a,ep(r.stepTypes));return{currentWorkspace:t,installedPackages:a,macros:ep(r.macros),mappings:ep(r.locations??{}),nodes:s,projects:ep(r.projects??{}),stepTypesParsed:X$(u),stepTypesYaml:u,refLinkLookup:wv(s)}};var url=r=>r.type==="sourceInput"?void 0:{name:r.name,locationName:r.locationName},crl=(r,t,n,i,o)=>{let s=new Set,a=0;for(let[c,l]of Object.entries(r)){if(l.runState!=="complete")continue;for(let f of l.queryResultSequence.queryResults){let{rowsInserted:h,rowsUpdated:A,rowsDeleted:E}=lrl(i.runType,f);for(let v of[h,A,E])typeof v=="number"&&(a+=v)}let d=o(c);if(d)try{s.add(IIt(t,{name:d.name,locationName:d.locationName},n))}catch{}}let u=i.runEndTime??i.runHeartbeat,p=i.runStartTime&&u?Math.max(0,fgr(u)-fgr(i.runStartTime)):0;return{targetTables:[...s],rowsAffected:a,durationMs:p}};var l4=Je("PIPELINE"),prl=async(r,t,n,i,o,s,a)=>{try{let u=r.analyticsCollector.toRunAnalyticsDocs(o,s);await t.writeRunAnalyticsSummary(i,n,u.summary,u.runPhases,u.planPhases,u.queries),l4.infoContext(a,"Successfully wrote run analytics to Firestore")}catch(u){l4.errorContext(a,"Failed to write run analytics to Firestore. This is non-critical.",u)}},_De=async(r,t,n)=>{let i="[buildPipeline]",{allWorkspaceData:o,connectionManager:s,logContext:a,nodesInRun:u,platform:p,renderer:c,runID:l,runInfo:d,supplementalNodeData:f,teamInfoAndFirebase:{featureFlags:h,rootRepository:A,teamInfo:{fbTeamID:E}},workspaceID:v,memoryMonitor:T}=t,w=new eTr({context:a,logger:l4});if(!c.render)throw l4.errorContext(a,i,"bad renderer"),new nt(`${i} bad renderer`);let{runType:N}=d,k=N==="devRun"?"devRun":"run",L=A.org(E),q=await uQo(k,v,l,L,a),G=d.runType==="deploy"&&"planID"in d.runDetails?d.runDetails.planID:void 0,H,V=jXe(L),W=async J=>{let Y=await V.workspace(v).fetch(),z=N==="refresh"?await u2r(Y.name,Y.currentlyRunningJobs,L.runs):void 0;return nTr(v,l,{type:N,deployFailed:J,hasActiveDeployRun:!!z},Y,a)},F=J=>{let Y;return()=>(Y??=tTr(N,J,v.toString(),l.toString(),a,bc().authToken).catch(z=>{l4.fatalContext(a,i,"Deploy service posted start event but failed to post terminal event. This could result in orphaned workspace_runs rows. Requires investigation.",z)}),Y)};try{n.beforeRun&&(await sQo(l,k,L),w.startPhase("beforeRun"),await n.beforeRun(),w.endPhase("beforeRun"));let J=arl(o,v,f,a);await sQo(l,k,L),w.startPhase("pipeline execution"),{eventHandler:H}=await srl(r,{...J,connectionManager:s,featureFlags:h,logContext:a,nodesInRun:u,platform:p,renderer:c,repository:A,runInfo:d,memoryMonitor:T,analyticsCollector:w}),w.endPhase("pipeline execution"),n.afterRun&&(w.startPhase("afterRun"),await n.afterRun(),w.endPhase("afterRun")),l4.appContext(a,i,"run finished successfully");let Y=F(!0);if(await q(!0,()=>drl(Y,()=>W(!1),a,i,"try"),void 0),await prl(H,L,k,l,G,N,a),N==="refresh")try{let z=await L.runs.get(l).fetch(),X=crl(H.runResults,Zq(o.locations??{},v),p.name,z,Z=>{try{return url(H.getSingleStepData(void 0,Z).operation)}catch(re){l4.debugContext(a,i,"could not resolve target table for node",{nodeID:Z,error:re});return}});X.rowsAffected>0&&X.targetTables.length===0&&l4.warnContext(a,i,"transform.job.completed resolved no target tables despite affected rows",{rowsAffected:X.rowsAffected}),await gQo(N7o.typeName,{jobId:l.toString(),durationMs:String(X.durationMs),rowsAffected:String(Math.max(0,X.rowsAffected)),targetTables:X.targetTables},bc().authToken,a)}catch(z){l4.errorContext(a,i,"failed to assemble transform.job.completed event",z)}}catch(J){l4.errorContext(a,i,"error during run",J);try{let Y=F(!1);await q(!1,()=>drl(Y,()=>W(!0),a,i,"catch"),J)}catch(Y){l4.emergContext(a,i,"error during status release",Y)}if(H&&await prl(H,L,k,l,G,N,a),N==="refresh"){let Y=YNe(J);if(!Y)try{let{runDetails:z}=await L.run(l).fetch();Y=!!z?.canceled}catch{}if(!Y)try{let{errorCode:z,failedNodes:X}=$tl(J);await gQo(D7o.typeName,{jobId:l.toString(),errorCode:z,failedNodes:X},bc().authToken,a)}catch(z){l4.errorContext(a,i,"failed to assemble transform.job.failed event",z)}}throw J}finally{l4.infoContext(a,i,"Calling onCleanup (heartbeat cleanup)"),await n.onCleanup(),l4.infoContext(a,i,"onCleanup (heartbeat cleanup) completed")}},frl=r=>r.forcedDeployment?!!r.forcedDeployment:r.forceIgnoreWorkspaceStatus?!!r.forceIgnoreWorkspaceStatus:!1,drl=async(r,t,n,i,o="test")=>{let s=await r(),a=await t();if(s&&s!==a.newStatus){let u=`Workspace run status from deploy service and repository do not match after running inside of a ${o} block.`;a.newStatus==="Failed Deploy"&&s==="Refreshing"&&(u+=" This could be legitimate due to services ability to track a proper terminal state."),l4.warnContext(n,i,u,{serviceStatus:s||"undefined",repoStatus:a.newStatus||"undefined"})}return a};var hEe=Je("PIPELINE"),vw1={installedPackages:"installedPackages",jobs:"jobs",macros:"macros",nodeTypes:"stepTypes",subgraphs:"folders",nodes:"steps"},hrl=async(r,t,n,i,o,s)=>{let a="[performSaves]",u=vw1[r],p=o[u]||{},c=i[r],l=await c.select(),d=l.map(({id:h})=>h),f;if(r==="subgraphs"&&(f=Object.fromEntries(l.map(h=>[h.id.toString(),h]))),hEe.appContext(s,a,`Deploying ${r}`,`
|
|
10051
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string")}switch(s){case 0:u=a,s=1;break;case 1:i[o++]=u<<2|(a&48)>>4,u=a,s=2;break;case 2:i[o++]=(u&15)<<4|(a&60)>>2,u=a,s=3;break;case 3:i[o++]=(u&3)<<6|a,s=0;break}}if(s==1)throw Error("invalid base64 string");return i.subarray(0,o)}var X2r,UKc,B$e;function ay1(r){return X2r||(X2r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),UKc=X2r.slice(0,-2).concat("-","_")),r=="url"?UKc:X2r}function uy1(){if(!B$e){B$e=[];let r=ay1("std");for(let t=0;t<r.length;t++)B$e[r[t].charCodeAt(0)]=t;B$e[45]=r.indexOf("+"),B$e[95]=r.indexOf("/")}return B$e}function UOt(r,t){return r!==null&&typeof r=="object"&&"$typeName"in r&&typeof r.$typeName=="string"?t===void 0?!0:t.typeName===r.$typeName:!1}var EX=class extends Error{constructor(t,n,i="FieldValueInvalidError"){super(n),this.name=i,this.field=()=>t}};function CX(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function zOt(r,t){var n,i,o,s;if(CX(r)&&oH in r&&"add"in r&&"field"in r&&typeof r.field=="function"){if(t!==void 0){let a=t,u=r.field();return a.listKind==u.listKind&&a.scalar===u.scalar&&((n=a.message)===null||n===void 0?void 0:n.typeName)===((i=u.message)===null||i===void 0?void 0:i.typeName)&&((o=a.enum)===null||o===void 0?void 0:o.typeName)===((s=u.enum)===null||s===void 0?void 0:s.typeName)}return!0}return!1}function QOt(r,t){var n,i,o,s;if(CX(r)&&oH in r&&"has"in r&&"field"in r&&typeof r.field=="function"){if(t!==void 0){let a=t,u=r.field();return a.mapKey===u.mapKey&&a.mapKind==u.mapKind&&a.scalar===u.scalar&&((n=a.message)===null||n===void 0?void 0:n.typeName)===((i=u.message)===null||i===void 0?void 0:i.typeName)&&((o=a.enum)===null||o===void 0?void 0:o.typeName)===((s=u.enum)===null||s===void 0?void 0:s.typeName)}return!0}return!1}function jOt(r,t){return CX(r)&&oH in r&&"desc"in r&&CX(r.desc)&&r.desc.kind==="message"&&(t===void 0||r.desc.typeName==t.typeName)}var g7o=Symbol.for("@bufbuild/protobuf/text-encoding");function Z2r(){if(globalThis[g7o]==null){let r=new globalThis.TextEncoder,t=new globalThis.TextDecoder,n;globalThis[g7o]={encodeUtf8(i){return r.encode(i)},decodeUtf8(i,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(i)):t.decode(i)},checkUtf8(i){try{return encodeURIComponent(i),!0}catch{return!1}}}}return globalThis[g7o]}var hF;(function(r){r[r.Varint=0]="Varint",r[r.Bit64=1]="Bit64",r[r.LengthDelimited=2]="LengthDelimited",r[r.StartGroup=3]="StartGroup",r[r.EndGroup=4]="EndGroup",r[r.Bit32=5]="Bit32"})(hF||(hF={}));var QKc=34028234663852886e22,jKc=-34028234663852886e22,GKc=4294967295,HKc=2147483647,VKc=-2147483648;var eCr=class{constructor(t,n=Z2r().decodeUtf8){this.decodeUtf8=n,this.varint64=mKc,this.uint32=EKc,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}tag(){let t=this.pos,n=this.uint32(),i=this.pos-t;if(i>5||i==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,s=n&7;if(o<=0||s>5)throw new Error("illegal tag: field no "+o+" wire type "+s);return[o,s]}skip(t,n){let i=this.pos;switch(t){case hF.Varint:for(;this.buf[this.pos++]&128;);break;case hF.Bit64:this.pos+=4;case hF.Bit32:this.pos+=4;break;case hF.LengthDelimited:let o=this.uint32();this.pos+=o;break;case hF.StartGroup:for(;;){let[s,a]=this.tag();if(a===hF.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(a,s)}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return rC.dec(...this.varint64())}uint64(){return rC.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),i=-(t&1);return t=(t>>>1|(n&1)<<31)^i,n=n>>>1^i,rC.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return rC.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return rC.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(t){return this.decodeUtf8(this.bytes(),t)}};function WKc(r,t){let n=r.fieldKind=="list"?zOt(t,r):r.fieldKind=="map"?QOt(t,r):m7o(r,t);if(n===!0)return;let i;switch(r.fieldKind){case"list":i=`expected ${$Kc(r)}, got ${rCr(t)}`;break;case"map":i=`expected ${XKc(r)}, got ${rCr(t)}`;break;default:i=tCr(r,t,n)}return new EX(r,i)}function A7o(r,t,n){let i=m7o(r,n);if(i!==!0)return new EX(r,`list item #${t+1}: ${tCr(r,n,i)}`)}function KKc(r,t,n){let i=YKc(t,r.mapKey);if(i!==!0)return new EX(r,`invalid map key: ${tCr({scalar:r.mapKey},t,i)}`);let o=m7o(r,n);if(o!==!0)return new EX(r,`map entry ${rCr(t)}: ${tCr(r,n,o)}`)}function m7o(r,t){return r.scalar!==void 0?YKc(t,r.scalar):r.enum!==void 0?r.enum.open?Number.isInteger(t):r.enum.values.some(n=>n.number===t):jOt(t,r.message)}function YKc(r,t){switch(t){case Mn.DOUBLE:return typeof r=="number";case Mn.FLOAT:return typeof r!="number"?!1:Number.isNaN(r)||!Number.isFinite(r)?!0:r>QKc||r<jKc?`${r.toFixed()} out of range`:!0;case Mn.INT32:case Mn.SFIXED32:case Mn.SINT32:return typeof r!="number"||!Number.isInteger(r)?!1:r>HKc||r<VKc?`${r.toFixed()} out of range`:!0;case Mn.FIXED32:case Mn.UINT32:return typeof r!="number"||!Number.isInteger(r)?!1:r>GKc||r<0?`${r.toFixed()} out of range`:!0;case Mn.BOOL:return typeof r=="boolean";case Mn.STRING:return typeof r!="string"?!1:Z2r().checkUtf8(r)||"invalid UTF8";case Mn.BYTES:return r instanceof Uint8Array;case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:if(typeof r=="bigint"||typeof r=="number"||typeof r=="string"&&r.length>0)try{return rC.parse(r),!0}catch{return`${r} out of range`}return!1;case Mn.FIXED64:case Mn.UINT64:if(typeof r=="bigint"||typeof r=="number"||typeof r=="string"&&r.length>0)try{return rC.uParse(r),!0}catch{return`${r} out of range`}return!1}}function tCr(r,t,n){return n=typeof n=="string"?`: ${n}`:`, got ${rCr(t)}`,r.scalar!==void 0?`expected ${cy1(r.scalar)}`+n:r.enum!==void 0?`expected ${r.enum.toString()}`+n:`expected ${JKc(r.message)}`+n}function rCr(r){switch(typeof r){case"object":return r===null?"null":r instanceof Uint8Array?`Uint8Array(${r.length})`:Array.isArray(r)?`Array(${r.length})`:zOt(r)?$Kc(r.field()):QOt(r)?XKc(r.field()):jOt(r)?JKc(r.desc):UOt(r)?`message ${r.$typeName}`:"object";case"string":return r.length>30?"string":`"${r.split('"').join('\\"')}"`;case"boolean":return String(r);case"number":return String(r);case"bigint":return String(r)+"n";default:return typeof r}}function JKc(r){return`ReflectMessage (${r.typeName})`}function $Kc(r){switch(r.listKind){case"message":return`ReflectList (${r.message.toString()})`;case"enum":return`ReflectList (${r.enum.toString()})`;case"scalar":return`ReflectList (${Mn[r.scalar]})`}}function XKc(r){switch(r.mapKind){case"message":return`ReflectMap (${Mn[r.mapKey]}, ${r.message.toString()})`;case"enum":return`ReflectMap (${Mn[r.mapKey]}, ${r.enum.toString()})`;case"scalar":return`ReflectMap (${Mn[r.mapKey]}, ${Mn[r.scalar]})`}}function cy1(r){switch(r){case Mn.STRING:return"string";case Mn.BOOL:return"boolean";case Mn.INT64:case Mn.SINT64:case Mn.SFIXED64:return"bigint (int64)";case Mn.UINT64:case Mn.FIXED64:return"bigint (uint64)";case Mn.BYTES:return"Uint8Array";case Mn.DOUBLE:return"number (float64)";case Mn.FLOAT:return"number (float32)";case Mn.FIXED32:case Mn.UINT32:return"number (uint32)";case Mn.INT32:case Mn.SFIXED32:case Mn.SINT32:return"number (int32)"}}function ZKc(r){return eYc(r.$typeName)}function nCr(r){let t=r.fields[0];return eYc(r.typeName)&&t!==void 0&&t.fieldKind=="scalar"&&t.name=="value"&&t.number==1}function eYc(r){return r.startsWith("google.protobuf.")&&["DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue"].includes(r.substring(16))}var ly1=999,py1=998,iCr=2;function b7o(r,t){if(UOt(t,r))return t;let n=Ay1(r);return t!==void 0&&dy1(r,n,t),n}function dy1(r,t,n){for(let i of r.members){let o=n[i.localName];if(o==null)continue;let s;if(i.kind=="oneof"){let a=V2r(n,i);if(!a)continue;s=a,o=W2r(n,a)}else s=i;switch(s.fieldKind){case"message":o=E7o(s,o);break;case"scalar":o=nYc(s,o);break;case"list":o=hy1(s,o);break;case"map":o=fy1(s,o);break}K2r(t,s,o)}return t}function nYc(r,t){return r.scalar==Mn.BYTES?C7o(t):t}function fy1(r,t){if(CX(t)){if(r.scalar==Mn.BYTES)return tYc(t,C7o);if(r.mapKind=="message")return tYc(t,n=>E7o(r,n))}return t}function hy1(r,t){if(Array.isArray(t)){if(r.scalar==Mn.BYTES)return t.map(C7o);if(r.listKind=="message")return t.map(n=>E7o(r,n))}return t}function E7o(r,t){if(r.fieldKind=="message"&&!r.oneof&&nCr(r.message))return nYc(r.message.fields[0],t);if(CX(t)){if(r.message.typeName=="google.protobuf.Struct"&&r.parent.typeName!=="google.protobuf.Value")return t;if(!UOt(t,r.message))return b7o(r.message,t)}return t}function C7o(r){return Array.isArray(r)?new Uint8Array(r):r}function tYc(r,t){let n={};for(let i of Object.entries(r))n[i[0]]=t(i[1]);return n}var gy1=Symbol(),rYc=new WeakMap;function Ay1(r){let t;if(my1(r)){let n=rYc.get(r),i,o;if(n)({prototype:i,members:o}=n);else{i={},o=new Set;for(let s of r.members)s.kind!="oneof"&&(s.fieldKind!="scalar"&&s.fieldKind!="enum"||s.presence!=iCr&&(o.add(s),i[s.localName]=y7o(s)));rYc.set(r,{prototype:i,members:o})}t=Object.create(i),t.$typeName=r.typeName;for(let s of r.members)o.has(s)||s.kind=="field"&&(s.fieldKind=="message"||(s.fieldKind=="scalar"||s.fieldKind=="enum")&&s.presence!=iCr)||(t[s.localName]=y7o(s))}else{t={$typeName:r.typeName};for(let n of r.members)(n.kind=="oneof"||n.presence==iCr)&&(t[n.localName]=y7o(n))}return t}function my1(r){switch(r.file.edition){case ly1:return!1;case py1:return!0;default:return r.fields.some(t=>t.presence!=iCr&&t.fieldKind!="message"&&!t.oneof)}}function y7o(r){if(r.kind=="oneof")return{case:void 0};if(r.fieldKind=="list")return[];if(r.fieldKind=="map")return{};if(r.fieldKind=="message")return gy1;let t=r.getDefaultValue();return t!==void 0?r.fieldKind=="scalar"&&r.longAsString?t.toString():t:r.fieldKind=="scalar"?vle(r.scalar,r.longAsString):r.enum.values[0].number}function aCr(r,t,n=!0){return new sCr(r,t,n)}var iYc=new WeakMap,sCr=class{get sortedFields(){let t=iYc.get(this.desc);if(t)return t;let n=this.desc.fields.concat().sort((i,o)=>i.number-o.number);return iYc.set(this.desc,n),n}constructor(t,n,i=!0){this.lists=new Map,this.maps=new Map,this.check=i,this.desc=t,this.message=this[oH]=n??b7o(t),this.fields=t.fields,this.oneofs=t.oneofs,this.members=t.members}findNumber(t){return this._fieldsByNumber||(this._fieldsByNumber=new Map(this.desc.fields.map(n=>[n.number,n]))),this._fieldsByNumber.get(t)}oneofCase(t){return GOt(this.message,t),V2r(this.message,t)}isSet(t){return GOt(this.message,t),_Kc(this.message,t)}clear(t){GOt(this.message,t),IKc(this.message,t)}get(t){GOt(this.message,t);let n=W2r(this.message,t);switch(t.fieldKind){case"list":let i=this.lists.get(t);return(!i||i[oH]!==n)&&this.lists.set(t,i=new T7o(t,n,this.check)),i;case"map":let o=this.maps.get(t);return(!o||o[oH]!==n)&&this.maps.set(t,o=new _7o(t,n,this.check)),o;case"message":return R7o(t,n,this.check);case"scalar":return n===void 0?vle(t.scalar,!1):O7o(t,n);case"enum":return n??t.enum.values[0].number}}set(t,n){if(GOt(this.message,t),this.check){let o=WKc(t,n);if(o)throw o}let i;t.fieldKind=="message"?i=I7o(t,n):QOt(n)||zOt(n)?i=n[oH]:i=w7o(t,n),K2r(this.message,t,i)}getUnknown(){return this.message.$unknown}setUnknown(t){this.message.$unknown=t}};function GOt(r,t){if(t.parent.typeName!==r.$typeName)throw new EX(t,`cannot use ${t.toString()} with message ${r.$typeName}`,"ForeignFieldError")}var T7o=class{field(){return this._field}get size(){return this._arr.length}constructor(t,n,i){this._field=t,this._arr=this[oH]=n,this.check=i}get(t){let n=this._arr[t];return n===void 0?void 0:S7o(this._field,n,this.check)}set(t,n){if(t<0||t>=this._arr.length)throw new EX(this._field,`list item #${t+1}: out of range`);if(this.check){let i=A7o(this._field,t,n);if(i)throw i}this._arr[t]=oYc(this._field,n)}add(t){if(this.check){let n=A7o(this._field,this._arr.length,t);if(n)throw n}this._arr.push(oYc(this._field,t))}clear(){this._arr.splice(0,this._arr.length)}[Symbol.iterator](){return this.values()}keys(){return this._arr.keys()}*values(){for(let t of this._arr)yield S7o(this._field,t,this.check)}*entries(){for(let t=0;t<this._arr.length;t++)yield[t,S7o(this._field,this._arr[t],this.check)]}};var _7o=class{constructor(t,n,i=!0){this.obj=this[oH]=n??{},this.check=i,this._field=t}field(){return this._field}set(t,n){if(this.check){let i=KKc(this._field,t,n);if(i)throw i}return this.obj[oCr(t)]=yy1(this._field,n),this}delete(t){let n=oCr(t),i=Object.prototype.hasOwnProperty.call(this.obj,n);return i&&delete this.obj[n],i}clear(){for(let t of Object.keys(this.obj))delete this.obj[t]}get(t){let n=this.obj[oCr(t)];return n!==void 0&&(n=v7o(this._field,n,this.check)),n}has(t){return Object.prototype.hasOwnProperty.call(this.obj,oCr(t))}*keys(){for(let t of Object.keys(this.obj))yield sYc(t,this._field.mapKey)}*entries(){for(let t of Object.entries(this.obj))yield[sYc(t[0],this._field.mapKey),v7o(this._field,t[1],this.check)]}[Symbol.iterator](){return this.entries()}get size(){return Object.keys(this.obj).length}*values(){for(let t of Object.values(this.obj))yield v7o(this._field,t,this.check)}forEach(t,n){for(let i of this.entries())t.call(n,i[1],i[0],this)}};function I7o(r,t){return jOt(t)?ZKc(t.message)&&!r.oneof&&r.fieldKind=="message"?t.message.value:t.desc.typeName=="google.protobuf.Struct"&&r.parent.typeName!="google.protobuf.Value"?uYc(t.message):t.message:t}function R7o(r,t,n){return t!==void 0&&(nCr(r.message)&&!r.oneof&&r.fieldKind=="message"?t={$typeName:r.message.typeName,value:O7o(r.message.fields[0],t)}:r.message.typeName=="google.protobuf.Struct"&&r.parent.typeName!="google.protobuf.Value"&&CX(t)&&(t=aYc(t))),new sCr(r.message,t,n)}function oYc(r,t){return r.listKind=="message"?I7o(r,t):w7o(r,t)}function S7o(r,t,n){return r.listKind=="message"?R7o(r,t,n):O7o(r,t)}function yy1(r,t){return r.mapKind=="message"?I7o(r,t):w7o(r,t)}function v7o(r,t,n){return r.mapKind=="message"?R7o(r,t,n):t}function oCr(r){return typeof r=="string"||typeof r=="number"?r:String(r)}function sYc(r,t){switch(t){case Mn.STRING:return r;case Mn.INT32:case Mn.FIXED32:case Mn.UINT32:case Mn.SFIXED32:case Mn.SINT32:{let n=Number.parseInt(r);if(Number.isFinite(n))return n;break}case Mn.BOOL:switch(r){case"true":return!0;case"false":return!1}break;case Mn.UINT64:case Mn.FIXED64:try{return rC.uParse(r)}catch{}break;default:try{return rC.parse(r)}catch{}break}return r}function O7o(r,t){switch(r.scalar){case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:"longAsString"in r&&r.longAsString&&typeof t=="string"&&(t=rC.parse(t));break;case Mn.FIXED64:case Mn.UINT64:"longAsString"in r&&r.longAsString&&typeof t=="string"&&(t=rC.uParse(t));break}return t}function w7o(r,t){switch(r.scalar){case Mn.INT64:case Mn.SFIXED64:case Mn.SINT64:"longAsString"in r&&r.longAsString?t=String(t):(typeof t=="string"||typeof t=="number")&&(t=rC.parse(t));break;case Mn.FIXED64:case Mn.UINT64:"longAsString"in r&&r.longAsString?t=String(t):(typeof t=="string"||typeof t=="number")&&(t=rC.uParse(t));break}return t}function aYc(r){let t={$typeName:"google.protobuf.Struct",fields:{}};if(CX(r))for(let[n,i]of Object.entries(r))t.fields[n]=lYc(i);return t}function uYc(r){let t={};for(let[n,i]of Object.entries(r.fields))t[n]=cYc(i);return t}function cYc(r){switch(r.kind.case){case"structValue":return uYc(r.kind.value);case"listValue":return r.kind.value.values.map(cYc);case"nullValue":case void 0:return null;default:return r.kind.value}}function lYc(r){let t={$typeName:"google.protobuf.Value",kind:{case:void 0}};switch(typeof r){case"number":t.kind={case:"numberValue",value:r};break;case"string":t.kind={case:"stringValue",value:r};break;case"boolean":t.kind={case:"boolValue",value:r};break;case"object":if(r===null)t.kind={case:"nullValue",value:0};else if(Array.isArray(r)){let n={$typeName:"google.protobuf.ListValue",values:[]};if(Array.isArray(r))for(let i of r)n.values.push(lYc(i));t.kind={case:"listValue",value:n}}else t.kind={case:"structValue",value:aYc(r)};break}return t}function HOt(r,t,...n){return n.reduce((i,o)=>i.nestedMessages[o],r.messages[t])}var M7o=kKc({name:"google/protobuf/descriptor.proto",package:"google.protobuf",messageType:[{name:"FileDescriptorSet",field:[{name:"file",number:1,type:11,label:3,typeName:".google.protobuf.FileDescriptorProto"}],extensionRange:[{start:536e6,end:536000001}]},{name:"FileDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"package",number:2,type:9,label:1},{name:"dependency",number:3,type:9,label:3},{name:"public_dependency",number:10,type:5,label:3},{name:"weak_dependency",number:11,type:5,label:3},{name:"option_dependency",number:15,type:9,label:3},{name:"message_type",number:4,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:5,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"service",number:6,type:11,label:3,typeName:".google.protobuf.ServiceDescriptorProto"},{name:"extension",number:7,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FileOptions"},{name:"source_code_info",number:9,type:11,label:1,typeName:".google.protobuf.SourceCodeInfo"},{name:"syntax",number:12,type:9,label:1},{name:"edition",number:14,type:14,label:1,typeName:".google.protobuf.Edition"}]},{name:"DescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"field",number:2,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"extension",number:6,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"nested_type",number:3,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"extension_range",number:5,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ExtensionRange"},{name:"oneof_decl",number:8,type:11,label:3,typeName:".google.protobuf.OneofDescriptorProto"},{name:"options",number:7,type:11,label:1,typeName:".google.protobuf.MessageOptions"},{name:"reserved_range",number:9,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ReservedRange"},{name:"reserved_name",number:10,type:9,label:3},{name:"visibility",number:11,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"ExtensionRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ExtensionRangeOptions"}]},{name:"ReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"ExtensionRangeOptions",field:[{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"},{name:"declaration",number:2,type:11,label:3,typeName:".google.protobuf.ExtensionRangeOptions.Declaration",options:{retention:2}},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"verification",number:3,type:14,label:1,typeName:".google.protobuf.ExtensionRangeOptions.VerificationState",defaultValue:"UNVERIFIED",options:{retention:2}}],nestedType:[{name:"Declaration",field:[{name:"number",number:1,type:5,label:1},{name:"full_name",number:2,type:9,label:1},{name:"type",number:3,type:9,label:1},{name:"reserved",number:5,type:8,label:1},{name:"repeated",number:6,type:8,label:1}]}],enumType:[{name:"VerificationState",value:[{name:"DECLARATION",number:0},{name:"UNVERIFIED",number:1}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:3,type:5,label:1},{name:"label",number:4,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Label"},{name:"type",number:5,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Type"},{name:"type_name",number:6,type:9,label:1},{name:"extendee",number:2,type:9,label:1},{name:"default_value",number:7,type:9,label:1},{name:"oneof_index",number:9,type:5,label:1},{name:"json_name",number:10,type:9,label:1},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FieldOptions"},{name:"proto3_optional",number:17,type:8,label:1}],enumType:[{name:"Type",value:[{name:"TYPE_DOUBLE",number:1},{name:"TYPE_FLOAT",number:2},{name:"TYPE_INT64",number:3},{name:"TYPE_UINT64",number:4},{name:"TYPE_INT32",number:5},{name:"TYPE_FIXED64",number:6},{name:"TYPE_FIXED32",number:7},{name:"TYPE_BOOL",number:8},{name:"TYPE_STRING",number:9},{name:"TYPE_GROUP",number:10},{name:"TYPE_MESSAGE",number:11},{name:"TYPE_BYTES",number:12},{name:"TYPE_UINT32",number:13},{name:"TYPE_ENUM",number:14},{name:"TYPE_SFIXED32",number:15},{name:"TYPE_SFIXED64",number:16},{name:"TYPE_SINT32",number:17},{name:"TYPE_SINT64",number:18}]},{name:"Label",value:[{name:"LABEL_OPTIONAL",number:1},{name:"LABEL_REPEATED",number:3},{name:"LABEL_REQUIRED",number:2}]}]},{name:"OneofDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"options",number:2,type:11,label:1,typeName:".google.protobuf.OneofOptions"}]},{name:"EnumDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"value",number:2,type:11,label:3,typeName:".google.protobuf.EnumValueDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumOptions"},{name:"reserved_range",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto.EnumReservedRange"},{name:"reserved_name",number:5,type:9,label:3},{name:"visibility",number:6,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"EnumReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"EnumValueDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumValueOptions"}]},{name:"ServiceDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"method",number:2,type:11,label:3,typeName:".google.protobuf.MethodDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ServiceOptions"}]},{name:"MethodDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"input_type",number:2,type:9,label:1},{name:"output_type",number:3,type:9,label:1},{name:"options",number:4,type:11,label:1,typeName:".google.protobuf.MethodOptions"},{name:"client_streaming",number:5,type:8,label:1,defaultValue:"false"},{name:"server_streaming",number:6,type:8,label:1,defaultValue:"false"}]},{name:"FileOptions",field:[{name:"java_package",number:1,type:9,label:1},{name:"java_outer_classname",number:8,type:9,label:1},{name:"java_multiple_files",number:10,type:8,label:1,defaultValue:"false",options:{}},{name:"java_generate_equals_and_hash",number:20,type:8,label:1,options:{deprecated:!0}},{name:"java_string_check_utf8",number:27,type:8,label:1,defaultValue:"false"},{name:"optimize_for",number:9,type:14,label:1,typeName:".google.protobuf.FileOptions.OptimizeMode",defaultValue:"SPEED"},{name:"go_package",number:11,type:9,label:1},{name:"cc_generic_services",number:16,type:8,label:1,defaultValue:"false"},{name:"java_generic_services",number:17,type:8,label:1,defaultValue:"false"},{name:"py_generic_services",number:18,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:23,type:8,label:1,defaultValue:"false"},{name:"cc_enable_arenas",number:31,type:8,label:1,defaultValue:"true"},{name:"objc_class_prefix",number:36,type:9,label:1},{name:"csharp_namespace",number:37,type:9,label:1},{name:"swift_prefix",number:39,type:9,label:1},{name:"php_class_prefix",number:40,type:9,label:1},{name:"php_namespace",number:41,type:9,label:1},{name:"php_metadata_namespace",number:44,type:9,label:1},{name:"ruby_package",number:45,type:9,label:1},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"OptimizeMode",value:[{name:"SPEED",number:1},{name:"CODE_SIZE",number:2},{name:"LITE_RUNTIME",number:3}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"MessageOptions",field:[{name:"message_set_wire_format",number:1,type:8,label:1,defaultValue:"false"},{name:"no_standard_descriptor_accessor",number:2,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"map_entry",number:7,type:8,label:1},{name:"deprecated_legacy_json_field_conflicts",number:11,type:8,label:1,options:{deprecated:!0}},{name:"features",number:12,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldOptions",field:[{name:"ctype",number:1,type:14,label:1,typeName:".google.protobuf.FieldOptions.CType",defaultValue:"STRING"},{name:"packed",number:2,type:8,label:1},{name:"jstype",number:6,type:14,label:1,typeName:".google.protobuf.FieldOptions.JSType",defaultValue:"JS_NORMAL"},{name:"lazy",number:5,type:8,label:1,defaultValue:"false"},{name:"unverified_lazy",number:15,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"weak",number:10,type:8,label:1,defaultValue:"false",options:{deprecated:!0}},{name:"debug_redact",number:16,type:8,label:1,defaultValue:"false"},{name:"retention",number:17,type:14,label:1,typeName:".google.protobuf.FieldOptions.OptionRetention"},{name:"targets",number:19,type:14,label:3,typeName:".google.protobuf.FieldOptions.OptionTargetType"},{name:"edition_defaults",number:20,type:11,label:3,typeName:".google.protobuf.FieldOptions.EditionDefault"},{name:"features",number:21,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"feature_support",number:22,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],nestedType:[{name:"EditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"value",number:2,type:9,label:1}]},{name:"FeatureSupport",field:[{name:"edition_introduced",number:1,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"edition_deprecated",number:2,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"deprecation_warning",number:3,type:9,label:1},{name:"edition_removed",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"removal_error",number:5,type:9,label:1}]}],enumType:[{name:"CType",value:[{name:"STRING",number:0},{name:"CORD",number:1},{name:"STRING_PIECE",number:2}]},{name:"JSType",value:[{name:"JS_NORMAL",number:0},{name:"JS_STRING",number:1},{name:"JS_NUMBER",number:2}]},{name:"OptionRetention",value:[{name:"RETENTION_UNKNOWN",number:0},{name:"RETENTION_RUNTIME",number:1},{name:"RETENTION_SOURCE",number:2}]},{name:"OptionTargetType",value:[{name:"TARGET_TYPE_UNKNOWN",number:0},{name:"TARGET_TYPE_FILE",number:1},{name:"TARGET_TYPE_EXTENSION_RANGE",number:2},{name:"TARGET_TYPE_MESSAGE",number:3},{name:"TARGET_TYPE_FIELD",number:4},{name:"TARGET_TYPE_ONEOF",number:5},{name:"TARGET_TYPE_ENUM",number:6},{name:"TARGET_TYPE_ENUM_ENTRY",number:7},{name:"TARGET_TYPE_SERVICE",number:8},{name:"TARGET_TYPE_METHOD",number:9}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"OneofOptions",field:[{name:"features",number:1,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumOptions",field:[{name:"allow_alias",number:2,type:8,label:1},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"deprecated_legacy_json_field_conflicts",number:6,type:8,label:1,options:{deprecated:!0}},{name:"features",number:7,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumValueOptions",field:[{name:"deprecated",number:1,type:8,label:1,defaultValue:"false"},{name:"features",number:2,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"debug_redact",number:3,type:8,label:1,defaultValue:"false"},{name:"feature_support",number:4,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"ServiceOptions",field:[{name:"features",number:34,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"MethodOptions",field:[{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"idempotency_level",number:34,type:14,label:1,typeName:".google.protobuf.MethodOptions.IdempotencyLevel",defaultValue:"IDEMPOTENCY_UNKNOWN"},{name:"features",number:35,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"IdempotencyLevel",value:[{name:"IDEMPOTENCY_UNKNOWN",number:0},{name:"NO_SIDE_EFFECTS",number:1},{name:"IDEMPOTENT",number:2}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"UninterpretedOption",field:[{name:"name",number:2,type:11,label:3,typeName:".google.protobuf.UninterpretedOption.NamePart"},{name:"identifier_value",number:3,type:9,label:1},{name:"positive_int_value",number:4,type:4,label:1},{name:"negative_int_value",number:5,type:3,label:1},{name:"double_value",number:6,type:1,label:1},{name:"string_value",number:7,type:12,label:1},{name:"aggregate_value",number:8,type:9,label:1}],nestedType:[{name:"NamePart",field:[{name:"name_part",number:1,type:9,label:2},{name:"is_extension",number:2,type:8,label:2}]}]},{name:"FeatureSet",field:[{name:"field_presence",number:1,type:14,label:1,typeName:".google.protobuf.FeatureSet.FieldPresence",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPLICIT",edition:900},{value:"IMPLICIT",edition:999},{value:"EXPLICIT",edition:1e3}]}},{name:"enum_type",number:2,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnumType",options:{retention:1,targets:[6,1],editionDefaults:[{value:"CLOSED",edition:900},{value:"OPEN",edition:999}]}},{name:"repeated_field_encoding",number:3,type:14,label:1,typeName:".google.protobuf.FeatureSet.RepeatedFieldEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPANDED",edition:900},{value:"PACKED",edition:999}]}},{name:"utf8_validation",number:4,type:14,label:1,typeName:".google.protobuf.FeatureSet.Utf8Validation",options:{retention:1,targets:[4,1],editionDefaults:[{value:"NONE",edition:900},{value:"VERIFY",edition:999}]}},{name:"message_encoding",number:5,type:14,label:1,typeName:".google.protobuf.FeatureSet.MessageEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"LENGTH_PREFIXED",edition:900}]}},{name:"json_format",number:6,type:14,label:1,typeName:".google.protobuf.FeatureSet.JsonFormat",options:{retention:1,targets:[3,6,1],editionDefaults:[{value:"LEGACY_BEST_EFFORT",edition:900},{value:"ALLOW",edition:999}]}},{name:"enforce_naming_style",number:7,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnforceNamingStyle",options:{retention:2,targets:[1,2,3,4,5,6,7,8,9],editionDefaults:[{value:"STYLE_LEGACY",edition:900},{value:"STYLE2024",edition:1001}]}},{name:"default_symbol_visibility",number:8,type:14,label:1,typeName:".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility",options:{retention:2,targets:[1],editionDefaults:[{value:"EXPORT_ALL",edition:900},{value:"EXPORT_TOP_LEVEL",edition:1001}]}}],nestedType:[{name:"VisibilityFeature",enumType:[{name:"DefaultSymbolVisibility",value:[{name:"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",number:0},{name:"EXPORT_ALL",number:1},{name:"EXPORT_TOP_LEVEL",number:2},{name:"LOCAL_ALL",number:3},{name:"STRICT",number:4}]}]}],enumType:[{name:"FieldPresence",value:[{name:"FIELD_PRESENCE_UNKNOWN",number:0},{name:"EXPLICIT",number:1},{name:"IMPLICIT",number:2},{name:"LEGACY_REQUIRED",number:3}]},{name:"EnumType",value:[{name:"ENUM_TYPE_UNKNOWN",number:0},{name:"OPEN",number:1},{name:"CLOSED",number:2}]},{name:"RepeatedFieldEncoding",value:[{name:"REPEATED_FIELD_ENCODING_UNKNOWN",number:0},{name:"PACKED",number:1},{name:"EXPANDED",number:2}]},{name:"Utf8Validation",value:[{name:"UTF8_VALIDATION_UNKNOWN",number:0},{name:"VERIFY",number:2},{name:"NONE",number:3}]},{name:"MessageEncoding",value:[{name:"MESSAGE_ENCODING_UNKNOWN",number:0},{name:"LENGTH_PREFIXED",number:1},{name:"DELIMITED",number:2}]},{name:"JsonFormat",value:[{name:"JSON_FORMAT_UNKNOWN",number:0},{name:"ALLOW",number:1},{name:"LEGACY_BEST_EFFORT",number:2}]},{name:"EnforceNamingStyle",value:[{name:"ENFORCE_NAMING_STYLE_UNKNOWN",number:0},{name:"STYLE2024",number:1},{name:"STYLE_LEGACY",number:2}]}],extensionRange:[{start:1e3,end:9995},{start:9995,end:1e4},{start:1e4,end:10001}]},{name:"FeatureSetDefaults",field:[{name:"defaults",number:1,type:11,label:3,typeName:".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"},{name:"minimum_edition",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"maximum_edition",number:5,type:14,label:1,typeName:".google.protobuf.Edition"}],nestedType:[{name:"FeatureSetEditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"overridable_features",number:4,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"fixed_features",number:5,type:11,label:1,typeName:".google.protobuf.FeatureSet"}]}]},{name:"SourceCodeInfo",field:[{name:"location",number:1,type:11,label:3,typeName:".google.protobuf.SourceCodeInfo.Location"}],nestedType:[{name:"Location",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"span",number:2,type:5,label:3,options:{packed:!0}},{name:"leading_comments",number:3,type:9,label:1},{name:"trailing_comments",number:4,type:9,label:1},{name:"leading_detached_comments",number:6,type:9,label:3}]}],extensionRange:[{start:536e6,end:536000001}]},{name:"GeneratedCodeInfo",field:[{name:"annotation",number:1,type:11,label:3,typeName:".google.protobuf.GeneratedCodeInfo.Annotation"}],nestedType:[{name:"Annotation",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"source_file",number:2,type:9,label:1},{name:"begin",number:3,type:5,label:1},{name:"end",number:4,type:5,label:1},{name:"semantic",number:5,type:14,label:1,typeName:".google.protobuf.GeneratedCodeInfo.Annotation.Semantic"}],enumType:[{name:"Semantic",value:[{name:"NONE",number:0},{name:"SET",number:1},{name:"ALIAS",number:2}]}]}]}],enumType:[{name:"Edition",value:[{name:"EDITION_UNKNOWN",number:0},{name:"EDITION_LEGACY",number:900},{name:"EDITION_PROTO2",number:998},{name:"EDITION_PROTO3",number:999},{name:"EDITION_2023",number:1e3},{name:"EDITION_2024",number:1001},{name:"EDITION_UNSTABLE",number:9999},{name:"EDITION_1_TEST_ONLY",number:1},{name:"EDITION_2_TEST_ONLY",number:2},{name:"EDITION_99997_TEST_ONLY",number:99997},{name:"EDITION_99998_TEST_ONLY",number:99998},{name:"EDITION_99999_TEST_ONLY",number:99999},{name:"EDITION_MAX",number:2147483647}]},{name:"SymbolVisibility",value:[{name:"VISIBILITY_UNSET",number:0},{name:"VISIBILITY_LOCAL",number:1},{name:"VISIBILITY_EXPORT",number:2}]}]});var xYc=HOt(M7o,1);var pYc;(function(r){r[r.DECLARATION=0]="DECLARATION",r[r.UNVERIFIED=1]="UNVERIFIED"})(pYc||(pYc={}));var dYc;(function(r){r[r.DOUBLE=1]="DOUBLE",r[r.FLOAT=2]="FLOAT",r[r.INT64=3]="INT64",r[r.UINT64=4]="UINT64",r[r.INT32=5]="INT32",r[r.FIXED64=6]="FIXED64",r[r.FIXED32=7]="FIXED32",r[r.BOOL=8]="BOOL",r[r.STRING=9]="STRING",r[r.GROUP=10]="GROUP",r[r.MESSAGE=11]="MESSAGE",r[r.BYTES=12]="BYTES",r[r.UINT32=13]="UINT32",r[r.ENUM=14]="ENUM",r[r.SFIXED32=15]="SFIXED32",r[r.SFIXED64=16]="SFIXED64",r[r.SINT32=17]="SINT32",r[r.SINT64=18]="SINT64"})(dYc||(dYc={}));var fYc;(function(r){r[r.OPTIONAL=1]="OPTIONAL",r[r.REPEATED=3]="REPEATED",r[r.REQUIRED=2]="REQUIRED"})(fYc||(fYc={}));var hYc;(function(r){r[r.SPEED=1]="SPEED",r[r.CODE_SIZE=2]="CODE_SIZE",r[r.LITE_RUNTIME=3]="LITE_RUNTIME"})(hYc||(hYc={}));var gYc;(function(r){r[r.STRING=0]="STRING",r[r.CORD=1]="CORD",r[r.STRING_PIECE=2]="STRING_PIECE"})(gYc||(gYc={}));var AYc;(function(r){r[r.JS_NORMAL=0]="JS_NORMAL",r[r.JS_STRING=1]="JS_STRING",r[r.JS_NUMBER=2]="JS_NUMBER"})(AYc||(AYc={}));var mYc;(function(r){r[r.RETENTION_UNKNOWN=0]="RETENTION_UNKNOWN",r[r.RETENTION_RUNTIME=1]="RETENTION_RUNTIME",r[r.RETENTION_SOURCE=2]="RETENTION_SOURCE"})(mYc||(mYc={}));var yYc;(function(r){r[r.TARGET_TYPE_UNKNOWN=0]="TARGET_TYPE_UNKNOWN",r[r.TARGET_TYPE_FILE=1]="TARGET_TYPE_FILE",r[r.TARGET_TYPE_EXTENSION_RANGE=2]="TARGET_TYPE_EXTENSION_RANGE",r[r.TARGET_TYPE_MESSAGE=3]="TARGET_TYPE_MESSAGE",r[r.TARGET_TYPE_FIELD=4]="TARGET_TYPE_FIELD",r[r.TARGET_TYPE_ONEOF=5]="TARGET_TYPE_ONEOF",r[r.TARGET_TYPE_ENUM=6]="TARGET_TYPE_ENUM",r[r.TARGET_TYPE_ENUM_ENTRY=7]="TARGET_TYPE_ENUM_ENTRY",r[r.TARGET_TYPE_SERVICE=8]="TARGET_TYPE_SERVICE",r[r.TARGET_TYPE_METHOD=9]="TARGET_TYPE_METHOD"})(yYc||(yYc={}));var bYc;(function(r){r[r.IDEMPOTENCY_UNKNOWN=0]="IDEMPOTENCY_UNKNOWN",r[r.NO_SIDE_EFFECTS=1]="NO_SIDE_EFFECTS",r[r.IDEMPOTENT=2]="IDEMPOTENT"})(bYc||(bYc={}));var EYc;(function(r){r[r.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0]="DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",r[r.EXPORT_ALL=1]="EXPORT_ALL",r[r.EXPORT_TOP_LEVEL=2]="EXPORT_TOP_LEVEL",r[r.LOCAL_ALL=3]="LOCAL_ALL",r[r.STRICT=4]="STRICT"})(EYc||(EYc={}));var CYc;(function(r){r[r.FIELD_PRESENCE_UNKNOWN=0]="FIELD_PRESENCE_UNKNOWN",r[r.EXPLICIT=1]="EXPLICIT",r[r.IMPLICIT=2]="IMPLICIT",r[r.LEGACY_REQUIRED=3]="LEGACY_REQUIRED"})(CYc||(CYc={}));var SYc;(function(r){r[r.ENUM_TYPE_UNKNOWN=0]="ENUM_TYPE_UNKNOWN",r[r.OPEN=1]="OPEN",r[r.CLOSED=2]="CLOSED"})(SYc||(SYc={}));var vYc;(function(r){r[r.REPEATED_FIELD_ENCODING_UNKNOWN=0]="REPEATED_FIELD_ENCODING_UNKNOWN",r[r.PACKED=1]="PACKED",r[r.EXPANDED=2]="EXPANDED"})(vYc||(vYc={}));var TYc;(function(r){r[r.UTF8_VALIDATION_UNKNOWN=0]="UTF8_VALIDATION_UNKNOWN",r[r.VERIFY=2]="VERIFY",r[r.NONE=3]="NONE"})(TYc||(TYc={}));var _Yc;(function(r){r[r.MESSAGE_ENCODING_UNKNOWN=0]="MESSAGE_ENCODING_UNKNOWN",r[r.LENGTH_PREFIXED=1]="LENGTH_PREFIXED",r[r.DELIMITED=2]="DELIMITED"})(_Yc||(_Yc={}));var IYc;(function(r){r[r.JSON_FORMAT_UNKNOWN=0]="JSON_FORMAT_UNKNOWN",r[r.ALLOW=1]="ALLOW",r[r.LEGACY_BEST_EFFORT=2]="LEGACY_BEST_EFFORT"})(IYc||(IYc={}));var RYc;(function(r){r[r.ENFORCE_NAMING_STYLE_UNKNOWN=0]="ENFORCE_NAMING_STYLE_UNKNOWN",r[r.STYLE2024=1]="STYLE2024",r[r.STYLE_LEGACY=2]="STYLE_LEGACY"})(RYc||(RYc={}));var OYc;(function(r){r[r.NONE=0]="NONE",r[r.SET=1]="SET",r[r.ALIAS=2]="ALIAS"})(OYc||(OYc={}));var wYc;(function(r){r[r.EDITION_UNKNOWN=0]="EDITION_UNKNOWN",r[r.EDITION_LEGACY=900]="EDITION_LEGACY",r[r.EDITION_PROTO2=998]="EDITION_PROTO2",r[r.EDITION_PROTO3=999]="EDITION_PROTO3",r[r.EDITION_2023=1e3]="EDITION_2023",r[r.EDITION_2024=1001]="EDITION_2024",r[r.EDITION_UNSTABLE=9999]="EDITION_UNSTABLE",r[r.EDITION_1_TEST_ONLY=1]="EDITION_1_TEST_ONLY",r[r.EDITION_2_TEST_ONLY=2]="EDITION_2_TEST_ONLY",r[r.EDITION_99997_TEST_ONLY=99997]="EDITION_99997_TEST_ONLY",r[r.EDITION_99998_TEST_ONLY=99998]="EDITION_99998_TEST_ONLY",r[r.EDITION_99999_TEST_ONLY=99999]="EDITION_99999_TEST_ONLY",r[r.EDITION_MAX=2147483647]="EDITION_MAX"})(wYc||(wYc={}));var MYc;(function(r){r[r.VISIBILITY_UNSET=0]="VISIBILITY_UNSET",r[r.VISIBILITY_LOCAL=1]="VISIBILITY_LOCAL",r[r.VISIBILITY_EXPORT=2]="VISIBILITY_EXPORT"})(MYc||(MYc={}));var PYc={readUnknownFields:!0};function by1(r){return r?Object.assign(Object.assign({},PYc),r):PYc}function NYc(r,t,n){let i=aCr(r,void 0,!1);return DYc(i,new eCr(t),by1(n),!1,t.byteLength),i.message}function DYc(r,t,n,i,o){var s;let a=i?t.len:t.pos+o,u,p,c=(s=r.getUnknown())!==null&&s!==void 0?s:[];for(;t.pos<a&&([u,p]=t.tag(),!(i&&p==hF.EndGroup));){let l=r.findNumber(u);if(!l){let d=t.skip(p,u);n.readUnknownFields&&c.push({no:u,wireType:p,data:d});continue}Ey1(r,t,l,p,n)}if(i&&(p!=hF.EndGroup||u!==o))throw new Error("invalid end group tag");c.length>0&&r.setUnknown(c)}function Ey1(r,t,n,i,o){var s;switch(n.fieldKind){case"scalar":r.set(n,L$e(t,n.scalar,n.utf8Validation));break;case"enum":let a=L$e(t,Mn.INT32);if(n.enum.open)r.set(n,a);else if(n.enum.values.some(p=>p.number===a))r.set(n,a);else if(o.readUnknownFields){let p=[];c7o(a,p);let c=(s=r.getUnknown())!==null&&s!==void 0?s:[];c.push({no:n.number,wireType:i,data:new Uint8Array(p)}),r.setUnknown(c)}break;case"message":r.set(n,x7o(t,o,n,r.get(n)));break;case"list":Sy1(t,i,r.get(n),o);break;case"map":Cy1(t,r.get(n),o);break}}function Cy1(r,t,n){let i=t.field(),o,s,a=r.uint32(),u=r.pos+a;for(;r.pos<u;){let[p]=r.tag();switch(p){case 1:o=L$e(r,i.mapKey,i.utf8Validation);break;case 2:switch(i.mapKind){case"scalar":s=L$e(r,i.scalar,i.utf8Validation);break;case"enum":s=r.int32();break;case"message":s=x7o(r,n,i);break}break}}if(o===void 0&&(o=vle(i.mapKey,!1)),s===void 0)switch(i.mapKind){case"scalar":s=vle(i.scalar,!1);break;case"enum":s=i.enum.values[0].number;break;case"message":s=aCr(i.message,void 0,!1);break}t.set(o,s)}function Sy1(r,t,n,i){var o;let s=n.field();if(s.listKind==="message"){n.add(x7o(r,i,s));return}let a=(o=s.scalar)!==null&&o!==void 0?o:Mn.INT32;if(!(t==hF.LengthDelimited&&a!=Mn.STRING&&a!=Mn.BYTES)){n.add(L$e(r,a,s.utf8Validation));return}let p=r.uint32()+r.pos;for(;r.pos<p;)n.add(L$e(r,a,s.utf8Validation))}function x7o(r,t,n,i){let o=n.delimitedEncoding,s=i??aCr(n.message,void 0,!1);return DYc(s,r,t,o,o?n.number:r.uint32()),s}function L$e(r,t,n=!1){switch(t){case Mn.STRING:return r.string(n);case Mn.BOOL:return r.bool();case Mn.DOUBLE:return r.double();case Mn.FLOAT:return r.float();case Mn.INT32:return r.int32();case Mn.INT64:return r.int64();case Mn.UINT64:return r.uint64();case Mn.FIXED64:return r.fixed64();case Mn.BYTES:return r.bytes();case Mn.FIXED32:return r.fixed32();case Mn.SFIXED32:return r.sfixed32();case Mn.SFIXED64:return r.sfixed64();case Mn.SINT64:return r.sint64();case Mn.UINT32:return r.uint32();case Mn.SINT32:return r.sint32()}}function SX(r,t){var n;let i=NYc(xYc,zKc(r));return i.messageType.forEach(kOt),i.dependency=(n=t?.map(s=>s.proto.name))!==null&&n!==void 0?n:[],J2r(i,s=>t?.find(a=>a.proto.name===s)).getFile(i.name)}var BYc=SX("Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJvdG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MYAiABKAVChQEKE2NvbS5nb29nbGUucHJvdG9idWZCDlRpbWVzdGFtcFByb3RvUAFaMmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3RpbWVzdGFtcHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM");var LYc=SX("Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIgASgFQoMBChNjb20uZ29vZ2xlLnByb3RvYnVmQg1EdXJhdGlvblByb3RvUAFaMWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2R1cmF0aW9ucGL4A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A0IHukgEIgIoABIVCg10YXJnZXRfdGFibGVzGAQgAygJIlcKCUpvYkZhaWxlZBIXCgZqb2JfaWQYASABKAlCB7pIBHICEAESGwoKZXJyb3JfY29kZRgCIAEoCUIHukgEcgIQARIUCgxmYWlsZWRfbm9kZXMYAyADKAliBnByb3RvMw",[qYc]),N7o=HOt(P7o,0),D7o=HOt(P7o,1);var GO1=yt(Ftl(),1);var HO1=yt(ztl(),1);var iK2=1440*60;var Xvr=class{constructor(t){this.logOptions=t;this.startTime=performance.now()}logOptions;phases=new Map;queries=[];startTime;startPhase(t){this.phases.set(t,{startTime:performance.now()})}endPhase(t){let n=this.phases.get(t);n&&!n.endTime&&(n.endTime=performance.now()),n||this.logOptions?.logger.errorContext(this.logOptions.context,"AnalyticsCollector.endPhase",`Phase ${t} not found`)}getPhaseDuration(t){let n=this.phases.get(t);if(n&&n.endTime){if(typeof n.startTime!="number"){this.logOptions?.logger.errorContext(this.logOptions.context,"AnalyticsCollector.getPhaseDuration",`Phase ${t} has an end time but start time was type of ${typeof n.startTime} - this should never happen`);return}return Math.round(n.endTime-n.startTime)}}addQueryTiming(t,n,i,o,s){this.queries.push({nodeId:t,stageName:n,durationMs:Math.round(i),success:o,executedAt:s})}getTotalDuration(){return Math.round(performance.now()-this.startTime)}getTotalQueryDuration(){return this.queries.reduce((t,n)=>t+n.durationMs,0)}stripUndefined(t){return Object.fromEntries(Object.entries(t).filter(([n,i])=>i!==void 0))}getQueryCount(){return this.queries.length}getQueries(){return this.queries}},Zvr=class extends Xvr{toPlanAnalytics(t){return{createdAt:new Date,workspaceID:t,totalDurationMs:this.getTotalDuration(),phases:this.stripUndefined({presyncDurationMs:this.getPhaseDuration("presync"),contextUploadDurationMs:this.getPhaseDuration("store plan context"),jinjaRenderingDurationMs:this.getPhaseDuration("render nodes"),schemasDurationMs:this.getPhaseDuration("schemas"),nodeEditsDurationMs:this.getPhaseDuration("node edits"),buildDependenciesDurationMs:this.getPhaseDuration("build dependencies & edits")})}}},eTr=class extends Xvr{toRunAnalyticsDocs(t,n){let i={runType:n,totalDurationMs:this.getTotalDuration(),createdAt:new Date,...this.stripUndefined({planID:t,totalQueryExecutionDurationMs:this.getTotalQueryDuration(),queryCount:this.getQueries().length})},o=this.stripUndefined({beforeRunDurationMs:this.getPhaseDuration("beforeRun"),afterRunDurationMs:this.getPhaseDuration("afterRun"),pipelineExecutionDurationMs:this.getPhaseDuration("pipeline execution"),initializeStepsDurationMs:this.getPhaseDuration("initializeSteps"),runExecutionDurationMs:this.getPhaseDuration("runExecution")}),s;if(n==="refresh"||n==="devRun"){let u=this.getPhaseDuration("rendering all nodes"),p=this.getPhaseDuration("building dependencies"),c;(u!==void 0||p!==void 0)&&(c=(u??0)+(p??0)),s=this.stripUndefined({renderingDurationMs:u,dependencyBuildingDurationMs:p,totalPlanDurationMs:c})}let a=this.getQueries().map(u=>({nodeId:u.nodeId,stageName:u.stageName,durationMs:u.durationMs,success:u.success,executedAt:u.executedAt}));return{summary:i,runPhases:o,planPhases:s,queries:a}}};var pK2=B.object({}).partial().passthrough(),VO1=B.object({orgID:B.string(),planID:B.string()}).partial().passthrough(),lf=B.object({error:B.object({errorString:B.string()})}),Qtl=B.object({environmentID:B.string(),nodeID:B.string(),hash:B.string(),ref:B.string()}).passthrough(),WO1=B.object({renderedRefs:B.array(Qtl)}).passthrough(),KO1=B.object({renderedRefs:B.array(Qtl)}).passthrough(),dK2=B.string(),iQo=B.object({workspaceID:B.string(),status:B.enum(["Waiting","Deploying","Refreshing","Failed Deploy"]),currentlyRunningJobs:B.array(B.number()),currentlyRunningDevJobs:B.array(B.number())}).passthrough(),tMt=B.object({status:B.array(iQo)}).partial().passthrough(),YO1=B.object({workspaceID:B.string(),deployStatus:B.enum(["waiting","failed"]).describe("Optional initial deploy status for the workspace. Used to seed the correct state when auto-creating from an existing Firestore workspace.").optional()}).passthrough(),JO1=B.object({workspaceID:B.string(),runID:B.string(),runType:B.enum(["deploy","refresh","dev"]),createdAt:B.string().datetime({offset:!0})}).passthrough(),$O1=B.object({workspaceRuns:B.array(JO1)}).passthrough(),XO1=B.object({runID:B.string().describe("The run ID to use when submitting an event for an existing run ID - ignored for `start_*` events and required for `complete_*/fail_*/cancel_*` events").optional(),workspaceID:B.string(),event:B.enum(["start_deploy","start_refresh","start_dev","complete_deploy","complete_refresh","complete_dev","fail_deploy","fail_refresh","fail_dev","cancel_refresh","force_start_deploy","force_start_refresh"])}).passthrough(),fK2=B.object({workspaceID:B.string()}).passthrough(),ZO1=B.object({reset:B.boolean().describe("Whether a stuck workspace was actually reset to Waiting"),reason:B.enum(["not_transitional","runs_present"]).describe("When reset is false, why no action was taken").optional(),status:B.array(iQo)}).passthrough(),ew1=B.object({workspaceID:B.string(),runID:B.string(),runType:B.enum(["deploy","refresh","dev"]).describe("Run type of the row to evict. Required to disambiguate dev vs deploy/refresh rows, which use separate run-ID counters and can share a numeric runID within a workspace.")}).passthrough(),tw1=B.object({evicted:B.boolean().describe("true if a workspace_runs row was deleted; false if no matching row existed (idempotent no-op)"),status:B.array(iQo)}).passthrough(),rw1=B.object({orgID:B.string().describe("Optional org override (requires superuser)").optional(),workspaceID:B.string(),status:B.enum(["Waiting","Deploying","Refreshing","Failed Deploy"]).describe("One of Waiting, Deploying, Refreshing, Failed Deploy")}).passthrough();var jtl=vgr([{method:"post",path:"/v1/evict_workspace_run",alias:"evictWorkspaceRun",description:"Reconciliation eviction (cleanup tool). Deletes a workspace_runs row whose run firestore no longer tracks as running, without attributing success or failure to the run. Clears only an unbacked transitional (running) status to waiting; preserves a failed deploy_status and any dimension still backed by a remaining run. Locked + idempotent server-side - no-op if the row is already gone. Scoped to the auth-context org. Used by the cleanup tool.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:ew1}],response:tw1,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/plan",alias:"createPlan",description:"Create a plan",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:B.object({}).partial().passthrough()}],response:VO1,errors:[{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/rendered_refs",alias:"getRenderedRefs",description:"Get rendered refs",requestFormat:"json",parameters:[{name:"environmentID",type:"Query",schema:B.string().describe("Environment to check for cached rendered refs")}],response:WO1,errors:[{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/rendered_refs",alias:"postRenderedRefs",description:"Post rendered refs",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:KO1}],response:B.string(),errors:[{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/reset_stuck_workspace_status",alias:"resetStuckWorkspaceStatus",description:"Conditionally reset a workspace stuck in a transitional state (Deploying/Refreshing) with zero workspace_runs rows back to Waiting. Locked and conditional server-side - no-ops if the workspace is not actually stuck. Scoped to the auth-context org. Used by the cleanup tool.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:B.object({workspaceID:B.string()}).passthrough()}],response:ZO1,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/stuck_workspace_statuses",alias:"listStuckWorkspaceStatuses",description:"List workspaces stuck in a transitional state (Deploying/Refreshing) with zero workspace_runs rows for the auth-context org. Detected via a single postgres join. Used by the cleanup tool to find workspaces needing a reset.",requestFormat:"json",response:tMt,errors:[{status:403,description:"Forbidden",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/support_workspace_status",alias:"setWorkspaceStatus",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:rw1}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/workspace_run_event",alias:"postWorkspaceRunEvent",description:"Post a workspace run event and return the resulting workspace_run_status - no state is persisted; status is computed and returned",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:XO1}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/workspace_run_status",alias:"listWorkspaceStatuses",description:"Get run status for workspaces",requestFormat:"json",parameters:[{name:"workspaceID",type:"Query",schema:B.string().describe("Workspace ID").optional()}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"post",path:"/v1/workspace_run_status",alias:"createWorkspaceStatus",description:"Create a workspace status row",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:YO1}],response:tMt,errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:409,description:"Conflict",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"delete",path:"/v1/workspace_run_status",alias:"deleteWorkspaceStatus",description:"Delete a workspace status row and its associated workspace runs",requestFormat:"json",parameters:[{name:"workspaceID",type:"Query",schema:B.string().describe("Workspace ID")}],response:B.void(),errors:[{status:400,description:"Bad Request",schema:lf},{status:403,description:"Forbidden",schema:lf},{status:404,description:"Workspace not found",schema:lf},{status:500,description:"Internal Error",schema:lf}]},{method:"get",path:"/v1/workspace_runs",alias:"listWorkspaceRunsForOrg",description:"List all workspace_runs rows for the auth-context org. Used by the cleanup tool to detect orphaned postgres rows that no longer correspond to a live Firestore Run doc.",requestFormat:"json",response:$O1,errors:[{status:403,description:"Forbidden",schema:lf},{status:500,description:"Internal Error",schema:lf}]}]),hK2=new gYe(jtl);function Gtl(r,t){return new gYe(r,jtl,t)}var vDe=r=>{try{if(!r&&!Xc.isInitialized)throw Je("COMMON").fatal("Deploy service client requires authentication! Provide explicit token or ensure ClientAuthService is initialized"),new nt("Deploy service client cannot be created without authentication");let t=jEt(),n=Gtl(`${t}/api/deploy`);return n.use(z4e({getToken:r?async()=>r:Xc.resolveAuthToken})),n}catch(t){throw t instanceof rue?(Je("COMMON").error("Deploy Service configuration error",t.diagnostics),new nt("Unable to connect to Coalesce Deploy Service. Please check your configuration and ensure you are properly authenticated.")):t}};var kle=Je("SERVICE_WORKSPACE_STATUS"),nw1=(r,t)=>r==="deploy"?t?"force_start_deploy":"start_deploy":r==="refresh"?t?"force_start_refresh":"start_refresh":"start_dev",iw1=(r,t)=>r==="deploy"?t?"complete_deploy":"fail_deploy":r==="refresh"?t?"complete_refresh":"fail_refresh":t?"complete_dev":"fail_dev",Htl=r=>({retryStrategy:{name:"backoff",base:1},checkError:t=>{if(!N1(t)||t.response&&t.response.status<500)return t},logOnRetry:`${r} retrying after transient failure`,retryLogLevel:"info",logOnFailure:`${r} failed, request never resolved after maximum allowed retries.`}),ow1=async(r,t,n,i)=>{let o="[ensureWorkspaceStatus]";try{await r.createWorkspaceStatus({workspaceID:t,deployStatus:i}),kle.infoContext(n,o,"ensured workspace status (created)",{workspaceID:t,initialDeployStatus:i})}catch(s){if(sw1(s)){kle.infoContext(n,o,"The workspace was already migrated to the deploy service and was not (re)created - continuing",s);return}throw s}},Vtl=async(r,t,n,i,o,s,a)=>{let u=`[postWorkspaceStartEvent][ws=${r}][run=${t}]`,p={...o,workspaceID:Number(r),runID:Number(t)};kle.infoContext(p,u,"getting deploy service client.",s?"with auth token":"without auth token");let c=vDe(s),l=nw1(n,i),d=a?a==="Failed Deploy"?"failed":"waiting":void 0;await cf(async()=>{await ow1(c,r,p,d),kle.infoContext(p,u,"posting start event...",{event:l,runID:t}),await c.postWorkspaceRunEvent({workspaceID:r,event:l,runID:t}),kle.infoContext(p,u,"posted start event",{event:l,runID:t})},3,kle,p,Htl(u))},tTr=async(r,t,n,i,o,s)=>{let a=`[postWorkspaceTerminalEvent][ws=${n}][run=${i}]`,u={...o,workspaceID:Number(n),runID:Number(i)},p=iw1(r,t),c=vDe(s),d=(await cf(async()=>(kle.infoContext(u,a,`posting terminal event ${p}...`),c.postWorkspaceRunEvent({workspaceID:n,event:p,runID:i})),3,kle,u,Htl(a))).status?.[0];if(!d)throw new nt(`Posted terminal event ${p} but deploy service returned no workspace run status.`);return kle.infoContext(u,a,`posted terminal event ${p}! Workspace run status: ${JSON.stringify(d)}`),d.status},sw1=r=>N1(r)&&(r.response?.status===409||r.status===409);var rTr=(r,t)=>{if(!r)return r;let n=Object.create(Object.getPrototypeOf(r));return Object.assign(n,r),t&&Object.assign(n,t),n},aw1=["run","runs","devRun","devRuns"],uw1=["createEntity","save","delete","recursiveDelete","merge","fetchAndMerge","mergeMetadata"],DX=class r{providers;flaggedRepositoryParent;_spiedProperties=new Map;constructor(t,n,i,o,s){return this.providers=n,this.flaggedRepositoryParent=t,new Proxy(this,{defineProperty:(a,u,p)=>{if("value"in p){let c=p.value;typeof c=="function"&&(typeof c.mockRestore=="function"||c._isMockFunction===!0)?a._spiedProperties.set(u,c):a._spiedProperties.delete(u)}return!0},getOwnPropertyDescriptor:(a,u)=>{if(u==="flaggedRepositoryParent"||u==="providers"||u==="_spiedProperties")return Reflect.getOwnPropertyDescriptor(a,u);let p=t[u];return p!==void 0?{configurable:!0,enumerable:!0,writable:!0,value:a._spiedProperties.get(u)??p}:Reflect.getOwnPropertyDescriptor(a,u)},get:(a,u)=>{if(a._spiedProperties.has(u))return a._spiedProperties.get(u);if(u==="flaggedRepositoryParent")return t;if(u==="providers")return n;if(aw1.includes(u))return this.providers.firebase[u];if(u==="batch"&&t.id==="root")return s;let{providerId:p,shouldMutateBoth:c}=o(u,i);if(!(p in this.providers))throw new nt("[FLAGGED_REPOSITORY] Attempted to access a flagged repository implementation that is not configured.",`Provider ID: ${p}`);let l=a.providers[p]?.[u];if(l instanceof Lce){let d=Object.fromEntries(Object.entries(this.providers).map(([f,h])=>[f,h?.[u]]));return new r(l,d,{...i},o,s)}return typeof l=="function"?(...d)=>{let f=t?.[u],h=l,A=this.providers.firebase?.[u],E=this.providers.service?.[u],v=f||h,T={};if(c&&u==="createEntity"){let X=t.generateID?.(d[0]);T.generateID=()=>X}let w=rTr(t,T),N=rTr(a.providers[p],T),k=rTr(this.providers.firebase,T),L=rTr(this.providers.service,T),q=f?.bind(w),G=h?.bind(N),H=A?.bind(k),V=E?.bind(L),F=(q||G)?.(...d);if(F instanceof Promise&&(F=new Promise((X,Z)=>{let re=F,oe=[re];uw1.includes(u)&&c&&(v===A?oe.push(V?.(...d)):oe.push(H?.(...d))),Promise.allSettled(oe).then(()=>{re.then(X).catch(Z)}).catch(()=>{console.error("Promise allSettled failed unexpectedly")})})),!(F instanceof Lce))return F;let J=Object.fromEntries(Object.entries(this.providers).map(([X,Z])=>[X,Z?.[u]?.bind(Z)?.(...d)])),Y=i.orgId;u==="org"&&(Y=d[0]),u==="get"&&t.id==="orgs"&&(Y=d[0]);let z=u==="get"?F:G?.(...d);return new r(z,J,{...i,orgId:Y},o,s)}:t[u]}})}},Wtl=(r,t,n,i)=>new DX(r,t,{},n,i),jXe=r=>{if(r instanceof DX){let t=r.providers.firebase;if(!t)Je("COMMON").error("[getFirestoreProvider] FlaggedRepository has no firebase provider configured. Cannot extract firestore provider for direct access. Defaulting to the parent repository instead.");else return t}return r};var pEe=class extends nt{constructor(n,i,o,s){super(`Unable to secure workspace ${n} for ${o} - cannot start a ${o} when workspace is in state ${i}`,s);this.workspaceName=n;this.workspaceStatus=i;this.runType=o}workspaceName;workspaceStatus;runType};var Ktl=(r,t)=>r?"Deploying":t?"Refreshing":"Waiting",nTr=(r,t,n,i,o)=>{let{status:s,currentlyRunningDevJobs:a,currentlyRunningJobs:u}=i,p=n.type,c=p==="devRun"?a:u,l=`Workspace ${i.name??r}`;if(!c)throw new nt(`Could not find corresponding workspace runs for run ${t} of type ${p}`);if(Zdr.includes(s))throw new nt(`Unable to release run from workspace in state ${s}`,`${l} is in state ${s}, context=${JSON.stringify(o)}.`);s==="Waiting"&&Je("SECURE_RUN_AND_WORKSPACE").warnContext(o,`${l} is in unexpected state ${s}`);let d=LWc(t,c);if(Je("SECURE_RUN_AND_WORKSPACE").infoContext(o,"getWorkspaceTerminalRunUpdate:",{workspace:l,workspaceStatus:s,completedRunID:t,currentlyRunningDevJobs:a,currentlyRunningJobs:u,remainingActiveRuns:d,...n}),p==="deploy"){let f=c.length>1;return{remainingActiveRuns:d,newStatus:n.deployFailed?"Failed Deploy":Ktl(!1,f)}}else if(p==="refresh"){let f=n.hasActiveDeployRun?d.length>1:!!d.length;return{remainingActiveRuns:d,newStatus:s==="Failed Deploy"?s:Ktl(n.hasActiveDeployRun,f)}}else return{remainingActiveRuns:d}},oQo=(r,t,n,i)=>{let{name:o,status:s,devEnv:a}=r;if(Je("SECURE_RUN_AND_WORKSPACE").infoContext(i,"checkRunCanStart: workspace status",{workspaceName:o,workspaceStatus:s,runType:t}),Zdr.includes(s))throw new pEe(o,s,t,`Cannot start any run when workspace is in state ${s}`);if(a&&t==="deploy")throw new pEe(o,s,t,"Cannot start a deploy for a development workspace");let u=()=>new pEe(o,s,t);if(n&&Je("SECURE_RUN_AND_WORKSPACE").infoContext(i,`checkRunCanStart: ${t} run passed with option to ignore workspace status; ignoring some default status checks`),t==="deploy"&&(s==="Deploying"||s==="Refreshing"&&!n)||t==="refresh"&&(s==="Deploying"||s==="Failed Deploy"&&!n))throw u()};var sQo=async(r,t,n)=>{if(!!(await(t==="run"?n.run(r):n.devRun(r)).fetch()).runDetails?.canceled)throw new wbe(r)};var cw1=3,Ytl=r=>r instanceof P$e||r instanceof QM,Jtl=r=>{let t=Ytl(r)?r.nodeErrors:void 0;if(Ytl(r)){let n=`${r.message}.`;if(t?.size){let i=[...t.values()].slice(0,cw1),o=i.map(u=>u.message).join("; "),s=t.size-i.length,a=s>0?` (+${s} more)`:"";return`${n} ${o}${a}`}return`${n} Check the failed nodes for details.`}return aa(r).error.errorString},$tl=r=>r instanceof Dbe?{errorCode:"render_failed",failedNodes:[...r.failedNodeIDs]}:r instanceof QM?{errorCode:"node_execution_failed",failedNodes:[...r.failedNodeIDs]}:r instanceof Mme?{errorCode:"warehouse_auth_failed",failedNodes:[]}:{errorCode:"run_error",failedNodes:[]};var Ztl=Je("PIPELINE"),Xtl=Je("RUN_TRANSACTION"),aQo=Je("SECURE_RUN_AND_WORKSPACE"),uQo=async(r,t,n,i,o)=>async(s,a,u)=>{s&&u&&Ztl.emergContext(o,"Unexpected error registered for a successful run",u);let p={runStatus:"completed"};if(!s){let{runDetails:l,runFailureReason:d}=await i[r](n).fetch(),f=l.canceled||!1;p.runStatus=f?"canceled":"failed",d||(p.runStatus==="canceled"?p.runFailureReason=`Run #${n} canceled by user.`:p.runFailureReason=`Run #${n} has failed. ${Jtl(u)}`)}return pw1(()=>i.releaseWorkspaceStatusAndEndRun(t,n,r,a,p),r,t,n,o)},lw1="does not match the required base version",pw1=async(r,t,n,i,o)=>{let s="terminalRunUpdatesWithRetries:";try{let u=await cf(()=>cf(r,10,Xtl,o,{checkError:p=>oWe(aa(p,!0),lw1)?!1:p,retryStrategy:{name:"backoff",base:2},logOnFailure:"ran out of attempts due to transaction contention",logOnRetry:"[runUpdatesWithRetries][inner retry] retrying release workspace (transaction contention)"}),3,Xtl,o,{logOnFailure:"ran out of attempts and failed to release workspace",logOnRetry:"[runUpdatesWithRetries][outer retry] retrying release workspace"});aQo.appContext(o,s,`successfully set workspace ${n} state to ${u} after ${t} ${i}`)}catch(a){aQo.errorContext(o,s,`failed to update workspace ${n} state for ${t} ${i}}`,a)}},rMt=async(r,t,n,i,o,s)=>{let a="[cleanUpRunAndWorkspaceOnFailedJob]";if(t==="plan"){aQo.alertContext(o,a,`plan job ${r} wants to clean up, but there's nothing to clean up`);return}let u=TG(r,`Unable to parse runID: ${r}`),p=t==="deploy",c=t==="rerun"?"refresh":t,l=n.runs.get(u);if(!l)throw new Du(`Run repository for run ${r} not found in org ${n.id}`);let d=await l.fetch();if(!d)throw new Du(`Run data for run ${r} not found in org ${n.id}`);let f=d.runDetails.environmentID;if(!f)throw new nt(`Workspace ID not found in runDetails for run ${r}`);let h=async()=>{let v=await n.workspace(+f).fetch(),T=c==="refresh"?await u2r(v.name,v.currentlyRunningJobs,n.runs):void 0;return nTr(+f,u,{type:c,deployFailed:p,hasActiveDeployRun:!!T},v,o)},A=await uQo("run",+f,u,n,o),E=async()=>{try{await tTr(c,!1,f.toString(),u.toString(),o,s??bc().authToken)}catch(v){Ztl.errorContext(o,a,"Failed to post terminal event to deploy service. This could result in orphaned workspace_runs row until the cleanup tool's next run.",v)}};await Promise.all([A(!1,h,i),E()])};var TDe=B.object({oldName:B.string(),oldLocation:B.string()}),dw1=B.object({nullable:B.boolean().optional(),dataType:B.string().optional(),description:B.string().optional(),name:B.string()}),fw1=B.object({name:B.string(),dataType:B.string(),nullable:B.boolean(),description:B.string(),defaultValue:B.string().optional()}),cQo=TDe.extend({addedColumns:B.array(fw1)}),lQo=TDe.extend({alteredColumns:B.array(dw1)}),hw1=B.object({name:B.string()}),pQo=TDe.extend({deletedColumns:B.array(hw1)}),dQo=TDe.extend({oldColumn:Pq,newColumn:Pq}),erl=[TDe,pQo,lQo,cQo,dQo],fY2=B.union(erl),gw1=[...erl,o0r,B.object({})],hY2=B.union(gw1);var h5="select 1 as coalesce_test",trl="SELECT name FROM sys.databases;";var dEe=T3o.merge(bmr),rrl=T3o.merge(I6o),Aw1=B.object({templateString:B.string(),macrosString:B.string(),runTimeParameters:Xvt.optional(),packages:w3o,renderDepth:B.number().optional(),formatSQL:B.boolean().optional(),nodeMetadata:B.union([dEe.strict(),rrl.strict()]),description:B.string().optional(),detailedError:B.string().optional()}).strict(),SY2=Mr("RenderNodeParams",Aw1),mw1=B.union([dEe.merge(TDe),dEe.merge(pQo),dEe.merge(lQo),dEe.merge(cQo),dEe.merge(dQo),dEe.merge(o0r),dEe.merge(B.object({})),rrl]),vY2=Mr("RenderDeployNodeMetadata",mw1);var fQo=r=>"fromWorkspaceData"in r&&r.version===2&&"phasedDependencies"in r&&"phasedNodeEdits"in r,yw1=r=>r.environmentID!==void 0&&!bw1(r)&&!fQo(r),bw1=r=>r.operationType!==void 0,nrl=r=>{if(!r?.runType||!r?.runDetails)throw new Error("Run info has invalid run type or run details!");let t=r.runType==="refresh";if(t&&!yw1(r.runDetails))throw new Error(`Refresh run ${r.id||r.reRunID} info has invalid run details!`);return t},irl=r=>!!r.reRunID;var GXe=(r,t)=>{let{jobID:n}=r;return n?`Refreshed Job - ${t[n]?.name||n}`:r.includeNodesSelector||r.excludeNodesSelector?"Refreshed an ad hoc Job":"Refreshed all Nodes"},orl=r=>{if(r.runType==="deploy"){let t=r.runDetails.deployCommitMessage?.substring(0,256)||"N/A",n=r.runDetails.deployCommit?.substring(0,8)||"N/A";return`Commit - ${t} (sha: ${n})`}else return r.runType==="refresh"?r.runDetails.refreshDescription?.substring(0,256)||"Refresh":r.runType==="devRun"?`Dev run (environment ${r.runDetails.environmentID})`:"N/A"};var fEe=Je("PIPELINE"),srl=async(r,t)=>{let{connectionManager:n,featureFlags:i,logContext:o,nodesInRun:s,platform:a,renderer:u,repository:p,runInfo:c,memoryMonitor:l,...d}=t,f=orl(c),h=`[runPipeline (${r.name} / job name '${f}']`;fEe.appContext(o,h,"creating event handler");let A=r.getEventHandler(d,p,o,c,t.analyticsCollector);t.analyticsCollector.startPhase("initializeSteps"),await A.initializeRunResults([...s]),t.analyticsCollector.endPhase("initializeSteps"),await A.repositoryStampExecutorInfo(a.name);let E,v;if(c.runType==="deploy")pd(fQo(c.runDetails),`${h} Malformed deploy run details!`,"PIPELINE",o,`version=${c.runDetails.version} / planID=${c.runDetails.planID}`,c.runDetails),E=c.runDetails.phasedDependencies,v=Nbe.fromRecord("phased node edits",c.runDetails.phasedNodeEdits),await A.repositoryUpdateRunStatus({expectedStatus:"initializing",newStatus:"running"});else{fEe.appContext(o,h,"rendering all nodes"),await A.repositoryUpdateRunStatus({expectedStatus:"initializing",newStatus:"rendering"});let w=r.getRenderer(d,u,a.name,o,s,l,c),N=G=>A.repositoryUpdateRenderingProgress(G);t.analyticsCollector.startPhase("rendering all nodes");let k;try{k=await w.renderAllNodes(d.stepTypesParsed,N)}catch(G){if(G instanceof Dbe)try{let H=Fmc.assert(G.makeRenderFailures(),{logArea:"PIPELINE",logContext:o}),V=A.getRepositoryForRun(),W=V.renderFailures,F=V.parent.parent.batch();for(let[J,Y]of Object.entries(H)){let z=W.get(J);await F.save(z,Y)}await F.commit(),fEe.infoContext(o,h,`Successfully wrote render failures to database for run ${c.id}`),await V.merge({hasRenderFailures:!0})}catch(H){fEe.errorContext(o,h,"Failed to write render failures to database",H)}throw G}t.analyticsCollector.endPhase("rendering all nodes"),v=k.toEdits(),fEe.appContext(o,h,"building dependencies");let L={};t.analyticsCollector.startPhase("building dependencies"),E=r.getDependencyBuilder(d.nodes,k,L,o).build(),t.analyticsCollector.endPhase("building dependencies"),await A.repositoryUpdateRunStatus({expectedStatus:"rendering",newStatus:"running"})}t.analyticsCollector.startPhase("populateQueuedStages"),await A.populatePlaceholderStages(v,r.phaseOrder),t.analyticsCollector.endPhase("populateQueuedStages");let T=new l2r(p,()=>A.getRepositoryForRun(),Mbe.buildRunResultEntitySave,A.runResults,fEe,o);A.setFlusher(T),fEe.infoContext(o,h,"executing run");try{let w=r.getRun(o,v,E,f,c);t.analyticsCollector.startPhase("runExecution"),await w.runAll(A,n,a)}finally{await A.disposeFlusher()}return t.analyticsCollector.endPhase("runExecution"),fEe.infoContext(o,h,"finished executing run"),{eventHandler:A}};var hQo=Je("PIPELINE"),Ew1=1e4,Cw1=r=>({retryStrategy:{name:"backoff",base:1},checkError:t=>!N1(t)||t.response&&t.response.status<500?t:void 0,logOnRetry:`${r} retrying after transient failure`,retryLogLevel:"info",logOnFailure:`${r} failed, request never resolved after maximum allowed retries`}),gQo=async(r,t,n,i)=>{let o=`[publishEventViaScheduler][${r}]`,s=`${QEt()}/api/v1/events/publish`;try{await cf(async()=>{let a=n??(Xc.isInitialized?await Xc.resolveAuthToken():void 0);return hQo.infoContext(i,o,"publishing via scheduler relay"),dc.post(s,{type:r,payload:t},{timeout:Ew1,headers:a?{Authorization:`Bearer ${a}`}:{}})},3,hQo,i,Cw1(o))}catch(a){hQo.errorContext(i,o,"failed to publish via scheduler relay",a)}};var Sw1=Je("RUNNER_BACKEND"),arl=(r,t,n,i)=>{Sw1.appContext(i,"[createCoalesceRunRequirements]","Creating run requirements");let s=r.steps;if(n)for(let[p,{operation:c}]of Object.entries(n))p in s||(s[p]={operation:c});let a=r?.installedPackages||{},u=VEr(a,ep(r.stepTypes));return{currentWorkspace:t,installedPackages:a,macros:ep(r.macros),mappings:ep(r.locations??{}),nodes:s,projects:ep(r.projects??{}),stepTypesParsed:X$(u),stepTypesYaml:u,refLinkLookup:wv(s)}};var url=r=>r.type==="sourceInput"?void 0:{name:r.name,locationName:r.locationName},crl=(r,t,n,i,o)=>{let s=new Set,a=0;for(let[c,l]of Object.entries(r)){if(l.runState!=="complete")continue;for(let f of l.queryResultSequence.queryResults){let{rowsInserted:h,rowsUpdated:A,rowsDeleted:E}=lrl(i.runType,f);for(let v of[h,A,E])typeof v=="number"&&(a+=v)}let d=o(c);if(d)try{s.add(IIt(t,{name:d.name,locationName:d.locationName},n))}catch{}}let u=i.runEndTime??i.runHeartbeat,p=i.runStartTime&&u?Math.max(0,fgr(u)-fgr(i.runStartTime)):0;return{targetTables:[...s],rowsAffected:a,durationMs:p}};var l4=Je("PIPELINE"),prl=async(r,t,n,i,o,s,a)=>{try{let u=r.analyticsCollector.toRunAnalyticsDocs(o,s);await t.writeRunAnalyticsSummary(i,n,u.summary,u.runPhases,u.planPhases,u.queries),l4.infoContext(a,"Successfully wrote run analytics to Firestore")}catch(u){l4.errorContext(a,"Failed to write run analytics to Firestore. This is non-critical.",u)}},_De=async(r,t,n)=>{let i="[buildPipeline]",{allWorkspaceData:o,connectionManager:s,logContext:a,nodesInRun:u,platform:p,renderer:c,runID:l,runInfo:d,supplementalNodeData:f,teamInfoAndFirebase:{featureFlags:h,rootRepository:A,teamInfo:{fbTeamID:E}},workspaceID:v,memoryMonitor:T}=t,w=new eTr({context:a,logger:l4});if(!c.render)throw l4.errorContext(a,i,"bad renderer"),new nt(`${i} bad renderer`);let{runType:N}=d,k=N==="devRun"?"devRun":"run",L=A.org(E),q=await uQo(k,v,l,L,a),G=d.runType==="deploy"&&"planID"in d.runDetails?d.runDetails.planID:void 0,H,V=jXe(L),W=async J=>{let Y=await V.workspace(v).fetch(),z=N==="refresh"?await u2r(Y.name,Y.currentlyRunningJobs,L.runs):void 0;return nTr(v,l,{type:N,deployFailed:J,hasActiveDeployRun:!!z},Y,a)},F=J=>{let Y;return()=>(Y??=tTr(N,J,v.toString(),l.toString(),a,bc().authToken).catch(z=>{l4.fatalContext(a,i,"Deploy service posted start event but failed to post terminal event. This could result in orphaned workspace_runs rows. Requires investigation.",z)}),Y)};try{n.beforeRun&&(await sQo(l,k,L),w.startPhase("beforeRun"),await n.beforeRun(),w.endPhase("beforeRun"));let J=arl(o,v,f,a);await sQo(l,k,L),w.startPhase("pipeline execution"),{eventHandler:H}=await srl(r,{...J,connectionManager:s,featureFlags:h,logContext:a,nodesInRun:u,platform:p,renderer:c,repository:A,runInfo:d,memoryMonitor:T,analyticsCollector:w}),w.endPhase("pipeline execution"),n.afterRun&&(w.startPhase("afterRun"),await n.afterRun(),w.endPhase("afterRun")),l4.appContext(a,i,"run finished successfully");let Y=F(!0);if(await q(!0,()=>drl(Y,()=>W(!1),a,i,"try"),void 0),await prl(H,L,k,l,G,N,a),N==="refresh")try{let z=await L.runs.get(l).fetch(),X=crl(H.runResults,Zq(o.locations??{},v),p.name,z,Z=>{try{return url(H.getSingleStepData(void 0,Z).operation)}catch(re){l4.debugContext(a,i,"could not resolve target table for node",{nodeID:Z,error:re});return}});X.rowsAffected>0&&X.targetTables.length===0&&l4.warnContext(a,i,"transform.job.completed resolved no target tables despite affected rows",{rowsAffected:X.rowsAffected}),await gQo(N7o.typeName,{jobId:l.toString(),durationMs:String(X.durationMs),rowsAffected:String(Math.max(0,X.rowsAffected)),targetTables:X.targetTables},bc().authToken,a)}catch(z){l4.errorContext(a,i,"failed to assemble transform.job.completed event",z)}}catch(J){l4.errorContext(a,i,"error during run",J);try{let Y=F(!1);await q(!1,()=>drl(Y,()=>W(!0),a,i,"catch"),J)}catch(Y){l4.emergContext(a,i,"error during status release",Y)}if(H&&await prl(H,L,k,l,G,N,a),N==="refresh"){let Y=YNe(J);if(!Y)try{let{runDetails:z}=await L.run(l).fetch();Y=!!z?.canceled}catch{}if(!Y)try{let{errorCode:z,failedNodes:X}=$tl(J);await gQo(D7o.typeName,{jobId:l.toString(),errorCode:z,failedNodes:X},bc().authToken,a)}catch(z){l4.errorContext(a,i,"failed to assemble transform.job.failed event",z)}}throw J}finally{l4.infoContext(a,i,"Calling onCleanup (heartbeat cleanup)"),await n.onCleanup(),l4.infoContext(a,i,"onCleanup (heartbeat cleanup) completed")}},frl=r=>r.forcedDeployment?!!r.forcedDeployment:r.forceIgnoreWorkspaceStatus?!!r.forceIgnoreWorkspaceStatus:!1,drl=async(r,t,n,i,o="test")=>{let s=await r(),a=await t();if(s&&s!==a.newStatus){let u=`Workspace run status from deploy service and repository do not match after running inside of a ${o} block.`;a.newStatus==="Failed Deploy"&&s==="Refreshing"&&(u+=" This could be legitimate due to services ability to track a proper terminal state."),l4.warnContext(n,i,u,{serviceStatus:s||"undefined",repoStatus:a.newStatus||"undefined"})}return a};var hEe=Je("PIPELINE"),vw1={installedPackages:"installedPackages",jobs:"jobs",macros:"macros",nodeTypes:"stepTypes",subgraphs:"folders",nodes:"steps"},hrl=async(r,t,n,i,o,s)=>{let a="[performSaves]",u=vw1[r],p=o[u]||{},c=i[r],l=await c.select(),d=l.map(({id:h})=>h),f;if(r==="subgraphs"&&(f=Object.fromEntries(l.map(h=>[h.id.toString(),h]))),hEe.appContext(s,a,`Deploying ${r}`,`
|
|
10052
10052
|
current state:`,d,`
|
|
10053
10053
|
desired state:`,Object.keys(p)),t==="delete"||t==="all"){let h=[];for(let A of d)if(!(A in p)){let E=p[A];await n.delete(c.get(A),E??{}),h.push(A)}hEe.appContext(s,`Deleting ${r}:`,h)}if(t==="update"||t==="all"){let h=[];for(let[A,E]of Object.entries(p)){let v=kce(E),T=r==="jobs"&&EHc(v)?m9o(v,o.folders,o.steps):v;if(r==="subgraphs"&&f){let w=f[A];w&&w.folderCounter!==void 0&&T.folderCounter===void 0&&(T.folderCounter=w.folderCounter)}await n.save(c.get(A),T),h.push(A)}hEe.appContext(s,`Updating ${r}:`,h)}},grl=async(r,t,n,i)=>{let o="[clearSelectedWorkspaceEntities]";hEe.infoContext(i,o,"Clearing existing workspace entities for",r.id);try{let s=FEr(t),a=r.parent.parent.batch();for(let u of n)await hrl(u,"delete",a,r,s,i);await a.commit(),hEe.infoContext(i,o,"Cleared existing workspace entities")}catch(s){hEe.errorContext(i,o,"Error clearing",s)}},Arl=(r,t,n)=>{let i="[getWorkspaceEntitySaver]";return async(o,s="all")=>{try{let a=r.parent.parent.batch();await hrl(o,s,a,r,t,n),await a.commit()}catch(a){hEe.errorContext(n,i,`Error deploying ${o}`,a)}}},mrl=async(r,t,n)=>{let i="[ensureNewMappingsExist]",{mappingsV1:o}=await r.fetch(),s=Sp(`Workspace ${r.id} mappingsV1`,o,Pme),a=t||{},u=Object.keys(a).filter(p=>!Object.hasOwn(s,p));if(u.length){let p=Object.fromEntries(u.map(d=>[d,a[d]])),c={...s,...p};hEe.infoContext(n,i,"Merging new location keys into workspace mappings:",u,"; current keys:",Object.keys(s));let l=UA(Pme.assert(c));await r.merge({mappingsV1:l})}};var yrl=["fabric"];var p4=class r extends Error{errors;constructor(t,n){super(t),this.name="SQLParseError",this.errors=n,Object.setPrototypeOf(this,r.prototype)}getCustomerFacingMessage(){return this.errors.length===0?this.message:`SQL parsing failed:
|
|
10054
10054
|
${this.errors.map(n=>{let i=`Line ${n.line}, Column ${n.column}: ${n.message}`;return n.suggestion&&(i+=`
|
|
@@ -10107,7 +10107,7 @@ ${w} ${T.source.source}`,T.source.alias&&(A+=` AS ${T.source.alias}`),T.matchCon
|
|
|
10107
10107
|
`)}return o}function lP1(r,t){if(!t.has(r))return t.add(r),r;let n=1;for(;t.has(`${r}${n}`);)n++;let i=`${r}${n}`;return t.add(i),i}function FZe(r,t,n){let i=[],o=new Set,s=r.query.projections.filter(a=>a instanceof qv&&!(a.expression instanceof ZX));for(let a of s){let u=typeof a.alias=="string"?a.alias:a.alias?.value,c=KL(a.expression)?.getText()??"",l=n?Eil(a.expression,n):"",d=u||Cil(a.expression),f=d||c||l||null;if(!f)continue;let h=lP1(f,o),A,E;if(a.expression instanceof sO)A=bil(a.expression),E=$M(a.expression.expression,t).sourceRefs;else{let T=$M(a.expression,t);A=T.dataType,E=T.sourceRefs}let v=l||(d?`"${d}"`:f);i.push({name:h,dataType:A,sourceAlias:void 0,transform:v,sourceRefs:E,annotations:[]})}return i}function Cil(r){if(r instanceof Ig)return typeof r.name=="string"?r.name:r.name?.value||null;if(r instanceof sO)return Cil(r.expression);let t=r.name;return t instanceof Wo&&t.value||null}var ywr=r=>$g({snowflake:()=>gd.SNOWFLAKE,databricks:()=>gd.DATABRICKS,fabric:()=>gd.MS_FABRIC,bigquery:()=>gd.BIGQUERY},r,"getDialectForPlatformKind");var pP1="TRANSIENT|TEMP|TEMPORARY|SECURE|MATERIALIZED|RECURSIVE|VOLATILE|ICEBERG|DYNAMIC|LOCAL|GLOBAL|HYBRID|EXTERNAL",Sil=new RegExp(`^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:(?:${pP1})\\s+)*(?:TABLE|VIEW)\\b[\\s\\S]*?\\bAS\\s+(?=(?:WITH|SELECT|\\())`,"i");function vil(r){if(!r)return null;let t=IWo(r);if(!Sil.test(t))return null;let n=t.replace(Sil,"").trim();return n.length>0?n:null}var dP1=/^\s*PIVOT\s*\(\s*([A-Za-z_][\w$]*)\s*\(\s*([\w$".]+)\s*\)(?:\s+(?:AS\s+)?([\w$"]+))?\s*FOR\s+([\w$".]+)\s+IN\s*\(([^)]*)\)\s*\)(?:\s+AS\s+[\w$"]+)?(?:\s*\(([^)]*)\))?/i,fP1=/^\s*UNPIVOT\s*(?:(?:INCLUDE|EXCLUDE)\s+NULLS\s*)?\(\s*([\w$".]+)\s+FOR\s+([\w$".]+)\s+IN\s*\(([^)]*)\)\s*\)/i,TWo=r=>{let t=[],n=0,i,o=0;for(let s=0;s<r.length;s++){let a=r[s];if(i){a===i&&(r[s+1]===i?s++:i=void 0);continue}if(a==="'"||a==='"'||a==="`"){i=a;continue}if(a==="("){o++;continue}if(a===")"){o=Math.max(0,o-1);continue}a===","&&o===0&&(t.push(r.slice(n,s).trim()),n=s+1)}return t.push(r.slice(n).trim()),t.filter(s=>s.length>0)},bwr=r=>{let t=r.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t.slice(1,-1):t},hP1=r=>{let t=!1,n=-1;for(let i=0;i<r.length;i++){let o=r[i];o==='"'||o==="`"?t=!t:o==="."&&!t&&(n=i)}return n>=0?r.slice(n+1):r},D4t=r=>bwr(hP1(r.trim())).toUpperCase(),Til=r=>{let t=/^(.*?)\s+(?:AS\s+)?([\w$"]+)$/i.exec(r.trim());return t?{value:t[1].trim(),alias:bwr(t[2]).toUpperCase()}:{value:r.trim()}},gP1=r=>{let t=r.replace(/'(?:[^']|'')*'/g,""),n=t.trim();return/^ANY\b/i.test(n)||/\bSELECT\b/i.test(t)};function IWo(r){let t="",n=0;for(;n<r.length;){let i=r[n],o=r[n+1];if(i==="-"&&o==="-"){for(;n<r.length&&r[n]!==`
|
|
10108
10108
|
`;)n++;continue}if(i==="/"&&o==="*"){for(n+=2;n<r.length&&!(r[n]==="*"&&r[n+1]==="/");)n++;n+=2,t+=" ";continue}if(i==="'"||i==='"'||i==="`"){let s=i;for(t+=i,n++;n<r.length;){if(t+=r[n],r[n]===s){if(r[n+1]===s){t+=r[n+1],n+=2;continue}n++;break}n++}continue}t+=i,n++}return t}function _il(r){if(!r)return null;let t=dP1.exec(r);if(t){if(gP1(t[5]))return null;let i=TWo(t[5]);if(i.length===0)return null;let o=t[6]?TWo(t[6]).map(s=>bwr(s).toUpperCase()):void 0;return{kind:"pivot",aggregate:t[1].toUpperCase(),valueColumn:D4t(t[2]),aggregateAlias:t[3]?bwr(t[3]).toUpperCase():void 0,pivotColumn:D4t(t[4]),inList:i,aliasList:o}}let n=fP1.exec(r);return n?{kind:"unpivot",valueColumn:D4t(n[1]),nameColumn:D4t(n[2]),inList:TWo(n[3]).map(i=>D4t(Til(i).value))}:null}var _Wo=(r,t)=>({name:r,dataType:t,sourceAlias:void 0,transform:`"${r}"`,sourceRefs:[],annotations:[]});function Iil(r,t,n){return r.kind==="pivot"?AP1(r,t,n):mP1(r,t,n)}function AP1(r,t,n){let i=[];for(let[p,c]of t.entries())p===r.valueColumn||p===r.pivotColumn||i.push(Ril(p,c));let o=t.get(r.valueColumn)?.dataType??"UNKNOWN",s=yP1(r.aggregate,o,n),a=r.inList.map(p=>{let c=Til(p),l=c.alias??c.value.trim(),d=r.aggregateAlias?`${l}_${r.aggregateAlias}`:l;return _Wo(d,s)}),u=[...i,...a];return r.aliasList&&r.aliasList.length===u.length?u.map((p,c)=>({...p,name:r.aliasList[c],transform:`"${r.aliasList[c]}"`})):u}function mP1(r,t,n){let i=new Set(r.inList),o=[];for(let[c,l]of t.entries())i.has(c)||o.push(Ril(c,l));let s=_Wo(r.nameColumn,"VARCHAR"),a=r.inList.map(c=>t.get(c)?.dataType??"UNKNOWN"),u=a.length===0?"UNKNOWN":a.reduce((c,l)=>eA(c,l,n)),p=_Wo(r.valueColumn,u);return[...o,s,p]}var Ril=(r,t)=>({name:r,dataType:t.dataType,sourceAlias:t.sourceAlias,transform:t.transform,sourceRefs:t.sourceRefs,annotations:t.annotations});function yP1(r,t,n){let i=vWo(r,n);return i?i([t]):"UNKNOWN"}var np=Je("SQL_PARSING");function Mil(r){let t=new Map;for(let n in r){let o=r[n]?.operation?.name;if(o){let s=o.toUpperCase();t.has(s)||t.set(s,new Set),t.get(s).add(n)}}return t}function bP1(r,t){let n=r?Mil(r):new Map;return np.debug(`Built table name mapping with ${n.size} entries:`,Array.from(n.keys())),{dialect:t,getDataTypeOfColumn:(i,o)=>{if(np.debug(`Looking up data type for column: ${o}, tableRef: ${i||"undefined"}`),r&&i){let s=i.toUpperCase(),a=n.get(s);if(np.debug(`Looking up table ${i} (${s}) in mapping, found: ${a?a.size:0} nodes`),a&&a.size===1){let p=Array.from(a)[0];if(p&&r[p]){let c=r[p];np.debug(`Found node ${p} for table ${i}, has columns: ${!!c?.operation?.metadata?.columns}`);let l=c?.operation?.metadata?.columns?.find(d=>d.name?.toUpperCase()===o.toUpperCase());if(l?.dataType)return np.debug(`Found column ${o} in physical table ${i} with type: ${l.dataType}`),l.dataType;np.debug(`Column ${o} not found in physical table ${i}`)}}else a&&a.size>1?np.debug(`Ambiguous table name: ${i} matches multiple nodes`):np.debug(`Table ${i} not found in physical table mapping`)}return np.info(`Could not find column ${o} in physical tables`),null},resolveColumnSource:(i,o)=>{if(r&&i){let s=i.toUpperCase(),a=n.get(s);if(a&&a.size===1){let p=Array.from(a)[0];if(p&&r[p]){let l=r[p]?.operation?.metadata?.columns?.find(d=>d.name?.toUpperCase()===o.toUpperCase());if(l){np.debug(`Resolved column ${o} in physical table ${i} to node ${p}`);let d=i?`"${i}"."${o}"`:`"${o}"`;return{type:"physical",stepCounter:p,columnCounter:l.columnReference.columnCounter,transform:d}}}}}return np.debug(`Could not resolve column ${o} to any source`),null}}}function EP1(r){return r.map(t=>typeof t.alias=="string"?t.alias:t.alias.value)}function CP1(r,t){return t.find(n=>(typeof n.alias=="string"?n.alias:n.alias.value)===r)}function wWo(r,t,n,i){return{dialect:i,getDataTypeOfColumn:(o,s)=>{let a=o?r.aliasToCteName.get(o.toUpperCase())||o:void 0;if(a&&r.cteColumns.has(a.toUpperCase())){let p=r.cteColumns.get(a.toUpperCase()).find(c=>c.name.toUpperCase()===s.toUpperCase());if(p)return np.debug(`Found column ${s} in CTE ${a} with type: ${p.dataType}`),p.dataType}if(!o)for(let[u,p]of r.cteColumns.entries()){let c=p.find(l=>l.name.toUpperCase()===s.toUpperCase());if(c)return np.debug(`Found column ${s} in CTE ${u} (unqualified) with type: ${c.dataType}`),c.dataType}if(o&&n&&t){let u=o.toUpperCase();for(let p of n){let c=l=>{if(l.table?.alias?.value?.toUpperCase()===u&&l.ref?.param2?.value){let f=l.ref.param2.value,h=Object.values(t).find(A=>A?.operation?.name===f);if(h?.operation?.metadata?.columns){let A=h.operation.metadata.columns.find(E=>E.name?.toUpperCase()===s.toUpperCase());if(A?.dataType)return np.debug(`Found column ${s} via alias ${o} -> ref ${f} with type: ${A.dataType}`),A.dataType}}return null};if(p instanceof z1){let l=c(p);if(l)return l}else if(p instanceof G3||p instanceof E5){for(let l of p.relations)if(l instanceof z1){let d=c(l);if(d)return d}}}}if(!o&&n&&t)for(let u of n){let p;if(u instanceof z1)p=u;else if(u instanceof G3||u instanceof E5){for(let c of u.relations)if(c instanceof z1){let l=c.ref?.param2?.value;if(l){let d=Object.values(t).find(f=>f?.operation?.name===l);if(d?.operation?.metadata?.columns){let f=d.operation.metadata.columns.find(h=>h.name?.toUpperCase()===s.toUpperCase());if(f?.dataType)return np.debug(`Found column ${s} in relation ref ${l} with type: ${f.dataType}`),f.dataType}}}}if(p&&p.ref?.param2?.value){let c=p.ref.param2.value,l=Object.values(t).find(d=>d?.operation?.name===c);if(l?.operation?.metadata?.columns){let d=l.operation.metadata.columns.find(f=>f.name?.toUpperCase()===s.toUpperCase());if(d?.dataType)return np.debug(`Found column ${s} in relation ref ${c} with type: ${d.dataType}`),d.dataType}}}return r.physicalTableContext.getDataTypeOfColumn(o,s)},resolveColumnSource:(o,s)=>{let a=o?r.aliasToCteName.get(o.toUpperCase())||o:void 0;if(a&&r.cteColumns.has(a.toUpperCase())){let p=r.cteColumns.get(a.toUpperCase()).find(c=>c.name.toUpperCase()===s.toUpperCase());if(p)return np.debug(`Resolved column ${s} to CTE ${a}`),{type:"cte",cteName:a.toUpperCase(),columnName:p.name,transform:p.transform}}if(!o)for(let[u,p]of r.cteColumns.entries()){let c=p.find(l=>l.name.toUpperCase()===s.toUpperCase());if(c)return np.debug(`Resolved unqualified column ${s} to CTE ${u}`),{type:"cte",cteName:u,columnName:c.name,transform:c.transform}}if(o&&n&&t){let u=o.toUpperCase();for(let p of n){let c=l=>{if(l.table?.alias?.value?.toUpperCase()===u&&l.ref?.param2?.value){let f=l.ref.param2.value,h=Object.entries(t).find(([,A])=>A?.operation?.name===f);if(h){let[A,E]=h,v=E?.operation?.metadata?.columns?.find(T=>T.name?.toUpperCase()===s.toUpperCase());if(v){np.debug(`Resolved column ${s} via alias ${o} -> node ${A}`);let T=o?`"${o}"."${s}"`:`"${s}"`;return{type:"physical",stepCounter:A,columnCounter:v.columnReference.columnCounter,transform:T}}}}return null};if(p instanceof z1){let l=c(p);if(l)return l}else if(p instanceof G3||p instanceof E5){for(let l of p.relations)if(l instanceof z1){let d=c(l);if(d)return d}}}}if(!o&&n&&t)for(let u of n){let p=c=>{let l=c.ref?.param2?.value;if(l){let d=Object.entries(t).find(([,f])=>f?.operation?.name===l);if(d){let[f,h]=d,A=h?.operation?.metadata?.columns?.find(E=>E.name?.toUpperCase()===s.toUpperCase());if(A)return np.debug(`Resolved unqualified column ${s} to node ${f}`),{type:"physical",stepCounter:f,columnCounter:A.columnReference.columnCounter,transform:`"${s}"`}}}return null};if(u instanceof z1){let c=p(u);if(c)return c}else if(u instanceof G3||u instanceof E5){for(let c of u.relations)if(c instanceof z1){let l=p(c);if(l)return l}}}return r.physicalTableContext.resolveColumnSource?r.physicalTableContext.resolveColumnSource(o,s):null}}}function SP1(r,t,n,i,o){let s=[];np.debug(`getAllColumnsFromSource called with tableRef: ${r}, hasRefRelation: ${!!i}`);let a=r?.toUpperCase(),u=a?t.aliasToCteName.get(a)||a:void 0;if(u&&t.cteColumns.has(u)){let c=t.cteColumns.get(u);np.debug(`Found ${c.length} columns in CTE ${u}`);let l=r||u;return c.map(d=>({...d,dataType:d.dataType,transform:`"${l}"."${d.name}"`,sourceAlias:l,sourceRefs:[{type:"cte",cteName:u,columnName:d.name,transform:`"${l}"."${d.name}"`}]}))}let p=(c,l,d,f)=>{let h=d||r;return{name:c.name,dataType:c.dataType,sourceAlias:h,transform:h?`"${h}"."${c.name}"`:`"${c.name}"`,sourceRefs:[{type:"physical",stepCounter:l,columnCounter:c.columnReference.columnCounter,transform:h?`"${h}"."${c.name}"`:`"${c.name}"`}],annotations:[]}};if(i&&i.ref?.param2?.value&&n){let c=i.ref.param2.value,l=i.table?.alias?.value;np.debug(`Looking up node directly by ref param2: ${c}`);let d=Object.entries(n).find(([,f])=>f?.operation?.name===c);if(d){let[f,h]=d;if(h?.operation?.metadata?.columns){for(let A of h.operation.metadata.columns)A.name&&A.dataType&&s.push(p(A,f,l,o));return np.debug(`Found ${s.length} columns in node ${c} via direct ref lookup`),s}}else np.debug(`Node ${c} not found or has no columns`)}if(r&&n){let c=r.toUpperCase(),d=Mil(n).get(c);if(d&&d.size===1){let h=Array.from(d)[0];if(h&&n[h]){let A=n[h];if(A?.operation?.metadata?.columns){for(let E of A.operation.metadata.columns)E.name&&E.dataType&&s.push(p(E,h,void 0,o));return np.debug(`Found ${s.length} columns in physical table ${r} via table mapping`),s}}}}return s.length===0&&np.debug(`No columns found for table reference: ${r||"undefined"}`),s}function RWo(r){if(r instanceof nl)return r.table?.alias?.value||r.table?.name?.value;if(r instanceof z1)return r.table?.alias?.value||r.ref?.param2?.value}function B4t(r){if(r instanceof nl)return r.table?.alias?.value||r.table?.name?.value;if(r instanceof z1)return r.table?.alias?.value||r.ref?.param2?.value;if(r instanceof AS)return r.alias?.value}function Oil(r,t,n,i){if(!r.query)return[];let o=wWo(t,n,r.query.relations??[],i),s={query:r.query};return FZe(s,o)}function Ewr(r,t){if(!(!r||r.length===0))for(let n of r){let i=o=>{if(o instanceof nl){let s=o.table?.name?.value,a=o.table?.alias?.value;if(a&&s){let u=s.toUpperCase(),p=a.toUpperCase();t.cteColumns.has(u)&&p!==u&&(t.aliasToCteName.set(p,u),np.debug(`Mapped alias ${p} -> CTE ${u}`))}}};if(n instanceof nl)i(n);else if(n instanceof G3||n instanceof E5)for(let o of n.relations)i(o)}}function OWo(r,t,n,i,o){let s=new Map;if(!r||r.length===0)return s;let a=o;Ewr(r,t);let u=(p,c)=>{if(!i)return!0;let l=i.toUpperCase(),d=p?.toUpperCase(),f=c?.toUpperCase();return l===d||l===f};for(let p of r){let c=[];if(p instanceof nl){let l=RWo(p),d=B4t(p);l&&u(l,d)&&c.push({tableRef:l,tableAlias:d})}else if(p instanceof z1){let l=RWo(p),d=B4t(p);l&&u(l,d)&&c.push({tableRef:l,tableAlias:d,refRelation:p})}else if(p instanceof G3||p instanceof E5)for(let l of p.relations)if(l instanceof AS){let d=B4t(l);if(u(d,d)){let f=Oil(l,t,n,a);for(let h of f)if(!s.has(h.name)){let A=d?`"${d}"."${h.name}"`:`"${h.name}"`;s.set(h.name,{dataType:h.dataType,sourceAlias:d,transform:A,sourceRefs:h.sourceRefs||[],annotations:[]})}}}else{let d=RWo(l),f=B4t(l);d&&u(d,f)&&c.push({tableRef:d,tableAlias:f,refRelation:l instanceof z1?l:void 0})}else if(p instanceof AS){let l=B4t(p);if(u(l,l)){let d=Oil(p,t,n,a);for(let f of d)if(!s.has(f.name)){let h=l?`"${l}"."${f.name}"`:`"${f.name}"`;s.set(f.name,{dataType:f.dataType,sourceAlias:l,transform:h,sourceRefs:f.sourceRefs||[],annotations:[]})}}}for(let{tableRef:l,tableAlias:d,refRelation:f}of c){let h=SP1(l,t,n,f,o);for(let A of h)s.has(A.name)||s.set(A.name,{dataType:A.dataType,sourceAlias:d||A.sourceAlias,transform:A.transform,sourceRefs:A.sourceRefs,annotations:[]})}}return s}function L4t(r){let t=r.trim();return t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1)),t.startsWith("'")&&t.endsWith("'")&&(t=t.slice(1,-1)),t.startsWith("`")&&t.endsWith("`")&&(t=t.slice(1,-1)),t}function Cwr(r){let t=[];for(let n of r)if(n instanceof b5){let i=n.table?.name?.value||n.table?.alias?.value,o=n._excludeColumns;t.push({isStar:!0,tableQualifier:i,excludeColumns:o})}else if(n instanceof qv){let i=n.expression;if(i instanceof ZX){let o=i.table?.name?.value;t.push({isStar:!0,tableQualifier:o})}}return t}function xil(r){return Cwr(r).length>0}function Pil(r){if(r instanceof Ig)return typeof r.name=="string"?r.name:r.name?.value||null;if(r instanceof sO)return Pil(r.expression);let t=r.name;return t instanceof Wo&&t.value||null}function vP1(r,t,n,i,o,s){let a=[],u=new Set,p=new Map;for(let d of t)p.set(d.name,{dataType:d.dataType,sourceAlias:d.sourceAlias,transform:d.transform,sourceRefs:d.sourceRefs,annotations:d.annotations});if(Ewr(n.relations??[],i),xil(r)){let d=Cwr(r);for(let f of d){let h=new Set(f.excludeColumns??[]),A=OWo(n.relations??[],i,o,f.tableQualifier,s);for(let[E,v]of A)h.has(E.toUpperCase())||u.has(E.toUpperCase())||(a.push({name:E,dataType:v.dataType,sourceAlias:v.sourceAlias,transform:v.transform,sourceRefs:v.sourceRefs,annotations:v.annotations}),u.add(E.toUpperCase()))}np.debug(`SELECT * found, got ${a.length} columns from relations`)}let l=r.filter(d=>d instanceof qv);for(let d of l){let f=typeof d.alias=="string"?d.alias:d.alias?.value,h;if(f)h=L4t(f);else{let E=Pil(d.expression);if(E)h=L4t(E);else{let v=KL(d.expression);if(v){let T=v.getText();if(T==="*")continue;let w=T.replace(/::[A-Za-z_][A-Za-z0-9_(),.]*$/i,"");w.includes(".")?h=L4t(w.split(".").pop()||""):h=L4t(w)}}}let A=h?L4t(h):void 0;if(A&&p.has(A)){let E=A.toUpperCase();if(!u.has(E)){let v=p.get(A);a.push({name:A,dataType:v.dataType,sourceAlias:v.sourceAlias,transform:v.transform,sourceRefs:v.sourceRefs,annotations:v.annotations}),u.add(E)}}}return a}function TP1(r,t,n,i){let o={cteColumns:new Map,aliasToCteName:new Map,physicalTableContext:bP1(t,i)};if(!r.commonTableExpressions||r.commonTableExpressions.length===0)return o;np.debug(`Processing ${r.commonTableExpressions.length} CTEs`);let s=EP1(r.commonTableExpressions);np.debug(`CTE processing order: ${s.join(", ")}`);for(let a of s){let u=CP1(a,r.commonTableExpressions);if(!u){np.warn(`CTE ${a} not found in common table expressions`);continue}np.debug(`Processing CTE: ${a}`),Ewr(u.query.relations??[],o);let p=wWo(o,t,u.query.relations??[],i);try{let c={query:u.query},l=FZe(c,p,n);np.debug(`Inferred types for CTE ${a}:`,l.map(h=>`${h.name}: ${h.dataType}`));let d=vP1(u.query.projections,l,u.query,o,t,i),f=a.toUpperCase();o.cteColumns.set(f,d),np.debug(`Added CTE ${f} to scope with ${d.length} columns`)}catch(c){np.warn(`Failed to process CTE ${a}:`,c)}}return o}function k4t(r,t,n,i){let o=vil(n);if(o){let f=wil(o,i);if(f)return k4t(f,t,o,i)}np.debug(`AST has CTEs: ${!!r.commonTableExpressions&&r.commonTableExpressions.length>0}`);let s=TP1(r,t,n,i);np.debug(`Scope created with ${s.cteColumns.size} CTEs`),Ewr(r.query.relations??[],s);let a=wWo(s,t,r.query.relations??[],i),u=Cwr(r.query.projections),p=u.length>0,c=[],l=new Set;if(p){for(let h of u){let A=new Set(h.excludeColumns??[]),E=OWo(r.query.relations??[],s,t,h.tableQualifier,i);for(let[v,T]of E)A.has(v.toUpperCase())||l.has(v)||(l.add(v),c.push({name:v,...T}))}np.debug("SELECT * found in final SELECT, inferred types from relations:",c.map(h=>`${h.name}: ${h.dataType} (${h.sourceAlias||"?"})`));let f=FZe(r,a,n);for(let h of f)l.has(h.name)||(l.add(h.name),c.push(h))}else{let f=FZe(r,a,n);for(let h of f)c.push(h);np.debug("Inferred types from AST:",c.map(h=>`${h.name}: ${h.dataType}`))}let d=r._setOperations;if(d&&d.length>0&&wP1(d,c,t,n,i),p&&n&&/pivot/i.test(n)){let f=r.query.relations??[],h=f.length>0&&f.every(v=>!!v.position?.end)?void 0:wil(n,i)??void 0,A=h?.query.relations??f,E=_il(OP1(A,n));if(E){let v=_P1(c);return v.size===0&&h&&(v=IP1(OWo(h.query.relations,s,t,void 0,i))),{columns:Iil(E,v,i),scope:s}}}return{columns:c,scope:s}}function _P1(r){let t=new Map;for(let n of r)t.set(n.name.toUpperCase(),{dataType:n.dataType,sourceAlias:n.sourceAlias,transform:n.transform,sourceRefs:n.sourceRefs,annotations:n.annotations});return t}function IP1(r){let t=new Map;for(let[n,i]of r)t.set(n.toUpperCase(),i);return t}function RP1(r,t){let n=r.split(`
|
|
10109
10109
|
`),i=0;for(let o=0;o<t.line-1&&o<n.length;o++)i+=n[o].length+1;return i+t.column}function OP1(r,t){if(!t||r.length===0)return;let n=-1;for(let i of r){let o=i.position?.end;if(!o)return;let s=RP1(t,o);s>n&&(n=s)}if(!(n<0||n>=t.length))return IWo(t.slice(n))}function wil(r,t){try{let o=new BZe(ywr(t)).parse(r).root?.statements?.[0];if(o instanceof s_)return o}catch(n){np.warn("Failed to re-parse recovered CTAS inner query:",n)}return null}function wP1(r,t,n,i,o){for(let s of r){let a;try{a=k4t(s.statement,n,i,o)}catch(p){np.warn(`Failed to infer types for set-op operand "${s.operatorText}", skipping branch:`,p);continue}let u=/\bBY\s+NAME\b/i.test(s.operatorText);for(let p=0;p<t.length;p++){let c=t[p];if(!c)continue;let l=u?a.columns.find(d=>d.name.toUpperCase()===c.name.toUpperCase()):a.columns[p];!l||l.sourceRefs.length===0||(c.sourceRefs=[...c.sourceRefs,...l.sourceRefs])}}}var doC=Je("SQL_PARSING");var zH=Je("SQL_PARSING"),MP1=HXe({includeSource:!1,requireSecondArg:!0}),Swr=class{originalSQL;constructor(t){this.originalSQL=t}visitSemanticViewStatement(t){zH.debug("visitSemanticViewStatement called");let n=t.tablesClause(),i=this.extractRefsFromTablesClause(n),o={tablesClause:this.extractTablesClause(n),refs:i,comment:this.extractComment(t.commentClause?.()),aiSqlGeneration:this.extractAiSqlGeneration(t.aiSqlGenerationClause?.()),aiQuestionCategorization:this.extractAiQuestionCategorization(t.aiQuestionCategorizationClause?.()),copyGrants:t.COPY?.()!==null&&t.GRANTS?.()!==null};zH.debug("Extracting semantic attributes");let s=t.relationshipsClause?.(),a=t.factsClause?.(),u=t.dimensionsClause?.(),p=t.metricsClause?.(),c={relationships:this.extractRelationships(s),facts:this.extractFacts(a),dimensions:this.extractDimensions(u),metrics:this.extractMetrics(p)};return zH.debug("Extracted semantic attributes",{relationships:c.relationships.length,facts:c.facts.length,dimensions:c.dimensions.length,metrics:c.metrics.length,refs:i.length}),{semanticAttributes:c,preservedParts:o,refs:i,type:"semanticView"}}extractTablesClause(t){if(!t)return"()";let n=t.start?.start,i=t.stop?.stop;return n===void 0||i===void 0?"()":this.originalSQL.substring(n,i+1)}extractRefsFromTablesClause(t){if(!t)return[];let n=[],i=t.logicalTable();for(let o of i){let s=this.extractRefFromLogicalTable(o);s&&n.push(s)}return n}extractRefFromLogicalTable(t){let n=t.tableName();if(!n)return null;let i=n.coalesceMacro();return i?this.extractRefFromMacro(i,t):null}extractRefFromMacro(t,n){let o=this.getText(t).match(MP1);if(!o)return null;let s=o[1],a=o[3],u=o[5];if(!a||!u)return null;let p=n.tableAlias(),c=p&&p.length>0?this.getText(p[0]?.identifier()):void 0,l=t.start?.start,d=t.stop?.stop,f=l!==void 0&&d!==void 0?{start:l,end:d+1}:void 0;return{macroType:s,locationName:a,nodeName:u,tableAlias:c,position:f}}extractComment(t){if(!t)return;let n=t.stringLiteral();return n?this.unquoteString(this.getText(n)):void 0}extractAiSqlGeneration(t){if(!t)return;let n=t.stringLiteral();return n?this.unquoteString(this.getText(n)):void 0}extractAiQuestionCategorization(t){if(!t)return;let n=t.stringLiteral();return n?this.unquoteString(this.getText(n)):void 0}extractRelationships(t){if(!t)return[];let n=[],i=t.relationshipDef();for(let o of i||[]){let s=this.parseRelationship(o);s&&n.push(s)}return n}parseRelationship(t){if(!t)return null;let n=t.relationshipIdentifier(),i=n?this.getText(n.identifier()):void 0,o=t.fromTableAlias(),s=o?this.getText(o.identifier()):"",a=t.columnNameList(),u=a?a.columnName().map(f=>this.getText(f.identifier())):[],p=t.toTableAlias(),c=p?this.getText(p.identifier()):"",l=t.toColumnList(),d=l&&l.toColumn()?l.toColumn().map(f=>{let h=f.columnName(),A=h?this.getText(h.identifier()):"",E=f.ASOF?.()!==null;return{name:A,asof:E}}):[];return{identifier:i,fromTableAlias:s,fromColumns:u,toTableAlias:c,toColumns:d}}extractFacts(t){if(!t)return[];let n=[],i=t.factExpression();for(let o of i||[]){let s=this.parseFact(o);s&&n.push(s)}return n}parseFact(t){if(!t)return null;try{let n=t.PRIVATE?.()?"PRIVATE":t.PUBLIC?.()?"PUBLIC":void 0,i="",o="";if(t.tableAlias){let c=t.tableAlias();i=c?this.getText(c.identifier?c.identifier():c):""}if(t.factName){let c=t.factName();o=c?this.getText(c.identifier?c.identifier():c):""}let s=t.sqlExpression?t.sqlExpression():null,a=s?this.extractSQLExpression(s):"",u=this.extractSynonyms(t),p=this.extractCommentFromClause(t);return{tableAlias:i,name:o,sqlExpression:a,visibility:n,synonyms:u,comment:p}}catch(n){return zH.error("Error parsing fact:",n),null}}extractDimensions(t){if(!t)return[];let n=[],i=t.dimensionExpression();for(let o of i||[]){let s=this.parseDimension(o);s&&n.push(s)}return n}parseDimension(t){if(!t)return null;try{let n="",i="";if(t.tableAlias){let c=t.tableAlias();n=c?this.getText(c.identifier?c.identifier():c):""}if(t.dimensionName){let c=t.dimensionName();i=c?this.getText(c.identifier?c.identifier():c):""}let o=t.sqlExpression?t.sqlExpression():null,s=o?this.extractSQLExpression(o):"",a=this.extractCortexSearchService(t),u=this.extractSynonyms(t),p=this.extractCommentFromClause(t);return{tableAlias:n,name:i,sqlExpression:s,cortexSearchService:a,synonyms:u,comment:p}}catch(n){return zH.debug("Error parsing dimension:",n),null}}extractMetrics(t){if(!t)return[];let n=[];try{let i=t.metricExpression?t.metricExpression():[],o=t.windowFunctionMetricExpression?t.windowFunctionMetricExpression():[];for(let s of i||[]){let a=this.parseMetric(s,!1);a&&n.push(a)}for(let s of o||[]){let a=this.parseMetric(s,!0);a&&n.push(a)}}catch(i){zH.debug("Error extracting metrics:",i)}return n}parseMetric(t,n){if(!t)return null;try{let i=t.PRIVATE?.()?"PRIVATE":t.PUBLIC?.()?"PUBLIC":void 0,o,s="";if(t.tableAlias){let l=t.tableAlias();o=l?this.getText(l.identifier?l.identifier():l):void 0}if(t.metricName){let l=t.metricName();s=l?this.getText(l.identifier?l.identifier():l):""}let a="",u;if(n&&"windowSpec"in t){let l=t.windowSpec?t.windowSpec():null;a=this.extractWindowFunctionSQL(t,l),u=this.extractWindowFunctionParams(l)}else if("sqlExpression"in t){let l=t.sqlExpression?t.sqlExpression():null;a=l?this.extractSQLExpression(l):""}let p=this.extractSynonyms(t),c=this.extractCommentFromClause(t);return{tableAlias:o,name:s,sqlExpression:a,isWindowFunction:n,windowFunctionParams:u,visibility:i,synonyms:p,comment:c}}catch(i){return zH.debug("Error parsing metric:",i),null}}extractSQLExpression(t){if(!t)return"";let n=t.start?.start,i=t.stop?.stop;return n===void 0||i===void 0?"":this.originalSQL.substring(n,i+1).trim()}extractWindowFunctionSQL(t,n){if(!t||!n)return"";let i=t.start?.start,o=t.stop?.stop;return i===void 0||o===void 0?"":this.originalSQL.substring(i,o+1).trim()}extractWindowFunctionParams(t){if(t)try{let n,i=t.dimensionList?t.dimensionList():null;if(i)n={type:"EXCLUDING",dimensions:(i.dimensionReference?i.dimensionReference():[]).map(l=>l.identifier?this.getText(l.identifier()):this.getText(l))};else{let p=t.partitionByExprs?t.partitionByExprs():null;p&&(n=(p.sqlExpression?p.sqlExpression():[]).map(l=>this.extractSQLExpression(l)).join(", "))}let o=t.orderByExprs?t.orderByExprs():null,s=o&&o.orderByExpr?o.orderByExpr().map(p=>{let c=p.sqlExpression?p.sqlExpression():null,l=c?this.extractSQLExpression(c):"",d=p.ASC?.()?"ASC":p.DESC?.()?"DESC":void 0,f=p.FIRST?.()?"FIRST":p.LAST?.()?"LAST":void 0;return{expression:l,direction:d,nulls:f}}):void 0,a=t.windowFrameClause?t.windowFrameClause():null,u=a?this.getText(a):void 0;if(n||s||u)return{partitionBy:n,orderBy:s,windowFrame:u}}catch(n){zH.debug("Error extracting window function params:",n)}}extractCortexSearchService(t){if(t)try{let i=this.getText(t).match(/WITH\s+CORTEX\s+SEARCH\s+SERVICE\s+([^\s(]+)(?:\s+USING\s+([^\s)]+))?/i);if(i&&i[1])return{serviceName:i[1],columnName:i[2]}}catch(n){zH.debug("Error extracting cortex search service:",n)}}extractSynonyms(t){if(t)try{let i=this.getText(t).match(/WITH\s+SYNONYMS\s*\(?\s*([^)]+)\)?/i);if(i&&i[1]){let s=i[1].matchAll(/'([^']+)'/g),a=Array.from(s,u=>u[1]).filter(u=>u!==void 0);return a.length>0?a:void 0}}catch(n){zH.debug("Error extracting synonyms:",n)}}extractCommentFromClause(t){if(t)try{let i=this.getText(t).match(/COMMENT\s*=\s*'([^']*)'/i);if(i&&i[1]!==void 0)return this.unquoteString(i[1])}catch(n){zH.debug("Error extracting comment:",n)}}getText(t){return t?typeof t.getText=="function"?t.getText():String(t):""}unquoteString(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}};var vwr=class{canHandle(t,n){if(n!=="snowflake")return!1;let i=t.semanticViewStatement?.();return i!=null}visit(t,n,i,o){let s=t.semanticViewStatement?.();if(!s)throw new Error("Expected semantic view statement context");return new Swr(n).visitSemanticViewStatement(s)}};function xP1(){aPt.register("snowflake",new vwr)}xP1();var QoC=Je("STEPS");var q4t=class extends nt{},UZe=class extends q4t{},Twr=class extends q4t{};var _wr=Je("SQL_PARSING");var Dil=(r,t)=>{try{let n=new sS(_wr),o=new hwr(ywr(t)).parse(r);return n.logMetricWithMinDuration("parseFrom",100,{sqlString:r,platformKind:t}),o}catch{let i=`Error parsing ${t} FROM: ${r}`;throw _wr.error(i),new Twr(i)}};var Nil,MWo,xWo=(r,t)=>{let n=`${t}::${r}`;if(Nil===n&&MWo!==void 0)return MWo;let o=Dil(r,t).root;if(!o)throw new UZe("AST unexpectedly had no root.");let s=[],a=u=>{if(!(!u.ref.param1||!u.ref.param2)){if(!u.alias){_wr.errorContext(GD,`RefRelation node missing name. Relation table name: ${u.ref.param2.value}, Relation storage location: ${u.ref.param1.value}`);return}s.push({alias:u.alias.value,nodeName:u.ref.param2.value,locationName:u.ref.param1.value})}};return o.relations.forEach(u=>{u instanceof E5?u.relations.filter(p=>p instanceof z1).forEach(p=>a(p)):u instanceof z1?a(u):_wr.infoContext(GD,`Other relation type detected. SQL string: ${r}`)}),Nil=n,MWo=s,s};var PWo=r=>({columns:[],scope:{cteColumns:new Map,aliasToCteName:new Map,physicalTableContext:{dialect:r,getDataTypeOfColumn:()=>null,resolveColumnSource:()=>null}}}),NWo=r=>{let t=o=>{let s=r?.find(a=>a.key.toLowerCase()===o.toLowerCase());if(s?.type==="keyValue"&&s.value.length>0&&s.value[0]!==void 0)return String(s.value[0])},n=t("id");if(!n)return{id:"",nodeType:"stage",materializationType:"table",description:"",errorMessage:'Missing @id annotation or @id has no value. Expected format: @id("node-123")'};let i=t("nodeType");return i?{id:n,nodeType:i,materializationType:t("materializationType")??"table",description:t("description")??""}:{id:n,nodeType:"",materializationType:"",description:"",errorMessage:'Missing @nodeType annotation or @nodeType has no value. Expected format: @nodeType("<nodeTypeID>")'}};var Bil=()=>({nullable:!0,defaultValue:"",name:"",dataType:"",description:"",columnReference:{stepCounter:"0",columnCounter:"0"},sourceColumnReferences:[{columnReferences:[{columnCounter:"0",stepCounter:"0"}],transform:""}],systemColumnType:"None",keyColumnType:"None",config:{},appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]}});var BP1=Je("SQL_PARSING"),Lil=r=>{let t=new Set,n=[];for(let i of r){let o=`${i.locationName}:${i.nodeName}`;t.has(o)||(t.add(o),n.push(i))}return n},kil=(r,t,n)=>{if(!r||t.length===0)return;let i=n??wv(r),o={};for(let s of t){let a=i.get(s.locationName,s.nodeName);if(a){let u=r[a];u&&(o[a]=u)}}return BP1.debug(`Built referenced nodes lookup with ${Object.keys(o).length} nodes from ${t.length} refs`),Object.keys(o).length>0?o:void 0},qil=r=>r.issues.length>0?r.issues.map(t=>{let n=t.message;if("position"in t&&t.position){let i=t.position;i.start&&i.start.line&&i.start.column!==void 0&&(n=`Line ${i.start.line}, Column ${i.start.column}: ${n}`)}return n}).join("; "):"SQL parsing failed. Please fix the SQL syntax first.";function DWo(r){let t={};for(let n of r)n.type==="simple"?t[n.key]=!0:n.type==="keyValue"&&(t[n.key]={parameters:n.value});return t}var LP1=new Map(XYe.map(r=>[r.toLowerCase(),r])),kP1=(r,t)=>{let n=DWo(t);for(let[i,o]of Object.entries(n)){let s=LP1.get(i.toLowerCase());s?r[s]=!0:r.config={...r.config,[i]:o}}};function qP1(r){let t=[...r].sort((i,o)=>i-o),n=[];for(let i of t){let o=n[n.length-1];o&&i===o.endLine+1?o.endLine=i:n.push({startLine:i,endLine:i})}return n}function F4t(r){let t=new Set,n=(o,s)=>{for(let a=o;a<=s;a++)t.add(a)};for(let o of r.comments)n(o.position.startLine,o.position.endLine);for(let o of r.topLevelAnnotations??[])o.position&&n(o.position.startLine,o.position.endLine);return r.originalSql.split(`
|
|
10110
|
-
`).forEach((o,s)=>{o.trim()===""&&t.add(s+1)}),qP1(t)}var Fil=(r,t)=>r.map(i=>zj(Bil(),o=>{o.name=i.name,o.dataType=i.dataType,o.transform=i.transform||"",o.columnReference={stepCounter:t,columnCounter:i.name};let s=(i.sourceRefs??[]).filter(p=>p.type==="physical").map(p=>({stepCounter:p.stepCounter,columnCounter:p.columnCounter})),a=new Set,u=s.filter(p=>{let c=`${p.stepCounter}::${p.columnCounter}`;return a.has(c)?!1:(a.add(c),!0)});o.sourceColumnReferences=[{columnReferences:u,transform:i.transform||""}],i.annotations&&i.annotations.length>0&&kP1(o,i.annotations)})),U4t=(r,t,n,i)=>[{name:i,join:{joinCondition:t},dependencies:n,noLinkRefs:[],customSQL:{customSQL:r}}];var Xy=Je("SQL_PARSING"),Iwr=new Map;var BWo=(r,t,n,i,o,s)=>{s>=200&&new sS(Je("PERFORMANCE"),{nodeID:r,platform:t}).logMetric("v2-antlr-parse",{sqlLength:n,platform:t,refCount:i,parseErrors:o},s)},LWo=()=>({columns:[],scope:{cteColumns:[],aliasToCteName:[]}}),FP1=r=>({columns:r.columns,scope:{cteColumns:Array.from(r.scope.cteColumns.entries()),aliasToCteName:Array.from(r.scope.aliasToCteName.entries())}}),UP1=(r,t)=>({columns:r.columns,scope:{cteColumns:new Map(r.scope.cteColumns),aliasToCteName:new Map(r.scope.aliasToCteName),physicalTableContext:{dialect:t,getDataTypeOfColumn:()=>null,resolveColumnSource:()=>null}}}),Uil=r=>Lil(r.map(t=>({locationName:t.param1??"",nodeName:t.param2??""}))),kWo=r=>r.topLevelAnnotations?.map(t=>t.type==="simple"?{type:"simple",key:t.key}:{type:"keyValue",key:t.key,value:t.value}),zP1=r=>{let{requestId:t,nodeID:n,sqlString:i,dialect:o,skipCache:s}=r;if(!o)throw Xy.fatal(`[handleExtractRefs] Dialect is missing for nodeID ${n} \u2014 this is a programming error`),new Error(`Dialect is required for extractRefs request for nodeID ${n}`);if(!s){let a=Iwr.get(n);if(a&&a.sqlString===i&&a.dialect===o)return Xy.debug(`[handleExtractRefs] Cache hit for nodeID ${n} \u2014 reusing previous parse`),{type:"extractRefsResult",requestId:t,nodeID:n,refs:a.refs,topLevelAnnotations:kWo(a.coalesceResult),errorMessage:a.errorMessage,nonSqlLineRanges:F4t({comments:a.coalesceResult.comments,topLevelAnnotations:a.coalesceResult.structured?.topLevelAnnotations,originalSql:i})}}Xy.debug(`[handleExtractRefs] Starting ref extraction for nodeID ${n}, dialect=${o}, sqlLength=${i.length}`);try{let a,u,p=performance.now();try{let d=qZe(i,o,n);if("type"in d&&d.type==="sql")u=d,a=u;else throw Xy.error(`[handleExtractRefs] Expected SQL result but got semantic view for nodeID ${n}`),new Error("Semantic view parsing not supported in extractRefs")}catch(d){if(d instanceof p4){let f=performance.now()-p;return BWo(n,o,i.length,0,d.errors?.length??-1,f),Xy.error(`[handleExtractRefs] CoalesceParser SQLParseError for nodeID ${n}:`,d.errors),{type:"extractRefsResult",requestId:t,nodeID:n,refs:[],errorMessage:d.getCustomerFacingMessage()}}throw d}let c=performance.now()-p;if(a.numberOfParserErrors>0){let d=qil(a),f=Uil(u.refs);BWo(n,o,i.length,f.length,a.numberOfParserErrors,c),Xy.info(`[handleExtractRefs] SQL parse errors for nodeID ${n}:`,`${a.numberOfParserErrors} error(s), extracted ${f.length} ref(s) despite errors`),a.ast&&!s&&Iwr.set(n,{ast:a.ast,parseResult:a,refs:f,sqlString:i,dialect:o,coalesceResult:u,errorMessage:d});let h=F4t({comments:u.comments,topLevelAnnotations:u.structured?.topLevelAnnotations,originalSql:i});return{type:"extractRefsResult",requestId:t,nodeID:n,refs:f,topLevelAnnotations:kWo(u),errorMessage:d,nonSqlLineRanges:h}}let l=Uil(u.refs);return BWo(n,o,i.length,l.length,0,c),a.ast&&!s&&Iwr.set(n,{ast:a.ast,parseResult:a,refs:l,sqlString:i,dialect:o,coalesceResult:u}),Xy.debug(`[handleExtractRefs] Successfully extracted ${l.length} ref(s) for nodeID ${n}`),{type:"extractRefsResult",requestId:t,nodeID:n,refs:l,topLevelAnnotations:kWo(u)}}catch(a){return Xy.error(`[handleExtractRefs] Unexpected error for nodeID ${n}:`,a),{type:"extractRefsResult",requestId:t,nodeID:n,refs:[],errorMessage:`extractRefs failed for nodeID ${n}: ${a}`}}},QP1=r=>{let{requestId:t,nodeID:n,referencedNodes:i}=r;Xy.debug(`[handleInferTypes] Starting type inference for nodeID ${n}`);let o=Iwr.get(n);if(!o)return Xy.error(`[handleInferTypes] No cached AST for nodeID ${n}`,"\u2014 extractRefs was not called first. This indicates an out-of-order processing bug."),{type:"inferTypesResult",requestId:t,nodeID:n,columns:[],sourceMapping:U4t("","",[],r.nodeName),cteString:"",inferenceResult:LWo(),errorMessage:`No cached AST for nodeID: ${n}. extractRefs must be called first.`,annotations:{},nonSqlLineRanges:[]};let{ast:s,parseResult:a,sqlString:u,coalesceResult:p}=o,c=Object.keys(i).length;Xy.debug(`[handleInferTypes] Cache hit for nodeID ${n}, dialect=${o.dialect}, referencedNodes=${c}`);try{let l=LWo();try{let v=o.dialect,T=k4t(s,i,u,v);l=FP1(T)}catch(v){let T=v instanceof Error?v.message:String(v);throw Xy.error(`Failed to infer types for nodeID ${n}:`,v),new Error(`Failed to infer types: ${T}`)}let d={};if(p.structured?.topLevelAnnotations&&p.structured.topLevelAnnotations.length>0&&(d=DWo(p.structured.topLevelAnnotations)),p.columnMetadata){let v=new Map;for(let T of p.columnMetadata)T.annotations&&T.annotations.length>0&&T.name&&v.set(T.name,T.annotations);if(v.size>0)for(let T of l.columns){let w=v.get(T.name);w&&(T.annotations=w)}}let f=Fil(l.columns,n),h=o.refs,A=U4t(u,a.joinString??"",h,r.nodeName),E=F4t({comments:p.comments,topLevelAnnotations:p.structured?.topLevelAnnotations,originalSql:u});return Xy.debug(`[handleInferTypes] Successfully inferred ${f.length} column(s) for nodeID ${n}`),{type:"inferTypesResult",requestId:t,nodeID:n,columns:f,sourceMapping:A,cteString:a.cteString??"",inferenceResult:l,annotations:d,topLevelAnnotations:p.structured?.topLevelAnnotations?.map(v=>v.type==="simple"?{type:"simple",key:v.key}:{type:"keyValue",key:v.key,value:v.value}),nonSqlLineRanges:E}}catch(l){let d=`inferTypes failed for nodeID ${n}: ${l}`;Xy.error(`Error in inferTypes for nodeID ${n}:`,l);let f=F4t({comments:p.comments,topLevelAnnotations:p.structured?.topLevelAnnotations,originalSql:u});return{type:"inferTypesResult",requestId:t,nodeID:n,columns:[],sourceMapping:U4t(u,"",[],r.nodeName),cteString:"",inferenceResult:LWo(),errorMessage:d,annotations:{},nonSqlLineRanges:f}}},jP1=r=>{let{requestId:t,nodeID:n,sqlString:i}=r;Xy.debug("handleParseSemanticView called",{nodeID:n,sqlLength:i.length});try{let o=qZe(i,"snowflake","");if("type"in o&&o.type==="semanticView"){let s=o;return Xy.debug("parseSqlScript (semantic view) result",{hasSemanticAttributes:!!s.semanticAttributes,hasPreservedParts:!!s.preservedParts,relationships:s.semanticAttributes?.relationships?.length,facts:s.semanticAttributes?.facts?.length,dimensions:s.semanticAttributes?.dimensions?.length,metrics:s.semanticAttributes?.metrics?.length}),{type:"parseSemanticViewResult",requestId:t,nodeID:n,semanticAttributes:s.semanticAttributes,preservedParts:s.preservedParts}}else throw new Error("Expected semantic view but got regular SQL")}catch(o){Xy.error("Error in parseSemanticView:",o);let s;return o instanceof p4?s=`parseSemanticView failed for nodeID ${n}: ${o.getCustomerFacingMessage()}`:o instanceof Error?s=`parseSemanticView failed for nodeID ${n}: ${o.message}`:s=`parseSemanticView failed for nodeID ${n}: ${String(o)}`,{type:"parseSemanticViewResult",requestId:t,nodeID:n,errorMessage:s,semanticAttributes:{relationships:[],facts:[],dimensions:[],metrics:[]},preservedParts:{tablesClause:"()",refs:[]}}}},GP1=r=>{let{requestId:t,sqlString:n,dialect:i}=r;if(!i)throw new Error("Dialect is required for extractJoinAliases request");try{let o=xWo(n,i);return{type:"extractJoinAliasesResult",requestId:t,aliases:o}}catch(o){let s=o instanceof Error?o.message:String(o);return o instanceof UZe||Xy.error("[handleExtractJoinAliases] Unexpected error:",o),{type:"extractJoinAliasesResult",requestId:t,aliases:[],errorMessage:s}}},Rwr={async sendExtractRefs(r){return zP1(r)},async sendInferTypes(r){return QP1(r)},async sendParseSemanticView(r){return jP1(r)},async sendExtractJoinAliases(r){return GP1(r)}},zil=async(r,t)=>{let{sqlString:n,stepCounter:i,allNodes:o,refLookup:s,dialect:a}=r;if(!i)throw Xy.fatal("[processSQL] stepCounter is missing \u2014 caller must provide a valid nodeID"),new Error("stepCounter is required");if(!o)throw Xy.fatal(`[processSQL] allNodes is missing for nodeID ${i} \u2014 caller must provide the nodes map`),new Error("allNodes is required");if(!a)throw Xy.fatal(`[processSQL] dialect is missing for nodeID ${i} \u2014 caller must specify the SQL dialect`),new Error("dialect is required");Xy.info(`[processSQL] Processing SQL for nodeID ${i}, dialect=${a}, sqlLength=${n.length}`);let u=i,p=await t.sendExtractRefs({type:"extractRefs",requestId:u,nodeID:i,sqlString:n,dialect:a}),l=o[i]?.operation?.name??"";if(p.errorMessage)return Xy.info(`[processSQL] Ref extraction returned errors for nodeID ${i}: ${p.errorMessage}`),{sourceMapping:U4t(n,"",p.refs,l),cteString:"",columns:[],errorMessage:p.errorMessage,inferenceResult:PWo(a),annotations:{},topLevelAnnotations:[],nonSqlLineRanges:p.nonSqlLineRanges??[]};let d=kil(o,p.refs,s)??{},f=await t.sendInferTypes({type:"inferTypes",requestId:u,nodeID:i,referencedNodes:d,nodeName:l});return f.errorMessage?(Xy.info(`[processSQL] Type inference returned errors for nodeID ${i}: ${f.errorMessage}`),{sourceMapping:f.sourceMapping,cteString:f.cteString,columns:f.columns,errorMessage:f.errorMessage,inferenceResult:PWo(a),annotations:f.annotations,topLevelAnnotations:f.topLevelAnnotations,nonSqlLineRanges:f.nonSqlLineRanges}):(Xy.debug(`[processSQL] Successfully processed SQL for nodeID ${i}: ${f.columns.length} column(s) inferred`),{sourceMapping:f.sourceMapping,cteString:f.cteString,columns:f.columns,inferenceResult:UP1(f.inferenceResult,a),annotations:f.annotations,topLevelAnnotations:f.topLevelAnnotations,nonSqlLineRanges:f.nonSqlLineRanges})};var Qil=Je("SQL_PARSING"),qWo=class{async processSQLAndGenerateMetadata(t,n,i,o,s){return Qil.debug("DirectSQLProcessingService.processSQLAndGenerateMetadata called",{stepCounter:n}),zil({sqlString:t,stepCounter:n,allNodes:i,refLookup:o,dialect:s},Rwr)}async extractRefs(t,n,i,o){Qil.debug("DirectSQLProcessingService.extractRefs called",{nodeID:i,dialect:n});let s=`extract-refs-${Date.now()}`,a=await Rwr.sendExtractRefs({type:"extractRefs",requestId:s,nodeID:i,sqlString:t,dialect:n,skipCache:o?.skipCache});return{refs:a.refs.map(p=>({locationName:p.locationName,nodeName:p.nodeName})),topLevelAnnotations:a.topLevelAnnotations,errorMessage:a.errorMessage}}async extractJoinAliases(t,n){let i=`extract-join-aliases-${Date.now()}`,o=await Rwr.sendExtractJoinAliases({type:"extractJoinAliases",requestId:i,sqlString:t,dialect:n});return{aliases:o.aliases,errorMessage:o.errorMessage}}},aO=new qWo;var HP1=r=>({type:"simple",key:r}),z4t=(r,t)=>({type:"keyValue",key:r,value:t}),FWo=r=>{let t=r[0];if(t?.type==="keyValue"&&t.value.length>0)return t.value[0];if(t?.type==="simple")return!0},Vil=(r,t,n)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",defaultValue:n,configToAnnotation(i){if(i==null)return null;let o=!!i;return o===n?null:z4t(r,[o])},annotationToConfig(i){let o=FWo(i);return o!==void 0?!!o:n}}),Wil=(r,t,n)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",defaultValue:n,configToAnnotation(i){let o=String(i??"");return o===n||o===""?null:z4t(r,[o])},annotationToConfig(i){let o=FWo(i);return o!==void 0?String(o):n}}),Kil=(r,t,n)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",defaultValue:n,configToAnnotation(i){let o=String(i??"");return o===String(n??"")||o===""?null:z4t(r,[o])},annotationToConfig(i){let o=i[0];if(!o||o.type==="simple")return n!==void 0?String(n):void 0;let s=o.type==="keyValue"&&o.value.length>0?o.value[0]:void 0;return s!==void 0?String(s):n!==void 0?String(n):void 0}}),VP1=(r,t)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",configToAnnotation(n){let i=String(n??"");return i?z4t(r,[i]):null},annotationToConfig(n){let i=FWo(n);return i!==void 0?String(i):void 0}}),Yil=(r,t)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"column-level",target:"column_flag",columnFlagKey:r,configToAnnotation(n){return HP1(r)},annotationToConfig(n){return n.length>0}}),WP1=(r,t,n)=>{let i=n.map(o=>o.attributeName);return{attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",isTabular:!0,configToAnnotation(o){return!Array.isArray(o)||o.length===0?null:o.map(s=>{let a=i.map(u=>{let p=s[u];return typeof p=="boolean"||typeof p=="number"?p:String(p??"")});return z4t(r,a)})},annotationToConfig(o){if(o.length!==0)return o.filter(s=>s.type==="keyValue").map(s=>{let a={};return i.forEach((u,p)=>{a[u]=(p<s.value.length?s.value[p]:void 0)??""}),a})}}},jil=(r,t,n,i)=>({...Vil(r,t,i),target:"node_field",nodeFieldKey:n}),KP1=(r,t,n,i)=>({...Wil(r,t,i),target:"node_field",nodeFieldKey:n}),Gil=(r,t,n)=>({...Yil(r,t),target:"column_flag",columnFlagKey:n}),YP1=()=>({...Kil("description","Description",""),target:"node_field",nodeFieldKey:"description"}),Hil=r=>wIt.includes(r),JP1=r=>{if(ZYe(r)){let t=k6o[r.type],n=t.attributeName;switch(r.type){case"multisourceToggle":return jil(n,t.displayName,n,r.default);case"overrideSQLToggle":return jil(n,t.displayName,n,r.default);case"materializationSelector":return KP1(n,t.displayName,n,r.default);case"businessKeyColumns":return Gil(n,t.displayName,n);case"changeTrackingColumns":return Gil(n,t.displayName,n);default:return null}}switch(r.type){case"toggleButton":{let t=Vil(r.attributeName,r.displayName,r.default);return Hil(r.attributeName)?{...t,target:"node_field",nodeFieldKey:r.attributeName}:t}case"dropdownSelector":{let t=Wil(r.attributeName,r.displayName,r.default);return Hil(r.attributeName)?{...t,target:"node_field",nodeFieldKey:r.attributeName}:t}case"textBox":return Kil(r.attributeName,r.displayName,r.default);case"columnDropdownSelector":return VP1(r.attributeName,r.displayName);case"columnSelector":return Yil(r.attributeName,r.displayName);case"tabular":return WP1(r.attributeName,r.displayName,r.columns);case"label":return null;default:return null}},UWo=r=>{let t=new Map,n=new Map,i=YP1();if(t.set(i.attributeName,i),n.set(i.annotationKey.toLowerCase(),i),r)for(let o of r)for(let s of o.items){let a=JP1(s);a&&(t.set(a.attributeName,a),n.set(a.annotationKey.toLowerCase(),a))}return{mappings:t,byAnnotationKey:n,getByAttribute(o){return t.get(o)},getByAnnotationKey(o){return n.get(o.toLowerCase())},isKnown(o){return n.has(o.toLowerCase())},annotationsToConfig(o){let s={},a={},u=[],p=[],c=new Map;for(let l of o){let d=l.key.toLowerCase(),f=c.get(d);f?f.push(l):c.set(d,[l])}for(let[l,d]of t){let f=c.get(d.annotationKey.toLowerCase())??[];if(d.target==="column_flag"){u.includes(d.annotationKey)||u.push(d.annotationKey);continue}if(d.isTabular&&p.push(d.attributeName),f.length===0){let A=d.defaultValue!==void 0?d.defaultValue:d.annotationToConfig([]);d.target==="node_field"&&d.nodeFieldKey?a[d.nodeFieldKey]=A:s[d.attributeName]=A;continue}let h=d.annotationToConfig(f);d.target==="node_field"&&d.nodeFieldKey?a[d.nodeFieldKey]=h:s[d.attributeName]=h}return{configUpdates:s,nodeFieldUpdates:a,columnFlagKeys:u,tabularKeys:p}}}};var o2e=class r{constructor(t,n,i){this.serviceName=t;this.childService=n;this.logger=i}serviceName;childService;logger;_mutex=new oce;_repository;initialize(t){return this._mutex.runExclusive(async()=>{this.isInitialized&&(this.logger.warning(`Closing ${this.serviceName} for re-initialization`),await this.close()),this.logger.info(`Initializing ${this.serviceName}`),this._repository=t.rootRepository,await this.init(t)})}identify(t){return this._mutex.runExclusive(async()=>{this.logger.debug("Identifying feature flags context",t);let n=await this.fetchOrg(t.org?.id);this.logger.debug("Identified feature flags context",n);let i=r.mergeOrgFlags(n),o;return r.isMockingLaunchDarkly(n)?(this.logger.warning(`Mocking LaunchDarkly integration for org ${n?.id}, fetching all flags from the org record`),o=new hv(i)):(o=await this.childService.identify(t),this.logger.debug("finished child service identify",n)),this.getFeatureFlagsCollection(i,o)})}async setOrgFlag(t,n,i){this.logger.info(`Setting org feature flag '${n}' for org ${t} to '${i}'`),await this.repository.org(t).merge({[n]:Ngr(),[`featureFlags.${n}`]:i})}async setTestFlag(t,n,i,o){if(kE(!DT[i].isLegacyOrgFlag||t==="org","Only orgs can be targeted for legacy feature flags",this.logger),t==="org"){let s=await this.repository.org(n).fetch();if(r.isMockingLaunchDarkly(s)||DT[i].isLegacyOrgFlag){DT[i].isLegacyOrgFlag||this.logger.warning(`Mocking LaunchDarkly integration for org ${n}, setting '${i}' to '${o}' on the org record`),await this.setOrgFlag(n,i,o);return}}await this.childService.setTestFlag(t,n,i,o)}async close(){this.logger.info(`Closing ${this.serviceName}`),this._repository=void 0,await this.childService.close()}get isInitialized(){return!!this._repository&&this.childService.isInitialized}get repository(){kE(!!this._repository,`${this.serviceName} is not initialized`,this.logger);let t=this._repository();return kE(!!t,`${this.serviceName}: org contexts cannot be identified before firestore is initialized`,this.logger),t}async fetchOrg(t){try{return t?await this.repository.org(t).fetch():void 0}catch(n){if(n instanceof Du||n instanceof Ww){this.logger.warning(`Unable to fetch feature flags for org ${t}: ${n.message}`);return}throw n}}static isMockingLaunchDarkly(t){return!!t?.mockLaunchDarklyIntegration}static mergeOrgFlags(t={}){let n={};for(let i of fgu)(r.isMockingLaunchDarkly(t)||DT[i].isLegacyOrgFlag)&&(n[i]=t.featureFlags?.[i]??t[i]);return n}};var $P1=["snowflake"];function nZ(r,t){return r.isFeatureEnabled("isSQLEditorEnabled",!1)?$P1.includes(t)?!0:r.isFeatureEnabled("enableSqlNodeV2AllPlatforms",!1):!1}var o2=Je("SQL_PARSING"),Jil=(r,t)=>zj(r,n=>{n.operation.metadata.columns=t.columns,n.operation.metadata.cteString=t.cteString,n.operation.metadata.sourceMapping=t.sourceMapping,t.config!==void 0&&(n.operation.config={...n.operation.config,...t.config}),n.operation.materializationType=t.materializationType;let i=n.operation;for(let[o,s]of Object.entries(t.nodeFieldUpdates))o!=="materializationType"&&s!==void 0&&(i[o]=s)}),XP1=async(r,t,n,i,o,s)=>{let a=s?.yieldEveryNNodes??2,u=s?.parseErrors;o2.info("hydrateSQLInputModeNodes: Starting hydration");let p=Object.keys(r);o2.debug(`hydrateSQLInputModeNodes: Found ${p.length} total nodes`);let c=new Map,l;try{l=n(p),o2.debug(`Topological sort completed: ${l.length} nodes in order`)}catch(A){throw o2.error("Error performing topological sort:",A),A}let d={...r},f=wv(d),h=0;for(let A of l){let E=d[A];if(!E)throw o2.fatal(`[hydrateSQLInputModeNodes] Node ${A} expected but missing from allNodes`,"\u2014 possible data corruption or race condition"),new Error(`Node ${A} not found in allNodes in hydrateSQLInputModeNodes`);if($P(E,{nodeID:A}))continue;if(!i0(E,{nodeID:A}))throw new Error(`Node ${A} is not a SQL step in hydrateSQLInputModeNode`);let v=E.operation.sqlType,T=t[v];if(!T){o2.debug(`Node type ${v} not found in stepTypesParsed for node ${A}`);continue}if(!U6o(T))continue;let N=BIt(E,0);try{o2.debug(`hydrateSQLInputModeNodes: Processing node ${A}, calling processSQLAndGenerateMetadata`);let k=performance.now(),L=await i.processSQLAndGenerateMetadata(N,A,d,f,o),q=performance.now()-k;if(o2.debug(`hydrateSQLInputModeNodes: processSQLAndGenerateMetadata completed for ${A} in ${q.toFixed(2)}ms`),L.errorMessage)throw o2.error(`[hydrateSQLInputModeNodes:${A}] SQL parse error: ${L.errorMessage}`),u?.set(A,L.errorMessage),new Error(`Error processing SQL for node ${A}: ${L.errorMessage}`);let G=T.metadata?.nodeMetadataSpec??null,H=G?UWo(G.config):null,V=L.topLevelAnnotations??Object.entries(L.annotations).map(([re,oe])=>oe===!0?{type:"simple",key:re}:{type:"keyValue",key:re,value:oe.parameters}),W={},F={};if(H){let re=H.annotationsToConfig(V);W=re.configUpdates,F=re.nodeFieldUpdates}let J=typeof F.materializationType=="string"?F.materializationType:null,Y=Object.entries(L.annotations).find(([re])=>re.toLowerCase()==="materializationtype")?.[1],z=typeof Y=="object"&&Y?.parameters?.[0]?String(Y.parameters[0]):null,X=J??z??"table",Z={columns:L.columns,cteString:L.cteString??"",sourceMapping:L.sourceMapping,config:H?W:void 0,materializationType:X,nodeFieldUpdates:F};c.set(A,Z),d[A]=Jil(E,Z),h++,o2.debug(`Successfully computed hydration for node ${A}`),h%a===0&&await new Promise(re=>setTimeout(re,0))}catch(k){o2.error(`[hydrateSQLInputModeNodes] Error processing SQL for node ${A} (type=${E.operation.sqlType}):`,k),u&&!u.has(A)&&u.set(A,k instanceof Error?k.message:String(k));continue}}return o2.info(`Computed hydration for ${h} SQL input mode nodes out of ${l.length} total nodes`),c},ZP1=(r,t)=>{if(t.size===0)return r;let n={...r};for(let[i,o]of t){let s=r[i];if(!s){o2.error(`[applySQLInputModeHydration] Node ${i} not found in allNodes \u2014 hydration result will be lost`);continue}if(!i0(s,{nodeID:i})){o2.error(`[applySQLInputModeHydration] Node ${i} is not a SQL step but was in hydration results \u2014 skipping`);continue}let a=s;n[i]=Jil(a,o)}return n},e41=(r,t)=>{let n=new Map;for(let a of t)n.set(a,0);for(let a of t){let u=r[a]||[];n.set(a,u.filter(p=>t.includes(p)).length)}let i=[];for(let a of t)(n.get(a)||0)===0&&i.push(a);let o=[],s=new Set;for(;i.length>0;){let a=i.shift();if(!s.has(a)){s.add(a),o.push(a);for(let[u,p]of Object.entries(r)){if(!t.includes(u))continue;if(p.includes(a)&&!s.has(u)){let l=(n.get(u)||0)-1;n.set(u,l),l===0&&i.push(u)}}}}for(let a of t)s.has(a)||(o2.debug(`Node ${a} was not in dependency graph, adding at end`),o.push(a));return o},Q4t=async(r,t,n,i,o,s)=>{o2.info("hydrateSQLInputModeNodesForAllContexts: Starting hydration");let a=X$(t),u=Object.keys(r);if(!nZ(bc().featureFlags,n)||!u.length)return o2.debug("No nodes to process"),r;o2.info(`hydrateSQLInputModeNodesForAllContexts: Found ${u.length} total nodes`);let p=o??wv(r),c={},l=[];for(let A of u){let E=r[A];if(!E||$P(E,{nodeID:A})||!i0(E,{nodeID:A}))continue;let v=E,T=v.operation.sqlType,w=a[T];if(!w||!U6o(w))continue;l.push(A);let N=v.operation.metadata.sourceMapping?.[0]?.dependencies??[],k=[];for(let L of N){let q=p.get(L.locationName,L.nodeName);q&&!k.includes(q)&&k.push(q)}c[A]=k}o2.info(`hydrateSQLInputModeNodesForAllContexts: Found ${l.length} SQL input mode nodes`);let f=await XP1(r,a,A=>{try{let E=e41(c,l);return o2.debug(`Topological sort completed: ${E.length} nodes in order`),E}catch(E){throw o2.error("[hydrateSQLInputModeNodesForAllContexts] Topological sort failed \u2014 possible circular dependency:",E),new Error("Error performing topological sort")}},i,n,{parseErrors:s});o2.info(`hydrateSQLInputModeNodesForAllContexts: Processed ${f.size} SQL input mode nodes`);let h=ZP1(r,f);return o2.info("hydrateSQLInputModeNodesForAllContexts: Returning updated nodes"),h};var zZe=class{suppress;constructor(){this.suppress=Uyu()}logMemory(t,n,i,o){if(this.suppress)return;let s=this.logTag+`(${n}): `,a=o.length>0?`${i} || ${o.join(" || ")}`:i;o.length?Je("PERFORMANCE").warnContext(t,s+a):Je("PERFORMANCE").infoContext(t,s+a)}async measureOperationAsync(t,n,i,o,s,a=!1){if(this.suppress||a)return await s();if(!this.getMemoryUsage(t))return await s();try{let p=this.getMemoryUsage(t);this.logMemorySnapshot(t,n,o);let c=await s();return this.logDeltaMetrics(t,p,o,i),c}catch(p){throw this.logMemorySnapshot(t,`(FAILED) ${i}`,o),p}}measureOperationSync(t,n,i,o,s){if(this.suppress||!this.getMemoryUsage(t))return s();try{let u=this.getMemoryUsage(t);this.logMemorySnapshot(t,n,o);let p=s();return this.logDeltaMetrics(t,u,o,i),p}catch(u){throw this.logMemorySnapshot(t,`(FAILED) ${i}`,o),u}}};var tk=class extends zZe{logTag="[NoopMemoryMonitor]: ";getMemoryReport(){}getLogContextWithMetrics(t,n,i){return{...t,metric_type:"memory_telemetry",operation:i}}cleanup(){}getMemoryUsage(){}logMemorySnapshot(){}logDeltaMetrics(){}};function s2e(r,t){return $g({snowflake:()=>r,fabric:()=>r,databricks:()=>r.toLowerCase(),bigquery:()=>r},t,"getNodeComparisonName")}function QZe(r,t){return $g({snowflake:()=>r,fabric:()=>r,databricks:()=>r.toLowerCase(),bigquery:()=>r.toLowerCase()},t,"getColumnComparisonName")}function j4t(r,t){return JSON.stringify([r,t])}function Owr(r,t,n,i){for(let[o,s]of Object.entries(r)){let{type:a,database:u,schema:p,name:c,metadata:l}=s.operation;if(a!=="sql")continue;let d=i?.[o]?.operation,f=t.get(j4t(u,p))?.get(s2e(c,n))??(d?t.get(j4t(d.database,d.schema))?.get(s2e(d.name,n)):void 0);s.operation.description=f?.objectComment??"";for(let h of l.columns)h.description=f?.columns[QZe(h.name,n)]??""}}var wwr=r=>"id"in r&&"presyncDetails"in r&&"targetEnvironment"in r&&"version"in r&&r.version===2&&"phasedDependencies"in r&&$il(r.phasedDependencies)&&"phasedNodeEdits"in r&&$il(r.phasedNodeEdits)&&!("dependencies"in r)&&!("nodeEdits"in r),$il=r=>typeof r=="object"&&!!r&&"addedTable"in r&&"alteredTable"in r&&"deletedTable"in r;var Xil=r=>typeof r=="object"&&!!r&&wwr(r),Zil=r=>tol(r)&&r.status==="failed"&&"error"in r,eol=r=>tol(r)&&r.status==="planning",tol=r=>typeof r=="object"&&!!r&&"status"in r&&(r.status==="planning"||r.status==="failed"),rol=r=>typeof r=="object"&&!!r&&"planStorageFilePath"in r&&typeof r.planStorageFilePath=="string";var a2e=(r,t)=>{let n=Object.entries(r).filter(([,i])=>i.operation.locationName===t);return{nodeIDs:n.map(([i])=>i),nodeNames:n.map(([,i])=>i.operation.name)}};var nol="Can't plan to specified environment as it is a development workspace";var t41=Je("PLAN"),iol=r=>{let t={};for(let n of Object.values(r))t[j4t(n.database,n.schema)]=n;return t};async function zWo(r,t,n,i){let o="[loadWarehouseComments]",s=iol(Z$(t,i)),a={...iol(Z$(n,i)),...s},u=new Map,p=new Map,c=(h,A)=>{let E=u.get(h);E||(E=new Map,u.set(h,E));let v=E.get(A);return v||(v={objectComment:"",columns:{}},E.set(A,v)),v},l=(h,A)=>{if(!r.isMissingLocationError(A))throw A;let E=s[h];if(!E||p.has(h))return;let{errorString:v}=ua(A).error;t41.warnContext(i,o,`[plan:missing-location] could not read desired-state comments for ${E.locationName} on ${r.name}`,A),p.set(h,{locationName:E.locationName,database:E.database,schema:E.schema,workspaceState:"desired",kind:"query-error",errorText:v,...a2e(t,E.locationName)})},[d,f]=await Promise.all([r.getObjects(a,!1,i),r.getColumns(a,!1,i)]);for(let[h,A]of Object.entries(d))A.handle(E=>{for(let v of E)c(h,s2e(v.name,r.name)).objectComment=v.comment},E=>l(h,E));for(let[h,A]of Object.entries(f))A.handle(E=>{for(let v of E)c(h,s2e(v.objectName,r.name)).columns[QZe(v.name,r.name)]=v.comment},E=>l(h,E));return{comments:u,missingLocations:[...p.values()]}}async function QWo(r,t,n,i){let{comments:o,missingLocations:s}=await zWo(r,n,t,i);return Owr(t,o,r.name),Owr(n,o,r.name,t),s}var jWo=B.object({subtitle:B.string(),title:B.string(),messages:B.array(B.string()).nonempty(),workspaceState:B.enum(["current","desired"]).optional()}),suC=B.object({stop:B.array(jWo),warn:B.array(jWo)}),Mwr=r=>!!r.stop.length,xwr=(r,t={})=>Ygc(r,Mwr,"Expected stop issue(s) were missing","PLAN",t,r),ool=(r,t={})=>{pd(!Mwr(r),"Unexpected stop issue(s) present","PLAN",t,r)};var sol=(r,t={})=>{if(!r)return;let n=B.array(jWo).safeParse(r);if(!n.success){Je("PLAN").errorContext(t,"[parseDeployIssues] malformed deploy issues; continuing without stopping plan creation",n.error.errors.map(i=>i.message).join(`
|
|
10110
|
+
`).forEach((o,s)=>{o.trim()===""&&t.add(s+1)}),qP1(t)}var Fil=(r,t)=>r.map(i=>zj(Bil(),o=>{o.name=i.name,o.dataType=i.dataType,o.transform=i.transform||"",o.columnReference={stepCounter:t,columnCounter:i.name};let s=(i.sourceRefs??[]).filter(p=>p.type==="physical").map(p=>({stepCounter:p.stepCounter,columnCounter:p.columnCounter})),a=new Set,u=s.filter(p=>{let c=`${p.stepCounter}::${p.columnCounter}`;return a.has(c)?!1:(a.add(c),!0)});o.sourceColumnReferences=[{columnReferences:u,transform:i.transform||""}],i.annotations&&i.annotations.length>0&&kP1(o,i.annotations)})),U4t=(r,t,n,i)=>[{name:i,join:{joinCondition:t},dependencies:n,noLinkRefs:[],customSQL:{customSQL:r}}];var Xy=Je("SQL_PARSING"),Iwr=new Map;var BWo=(r,t,n,i,o,s)=>{s>=200&&new sS(Je("PERFORMANCE"),{nodeID:r,platform:t}).logMetric("v2-antlr-parse",{sqlLength:n,platform:t,refCount:i,parseErrors:o},s)},LWo=()=>({columns:[],scope:{cteColumns:[],aliasToCteName:[]}}),FP1=r=>({columns:r.columns,scope:{cteColumns:Array.from(r.scope.cteColumns.entries()),aliasToCteName:Array.from(r.scope.aliasToCteName.entries())}}),UP1=(r,t)=>({columns:r.columns,scope:{cteColumns:new Map(r.scope.cteColumns),aliasToCteName:new Map(r.scope.aliasToCteName),physicalTableContext:{dialect:t,getDataTypeOfColumn:()=>null,resolveColumnSource:()=>null}}}),Uil=r=>Lil(r.map(t=>({locationName:t.param1??"",nodeName:t.param2??""}))),kWo=r=>r.topLevelAnnotations?.map(t=>t.type==="simple"?{type:"simple",key:t.key}:{type:"keyValue",key:t.key,value:t.value}),zP1=r=>{let{requestId:t,nodeID:n,sqlString:i,dialect:o,skipCache:s}=r;if(!o)throw Xy.fatal(`[handleExtractRefs] Dialect is missing for nodeID ${n} \u2014 this is a programming error`),new Error(`Dialect is required for extractRefs request for nodeID ${n}`);if(!s){let a=Iwr.get(n);if(a&&a.sqlString===i&&a.dialect===o)return Xy.debug(`[handleExtractRefs] Cache hit for nodeID ${n} \u2014 reusing previous parse`),{type:"extractRefsResult",requestId:t,nodeID:n,refs:a.refs,topLevelAnnotations:kWo(a.coalesceResult),errorMessage:a.errorMessage,nonSqlLineRanges:F4t({comments:a.coalesceResult.comments,topLevelAnnotations:a.coalesceResult.structured?.topLevelAnnotations,originalSql:i})}}Xy.debug(`[handleExtractRefs] Starting ref extraction for nodeID ${n}, dialect=${o}, sqlLength=${i.length}`);try{let a,u,p=performance.now();try{let d=qZe(i,o,n);if("type"in d&&d.type==="sql")u=d,a=u;else throw Xy.error(`[handleExtractRefs] Expected SQL result but got semantic view for nodeID ${n}`),new Error("Semantic view parsing not supported in extractRefs")}catch(d){if(d instanceof p4){let f=performance.now()-p;return BWo(n,o,i.length,0,d.errors?.length??-1,f),Xy.error(`[handleExtractRefs] CoalesceParser SQLParseError for nodeID ${n}:`,d.errors),{type:"extractRefsResult",requestId:t,nodeID:n,refs:[],errorMessage:d.getCustomerFacingMessage()}}throw d}let c=performance.now()-p;if(a.numberOfParserErrors>0){let d=qil(a),f=Uil(u.refs);BWo(n,o,i.length,f.length,a.numberOfParserErrors,c),Xy.info(`[handleExtractRefs] SQL parse errors for nodeID ${n}:`,`${a.numberOfParserErrors} error(s), extracted ${f.length} ref(s) despite errors`),a.ast&&!s&&Iwr.set(n,{ast:a.ast,parseResult:a,refs:f,sqlString:i,dialect:o,coalesceResult:u,errorMessage:d});let h=F4t({comments:u.comments,topLevelAnnotations:u.structured?.topLevelAnnotations,originalSql:i});return{type:"extractRefsResult",requestId:t,nodeID:n,refs:f,topLevelAnnotations:kWo(u),errorMessage:d,nonSqlLineRanges:h}}let l=Uil(u.refs);return BWo(n,o,i.length,l.length,0,c),a.ast&&!s&&Iwr.set(n,{ast:a.ast,parseResult:a,refs:l,sqlString:i,dialect:o,coalesceResult:u}),Xy.debug(`[handleExtractRefs] Successfully extracted ${l.length} ref(s) for nodeID ${n}`),{type:"extractRefsResult",requestId:t,nodeID:n,refs:l,topLevelAnnotations:kWo(u)}}catch(a){return Xy.error(`[handleExtractRefs] Unexpected error for nodeID ${n}:`,a),{type:"extractRefsResult",requestId:t,nodeID:n,refs:[],errorMessage:`extractRefs failed for nodeID ${n}: ${a}`}}},QP1=r=>{let{requestId:t,nodeID:n,referencedNodes:i}=r;Xy.debug(`[handleInferTypes] Starting type inference for nodeID ${n}`);let o=Iwr.get(n);if(!o)return Xy.error(`[handleInferTypes] No cached AST for nodeID ${n}`,"\u2014 extractRefs was not called first. This indicates an out-of-order processing bug."),{type:"inferTypesResult",requestId:t,nodeID:n,columns:[],sourceMapping:U4t("","",[],r.nodeName),cteString:"",inferenceResult:LWo(),errorMessage:`No cached AST for nodeID: ${n}. extractRefs must be called first.`,annotations:{},nonSqlLineRanges:[]};let{ast:s,parseResult:a,sqlString:u,coalesceResult:p}=o,c=Object.keys(i).length;Xy.debug(`[handleInferTypes] Cache hit for nodeID ${n}, dialect=${o.dialect}, referencedNodes=${c}`);try{let l=LWo();try{let v=o.dialect,T=k4t(s,i,u,v);l=FP1(T)}catch(v){let T=v instanceof Error?v.message:String(v);throw Xy.error(`Failed to infer types for nodeID ${n}:`,v),new Error(`Failed to infer types: ${T}`)}let d={};if(p.structured?.topLevelAnnotations&&p.structured.topLevelAnnotations.length>0&&(d=DWo(p.structured.topLevelAnnotations)),p.columnMetadata){let v=new Map;for(let T of p.columnMetadata)T.annotations&&T.annotations.length>0&&T.name&&v.set(T.name,T.annotations);if(v.size>0)for(let T of l.columns){let w=v.get(T.name);w&&(T.annotations=w)}}let f=Fil(l.columns,n),h=o.refs,A=U4t(u,a.joinString??"",h,r.nodeName),E=F4t({comments:p.comments,topLevelAnnotations:p.structured?.topLevelAnnotations,originalSql:u});return Xy.debug(`[handleInferTypes] Successfully inferred ${f.length} column(s) for nodeID ${n}`),{type:"inferTypesResult",requestId:t,nodeID:n,columns:f,sourceMapping:A,cteString:a.cteString??"",inferenceResult:l,annotations:d,topLevelAnnotations:p.structured?.topLevelAnnotations?.map(v=>v.type==="simple"?{type:"simple",key:v.key}:{type:"keyValue",key:v.key,value:v.value}),nonSqlLineRanges:E}}catch(l){let d=`inferTypes failed for nodeID ${n}: ${l}`;Xy.error(`Error in inferTypes for nodeID ${n}:`,l);let f=F4t({comments:p.comments,topLevelAnnotations:p.structured?.topLevelAnnotations,originalSql:u});return{type:"inferTypesResult",requestId:t,nodeID:n,columns:[],sourceMapping:U4t(u,"",[],r.nodeName),cteString:"",inferenceResult:LWo(),errorMessage:d,annotations:{},nonSqlLineRanges:f}}},jP1=r=>{let{requestId:t,nodeID:n,sqlString:i}=r;Xy.debug("handleParseSemanticView called",{nodeID:n,sqlLength:i.length});try{let o=qZe(i,"snowflake","");if("type"in o&&o.type==="semanticView"){let s=o;return Xy.debug("parseSqlScript (semantic view) result",{hasSemanticAttributes:!!s.semanticAttributes,hasPreservedParts:!!s.preservedParts,relationships:s.semanticAttributes?.relationships?.length,facts:s.semanticAttributes?.facts?.length,dimensions:s.semanticAttributes?.dimensions?.length,metrics:s.semanticAttributes?.metrics?.length}),{type:"parseSemanticViewResult",requestId:t,nodeID:n,semanticAttributes:s.semanticAttributes,preservedParts:s.preservedParts}}else throw new Error("Expected semantic view but got regular SQL")}catch(o){Xy.error("Error in parseSemanticView:",o);let s;return o instanceof p4?s=`parseSemanticView failed for nodeID ${n}: ${o.getCustomerFacingMessage()}`:o instanceof Error?s=`parseSemanticView failed for nodeID ${n}: ${o.message}`:s=`parseSemanticView failed for nodeID ${n}: ${String(o)}`,{type:"parseSemanticViewResult",requestId:t,nodeID:n,errorMessage:s,semanticAttributes:{relationships:[],facts:[],dimensions:[],metrics:[]},preservedParts:{tablesClause:"()",refs:[]}}}},GP1=r=>{let{requestId:t,sqlString:n,dialect:i}=r;if(!i)throw new Error("Dialect is required for extractJoinAliases request");try{let o=xWo(n,i);return{type:"extractJoinAliasesResult",requestId:t,aliases:o}}catch(o){let s=o instanceof Error?o.message:String(o);return o instanceof UZe||Xy.error("[handleExtractJoinAliases] Unexpected error:",o),{type:"extractJoinAliasesResult",requestId:t,aliases:[],errorMessage:s}}},Rwr={async sendExtractRefs(r){return zP1(r)},async sendInferTypes(r){return QP1(r)},async sendParseSemanticView(r){return jP1(r)},async sendExtractJoinAliases(r){return GP1(r)}},zil=async(r,t)=>{let{sqlString:n,stepCounter:i,allNodes:o,refLookup:s,dialect:a}=r;if(!i)throw Xy.fatal("[processSQL] stepCounter is missing \u2014 caller must provide a valid nodeID"),new Error("stepCounter is required");if(!o)throw Xy.fatal(`[processSQL] allNodes is missing for nodeID ${i} \u2014 caller must provide the nodes map`),new Error("allNodes is required");if(!a)throw Xy.fatal(`[processSQL] dialect is missing for nodeID ${i} \u2014 caller must specify the SQL dialect`),new Error("dialect is required");Xy.info(`[processSQL] Processing SQL for nodeID ${i}, dialect=${a}, sqlLength=${n.length}`);let u=i,p=await t.sendExtractRefs({type:"extractRefs",requestId:u,nodeID:i,sqlString:n,dialect:a}),l=o[i]?.operation?.name??"";if(p.errorMessage)return Xy.info(`[processSQL] Ref extraction returned errors for nodeID ${i}: ${p.errorMessage}`),{sourceMapping:U4t(n,"",p.refs,l),cteString:"",columns:[],errorMessage:p.errorMessage,inferenceResult:PWo(a),annotations:{},topLevelAnnotations:[],nonSqlLineRanges:p.nonSqlLineRanges??[]};let d=kil(o,p.refs,s)??{},f=await t.sendInferTypes({type:"inferTypes",requestId:u,nodeID:i,referencedNodes:d,nodeName:l});return f.errorMessage?(Xy.info(`[processSQL] Type inference returned errors for nodeID ${i}: ${f.errorMessage}`),{sourceMapping:f.sourceMapping,cteString:f.cteString,columns:f.columns,errorMessage:f.errorMessage,inferenceResult:PWo(a),annotations:f.annotations,topLevelAnnotations:f.topLevelAnnotations,nonSqlLineRanges:f.nonSqlLineRanges}):(Xy.debug(`[processSQL] Successfully processed SQL for nodeID ${i}: ${f.columns.length} column(s) inferred`),{sourceMapping:f.sourceMapping,cteString:f.cteString,columns:f.columns,inferenceResult:UP1(f.inferenceResult,a),annotations:f.annotations,topLevelAnnotations:f.topLevelAnnotations,nonSqlLineRanges:f.nonSqlLineRanges})};var Qil=Je("SQL_PARSING"),qWo=class{async processSQLAndGenerateMetadata(t,n,i,o,s){return Qil.debug("DirectSQLProcessingService.processSQLAndGenerateMetadata called",{stepCounter:n}),zil({sqlString:t,stepCounter:n,allNodes:i,refLookup:o,dialect:s},Rwr)}async extractRefs(t,n,i,o){Qil.debug("DirectSQLProcessingService.extractRefs called",{nodeID:i,dialect:n});let s=`extract-refs-${Date.now()}`,a=await Rwr.sendExtractRefs({type:"extractRefs",requestId:s,nodeID:i,sqlString:t,dialect:n,skipCache:o?.skipCache});return{refs:a.refs.map(p=>({locationName:p.locationName,nodeName:p.nodeName})),topLevelAnnotations:a.topLevelAnnotations,errorMessage:a.errorMessage}}async extractJoinAliases(t,n){let i=`extract-join-aliases-${Date.now()}`,o=await Rwr.sendExtractJoinAliases({type:"extractJoinAliases",requestId:i,sqlString:t,dialect:n});return{aliases:o.aliases,errorMessage:o.errorMessage}}},aO=new qWo;var HP1=r=>({type:"simple",key:r}),z4t=(r,t)=>({type:"keyValue",key:r,value:t}),FWo=r=>{let t=r[0];if(t?.type==="keyValue"&&t.value.length>0)return t.value[0];if(t?.type==="simple")return!0},Vil=(r,t,n)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",defaultValue:n,configToAnnotation(i){if(i==null)return null;let o=!!i;return o===n?null:z4t(r,[o])},annotationToConfig(i){let o=FWo(i);return o!==void 0?!!o:n}}),Wil=(r,t,n)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",defaultValue:n,configToAnnotation(i){let o=String(i??"");return o===n||o===""?null:z4t(r,[o])},annotationToConfig(i){let o=FWo(i);return o!==void 0?String(o):n}}),Kil=(r,t,n)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",defaultValue:n,configToAnnotation(i){let o=String(i??"");return o===String(n??"")||o===""?null:z4t(r,[o])},annotationToConfig(i){let o=i[0];if(!o||o.type==="simple")return n!==void 0?String(n):void 0;let s=o.type==="keyValue"&&o.value.length>0?o.value[0]:void 0;return s!==void 0?String(s):n!==void 0?String(n):void 0}}),VP1=(r,t)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",configToAnnotation(n){let i=String(n??"");return i?z4t(r,[i]):null},annotationToConfig(n){let i=FWo(n);return i!==void 0?String(i):void 0}}),Yil=(r,t)=>({attributeName:r,displayName:t,annotationKey:r,annotationLevel:"column-level",target:"column_flag",columnFlagKey:r,configToAnnotation(n){return HP1(r)},annotationToConfig(n){return n.length>0}}),WP1=(r,t,n)=>{let i=n.map(o=>o.attributeName);return{attributeName:r,displayName:t,annotationKey:r,annotationLevel:"top-level",target:"config",isTabular:!0,configToAnnotation(o){return!Array.isArray(o)||o.length===0?null:o.map(s=>{let a=i.map(u=>{let p=s[u];return typeof p=="boolean"||typeof p=="number"?p:String(p??"")});return z4t(r,a)})},annotationToConfig(o){if(o.length!==0)return o.filter(s=>s.type==="keyValue").map(s=>{let a={};return i.forEach((u,p)=>{a[u]=(p<s.value.length?s.value[p]:void 0)??""}),a})}}},jil=(r,t,n,i)=>({...Vil(r,t,i),target:"node_field",nodeFieldKey:n}),KP1=(r,t,n,i)=>({...Wil(r,t,i),target:"node_field",nodeFieldKey:n}),Gil=(r,t,n)=>({...Yil(r,t),target:"column_flag",columnFlagKey:n}),YP1=()=>({...Kil("description","Description",""),target:"node_field",nodeFieldKey:"description"}),Hil=r=>wIt.includes(r),JP1=r=>{if(ZYe(r)){let t=k6o[r.type],n=t.attributeName;switch(r.type){case"multisourceToggle":return jil(n,t.displayName,n,r.default);case"overrideSQLToggle":return jil(n,t.displayName,n,r.default);case"materializationSelector":return KP1(n,t.displayName,n,r.default);case"businessKeyColumns":return Gil(n,t.displayName,n);case"changeTrackingColumns":return Gil(n,t.displayName,n);default:return null}}switch(r.type){case"toggleButton":{let t=Vil(r.attributeName,r.displayName,r.default);return Hil(r.attributeName)?{...t,target:"node_field",nodeFieldKey:r.attributeName}:t}case"dropdownSelector":{let t=Wil(r.attributeName,r.displayName,r.default);return Hil(r.attributeName)?{...t,target:"node_field",nodeFieldKey:r.attributeName}:t}case"textBox":return Kil(r.attributeName,r.displayName,r.default);case"columnDropdownSelector":return VP1(r.attributeName,r.displayName);case"columnSelector":return Yil(r.attributeName,r.displayName);case"tabular":return WP1(r.attributeName,r.displayName,r.columns);case"label":return null;default:return null}},UWo=r=>{let t=new Map,n=new Map,i=YP1();if(t.set(i.attributeName,i),n.set(i.annotationKey.toLowerCase(),i),r)for(let o of r)for(let s of o.items){let a=JP1(s);a&&(t.set(a.attributeName,a),n.set(a.annotationKey.toLowerCase(),a))}return{mappings:t,byAnnotationKey:n,getByAttribute(o){return t.get(o)},getByAnnotationKey(o){return n.get(o.toLowerCase())},isKnown(o){return n.has(o.toLowerCase())},annotationsToConfig(o){let s={},a={},u=[],p=[],c=new Map;for(let l of o){let d=l.key.toLowerCase(),f=c.get(d);f?f.push(l):c.set(d,[l])}for(let[l,d]of t){let f=c.get(d.annotationKey.toLowerCase())??[];if(d.target==="column_flag"){u.includes(d.annotationKey)||u.push(d.annotationKey);continue}if(d.isTabular&&p.push(d.attributeName),f.length===0){let A=d.defaultValue!==void 0?d.defaultValue:d.annotationToConfig([]);d.target==="node_field"&&d.nodeFieldKey?a[d.nodeFieldKey]=A:s[d.attributeName]=A;continue}let h=d.annotationToConfig(f);d.target==="node_field"&&d.nodeFieldKey?a[d.nodeFieldKey]=h:s[d.attributeName]=h}return{configUpdates:s,nodeFieldUpdates:a,columnFlagKeys:u,tabularKeys:p}}}};var o2e=class r{constructor(t,n,i){this.serviceName=t;this.childService=n;this.logger=i}serviceName;childService;logger;_mutex=new oce;_repository;initialize(t){return this._mutex.runExclusive(async()=>{this.isInitialized&&(this.logger.warning(`Closing ${this.serviceName} for re-initialization`),await this.close()),this.logger.info(`Initializing ${this.serviceName}`),this._repository=t.rootRepository,await this.init(t)})}identify(t){return this._mutex.runExclusive(async()=>{this.logger.debug("Identifying feature flags context",t);let n=await this.fetchOrg(t.org?.id);this.logger.debug("Identified feature flags context",n);let i=r.mergeOrgFlags(n),o;return r.isMockingLaunchDarkly(n)?(this.logger.warning(`Mocking LaunchDarkly integration for org ${n?.id}, fetching all flags from the org record`),o=new hv(i)):(o=await this.childService.identify(t),this.logger.debug("finished child service identify",n)),this.getFeatureFlagsCollection(i,o)})}async setOrgFlag(t,n,i){this.logger.info(`Setting org feature flag '${n}' for org ${t} to '${i}'`),await this.repository.org(t).merge({[n]:Ngr(),[`featureFlags.${n}`]:i})}async setTestFlag(t,n,i,o){if(kE(!DT[i].isLegacyOrgFlag||t==="org","Only orgs can be targeted for legacy feature flags",this.logger),t==="org"){let s=await this.repository.org(n).fetch();if(r.isMockingLaunchDarkly(s)||DT[i].isLegacyOrgFlag){DT[i].isLegacyOrgFlag||this.logger.warning(`Mocking LaunchDarkly integration for org ${n}, setting '${i}' to '${o}' on the org record`),await this.setOrgFlag(n,i,o);return}}await this.childService.setTestFlag(t,n,i,o)}async close(){this.logger.info(`Closing ${this.serviceName}`),this._repository=void 0,await this.childService.close()}get isInitialized(){return!!this._repository&&this.childService.isInitialized}get repository(){kE(!!this._repository,`${this.serviceName} is not initialized`,this.logger);let t=this._repository();return kE(!!t,`${this.serviceName}: org contexts cannot be identified before firestore is initialized`,this.logger),t}async fetchOrg(t){try{return t?await this.repository.org(t).fetch():void 0}catch(n){if(n instanceof Du||n instanceof Ww){this.logger.warning(`Unable to fetch feature flags for org ${t}: ${n.message}`);return}throw n}}static isMockingLaunchDarkly(t){return!!t?.mockLaunchDarklyIntegration}static mergeOrgFlags(t={}){let n={};for(let i of fgu)(r.isMockingLaunchDarkly(t)||DT[i].isLegacyOrgFlag)&&(n[i]=t.featureFlags?.[i]??t[i]);return n}};var $P1=["snowflake"];function nZ(r,t){return r.isFeatureEnabled("isSQLEditorEnabled",!1)?$P1.includes(t)?!0:r.isFeatureEnabled("enableSqlNodeV2AllPlatforms",!1):!1}var o2=Je("SQL_PARSING"),Jil=(r,t)=>zj(r,n=>{n.operation.metadata.columns=t.columns,n.operation.metadata.cteString=t.cteString,n.operation.metadata.sourceMapping=t.sourceMapping,t.config!==void 0&&(n.operation.config={...n.operation.config,...t.config}),n.operation.materializationType=t.materializationType;let i=n.operation;for(let[o,s]of Object.entries(t.nodeFieldUpdates))o!=="materializationType"&&s!==void 0&&(i[o]=s)}),XP1=async(r,t,n,i,o,s)=>{let a=s?.yieldEveryNNodes??2,u=s?.parseErrors;o2.info("hydrateSQLInputModeNodes: Starting hydration");let p=Object.keys(r);o2.debug(`hydrateSQLInputModeNodes: Found ${p.length} total nodes`);let c=new Map,l;try{l=n(p),o2.debug(`Topological sort completed: ${l.length} nodes in order`)}catch(A){throw o2.error("Error performing topological sort:",A),A}let d={...r},f=wv(d),h=0;for(let A of l){let E=d[A];if(!E)throw o2.fatal(`[hydrateSQLInputModeNodes] Node ${A} expected but missing from allNodes`,"\u2014 possible data corruption or race condition"),new Error(`Node ${A} not found in allNodes in hydrateSQLInputModeNodes`);if($P(E,{nodeID:A}))continue;if(!i0(E,{nodeID:A}))throw new Error(`Node ${A} is not a SQL step in hydrateSQLInputModeNode`);let v=E.operation.sqlType,T=t[v];if(!T){o2.debug(`Node type ${v} not found in stepTypesParsed for node ${A}`);continue}if(!U6o(T))continue;let N=BIt(E,0);try{o2.debug(`hydrateSQLInputModeNodes: Processing node ${A}, calling processSQLAndGenerateMetadata`);let k=performance.now(),L=await i.processSQLAndGenerateMetadata(N,A,d,f,o),q=performance.now()-k;if(o2.debug(`hydrateSQLInputModeNodes: processSQLAndGenerateMetadata completed for ${A} in ${q.toFixed(2)}ms`),L.errorMessage)throw o2.error(`[hydrateSQLInputModeNodes:${A}] SQL parse error: ${L.errorMessage}`),u?.set(A,L.errorMessage),new Error(`Error processing SQL for node ${A}: ${L.errorMessage}`);let G=T.metadata?.nodeMetadataSpec??null,H=G?UWo(G.config):null,V=L.topLevelAnnotations??Object.entries(L.annotations).map(([re,oe])=>oe===!0?{type:"simple",key:re}:{type:"keyValue",key:re,value:oe.parameters}),W={},F={};if(H){let re=H.annotationsToConfig(V);W=re.configUpdates,F=re.nodeFieldUpdates}let J=typeof F.materializationType=="string"?F.materializationType:null,Y=Object.entries(L.annotations).find(([re])=>re.toLowerCase()==="materializationtype")?.[1],z=typeof Y=="object"&&Y?.parameters?.[0]?String(Y.parameters[0]):null,X=J??z??"table",Z={columns:L.columns,cteString:L.cteString??"",sourceMapping:L.sourceMapping,config:H?W:void 0,materializationType:X,nodeFieldUpdates:F};c.set(A,Z),d[A]=Jil(E,Z),h++,o2.debug(`Successfully computed hydration for node ${A}`),h%a===0&&await new Promise(re=>setTimeout(re,0))}catch(k){o2.error(`[hydrateSQLInputModeNodes] Error processing SQL for node ${A} (type=${E.operation.sqlType}):`,k),u&&!u.has(A)&&u.set(A,k instanceof Error?k.message:String(k));continue}}return o2.info(`Computed hydration for ${h} SQL input mode nodes out of ${l.length} total nodes`),c},ZP1=(r,t)=>{if(t.size===0)return r;let n={...r};for(let[i,o]of t){let s=r[i];if(!s){o2.error(`[applySQLInputModeHydration] Node ${i} not found in allNodes \u2014 hydration result will be lost`);continue}if(!i0(s,{nodeID:i})){o2.error(`[applySQLInputModeHydration] Node ${i} is not a SQL step but was in hydration results \u2014 skipping`);continue}let a=s;n[i]=Jil(a,o)}return n},e41=(r,t)=>{let n=new Map;for(let a of t)n.set(a,0);for(let a of t){let u=r[a]||[];n.set(a,u.filter(p=>t.includes(p)).length)}let i=[];for(let a of t)(n.get(a)||0)===0&&i.push(a);let o=[],s=new Set;for(;i.length>0;){let a=i.shift();if(!s.has(a)){s.add(a),o.push(a);for(let[u,p]of Object.entries(r)){if(!t.includes(u))continue;if(p.includes(a)&&!s.has(u)){let l=(n.get(u)||0)-1;n.set(u,l),l===0&&i.push(u)}}}}for(let a of t)s.has(a)||(o2.debug(`Node ${a} was not in dependency graph, adding at end`),o.push(a));return o},Q4t=async(r,t,n,i,o,s)=>{o2.info("hydrateSQLInputModeNodesForAllContexts: Starting hydration");let a=X$(t),u=Object.keys(r);if(!nZ(bc().featureFlags,n)||!u.length)return o2.debug("No nodes to process"),r;o2.info(`hydrateSQLInputModeNodesForAllContexts: Found ${u.length} total nodes`);let p=o??wv(r),c={},l=[];for(let A of u){let E=r[A];if(!E||$P(E,{nodeID:A})||!i0(E,{nodeID:A}))continue;let v=E,T=v.operation.sqlType,w=a[T];if(!w||!U6o(w))continue;l.push(A);let N=v.operation.metadata.sourceMapping?.[0]?.dependencies??[],k=[];for(let L of N){let q=p.get(L.locationName,L.nodeName);q&&!k.includes(q)&&k.push(q)}c[A]=k}o2.info(`hydrateSQLInputModeNodesForAllContexts: Found ${l.length} SQL input mode nodes`);let f=await XP1(r,a,A=>{try{let E=e41(c,l);return o2.debug(`Topological sort completed: ${E.length} nodes in order`),E}catch(E){throw o2.error("[hydrateSQLInputModeNodesForAllContexts] Topological sort failed \u2014 possible circular dependency:",E),new Error("Error performing topological sort")}},i,n,{parseErrors:s});o2.info(`hydrateSQLInputModeNodesForAllContexts: Processed ${f.size} SQL input mode nodes`);let h=ZP1(r,f);return o2.info("hydrateSQLInputModeNodesForAllContexts: Returning updated nodes"),h};var zZe=class{suppress;constructor(){this.suppress=Uyu()}logMemory(t,n,i,o){if(this.suppress)return;let s=this.logTag+`(${n}): `,a=o.length>0?`${i} || ${o.join(" || ")}`:i;o.length?Je("PERFORMANCE").warnContext(t,s+a):Je("PERFORMANCE").infoContext(t,s+a)}async measureOperationAsync(t,n,i,o,s,a=!1){if(this.suppress||a)return await s();if(!this.getMemoryUsage(t))return await s();try{let p=this.getMemoryUsage(t);this.logMemorySnapshot(t,n,o);let c=await s();return this.logDeltaMetrics(t,p,o,i),c}catch(p){throw this.logMemorySnapshot(t,`(FAILED) ${i}`,o),p}}measureOperationSync(t,n,i,o,s){if(this.suppress||!this.getMemoryUsage(t))return s();try{let u=this.getMemoryUsage(t);this.logMemorySnapshot(t,n,o);let p=s();return this.logDeltaMetrics(t,u,o,i),p}catch(u){throw this.logMemorySnapshot(t,`(FAILED) ${i}`,o),u}}};var tk=class extends zZe{logTag="[NoopMemoryMonitor]: ";getMemoryReport(){}getLogContextWithMetrics(t,n,i){return{...t,metric_type:"memory_telemetry",operation:i}}cleanup(){}getMemoryUsage(){}logMemorySnapshot(){}logDeltaMetrics(){}};function s2e(r,t){return $g({snowflake:()=>r,fabric:()=>r,databricks:()=>r.toLowerCase(),bigquery:()=>r},t,"getNodeComparisonName")}function QZe(r,t){return $g({snowflake:()=>r,fabric:()=>r,databricks:()=>r.toLowerCase(),bigquery:()=>r.toLowerCase()},t,"getColumnComparisonName")}function j4t(r,t){return JSON.stringify([r,t])}function Owr(r,t,n,i){for(let[o,s]of Object.entries(r)){let{type:a,database:u,schema:p,name:c,metadata:l}=s.operation;if(a!=="sql")continue;let d=i?.[o]?.operation,f=t.get(j4t(u,p))?.get(s2e(c,n))??(d?t.get(j4t(d.database,d.schema))?.get(s2e(d.name,n)):void 0);s.operation.description=f?.objectComment??"";for(let h of l.columns)h.description=f?.columns[QZe(h.name,n)]??""}}var wwr=r=>"id"in r&&"presyncDetails"in r&&"targetEnvironment"in r&&"version"in r&&r.version===2&&"phasedDependencies"in r&&$il(r.phasedDependencies)&&"phasedNodeEdits"in r&&$il(r.phasedNodeEdits)&&!("dependencies"in r)&&!("nodeEdits"in r),$il=r=>typeof r=="object"&&!!r&&"addedTable"in r&&"alteredTable"in r&&"deletedTable"in r;var Xil=r=>typeof r=="object"&&!!r&&wwr(r),Zil=r=>tol(r)&&r.status==="failed"&&"error"in r,eol=r=>tol(r)&&r.status==="planning",tol=r=>typeof r=="object"&&!!r&&"status"in r&&(r.status==="planning"||r.status==="failed"),rol=r=>typeof r=="object"&&!!r&&"planStorageFilePath"in r&&typeof r.planStorageFilePath=="string";var a2e=(r,t)=>{let n=Object.entries(r).filter(([,i])=>i.operation.locationName===t);return{nodeIDs:n.map(([i])=>i),nodeNames:n.map(([,i])=>i.operation.name)}};var nol="Can't plan to specified environment as it is a development workspace";var t41=Je("PLAN"),iol=r=>{let t={};for(let n of Object.values(r))t[j4t(n.database,n.schema)]=n;return t};async function zWo(r,t,n,i){let o="[loadWarehouseComments]",s=iol(Z$(t,i)),a={...iol(Z$(n,i)),...s},u=new Map,p=new Map,c=(h,A)=>{let E=u.get(h);E||(E=new Map,u.set(h,E));let v=E.get(A);return v||(v={objectComment:"",columns:{}},E.set(A,v)),v},l=(h,A)=>{if(!r.isMissingLocationError(A))throw A;let E=s[h];if(!E||p.has(h))return;let{errorString:v}=aa(A).error;t41.warnContext(i,o,`[plan:missing-location] could not read desired-state comments for ${E.locationName} on ${r.name}`,A),p.set(h,{locationName:E.locationName,database:E.database,schema:E.schema,workspaceState:"desired",kind:"query-error",errorText:v,...a2e(t,E.locationName)})},[d,f]=await Promise.all([r.getObjects(a,!1,i),r.getColumns(a,!1,i)]);for(let[h,A]of Object.entries(d))A.handle(E=>{for(let v of E)c(h,s2e(v.name,r.name)).objectComment=v.comment},E=>l(h,E));for(let[h,A]of Object.entries(f))A.handle(E=>{for(let v of E)c(h,s2e(v.objectName,r.name)).columns[QZe(v.name,r.name)]=v.comment},E=>l(h,E));return{comments:u,missingLocations:[...p.values()]}}async function QWo(r,t,n,i){let{comments:o,missingLocations:s}=await zWo(r,n,t,i);return Owr(t,o,r.name),Owr(n,o,r.name,t),s}var jWo=B.object({subtitle:B.string(),title:B.string(),messages:B.array(B.string()).nonempty(),workspaceState:B.enum(["current","desired"]).optional()}),suC=B.object({stop:B.array(jWo),warn:B.array(jWo)}),Mwr=r=>!!r.stop.length,xwr=(r,t={})=>Ygc(r,Mwr,"Expected stop issue(s) were missing","PLAN",t,r),ool=(r,t={})=>{pd(!Mwr(r),"Unexpected stop issue(s) present","PLAN",t,r)};var sol=(r,t={})=>{if(!r)return;let n=B.array(jWo).safeParse(r);if(!n.success){Je("PLAN").errorContext(t,"[parseDeployIssues] malformed deploy issues; continuing without stopping plan creation",n.error.errors.map(i=>i.message).join(`
|
|
10111
10111
|
`));return}return n.data};var u2e=class extends nt{issues;constructor(t){xwr(t),super("Issues preventing deployment were found",r41(t)),this.issues=t}toFormattedString(){return`${this.message}; please review the issues itemized above.`}},aol=r=>r.map(({title:t,subtitle:n,messages:i,workspaceState:o})=>`${o?`[${o} state] `:""}${t}
|
|
10112
10112
|
${n}
|
|
10113
10113
|
${i.map(s=>`- ${s}`).join(`
|
|
@@ -10119,9 +10119,9 @@ ${i.map(s=>`- ${s}`).join(`
|
|
|
10119
10119
|
`,...aol(r.warn)),[...t,`
|
|
10120
10120
|
`].join(`
|
|
10121
10121
|
`)};var G4t=class{stop=[];warn=[];addIssue(t,n){n&&this[t].push(n)}scan(t,n,i,o){for(let a of t.detectIssues(n))this.addIssue("stop",{...a,workspaceState:o.workspaceState});for(let a of t.detectIssues(i,o.jobSchedules))this.addIssue("warn",{...a,workspaceState:o.workspaceState});if((o.shouldThrow??!0)&&Mwr(this))throw new u2e(this)}foldWarnIssues(t,n={}){if(!t)return;let i=u=>[u.title,u.workspaceState??"",...u.messages].join(`
|
|
10122
|
-
`),o=new Set(t.warn.map(i)),s=this.warn.filter(u=>!o.has(i(u)));s.length&&Je("PLAN").alertContext(n,"[DeployIssueTracker.foldWarnIssues] plan-borne issues lack warn issues the tracker holds \u2014 the issues round-trip dropped something; keeping the tracker's copies:",s);let a=new Set(this.warn.map(i));for(let u of t.warn)a.has(i(u))||this.addIssue("warn",u)}async monitor(t,n){try{let i=await n();return ool(this,t),i}catch(i){if(Je("PLAN").errorContext(t,"[DeployIssueTracker.monitor] error:",Gdr(i)),i instanceof u2e)throw i;let o;if(i instanceof nt||Ome(i)){let{error:{errorString:s,errorDetail:a}}=
|
|
10122
|
+
`),o=new Set(t.warn.map(i)),s=this.warn.filter(u=>!o.has(i(u)));s.length&&Je("PLAN").alertContext(n,"[DeployIssueTracker.foldWarnIssues] plan-borne issues lack warn issues the tracker holds \u2014 the issues round-trip dropped something; keeping the tracker's copies:",s);let a=new Set(this.warn.map(i));for(let u of t.warn)a.has(i(u))||this.addIssue("warn",u)}async monitor(t,n){try{let i=await n();return ool(this,t),i}catch(i){if(Je("PLAN").errorContext(t,"[DeployIssueTracker.monitor] error:",Gdr(i)),i instanceof u2e)throw i;let o;if(i instanceof nt||Ome(i)){let{error:{errorString:s,errorDetail:a}}=aa(i);o=a&&a!==s?`${s}
|
|
10123
10123
|
|
|
10124
|
-
${a}`:s}else o=
|
|
10124
|
+
${a}`:s}else o=aa(i).error.errorString;throw this.addIssue("stop",{title:"Errors Detected",subtitle:"These errors must be addressed before proceeding.",messages:[o]}),new u2e(xwr(this,t))}}};var c2e=r=>{let t=new Set,n=/\{\{\s*parameters\.([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\b|\{\{\s*parameters\['([^']+)'\]|\{\{\s*parameters\["([^"]+)"\]/g,i;for(;(i=n.exec(r))!==null;){let o=i[1]||i[2]||i[3];o&&t.add(o)}return t},B5e=(r,t)=>{let n=t.split("."),i=r;for(let o of n){if(i==null||typeof i!="object"||!(o in i))return!1;i=i[o]}return!0},iZ=class{constructor(t,n=0,i={},o=new Map){this.workspaceData=t;this.workspaceID=n;this.runtimeParameters=i;this.sqlParseErrors=o;let s=Smr(this.workspaceData.steps);this.nodesWithInvalidRefs=new Set(Object.keys(tkc(s)))}workspaceData;workspaceID;runtimeParameters;sqlParseErrors;issues=[];nodesWithInvalidRefs;parameterReferenceCache=new Map;getNodeTypeParameterReferences(t){if(this.parameterReferenceCache.has(t))return this.parameterReferenceCache.get(t);let n=new Set,i=this.workspaceData.stepTypes[t];return i?.metadata&&(i.metadata.templates?.create?.templateString&&c2e(i.metadata.templates.create.templateString).forEach(o=>n.add(o)),i.metadata.templates?.run?.templateString&&c2e(i.metadata.templates.run.templateString).forEach(o=>n.add(o)),this.parameterReferenceCache.set(t,n)),n}buildIssue=(t,n,i,o)=>({subtitle:t,title:n,messages:i,workspaceState:o});detectAndAddIssues(t,n,i){let o={};for(let[s,a]of Object.entries(n))for(let u of t){let p=u.detect(a,s);if(p){let c=o[u.name];c?c.details.push(p):o[u.name]={details:[p],case_:u}}}for(let{details:s,case_:a}of Object.values(o))this.issues.push(this.buildIssue(a.copy.subtitle,a.copy.title,s,i))}getCasesForCollection(t,n){let i=[];return Object.entries(this.cases()).forEach(([o,s])=>{s.collection===n&&t.includes(o)&&i.push({...s,name:o})}),i.length||Je("PLAN").warnContext({workspaceID:this.workspaceID},`No cases found for collection ${n}`),i}detectIssues(t,n){if(this.issues=[],n){let s=i$(n.filter(a=>a.environmentId===this.workspaceID&&!(a.jobId in this.workspaceData.jobs)).map(a=>`Job Schedule "${a.name}" will be deleted.`));s&&this.issues.push(this.buildIssue("The Jobs associated with these Schedules have been deleted. The following Job Schedules will not run and will be deleted after deployment.","Job Schedules will be deleted",s))}let i=t.map(s=>{let a=this.cases()[s];if(!a)throw new nt(`Unknown issue detection case: ${s}`);return a.collection}),o=new Set(i);for(let s of o){let a=this.workspaceData[s];if(s==="locations"&&(!this.workspaceData.locations||!Object.keys(this.workspaceData.locations).length)&&(this.issues.push(this.buildIssue("To fix this issue, checkout the commit being deployed in a Workspace and create Storage Locations in Build Settings. Commit the changes and deploy again.","Missing Storage Locations",["No storage locations found."])),a={}),!a)throw new nt(`Unknown workspace data collection: ${s}`);this.detectAndAddIssues(this.getCasesForCollection(t,s),a)}return this.issues}cases(){return{invalidStorageMappings:{collection:"locations",copy:{title:"Missing or Invalid Storage Mappings",subtitle:"To fix this issue, checkout the commit being deployed in a Workspace. Go to Build Settings, Environments and find the Environment being deployed to. Under Environment Settings, Storage Mappings, ensure the mappings for the Storage Locations listed below are valid. Commit the changes and deploy again."},detect:(t,n)=>{let i=K6o(t,this.workspaceID,n);return!i.schema||!i.database?`Storage Location ${n} has an invalid schema or database value. Schema: "${i.schema||"N/A"}", Database: "${i.database||"N/A"}".`:null}},invalidNodeTypes:{collection:"stepTypes",copy:{title:"Invalid Node Type",subtitle:"To fix this issue, checkout the commit being deployed in a Workspace. Go to Build Settings, Node Types and find Node Types in an invalid state. Edit the Node Type and fix any errors in the Node Definition. Commit the changes and deploy again."},detect:t=>{let n=F6o(t.name,t.metadata.nodeMetadataSpec).errorString;if(!Imr(t)||n){let i=`Node type with ID: ${t.id}`;return`${t.name||i} is in an invalid state. ${n}`}return null}},invalidStorageLocations:{collection:"steps",copy:{title:"Invalid Storage Location",subtitle:"To fix this issue, checkout the commit being deployed in a Workspace. Ensure that the Storage Location used by the Node has a valid mapping or update the Node to use a valid Storage Location. Commit the changes and deploy again."},detect:t=>{let{name:n,locationName:i}=t.operation,o=this.workspaceData.locations?.[i];if(!o)return`Node ${n} is configured to use the Storage Location ${i}, but the Storage Location does not exist for this Environment.`;let{schema:s,database:a}=K6o(o,this.workspaceID,i);return!s||!a?`Node ${n} is configured to use the Storage Location ${i}, but the Mapping of the Storage Location has an invalid schema or database value. Schema: ${s||"N/A"}, Database: ${a||"N/A"}.`:null}},missingNodeTypes:{collection:"steps",copy:{title:"Missing Node Type",subtitle:"To fix this issue, check out the commit being deployed in a Workspace. Go to Build Settings, Node Types, and ensure the Node Type referenced by the Nodes exists. Also confirm that the Node Type definition has been committed to Git. If the Node Type is part of a Package, ensure the Package has been committed to Git."},detect:t=>{let{sqlType:n,name:i,locationName:o}=t.operation;return!n||!this.workspaceData.stepTypes[n]?o?`Node ${i} (${o}) is using a Node Type that doesn\u2019t exist. Invalid Node Type: ${n}.`:`Node ${i} is using a Node Type that doesn\u2019t exist. Invalid Node Type: ${n}.`:null}},invalidNodeLocationData:{collection:"steps",copy:{title:"Missing Location Data",subtitle:"To fix this issue, checkout the commit being deployed in a Workspace. Go to Build Settings and confirm that the Storage Locations have been added. Then, go to Build Settings, Environments and find the Environment being deployed to. Under Environment Settings, Storage Mappings, ensure the mappings for the Storage Locations listed below are valid. Also, assign Storage Locations to any Nodes that don\u2019t have a storage location assigned. Commit the changes and deploy again."},detect:t=>{let{locationName:n,database:i,schema:o,name:s}=t.operation;return!n||!i||!o?`Node ${s} is missing required location data. Location: ${n||"N/A"}, Database: ${i||"N/A"}, Schema: ${o||"N/A"}.`:null}},invalidColumnSources:{collection:"steps",copy:{title:"Invalid Reference In Node Join",subtitle:"Invalid refs will cause refreshes to fail. Refs in Join conditions don't automatically update when a Node name or a Storage Location has changed and have to be updated manually. To fix this issue, check out the commit being deployed in a Workspace. Find the Nodes with the invalid reference, open the Join tab and confirm that all refs are pointing to a valid Node name and Storage Location. Commit the changes and deploy again."},detect:(t,n)=>{let{name:i,locationName:o}=t.operation;return this.nodesWithInvalidRefs.has(n)?o?`${i} (${o})`:`${i}`:null}},emptyColumnNames:{collection:"steps",copy:{title:"Empty Column Names",subtitle:"All columns must have a valid name. To fix this issue, check out the commit being deployed in a Workspace. Find the Nodes with empty column names and provide a name for each column. Commit the changes and deploy again."},detect:t=>{let{name:n,locationName:i}=t.operation,s=(t.operation.metadata.columns||[]).filter(a=>!a.name||a.name.trim()==="");if(s.length>0){let a=i?` (${i})`:"",u=s.length===1?"column":"columns";return`Node ${n}${a} has ${s.length} ${u} with empty names. Empty column IDs:
|
|
10125
10125
|
${s.map(p=>p.columnReference.columnCounter).join(`
|
|
10126
10126
|
`)}`}return null}},databricksUppercaseNodeNames:{collection:"steps",copy:{title:"Uppercase Node Names Not Allowed",subtitle:"Databricks requires node names to be lowercase. To fix this issue, check out the commit being deployed in a Workspace. Rename the Nodes listed below to use lowercase characters only. Commit the changes and deploy again."},detect:t=>{let{name:n,locationName:i}=t.operation;return n!==n.toLowerCase()?`Node ${n} (${i}) contains uppercase characters. Rename to "${n.toLowerCase()}" or another lowercase name.`:null}},invalidParameterReferences:{collection:"steps",copy:{title:"Invalid Parameter References",subtitle:"Undefined parameter references detected. Check for errors in how parameters are referenced in nodes/node types, environment parameter definitions, or parameter overrides (if applicable)."},detect:(t,n)=>{let i=new Map,s=[...this.getNodeTypeParameterReferences(t.operation.sqlType)].filter(l=>!B5e(this.runtimeParameters,l));if(s.length>0){let l=this.workspaceData.stepTypes[t.operation.sqlType]?.name||t.operation.sqlType;i.set(`Node type "${l}" templates`,new Set(s))}if(i0({operation:t.operation},{})){let l=t.operation,d=(l.metadata.sourceMapping?.length??0)>1;if(l.metadata.sourceMapping?.forEach(A=>{let E=A.name,v=d?` in '${E}'`:"";if(A.join?.joinCondition){let w=[...c2e(A.join.joinCondition)].filter(N=>!B5e(this.runtimeParameters,N));w.length>0&&i.set(`Join${v}`,new Set(w))}if(A.customSQL?.customSQL){let w=[...c2e(A.customSQL.customSQL)].filter(N=>!B5e(this.runtimeParameters,N));w.length>0&&i.set(`Custom SQL${v}`,new Set(w))}}),l.metadata.cteString){let E=[...c2e(l.metadata.cteString)].filter(v=>!B5e(this.runtimeParameters,v));E.length>0&&i.set("CTE string",new Set(E))}l.metadata.columns?.forEach(A=>{A.sourceColumnReferences?.forEach((E,v)=>{if(E.transform){let w=[...c2e(E.transform)].filter(N=>!B5e(this.runtimeParameters,N));if(w.length>0){let N=d?` (source ${v})`:"";i.set(`Column "${A.name}" transform${N}`,new Set(w))}}})});let f=l.config?.preSQL;if(typeof f=="string"){let E=[...c2e(f)].filter(v=>!B5e(this.runtimeParameters,v));E.length>0&&i.set("PRE-SQL",new Set(E))}let h=l.config?.postSQL;if(typeof h=="string"){let E=[...c2e(h)].filter(v=>!B5e(this.runtimeParameters,v));E.length>0&&i.set("POST-SQL",new Set(E))}}else if(i.size===0)return null;if(i.size===0)return null;let{name:a,locationName:u}=t.operation,p=u?` (${u})`:"",c=Array.from(i.entries()).map(([l,d])=>` - ${l}: ${Array.from(d).join(", ")}`);return`Node ${a}${p} references undefined parameters:
|
|
10127
10127
|
${c.join(`
|
|
@@ -10482,19 +10482,19 @@ Schema: ${c}`;throw new nt(h,A)}return a[$Wo(p,c,l)]=u,a},{}),i=Z$(n,this.baseLo
|
|
|
10482
10482
|
|
|
10483
10483
|
`+Pol(l):null}),s=new Set;if((await Promise.all(o)).forEach(a=>{a&&s.add(a)}),n3(s)){let a="Tables are missing required TBLPROPERTIES for proper schema evolution. Required table property: delta.columnMapping.mode=name",u=Array.from(s).join(`
|
|
10484
10484
|
|
|
10485
|
-
`);throw new nt(a,u)}}};var Uwr=r=>r.presync;var E41=Je("ACTUAL_STATE"),aZ=class{constructor(t,n,i,o){this.objectLookup=t;this.columnLookup=n;this.locations=i;this.referenceNodes=o}objectLookup;columnLookup;locations;referenceNodes;lookupIncludesNode(t,n,i){let o=n==="table"?this.objectLookup.tables:this.objectLookup.views,s=o[i];return s?s.has(t):(E41.debug(`Location "${i}" not found in object list:`,Object.keys(o)),!1)}materializationTypeOnWarehouse=t=>{let n=this.referenceNodes[t];if(!n)throw new nt(`Node with id "${t}" not found in nodes`);let{name:i,locationName:o}=n.operation;return this.lookupIncludesNode(i,"view",o)?"view":this.lookupIncludesNode(i,"table",o)?"table":null};materializationTypeInMetadata=t=>{let i=g1(t,this.referenceNodes,"[ActualState.materializationTypeInMetadata()]").operation.materializationType;if(!i)throw new nt(`Node with id "${t}" has no materialization type`);if(i!=="table"&&i!=="view")throw new nt(`Found node using unsupported materialization type "${i}" in actual state`);return i}};var JZe=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);if(o.name=n.name,o.description=n.comment,i==="table"){let u=n.extra.IS_NULLABLE,p={YES:!0,NO:!1}[u];o.nullable=p}let s=n.extra.COLUMN_DEFAULT,a=o.defaultValue;return(s||a)&&(o.defaultValue=s||void 0),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[SnowflakeActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, database: ${s.database}, schema: ${s.schema}`);let u=[];for(let p of a)p.objectName===o&&u.push([p.name,p]);return u}};var $Ze=class r extends JZe{constructor(t){let{objectLookup:n,columnLookup:i,locations:o,referenceNodes:s}=t;super(r.convertLookupArraysToSets(n),i,o,s)}static convertLookupArraysToSets(t){let n=t.tables,i=t.views,o={},s={};for(let[a,u]of Object.entries(n))o[a]=new Set(u);for(let[a,u]of Object.entries(i))s[a]=new Set(u);return{tables:o,views:s}}static convertLookupSetsToArrays(t){let n=t.tables,i=t.views,o={},s={};for(let[a,u]of Object.entries(n))o[a]=[...u];for(let[a,u]of Object.entries(i))s[a]=[...u];return{tables:o,views:s}}static convertActualStateToParts(t){let{objectLookup:n,columnLookup:i,locations:o,referenceNodes:s}=t;return{objectLookup:r.convertLookupSetsToArrays(n),columnLookup:i,locations:o,referenceNodes:s}}};var C41=Je("PRESYNC"),Dol=async(r,t,n,i,o,s,a)=>{if(!t.locations||!n.locations)throw C41.errorContext(s,"Current locations are required for Actual State. current locations: ",t.locations,"updated locations: ",n.locations),new nt("Locations are required to initialize actual state.");let u=a??Bol(r.name,i,s,o);return await u.setup(r,t,n),{...await u.syncNodes(r),currentActualState:$Ze.convertActualStateToParts(u.currentActualState),updatedActualState:$Ze.convertActualStateToParts(u.updatedActualState)}},Bol=(r,t,n,i)=>r==="databricks"?new Fwr(r,t,n,i):new qwr(r,t,n,i);var fpC=Je("DEBUG");var S41=Je("PLAN"),v41=r=>{if(!r.path)return!1;let{isNodeConfigMetadata:t,isColumnMetadata:n}=Nwr(r.path);return!!(t||n)},Lol=(r,t,n,i)=>KZe(r,t,v41,()=>{},n,"hasMetadataDiff",i)?!0:Uwr(r)?(S41.debugContext(n,`${t.operation.name} has presync data and is eligible for database update.`),!0):!1;var Epe=Je("PLAN"),zwr=async(r,t,n,i)=>{let o="[getSchemas]",{measure:s,printSummary:a}=Bf(o,i);Epe.appContext(i,o,"Getting schemas for current and updated workspace states");let{entitiesWithPossibleEdits:u}=j4e(n,t),[p,c]=await Promise.all([s("platform.getSchemas (current)",()=>kol(r,t,u,"current",i)),s("platform.getSchemas (updated)",()=>kol(r,n,u,"desired",i))]);return Epe.appContext(i,o,"Got schemas. current:",p.schemas,"updated:",c.schemas),a(),{current:p.schemas,updated:c.schemas,missingLocations:[...p.missingLocations,...c.missingLocations]}},kol=async(r,t,n,i,o)=>{let s="[getImplementedSchemas]",a=new Set(n);Epe.debugContext(o,"Getting implemented schemas for subset of nodes:",n);let u=Object.fromEntries(Object.entries(t).filter(([f])=>a.has(f)));Epe.debugContext(o,"Getting used step locations lookup for subset");let p=Z$(u,o);Epe.infoContext(o,"Got implemented locations:",p);let c={},l=[],d=await r.getSchemas(p,!1,o);for(let[f,h]of Object.entries(d))h.handle(A=>{if(!A.length){let{schema:E,database:v}=Xq(f,p,`${s} (this should never happen)`);Epe.warnContext(o,s,`[plan:missing-location] no ${i}-state schema found for ${f} using database ${v} and schema ${E} on ${r.name}`),l.push({locationName:f,database:v,schema:E,workspaceState:i,kind:"not-found",...a2e(u,f)});return}A.length!==1?Epe.alertContext(o,"Found",A.length,"schemas in output, expected exactly 1",A):c[f]=A[0]},A=>{let E=p[f];if(r.isMissingLocationError(A)){let{errorString:v}=ua(A).error;Epe.warnContext(o,s,`[plan:missing-location] could not get ${i}-state schemas for`,f,"at",E?r.toLocationString(E):"","error:",A),l.push({locationName:f,database:E?.database??"",schema:E?.schema??"",workspaceState:i,kind:"query-error",errorText:v,...a2e(u,f)});return}throw Epe.errorContext(o,"Could not get any schemas for",f,"at",E?r.toLocationString(E):"","error:",A),A});return{schemas:c,missingLocations:l}};var Fal=yt(uet());var GdC=Je("STEPS");var iMr=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);o.name=n.name,o.description=n.comment,i==="table"&&(o.nullable=n.extra.is_nullable==="YES");let s=n.extra.column_default,a=o.defaultValue;return(s||a)&&(o.defaultValue=s||void 0),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[BigQueryActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, project: ${s.database}, dataset: ${s.schema}`);let u=[];for(let p of a)p.objectName===o&&u.push([p.name.toLowerCase(),p]);return u}};var oMr=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);return o.name=n.name,o.description=n.comment,i==="table"&&(o.nullable=n.extra.is_nullable==="YES"),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[DatabricksActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, database: ${s.database}, schema: ${s.schema}`);let u=[];for(let p of a)p.objectName.toLowerCase()===o.toLowerCase()&&u.push([p.name.toLowerCase(),p]);return u}lookupIncludesNode(t,n,i){return super.lookupIncludesNode(t.toLowerCase(),n,i)}};var sMr=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);return o.name=n.name,o.description=n.comment,i==="table"&&(o.nullable=n.extra.is_nullable==="YES"),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[FabricActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, database: ${s.database}, schema: ${s.schema}`);let u=[];for(let p of a)p.objectName.toLowerCase()===o.toLowerCase()&&u.push([p.name.toLowerCase(),p]);return u}lookupIncludesNode(t,n,i){return super.lookupIncludesNode(t.toLowerCase(),n,i)}};var uNt=class r extends nt{workingPlatforms;constructor(t,n){super(n,"Platform error occurred",400),this.workingPlatforms=t}static checkPlatformMismatch(t,n){if(t!==n)throw new r({repoPlatformKind:n,workspacePlatformKind:t},`Platform mismatch: Git repository platform ${n} does not match workspace platform ${t}`)}},cet=class extends nt{constructor(n,i){let{errorString:o,errorDetail:s}=ua(i).error,a=n.length>50?n.substring(0,50)+"...":n;super(`SQL execution error executing ${a}: ${o}`,s);this.query=n;this.coalesceCause=i}query;coalesceCause};var pet=Je("PLATFORM"),cNt=class{validate(t){return this.validator.assert(t,{failureLogLevel:iWe})}validateAndConvert(t){return this.convert(this.validate(t))}async runQuery(t,n,i){let o=`${this.runQuery.name}:`,s=await n(t);return pet.infoContext(i,o,`query (ID ${s.runDetails.queryID}) completed with status ${s.data.status}`),s.data.rows.map(a=>this.validateAndConvert(a))}},aMr=class{constructor(t,n,i,o,s){this.logContext=t;this.logName=n;this.locations=i;this.query=o;this.throwIfLocationHasError=s;for(let[a,u]of Object.entries(i)){let p=o.query(u);this.queryByLocation[a]=p;let c=this.queries[p];c?c.push(a):(this.queries[p]=[a],this.queryResults[p]=[],this.queryErrors[p]=[])}}logContext;logName;locations;query;throwIfLocationHasError;queryByLocation={};queries={};queryResults={};queryErrors={};async runOneQuery(t,n){let i=`${this.logName}.runLocationQueries`,o=this.queryResults[t];if(!o)throw new nt("No destination found for queryText",t);let s=this.queryErrors[t];if(!s)throw new nt("No errors destination found for queryText",t);let a=()=>this.query.runQuery(t,n,this.logContext);try{let u=await a();for(let p of u)o.push(p)}catch(u){let p=Wgc(u);if(s.push(p),this.throwIfLocationHasError)throw pet.infoContext(this.logContext,i,"error in query for",this.queries[t],u,u.stack),p;pet.errorContext(this.logContext,i,`location ${this.queries[t]} had an error`,t,u)}}async runLocationQueries(t){let n=`${this.logName}.runLocationQueries`;pet.debugContext(this.logContext,n,"querying warehouse",this.queries),await UP(Object.keys(this.queries).map(o=>this.runOneQuery(o,t))),pet.debugContext(this.logContext,n,"Finished querying, building response");let i=fv(this.queryByLocation,o=>{let a=this.queryErrors[o]?.[0];if(a){if(this.throwIfLocationHasError)throw a;return new J$(a)}else return new J$(this.queryResults[o]??[])});return pet.debugContext(this.logContext,n,"built response for all locations"),i}},fZ=class extends cNt{},hZ=class extends cNt{},gZ=class extends cNt{};var m2e=Je("ACTUAL_STATE"),bD1=Je("PLATFORM"),ED1=5e4,AZ=class{constructor(t){this.name=t}name;toLocationString(t){return`${t.database}.${t.schema}`}isVariantType(t){return t.toUpperCase()==="VARIANT"}getName(t,n){let i=Xq(n.locationName,t,"[Platform.getName()]");return zA([i.database,i.schema,n.name],this.name)}runQueryForAllLocations=async(t,n,i,o,s)=>await new aMr(s,t,n,i,o).runLocationQueries(async u=>{try{return await this.runSQL({sql:u})}catch(p){throw new cet(u,p)}});async getObjects(t,n,i){return this.runQueryForAllLocations("objects",t,this.getObjectsImplementation,n,i)}getColumns(t,n,i){return this.runQueryForAllLocations("columns",t,this.getColumnsImplementation,n,i)}async getSchemas(t,n,i){let o=await this.runQueryForAllLocations("schemas",t,this.getSchemasImplementation,n,i);return fv(o,(s,a)=>s.handle(u=>new J$(u.filter(p=>p.name===t[a].schema)),u=>new J$(u)))}async getRows(t){return(await this.runSQL({sql:t})).data.rows}warnAboutLargeQuery(t){t.length>ED1&&bD1.warn(`Large query: ${t.length} chars. If Jinja, ensure {%- -%} whitespace control is used.`)}async getSQLQueryResult(t){let n=new Date,{sql:i,options:o}=t,s=await this.runSQL({sql:i,options:o});return this.getQueryResultFromTemplateRunResult(s,n)}async getSQLQueryResultWithRetries(t,n){let i=new Date,o=mu(),s=3,a=3,{sql:u,options:p}=n,c=()=>this.runSQL({sql:u,overrideRequestID:o,options:p}),l={name:"backoff",base:a},d=h=>{let A=LE(h)?h.toString():"";return A.includes("NetworkError")||A.includes("Network Error")?null:h},f=await cf(c,s,Je("RUNNER"),t,{retryStrategy:l,checkError:d,logOnRetry:`Got a network error, retrying query ${o}`,retryLogLevel:"info"});return this.getQueryResultFromTemplateRunResult(f,i)}isMissingLocationError(t){return!1}collectMissingLocations(t,n,i){let o=new Map;for(let[s,a]of Object.entries(t))a.handle(()=>{},u=>{if(this.isMissingLocationError(u)){m2e.debugContext(n,i,`location ${s} does not exist on the warehouse; treating it as empty`),o.set(s,ua(u).error.errorString);return}throw u});return o}async getDataWarehouseColumns(t,n){let i="getDataWarehouseColumns:";m2e.infoContext(n,i,"initializing ActualState: Getting column lookup");let{warehouseCols:o,missingLocations:s}=await Ah(i,n,"ACTUAL_STATE",async()=>{try{let u=await this.getColumns(t,!1,n);return{warehouseCols:u,missingLocations:this.collectMissingLocations(u,n,i)}}catch(u){throw yg(u,"Could not build columns lookup")}},"info");try{let{details:u,totalObjects:p}=v6o(t,o);m2e.appContext(n,i,`
|
|
10485
|
+
`);throw new nt(a,u)}}};var Uwr=r=>r.presync;var E41=Je("ACTUAL_STATE"),aZ=class{constructor(t,n,i,o){this.objectLookup=t;this.columnLookup=n;this.locations=i;this.referenceNodes=o}objectLookup;columnLookup;locations;referenceNodes;lookupIncludesNode(t,n,i){let o=n==="table"?this.objectLookup.tables:this.objectLookup.views,s=o[i];return s?s.has(t):(E41.debug(`Location "${i}" not found in object list:`,Object.keys(o)),!1)}materializationTypeOnWarehouse=t=>{let n=this.referenceNodes[t];if(!n)throw new nt(`Node with id "${t}" not found in nodes`);let{name:i,locationName:o}=n.operation;return this.lookupIncludesNode(i,"view",o)?"view":this.lookupIncludesNode(i,"table",o)?"table":null};materializationTypeInMetadata=t=>{let i=g1(t,this.referenceNodes,"[ActualState.materializationTypeInMetadata()]").operation.materializationType;if(!i)throw new nt(`Node with id "${t}" has no materialization type`);if(i!=="table"&&i!=="view")throw new nt(`Found node using unsupported materialization type "${i}" in actual state`);return i}};var JZe=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);if(o.name=n.name,o.description=n.comment,i==="table"){let u=n.extra.IS_NULLABLE,p={YES:!0,NO:!1}[u];o.nullable=p}let s=n.extra.COLUMN_DEFAULT,a=o.defaultValue;return(s||a)&&(o.defaultValue=s||void 0),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[SnowflakeActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, database: ${s.database}, schema: ${s.schema}`);let u=[];for(let p of a)p.objectName===o&&u.push([p.name,p]);return u}};var $Ze=class r extends JZe{constructor(t){let{objectLookup:n,columnLookup:i,locations:o,referenceNodes:s}=t;super(r.convertLookupArraysToSets(n),i,o,s)}static convertLookupArraysToSets(t){let n=t.tables,i=t.views,o={},s={};for(let[a,u]of Object.entries(n))o[a]=new Set(u);for(let[a,u]of Object.entries(i))s[a]=new Set(u);return{tables:o,views:s}}static convertLookupSetsToArrays(t){let n=t.tables,i=t.views,o={},s={};for(let[a,u]of Object.entries(n))o[a]=[...u];for(let[a,u]of Object.entries(i))s[a]=[...u];return{tables:o,views:s}}static convertActualStateToParts(t){let{objectLookup:n,columnLookup:i,locations:o,referenceNodes:s}=t;return{objectLookup:r.convertLookupSetsToArrays(n),columnLookup:i,locations:o,referenceNodes:s}}};var C41=Je("PRESYNC"),Dol=async(r,t,n,i,o,s,a)=>{if(!t.locations||!n.locations)throw C41.errorContext(s,"Current locations are required for Actual State. current locations: ",t.locations,"updated locations: ",n.locations),new nt("Locations are required to initialize actual state.");let u=a??Bol(r.name,i,s,o);return await u.setup(r,t,n),{...await u.syncNodes(r),currentActualState:$Ze.convertActualStateToParts(u.currentActualState),updatedActualState:$Ze.convertActualStateToParts(u.updatedActualState)}},Bol=(r,t,n,i)=>r==="databricks"?new Fwr(r,t,n,i):new qwr(r,t,n,i);var fpC=Je("DEBUG");var S41=Je("PLAN"),v41=r=>{if(!r.path)return!1;let{isNodeConfigMetadata:t,isColumnMetadata:n}=Nwr(r.path);return!!(t||n)},Lol=(r,t,n,i)=>KZe(r,t,v41,()=>{},n,"hasMetadataDiff",i)?!0:Uwr(r)?(S41.debugContext(n,`${t.operation.name} has presync data and is eligible for database update.`),!0):!1;var Epe=Je("PLAN"),zwr=async(r,t,n,i)=>{let o="[getSchemas]",{measure:s,printSummary:a}=Bf(o,i);Epe.appContext(i,o,"Getting schemas for current and updated workspace states");let{entitiesWithPossibleEdits:u}=j4e(n,t),[p,c]=await Promise.all([s("platform.getSchemas (current)",()=>kol(r,t,u,"current",i)),s("platform.getSchemas (updated)",()=>kol(r,n,u,"desired",i))]);return Epe.appContext(i,o,"Got schemas. current:",p.schemas,"updated:",c.schemas),a(),{current:p.schemas,updated:c.schemas,missingLocations:[...p.missingLocations,...c.missingLocations]}},kol=async(r,t,n,i,o)=>{let s="[getImplementedSchemas]",a=new Set(n);Epe.debugContext(o,"Getting implemented schemas for subset of nodes:",n);let u=Object.fromEntries(Object.entries(t).filter(([f])=>a.has(f)));Epe.debugContext(o,"Getting used step locations lookup for subset");let p=Z$(u,o);Epe.infoContext(o,"Got implemented locations:",p);let c={},l=[],d=await r.getSchemas(p,!1,o);for(let[f,h]of Object.entries(d))h.handle(A=>{if(!A.length){let{schema:E,database:v}=Xq(f,p,`${s} (this should never happen)`);Epe.warnContext(o,s,`[plan:missing-location] no ${i}-state schema found for ${f} using database ${v} and schema ${E} on ${r.name}`),l.push({locationName:f,database:v,schema:E,workspaceState:i,kind:"not-found",...a2e(u,f)});return}A.length!==1?Epe.alertContext(o,"Found",A.length,"schemas in output, expected exactly 1",A):c[f]=A[0]},A=>{let E=p[f];if(r.isMissingLocationError(A)){let{errorString:v}=aa(A).error;Epe.warnContext(o,s,`[plan:missing-location] could not get ${i}-state schemas for`,f,"at",E?r.toLocationString(E):"","error:",A),l.push({locationName:f,database:E?.database??"",schema:E?.schema??"",workspaceState:i,kind:"query-error",errorText:v,...a2e(u,f)});return}throw Epe.errorContext(o,"Could not get any schemas for",f,"at",E?r.toLocationString(E):"","error:",A),A});return{schemas:c,missingLocations:l}};var Fal=yt(uet());var GdC=Je("STEPS");var iMr=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);o.name=n.name,o.description=n.comment,i==="table"&&(o.nullable=n.extra.is_nullable==="YES");let s=n.extra.column_default,a=o.defaultValue;return(s||a)&&(o.defaultValue=s||void 0),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[BigQueryActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, project: ${s.database}, dataset: ${s.schema}`);let u=[];for(let p of a)p.objectName===o&&u.push([p.name.toLowerCase(),p]);return u}};var oMr=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);return o.name=n.name,o.description=n.comment,i==="table"&&(o.nullable=n.extra.is_nullable==="YES"),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[DatabricksActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, database: ${s.database}, schema: ${s.schema}`);let u=[];for(let p of a)p.objectName.toLowerCase()===o.toLowerCase()&&u.push([p.name.toLowerCase(),p]);return u}lookupIncludesNode(t,n,i){return super.lookupIncludesNode(t.toLowerCase(),n,i)}};var sMr=class extends aZ{updateColumnWithWarehouseColumn(t,n,i){let o=ep(t);return o.name=n.name,o.description=n.comment,i==="table"&&(o.nullable=n.extra.is_nullable==="YES"),o}getDataWarehouseColumns(t){let n=g1(t,this.referenceNodes,"[FabricActualState.getDataWarehouseColumns()]");if(!n.operation.metadata.columns.length&&this.materializationTypeInMetadata(t)==="table")throw new nt(`Table "${n.operation.name}" has no columns - this is a no op.`);let{locationName:i,name:o}=n.operation,s=B3(n,{nodeID:t});if(!s)throw new nt(`Location "${i}" used by "${o}" was not found in workspace locations.`);let a=this.columnLookup[i];if(!a)throw new nt(`Columns at location "${i}" not found in column lookup.`,`location: ${s.locationName}, database: ${s.database}, schema: ${s.schema}`);let u=[];for(let p of a)p.objectName.toLowerCase()===o.toLowerCase()&&u.push([p.name.toLowerCase(),p]);return u}lookupIncludesNode(t,n,i){return super.lookupIncludesNode(t.toLowerCase(),n,i)}};var uNt=class r extends nt{workingPlatforms;constructor(t,n){super(n,"Platform error occurred",400),this.workingPlatforms=t}static checkPlatformMismatch(t,n){if(t!==n)throw new r({repoPlatformKind:n,workspacePlatformKind:t},`Platform mismatch: Git repository platform ${n} does not match workspace platform ${t}`)}},cet=class extends nt{constructor(n,i){let{errorString:o,errorDetail:s}=aa(i).error,a=n.length>50?n.substring(0,50)+"...":n;super(`SQL execution error executing ${a}: ${o}`,s);this.query=n;this.coalesceCause=i}query;coalesceCause};var pet=Je("PLATFORM"),cNt=class{validate(t){return this.validator.assert(t,{failureLogLevel:iWe})}validateAndConvert(t){return this.convert(this.validate(t))}async runQuery(t,n,i){let o=`${this.runQuery.name}:`,s=await n(t);return pet.infoContext(i,o,`query (ID ${s.runDetails.queryID}) completed with status ${s.data.status}`),s.data.rows.map(a=>this.validateAndConvert(a))}},aMr=class{constructor(t,n,i,o,s){this.logContext=t;this.logName=n;this.locations=i;this.query=o;this.throwIfLocationHasError=s;for(let[a,u]of Object.entries(i)){let p=o.query(u);this.queryByLocation[a]=p;let c=this.queries[p];c?c.push(a):(this.queries[p]=[a],this.queryResults[p]=[],this.queryErrors[p]=[])}}logContext;logName;locations;query;throwIfLocationHasError;queryByLocation={};queries={};queryResults={};queryErrors={};async runOneQuery(t,n){let i=`${this.logName}.runLocationQueries`,o=this.queryResults[t];if(!o)throw new nt("No destination found for queryText",t);let s=this.queryErrors[t];if(!s)throw new nt("No errors destination found for queryText",t);let a=()=>this.query.runQuery(t,n,this.logContext);try{let u=await a();for(let p of u)o.push(p)}catch(u){let p=Wgc(u);if(s.push(p),this.throwIfLocationHasError)throw pet.infoContext(this.logContext,i,"error in query for",this.queries[t],u,u.stack),p;pet.errorContext(this.logContext,i,`location ${this.queries[t]} had an error`,t,u)}}async runLocationQueries(t){let n=`${this.logName}.runLocationQueries`;pet.debugContext(this.logContext,n,"querying warehouse",this.queries),await UP(Object.keys(this.queries).map(o=>this.runOneQuery(o,t))),pet.debugContext(this.logContext,n,"Finished querying, building response");let i=fv(this.queryByLocation,o=>{let a=this.queryErrors[o]?.[0];if(a){if(this.throwIfLocationHasError)throw a;return new J$(a)}else return new J$(this.queryResults[o]??[])});return pet.debugContext(this.logContext,n,"built response for all locations"),i}},fZ=class extends cNt{},hZ=class extends cNt{},gZ=class extends cNt{};var m2e=Je("ACTUAL_STATE"),bD1=Je("PLATFORM"),ED1=5e4,AZ=class{constructor(t){this.name=t}name;toLocationString(t){return`${t.database}.${t.schema}`}isVariantType(t){return t.toUpperCase()==="VARIANT"}getName(t,n){let i=Xq(n.locationName,t,"[Platform.getName()]");return zA([i.database,i.schema,n.name],this.name)}runQueryForAllLocations=async(t,n,i,o,s)=>await new aMr(s,t,n,i,o).runLocationQueries(async u=>{try{return await this.runSQL({sql:u})}catch(p){throw new cet(u,p)}});async getObjects(t,n,i){return this.runQueryForAllLocations("objects",t,this.getObjectsImplementation,n,i)}getColumns(t,n,i){return this.runQueryForAllLocations("columns",t,this.getColumnsImplementation,n,i)}async getSchemas(t,n,i){let o=await this.runQueryForAllLocations("schemas",t,this.getSchemasImplementation,n,i);return fv(o,(s,a)=>s.handle(u=>new J$(u.filter(p=>p.name===t[a].schema)),u=>new J$(u)))}async getRows(t){return(await this.runSQL({sql:t})).data.rows}warnAboutLargeQuery(t){t.length>ED1&&bD1.warn(`Large query: ${t.length} chars. If Jinja, ensure {%- -%} whitespace control is used.`)}async getSQLQueryResult(t){let n=new Date,{sql:i,options:o}=t,s=await this.runSQL({sql:i,options:o});return this.getQueryResultFromTemplateRunResult(s,n)}async getSQLQueryResultWithRetries(t,n){let i=new Date,o=mu(),s=3,a=3,{sql:u,options:p}=n,c=()=>this.runSQL({sql:u,overrideRequestID:o,options:p}),l={name:"backoff",base:a},d=h=>{let A=LE(h)?h.toString():"";return A.includes("NetworkError")||A.includes("Network Error")?null:h},f=await cf(c,s,Je("RUNNER"),t,{retryStrategy:l,checkError:d,logOnRetry:`Got a network error, retrying query ${o}`,retryLogLevel:"info"});return this.getQueryResultFromTemplateRunResult(f,i)}isMissingLocationError(t){return!1}collectMissingLocations(t,n,i){let o=new Map;for(let[s,a]of Object.entries(t))a.handle(()=>{},u=>{if(this.isMissingLocationError(u)){m2e.debugContext(n,i,`location ${s} does not exist on the warehouse; treating it as empty`),o.set(s,aa(u).error.errorString);return}throw u});return o}async getDataWarehouseColumns(t,n){let i="getDataWarehouseColumns:";m2e.infoContext(n,i,"initializing ActualState: Getting column lookup");let{warehouseCols:o,missingLocations:s}=await Ah(i,n,"ACTUAL_STATE",async()=>{try{let u=await this.getColumns(t,!1,n);return{warehouseCols:u,missingLocations:this.collectMissingLocations(u,n,i)}}catch(u){throw yg(u,"Could not build columns lookup")}},"info");try{let{details:u,totalObjects:p}=v6o(t,o);m2e.appContext(n,i,`
|
|
10486
10486
|
Total columns by schema: `,u,`
|
|
10487
10487
|
Total columns from all schemas: `,p)}catch(u){m2e.errorContext(n,i,"Failed to log object list details",u)}let a={};for(let[u,p]of Object.entries(o))p.handle(c=>{a[u]=c},()=>{});return{columnLookup:a,missingLocations:s}}buildObjectsByLocationLookup(t){let n={},i={};for(let[o,s]of Object.entries(t))s.handle(a=>{let{tables:u,views:p}=this.convertObjectRowsToMaterializationKinds(a);n[o]=new Set(u),i[o]=new Set(p)},()=>{});return{views:i,tables:n}}async getDataWarehouseObjectsByLocation(t,n){let i="getDataWarehouseObjectsByLocation:";return Ah(i,n,"ACTUAL_STATE",async()=>{try{let o=await this.getObjects(t,!1,n),s=this.collectMissingLocations(o,n,i);try{let{details:a,totalObjects:u}=v6o(t,o);m2e.appContext(n,i,`
|
|
10488
10488
|
Total objects by schema: `,a,`
|
|
10489
|
-
Total objects from all schemas: `,u)}catch(a){m2e.errorContext(n,i,"failed to log object list details",a)}return{objectLookup:this.buildObjectsByLocationLookup(o),missingLocations:s}}catch(o){throw m2e.errorContext(n,i,'Error when building object by location name lookup for objectType "objects"',o),o}},"info")}async getObjectAndColumnLookups(t,n,i){try{let[{objectLookup:o,missingLocations:s},{columnLookup:a,missingLocations:u}]=await Promise.all([this.getDataWarehouseObjectsByLocation(t,i),this.getDataWarehouseColumns(t,i)]),p={tables:{},views:{}},c={},l=T6o(t),d=T6o(n),f={};for(let[N,k]of Object.entries(d)){let q=l[N]?.[0];if(q){let G=o.tables[q]??new Set,H=o.views[q]??new Set,V=a[q]??[];for(let W of k)p.tables[W]=G,p.views[W]=H,c[W]=V}else for(let G of k){let H=n[G];H&&(f[G]=H)}}let[{objectLookup:h,missingLocations:A},{columnLookup:E,missingLocations:v}]=await Promise.all([this.getDataWarehouseObjectsByLocation(f,i),this.getDataWarehouseColumns(f,i)]),T={tables:{...p.tables,...h.tables},views:{...p.views,...h.views}},w={...c,...E};return{currentLookup:{objectLookup:o,columnLookup:a},updatedLookup:{objectLookup:T,columnLookup:w},missingLocations:{current:new Map([...s,...u]),updated:new Map([...A,...v])}}}catch(o){throw m2e.errorContext(i,"getting object and column lookups failed",o),yg(o,"Could not get object and column lookups: ")}}wrapSQLWithTest=t=>`SELECT 1 WHERE EXISTS (${t})`;getTemplateString=(t,n,i)=>{let o=t;return i&&(o=this.wrapSQLWithTest(o)),n&&(o=this.wrapSQLWithExplain(o)),o}};var det=class extends nt{noRoleFound;noWarehouseFound;isWarehouseInvalid;constructor(t,n){let i="Snowflake user authentication unsuccessful: ";t.invalidWarehouseInfo?i+=`Warehouse not found, is invalid, or the user with current role ${t.invalidWarehouseInfo.role} does not have permission.`:i+=`${t.noRoleFound?`Role${t.noWarehouseFound?" and Warehouse":""}`:"Warehouse"} must be provided.`,super(i,n),this.noRoleFound=!!t.noRoleFound,this.noWarehouseFound=!!t.noWarehouseFound,this.isWarehouseInvalid=!!t.invalidWarehouseInfo}},_al=r=>typeof r=="object"&&r instanceof det;var uMr=Je("PLATFORM"),lNt=class{constructor(t,n,i,o){this.runner=i;if(t.toLowerCase().includes("limit")||t.toLowerCase().includes("offset")||t.toLowerCase().includes("order by"))throw new nt("[BatchedQuery] Base query must not contain 'LIMIT', 'OFFSET', or 'ORDER BY', which are reserved for batching");this.queryParams.orderBy.push(...n),this.sql=`${t} ORDER BY ${n.join(", ")}`,this.logContext={...o,queryParams:this.queryParams,sql:t}}runner;aggregateRows=[];batchCount=0;isComplete=!1;logContext;meta=new Map;queryParams={limit:0,offset:0,orderBy:[]};sql;async runOneBatch(){let t="[BatchedQuery.runOneBatch()]";uMr.infoContext({...this.logContext,batch:this.batchCount},t,"Running batch query");try{let{data:{rows:n,status:i},runDetails:{queryID:o}}=await this.runner(this.batchCount===1?this.sql:`${this.sql} LIMIT ${this.queryParams.limit} OFFSET ${this.queryParams.offset}`);switch(this.aggregateRows.push(...n),this.meta.set(this.batchCount,{queryID:o,queryParams:{...this.queryParams},rowCount:n.length,status:i}),i){case"Canceled":case"Failure":throw new nt(`${t} Query finished with status '${i}'`);case"Success":this.isComplete=!this.queryParams.limit||n.length<this.queryParams.limit;break;case dL:{let s=Math.floor(n.length*(1-.1));if(s<1e3)throw new nt(`Unable to project a safe row count limit - query ${o?`'${o}'`:"(no ID)"} unexpectedly truncated at ${n.length} rows. Row data may be unusually large.`);this.queryParams.limit=s;break}}this.queryParams.offset+=n.length}catch(n){uMr.errorContext(this.logContext,t,"Batch failed",n);let i=this.meta.get(this.batchCount);throw this.meta.set(this.batchCount,{...i,error:n}),n}}async run(){let t="[BatchedQuery.run()]",{measure:n,printSummary:i}=Bf(t,this.logContext);uMr.infoContext(this.logContext,t,"Starting");try{do this.batchCount++,await n(`batch ${this.batchCount}`,()=>this.runOneBatch());while(!this.isComplete)}finally{i(),uMr.infoContext(this.logContext,t,`Finished all batches with ${this.aggregateRows.length} total rows; query metadata:`,Object.fromEntries([...this.meta.entries()]))}}checkForDuplicates(t){let n="[BatchedQuery.checkForDuplicates()]",i=new Set,o=new Set;for(let s of this.aggregateRows){let a=t.map(u=>s[u]).join(".");i.has(a)?o.add(a):i.add(a)}if(o.size)throw new nt(`${n} Found ${o.size} duplicate row(s) in query '${this.sql}'`,`Duplicate rows: ${JSON.stringify([...o])}`)}};var Ial=(r,t,n,i)=>{let o=i?` ORDER BY ${i}`:"";return`SELECT * FROM TABLE(RESULT_SCAN('${r}'))${o} LIMIT ${t} OFFSET ${n}`};var XM=Je("PLATFORM"),vD1=B.object({TABLE_NAME:B.string(),COMMENT:B.string().nullable(),TABLE_TYPE:B.string()}),cMr=class extends fZ{validator=Mr("InformationSchemaTablesRow",vD1);query(t){return`SELECT TABLE_NAME, TABLE_TYPE, COMMENT from "${t.database}".INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${t.schema}';`}convert(t){let{TABLE_NAME:n,COMMENT:i,...o}=t;return{kind:o.TABLE_TYPE.match(/^(.+\s)?TABLE$/)?"TABLE":o.TABLE_TYPE.match(/^(.+\s)?VIEW$/)?"VIEW":"<unknown>",name:n,comment:i??"",extra:o}}},TD1=B.object({TABLE_NAME:B.string(),COMMENT:B.string().nullable(),COLUMN_NAME:B.string(),IS_NULLABLE:B.union([B.literal("YES"),B.literal("NO")]),COLUMN_DEFAULT:B.string().nullable()}),lMr=class extends hZ{_logTag="log-tag-not-set";setLogTag(t){this._logTag=t}get logTag(){return this._logTag}validator=Mr("InformationSchemaColumnsRow",TD1);get columnsString(){return"TABLE_NAME, COLUMN_NAME, IS_NULLABLE, COMMENT, COLUMN_DEFAULT"}query(t){return`SELECT ${this.columnsString} from "${t.database}".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${t.schema}' ORDER BY TABLE_NAME, COLUMN_NAME`}convert(t){let{TABLE_NAME:n,COLUMN_NAME:i,COMMENT:o,...s}=t;return{name:i,objectName:n,comment:o??"",extra:s}}async runQuery(t,n,i){let o="[SnowflakeInformationSchemaColumnsImplementation] ";if(!t.toUpperCase().includes("ORDER BY TABLE_NAME, COLUMN_NAME")){let f="INFORMATION_SCHEMA.COLUMNS query missing required ORDER BY TABLE_NAME, COLUMN_NAME clause. This can lead to non-deterministic results when Snowflake truncates large result sets. Add ORDER BY TABLE_NAME, COLUMN_NAME clause to ensure consistent behavior. SQL text: "+t;throw XM.errorContext(i,o,f),new nt(f)}let s=await n(t),{status:a,rows:u}=s.data,{queryID:p}=s.runDetails;if(!p)throw XM.fatalContext(i,o,`query ID was unexpectedly ${p}`),new nt(`Query ID was unexpectedly ${p} when querying warehouse columns`);let c={...i,initialQueryID:p};if(this.setLogTag(`${o}[initial query ID=${p}] `),u.length===0)return XM.infoContext(c,this.logTag,"initial query returned 0 rows. No pagination needed. Returning empty array."),[];if(a!==dL)return XM.infoContext(c,this.logTag,`initial query returned all ${u.length} rows without truncation. No pagination needed.`),u.map(f=>this.validateAndConvert(f));let l=this.initializePaginationStateForTruncatedResponse(u,a,p,c),d=await this.paginateResults(p,l,n,c);return this.auditPaginatedResultsForDuplicates(d,c),XM.infoContext(c,this.logTag,`finished querying ${d.length} rows in ${l.batchNumber} pagination ${l.batchNumber===1?"batch":"batches"}.`),d}initializePaginationStateForTruncatedResponse(t,n,i,o){if(n!==dL)throw new nt(`Programming error: initializePaginationStateForTruncatedResponse called with non-truncated initial status ${n} for query ${i}`);let s=t.length,a=Math.floor(s*.9),u=0;return XM.infoContext(o,this.logTag,`initial query truncated - applying 10% safety margin to max batch size of ${a}. Discarding initial results and fetching all data via RESULT_SCAN. batchSize=${a},maxBatchSize=${a},offset=${u}`),{aggregateRows:[],offset:u,batchSize:a,maxBatchSize:a,batchNumber:1,failedBatchSize:void 0}}async paginateResults(t,n,i,o){let s=!1;for(;!s;){let a=n.batchSize,{paginatedRows:u,batchStatus:p,batchQueryID:c}=await this.fetchBatch(t,n.batchSize,n.offset,n.batchNumber,i,o);XM.infoContext(o,this.logTag,`[batch query ID=${c}] for batch ${n.batchNumber} completed with status "${p}" returned ${u.length} records`);let l=p===dL;l?(n.batchSize=this.adjustBatchSizeAfterTruncation(n.batchNumber,n.batchSize,u.length,o),n.failedBatchSize=n.batchSize):u.length===a&&n.failedBatchSize===void 0&&(n.batchSize=this.adjustBatchSizeAfterSuccess(n.batchNumber,n.batchSize,n.maxBatchSize,o));for(let d of u)n.aggregateRows.push(d);s=u.length<a&&!l,s||(n.offset+=u.length,n.batchNumber++)}return n.aggregateRows}async fetchBatch(t,n,i,o,s,a){try{let u=Ial(t,n,i,"TABLE_NAME, COLUMN_NAME"),{data:{rows:p,status:c},runDetails:{queryID:l}}=await s(u);return{paginatedRows:p.map(f=>this.validateAndConvert(f)),batchStatus:c,batchQueryID:l}}catch(u){throw XM.errorContext(a,this.logTag,`query for batch ${o} failed with error`,u),u}}adjustBatchSizeAfterTruncation(t,n,i,o){let u=Math.floor(i*.75);if(n<=1e3&&u<1e3)throw XM.fatalContext(o,this.logTag,`[batch=${t}]: already at minimum batch size 1000 and still truncating at ${i} rows. Cannot reduce batch size any further.`,{batch_number:t,paginated_request_batch_size:n,truncated_row_count:i,min_batch_size:1e3,calculated_size:u}),new nt("Already at minimum batch size of 1000 and still experiencing truncation. Cannot paginate this query - even 1000 rows exceed data limits.");let p=Math.max(1e3,u);return XM.infoContext(o,this.logTag,`[batch=${t}]: reducing batch size by factor ${.75}. From ${n} -> ${p}. Min batch size 1000`),p}adjustBatchSizeAfterSuccess(t,n,i,o){if(n<i){let a=Math.min(i,Math.floor(n*1.25));return XM.infoContext(o,this.logTag,`[batch=${t}]: increasing batch size by ${1.25}. From ${n} -> ${a}. Max batch size ${i}`),a}else if(n>i)return XM.infoContext(o,this.logTag,`[batch=${t}]: current batch size ${n} exceeds max batch size ${i}. Scaling down.`),i;return n}auditPaginatedResultsForDuplicates(t,n){try{XM.infoContext(n,this.logTag,`Auditing ${t.length} paginated results for duplicates...`);let i=new Map,o=new Map,s=0;for(let a of t){let u=`${a.objectName}.${a.name}`,p=i.get(u);p?(p.count++,o.set(u,p),s++):i.set(u,{table:a.objectName,column:a.name,count:1})}s?XM.errorContext(n,this.logTag,"Duplicate rows detected after pagination! This indicates RESULT_SCAN ordering issue.",{total_rows:t.length,unique_rows:i.size,duplicate_count:s,first_10_duplicates:Array.from(o.values()).slice(0,10)}):XM.infoContext(n,this.logTag,`Audit passed: all ${t.length} rows are unique by (TABLE_NAME, COLUMN_NAME).`)}catch(i){XM.errorContext(n,this.logTag,"Audit of paginated results for duplicates failed with error",i)}}},_D1=B.object({name:B.string(),owner:B.string(),comment:B.string(),budget:B.string().nullable().optional(),is_default:B.union([B.literal("Y"),B.literal("N")]),is_current:B.union([B.literal("Y"),B.literal("N")]),retention_time:B.string(),created_on:B.union([B.date(),B.string()]),options:B.string(),owner_role_type:B.string(),database_name:B.string()}),pMr=class extends gZ{validator=Mr("SnowflakeShowSchemaRow",_D1);convert(t){let{name:n,options:i,...o}=t;return{name:n,extra:{...o,options:new Set(i.length?i.split(", "):[])}}}query(t){return`SHOW SCHEMAS IN DATABASE "${t.database}"`}};var ID1=["002003","002043"],RD1=r=>{let t=r instanceof cet?r.coalesceCause:r;if(t instanceof yle){let n=String(t.getSnowflakeErrorCode()??"");return ID1.includes(n)}return!1},pNt=class extends AZ{constructor(n){super("snowflake");this.userContext=n}userContext;log(n,...i){Je("PLATFORM")[n]({orgID:this.userContext.orgID,workspaceID:this.userContext.environmentID,...i})}getObjectsImplementation=new cMr;getColumnsImplementation=new lMr;getSchemasImplementation=new pMr;isMissingLocationError(n){return RD1(n)}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n?.data?.status||"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data){let a=n.data.columns.map(c=>c.Name),u=n.data.rows.map(c=>({values:YYe(a,c)})),p=n.data.columns.map(c=>({name:c.Name,type:c.DataType||""}));s.fields=p,s.rows=u}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}validateUserContext(){let n="In your environment settings, verify that you have";if(!this.userContext)throw new nt(`Missing ${this.name} connection information! ${n} selected and authenticated a connection type.`);if(pd(this.userContext.kind==="snowflake",`Expected snowflake user context but received kind ${this.userContext.kind}`,"PLATFORM"),!this.userContext.accountName?.trim())throw new nt(`Missing ${this.name} account information! ${n} added an account.`);let i=PKo(this.userContext),o=`Missing ${this.name} credentials! ${n} added a`,s=Dme(i,a=>a.snowflakeUsername.trim()&&a.snowflakePassword?null:`${o} username and password.`,()=>null,()=>null,a=>a.snowflakeUsername?.trim()?null:`${o} username.`);if(s)throw new nt(s)}async testConnection(n=!1){if(n)try{this.validateUserContext();let i=(await this.getRows("select current_role()"))[0]?.["CURRENT_ROLE()"],o=(await this.getRows("select current_warehouse()"))[0]?.["CURRENT_WAREHOUSE()"],s=!1,a=!1;if(!o){if(this.userContext.warehouse)throw new det({invalidWarehouseInfo:{warehouse:this.userContext.warehouse,role:i??""}});a=!0}if((!i||i==="PUBLIC")&&!this.userContext.role&&(s=!0),a||s)throw new det({noRoleFound:s,noWarehouseFound:a})}catch(i){throw _al(i)?i:LE(i)?new nt(`${TD(this.name)} user authentication unsuccessful: ${i.message}`,i.detail):new nt(`${TD(this.name)} user authentication unsuccessful:`,ua(i).error.errorDetail)}else try{await this.runSQL({sql:h5})}catch(i){throw LE(i)?new nt(`Could not validate connection to ${this.name}: ${i.message}`,i.detail):new nt(`Could not validate connection to ${this.name}`,ua(i).error.errorDetail)}}async getDatabaseNames(){return(await this.getRows("SHOW DATABASES")).map(i=>i.name)}async getSchemaNames(n){return(await this.getRows(`SHOW SCHEMAS IN "${n}"`)).map(o=>o.name)}async getVariantRows(n,i,o,s){let a=this.getName(s,o),u=`SELECT "${n}" FROM ${a} SAMPLE (${i} ROWS)`;return this.getSQLQueryResult({sql:u})}async getObjectRows(n,i,o){let s=`SELECT * FROM ${this.getName(n,i)} LIMIT 100`;return o&&(s=this.wrapSQLWithExplain(s)),this.getSQLQueryResult({sql:s})}createColumnMetadata(n,i){return{name:n.name,dataType:n.type,transform:"",nullable:n["null?"]==="Y",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},primaryKey:n["primary key"]==="Y",uniqueKey:n["unique key"]==="Y",description:n.comment||"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async describeObject(n,i,o,s){let a=`DESC ${o.toUpperCase()} ${this.getName(n,i)}`;return(await this.runSQL({sql:a,overrideRequestID:mu()})).data.rows.map(p=>this.createColumnMetadata(p,s))}convertObjectRowsToMaterializationKinds(n){let i="convertObjectRowsToMaterializationKinds:",o=[],s=[];for(let a of n)a.kind==="TABLE"?o.push(a.name):a.kind==="VIEW"?s.push(a.name):this.log("emergContext",i,`table ${a.name} is of unexpected table type ${a.kind}`);return{tables:o,views:s}}createState(n,i,o,s){return new JZe(s,o,i,n)}wrapSQLWithExplain(n){return`EXPLAIN USING text ${n}`}},PKo=r=>({platformKind:"snowflake",snowflakeAccount:r.accountName||"",snowflakeAccessUrl:r.accessUrl,snowflakeUsername:r.user||"",snowflakePassword:r.password||"",snowflakeKeyPairKey:r.keyPairKey,snowflakeRole:r.role||"",snowflakeWarehouse:r.warehouse||"",snowflakeAuthType:r.authenticator,snowflakeKeyPairPass:r.keyPairPass??void 0});function V5e(r){if(r==="ApplicationDefault")throw new Vi("BigQuery ApplicationDefault auth is local-CLI-only and has no cloud connection type.");return r}var Ral=Je("RUNNER");var OD1=r=>{if(r.authenticator==="Token")return{token:r.token??"",path:r.path,host:r.host,databricksAuthType:r.authenticator,platformKind:"databricks"};if(r.authenticator==="Cloud")return{path:r.path,databricksAuthType:r.authenticator,host:r.host,platformKind:"databricks"};if(r.authenticator==="OAuthU2M")return{path:r.path,databricksAuthType:r.authenticator,host:r.host,platformKind:"databricks",accessToken:r.accessToken};if(r.authenticator==="OAuthM2M")return{path:r.path,databricksAuthType:r.authenticator,host:r.host,clientID:r.clientID??"",clientSecret:r.secret??"",platformKind:"databricks"};{let t=r.authenticator;throw new nt(`Databricks authenticator not supported: ${t}`)}},wD1=r=>({platformKind:"bigquery",bigQueryAuthType:V5e(r.authenticator),serviceAccountKey:r.serviceAccountKey}),MD1=r=>{if(r.authenticator==="oauth")return{credentials:r.credentials,connectionString:r.connectionString,fabricAuthType:r.authenticator,platformKind:"fabric"};{let t=r.authenticator;throw new nt(`Fabric authenticator not supported: ${t}`)}},Oal=r=>fL(r,{snowflake:t=>PKo(t),databricks:t=>OD1(t),fabric:t=>MD1(t),bigquery:t=>wD1(t)}),fet=(r,t)=>fL(t,{snowflake:n=>{if(!CWe(r))throw new Vi("Provided credentials are not Snowflake credentials");let i=Dme(r,()=>{},o=>o.snowflakeKeyPairKey,()=>{},()=>{},()=>{});return{snowflakeAccount:n.accountName,snowflakeAccessUrl:n.accessUrl,snowflakeKeyPairKey:i,snowflakeUsername:n.user,snowflakeRole:n.role,snowflakeWarehouse:n.warehouse,snowflakeAuthType:n.authenticator}},databricks:n=>{if(!w0r(r))throw new Vi("Provided credentials are not Databricks credentials");let i=r.databricksAuthType==="Token"?r.token:void 0;return{databricksAuthType:r.databricksAuthType,databricksPath:r.path,databricksHost:n.host,databricksToken:i,platformKind:"databricks"}},fabric:n=>{if(!M0r(r))throw new Vi("Provided credentials are not Fabric credentials");return{fabricAuthType:r.fabricAuthType,fabricConnectionString:n.connectionString,platformKind:"fabric"}},bigquery:n=>{if(!x0r(r))throw new Vi("Provided credentials are not BigQuery credentials");let i=r.bigQueryAuthType,o=i==="ServiceAccount"?r.serviceAccountKey||n.serviceAccountKey:void 0;if(i==="ServiceAccount"&&!o)throw new Vi("Missing required BigQuery credentials: serviceAccountKey");return{bigQueryAuthType:i,bigQueryServiceAccountKey:o,platformKind:"bigquery"}}});var wal=async(r,t=Xc.resolveAuthToken)=>{Ral.app("Attempting to cancel run",r);try{await rJe("/scheduler/cancelRun",r,t)}catch(n){let i=ua(n);throw Ral.error(i),i}};var NKo=Je("PLAN");var Mal=(r,t,n,i,o,s,a)=>dMr(`${r} workspace data`,t,n,i,o,`${r}WorkspaceData`,s,a),xal=async(r,t,n,i,o,s)=>{await dMr("plan context",r,t,n,i,"context",o,s)},Pal=async(r,t,n,i,o,s)=>await dMr("plan (completed)",r,t,n,i,"plan",o,s),Nal=async(r,t,n,i,o,s)=>await dMr("plan (unrealized)",r,t,n,i,"plan",o,s),dMr=async(r,t,n,i,o,s,a,u)=>{let p="[storePlanData]",c=PD1(n,i,o,s);return await Ah(`${p} (${r})`,u,"PLAN",async()=>{try{return NKo.infoContext(u,p,`Storing ${r} (${typeof a}) to ${c}`),await t.storage().uploadFile(c,a),NKo.infoContext(u,p,`Successfully stored ${r} (${typeof a}) to ${c}`),c}catch(l){throw NKo.errorContext(u,p,`Failed to store ${r} (${typeof a}) to ${c}`,l),l}},"info")},PD1=(r,t,n,i)=>`user/${r}/environment/${t}/planContext/${n}.${i}`;var qi;(function(r){r[r.BACKSPACE=8]="BACKSPACE",r[r.FORM_FEED=12]="FORM_FEED",r[r.NEWLINE=10]="NEWLINE",r[r.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",r[r.TAB=9]="TAB",r[r.SPACE=32]="SPACE",r[r.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",r[r.QUOTATION_MARK=34]="QUOTATION_MARK",r[r.NUMBER_SIGN=35]="NUMBER_SIGN",r[r.DOLLAR_SIGN=36]="DOLLAR_SIGN",r[r.PERCENT_SIGN=37]="PERCENT_SIGN",r[r.AMPERSAND=38]="AMPERSAND",r[r.APOSTROPHE=39]="APOSTROPHE",r[r.LEFT_PARENTHESIS=40]="LEFT_PARENTHESIS",r[r.RIGHT_PARENTHESIS=41]="RIGHT_PARENTHESIS",r[r.ASTERISK=42]="ASTERISK",r[r.PLUS_SIGN=43]="PLUS_SIGN",r[r.COMMA=44]="COMMA",r[r.HYPHEN_MINUS=45]="HYPHEN_MINUS",r[r.FULL_STOP=46]="FULL_STOP",r[r.SOLIDUS=47]="SOLIDUS",r[r.DIGIT_ZERO=48]="DIGIT_ZERO",r[r.DIGIT_ONE=49]="DIGIT_ONE",r[r.DIGIT_TWO=50]="DIGIT_TWO",r[r.DIGIT_THREE=51]="DIGIT_THREE",r[r.DIGIT_FOUR=52]="DIGIT_FOUR",r[r.DIGIT_FIVE=53]="DIGIT_FIVE",r[r.DIGIT_SIX=54]="DIGIT_SIX",r[r.DIGIT_SEVEN=55]="DIGIT_SEVEN",r[r.DIGIT_EIGHT=56]="DIGIT_EIGHT",r[r.DIGIT_NINE=57]="DIGIT_NINE",r[r.COLON=58]="COLON",r[r.SEMICOLON=59]="SEMICOLON",r[r.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",r[r.EQUALS_SIGN=61]="EQUALS_SIGN",r[r.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",r[r.QUESTION_MARK=63]="QUESTION_MARK",r[r.COMMERCIAL_AT=64]="COMMERCIAL_AT",r[r.LATIN_CAPITAL_LETTER_A=65]="LATIN_CAPITAL_LETTER_A",r[r.LATIN_CAPITAL_LETTER_B=66]="LATIN_CAPITAL_LETTER_B",r[r.LATIN_CAPITAL_LETTER_C=67]="LATIN_CAPITAL_LETTER_C",r[r.LATIN_CAPITAL_LETTER_D=68]="LATIN_CAPITAL_LETTER_D",r[r.LATIN_CAPITAL_LETTER_E=69]="LATIN_CAPITAL_LETTER_E",r[r.LATIN_CAPITAL_LETTER_F=70]="LATIN_CAPITAL_LETTER_F",r[r.LATIN_CAPITAL_LETTER_G=71]="LATIN_CAPITAL_LETTER_G",r[r.LATIN_CAPITAL_LETTER_H=72]="LATIN_CAPITAL_LETTER_H",r[r.LATIN_CAPITAL_LETTER_I=73]="LATIN_CAPITAL_LETTER_I",r[r.LATIN_CAPITAL_LETTER_J=74]="LATIN_CAPITAL_LETTER_J",r[r.LATIN_CAPITAL_LETTER_K=75]="LATIN_CAPITAL_LETTER_K",r[r.LATIN_CAPITAL_LETTER_L=76]="LATIN_CAPITAL_LETTER_L",r[r.LATIN_CAPITAL_LETTER_M=77]="LATIN_CAPITAL_LETTER_M",r[r.LATIN_CAPITAL_LETTER_N=78]="LATIN_CAPITAL_LETTER_N",r[r.LATIN_CAPITAL_LETTER_O=79]="LATIN_CAPITAL_LETTER_O",r[r.LATIN_CAPITAL_LETTER_P=80]="LATIN_CAPITAL_LETTER_P",r[r.LATIN_CAPITAL_LETTER_Q=81]="LATIN_CAPITAL_LETTER_Q",r[r.LATIN_CAPITAL_LETTER_R=82]="LATIN_CAPITAL_LETTER_R",r[r.LATIN_CAPITAL_LETTER_S=83]="LATIN_CAPITAL_LETTER_S",r[r.LATIN_CAPITAL_LETTER_T=84]="LATIN_CAPITAL_LETTER_T",r[r.LATIN_CAPITAL_LETTER_U=85]="LATIN_CAPITAL_LETTER_U",r[r.LATIN_CAPITAL_LETTER_V=86]="LATIN_CAPITAL_LETTER_V",r[r.LATIN_CAPITAL_LETTER_W=87]="LATIN_CAPITAL_LETTER_W",r[r.LATIN_CAPITAL_LETTER_X=88]="LATIN_CAPITAL_LETTER_X",r[r.LATIN_CAPITAL_LETTER_Y=89]="LATIN_CAPITAL_LETTER_Y",r[r.LATIN_CAPITAL_LETTER_Z=90]="LATIN_CAPITAL_LETTER_Z",r[r.LEFT_SQUARE_BRACKET=91]="LEFT_SQUARE_BRACKET",r[r.REVERSE_SOLIDUS=92]="REVERSE_SOLIDUS",r[r.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",r[r.CIRCUMFLEX_ACCENT=94]="CIRCUMFLEX_ACCENT",r[r.LOW_LINE=95]="LOW_LINE",r[r.GRAVE_ACCENT=96]="GRAVE_ACCENT",r[r.LATIN_SMALL_LETTER_A=97]="LATIN_SMALL_LETTER_A",r[r.LATIN_SMALL_LETTER_B=98]="LATIN_SMALL_LETTER_B",r[r.LATIN_SMALL_LETTER_C=99]="LATIN_SMALL_LETTER_C",r[r.LATIN_SMALL_LETTER_D=100]="LATIN_SMALL_LETTER_D",r[r.LATIN_SMALL_LETTER_E=101]="LATIN_SMALL_LETTER_E",r[r.LATIN_SMALL_LETTER_F=102]="LATIN_SMALL_LETTER_F",r[r.LATIN_SMALL_LETTER_G=103]="LATIN_SMALL_LETTER_G",r[r.LATIN_SMALL_LETTER_H=104]="LATIN_SMALL_LETTER_H",r[r.LATIN_SMALL_LETTER_I=105]="LATIN_SMALL_LETTER_I",r[r.LATIN_SMALL_LETTER_J=106]="LATIN_SMALL_LETTER_J",r[r.LATIN_SMALL_LETTER_K=107]="LATIN_SMALL_LETTER_K",r[r.LATIN_SMALL_LETTER_L=108]="LATIN_SMALL_LETTER_L",r[r.LATIN_SMALL_LETTER_M=109]="LATIN_SMALL_LETTER_M",r[r.LATIN_SMALL_LETTER_N=110]="LATIN_SMALL_LETTER_N",r[r.LATIN_SMALL_LETTER_O=111]="LATIN_SMALL_LETTER_O",r[r.LATIN_SMALL_LETTER_P=112]="LATIN_SMALL_LETTER_P",r[r.LATIN_SMALL_LETTER_Q=113]="LATIN_SMALL_LETTER_Q",r[r.LATIN_SMALL_LETTER_R=114]="LATIN_SMALL_LETTER_R",r[r.LATIN_SMALL_LETTER_S=115]="LATIN_SMALL_LETTER_S",r[r.LATIN_SMALL_LETTER_T=116]="LATIN_SMALL_LETTER_T",r[r.LATIN_SMALL_LETTER_U=117]="LATIN_SMALL_LETTER_U",r[r.LATIN_SMALL_LETTER_V=118]="LATIN_SMALL_LETTER_V",r[r.LATIN_SMALL_LETTER_W=119]="LATIN_SMALL_LETTER_W",r[r.LATIN_SMALL_LETTER_X=120]="LATIN_SMALL_LETTER_X",r[r.LATIN_SMALL_LETTER_Y=121]="LATIN_SMALL_LETTER_Y",r[r.LATIN_SMALL_LETTER_Z=122]="LATIN_SMALL_LETTER_Z",r[r.LEFT_CURLY_BRACKET=123]="LEFT_CURLY_BRACKET",r[r.VERTICAL_LINE=124]="VERTICAL_LINE",r[r.RIGHT_CURLY_BRACKET=125]="RIGHT_CURLY_BRACKET",r[r.TILDE=126]="TILDE"})(qi||(qi={}));var Dal={[qi.QUOTATION_MARK]:qi.QUOTATION_MARK,[qi.REVERSE_SOLIDUS]:qi.REVERSE_SOLIDUS,[qi.SOLIDUS]:qi.SOLIDUS,[qi.LATIN_SMALL_LETTER_B]:qi.BACKSPACE,[qi.LATIN_SMALL_LETTER_F]:qi.FORM_FEED,[qi.LATIN_SMALL_LETTER_N]:qi.NEWLINE,[qi.LATIN_SMALL_LETTER_R]:qi.CARRIAGE_RETURN,[qi.LATIN_SMALL_LETTER_T]:qi.TAB};var dNt=class{constructor(){this.decoder=new TextDecoder("utf-8"),this.strings=[],this.byteLength=0}appendChar(t){this.strings.push(String.fromCharCode(t)),this.byteLength+=1}appendBuf(t,n=0,i=t.length){this.strings.push(this.decoder.decode(t.subarray(n,i))),this.byteLength+=i-n}reset(){this.strings=[],this.byteLength=0}toString(){return this.strings.join("")}},fNt=class{constructor(t){this.decoder=new TextDecoder("utf-8"),this.bufferOffset=0,this.string="",this.byteLength=0,this.buffer=new Uint8Array(t)}appendChar(t){this.bufferOffset>=this.buffer.length&&this.flushStringBuffer(),this.buffer[this.bufferOffset++]=t,this.byteLength+=1}appendBuf(t,n=0,i=t.length){let o=i-n;this.bufferOffset+o>this.buffer.length&&this.flushStringBuffer(),this.buffer.set(t.subarray(n,i),this.bufferOffset),this.bufferOffset+=o,this.byteLength+=o}flushStringBuffer(){this.string+=this.decoder.decode(this.buffer.subarray(0,this.bufferOffset)),this.bufferOffset=0}reset(){this.string="",this.bufferOffset=0,this.byteLength=0}toString(){return this.flushStringBuffer(),this.string}};var DKo;(function(r){r[r.LEFT_BRACE=0]="LEFT_BRACE",r[r.RIGHT_BRACE=1]="RIGHT_BRACE",r[r.LEFT_BRACKET=2]="LEFT_BRACKET",r[r.RIGHT_BRACKET=3]="RIGHT_BRACKET",r[r.COLON=4]="COLON",r[r.COMMA=5]="COMMA",r[r.TRUE=6]="TRUE",r[r.FALSE=7]="FALSE",r[r.NULL=8]="NULL",r[r.STRING=9]="STRING",r[r.NUMBER=10]="NUMBER",r[r.SEPARATOR=11]="SEPARATOR"})(DKo||(DKo={}));var Ud=DKo;var Xn;(function(r){r[r.START=0]="START",r[r.ENDED=1]="ENDED",r[r.ERROR=2]="ERROR",r[r.TRUE1=3]="TRUE1",r[r.TRUE2=4]="TRUE2",r[r.TRUE3=5]="TRUE3",r[r.FALSE1=6]="FALSE1",r[r.FALSE2=7]="FALSE2",r[r.FALSE3=8]="FALSE3",r[r.FALSE4=9]="FALSE4",r[r.NULL1=10]="NULL1",r[r.NULL2=11]="NULL2",r[r.NULL3=12]="NULL3",r[r.STRING_DEFAULT=13]="STRING_DEFAULT",r[r.STRING_AFTER_BACKSLASH=14]="STRING_AFTER_BACKSLASH",r[r.STRING_UNICODE_DIGIT_1=15]="STRING_UNICODE_DIGIT_1",r[r.STRING_UNICODE_DIGIT_2=16]="STRING_UNICODE_DIGIT_2",r[r.STRING_UNICODE_DIGIT_3=17]="STRING_UNICODE_DIGIT_3",r[r.STRING_UNICODE_DIGIT_4=18]="STRING_UNICODE_DIGIT_4",r[r.STRING_INCOMPLETE_CHAR=19]="STRING_INCOMPLETE_CHAR",r[r.NUMBER_AFTER_INITIAL_MINUS=20]="NUMBER_AFTER_INITIAL_MINUS",r[r.NUMBER_AFTER_INITIAL_ZERO=21]="NUMBER_AFTER_INITIAL_ZERO",r[r.NUMBER_AFTER_INITIAL_NON_ZERO=22]="NUMBER_AFTER_INITIAL_NON_ZERO",r[r.NUMBER_AFTER_FULL_STOP=23]="NUMBER_AFTER_FULL_STOP",r[r.NUMBER_AFTER_DECIMAL=24]="NUMBER_AFTER_DECIMAL",r[r.NUMBER_AFTER_E=25]="NUMBER_AFTER_E",r[r.NUMBER_AFTER_E_AND_SIGN=26]="NUMBER_AFTER_E_AND_SIGN",r[r.NUMBER_AFTER_E_AND_DIGIT=27]="NUMBER_AFTER_E_AND_DIGIT",r[r.SEPARATOR=28]="SEPARATOR",r[r.BOM_OR_START=29]="BOM_OR_START",r[r.BOM=30]="BOM"})(Xn||(Xn={}));function Bal(r){return["START","ENDED","ERROR","TRUE1","TRUE2","TRUE3","FALSE1","FALSE2","FALSE3","FALSE4","NULL1","NULL2","NULL3","STRING_DEFAULT","STRING_AFTER_BACKSLASH","STRING_UNICODE_DIGIT_1","STRING_UNICODE_DIGIT_2","STRING_UNICODE_DIGIT_3","STRING_UNICODE_DIGIT_4","STRING_INCOMPLETE_CHAR","NUMBER_AFTER_INITIAL_MINUS","NUMBER_AFTER_INITIAL_ZERO","NUMBER_AFTER_INITIAL_NON_ZERO","NUMBER_AFTER_FULL_STOP","NUMBER_AFTER_DECIMAL","NUMBER_AFTER_E","NUMBER_AFTER_E_AND_SIGN","NUMBER_AFTER_E_AND_DIGIT","SEPARATOR","BOM_OR_START","BOM"][r]}var DD1={stringBufferSize:0,numberBufferSize:0,separator:void 0,emitPartialTokens:!1},het=class r extends Error{constructor(t){super(t),Object.setPrototypeOf(this,r.prototype)}},get=class{constructor(t){this.state=Xn.BOM_OR_START,this.bomIndex=0,this.separatorIndex=0,this.escapedCharsByteLength=0,this.bytes_remaining=0,this.bytes_in_sequence=0,this.char_split_buffer=new Uint8Array(4),this.encoder=new TextEncoder,this.offset=-1,t=Object.assign(Object.assign({},DD1),t),this.emitPartialTokens=t.emitPartialTokens===!0,this.bufferedString=t.stringBufferSize&&t.stringBufferSize>4?new fNt(t.stringBufferSize):new dNt,this.bufferedNumber=t.numberBufferSize&&t.numberBufferSize>0?new fNt(t.numberBufferSize):new dNt,this.separator=t.separator,this.separatorBytes=t.separator?this.encoder.encode(t.separator):void 0}get isEnded(){return this.state===Xn.ENDED}write(t){try{let n;if(t instanceof Uint8Array)n=t;else if(typeof t=="string")n=this.encoder.encode(t);else if(Array.isArray(t))n=Uint8Array.from(t);else if(ArrayBuffer.isView(t))n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else throw new TypeError("Unexpected type. The `write` function only accepts Arrays, TypedArrays and Strings.");for(let i=0;i<n.length;i+=1){let o=n[i];switch(this.state){case Xn.BOM_OR_START:if(t instanceof Uint8Array&&o===239){this.bom=[239,187,191],this.bomIndex+=1,this.state=Xn.BOM;continue}if(t instanceof Uint16Array){if(o===254){this.bom=[254,255],this.bomIndex+=1,this.state=Xn.BOM;continue}if(o===255){this.bom=[255,254],this.bomIndex+=1,this.state=Xn.BOM;continue}}if(t instanceof Uint32Array){if(o===0){this.bom=[0,0,254,255],this.bomIndex+=1,this.state=Xn.BOM;continue}if(o===255){this.bom=[255,254,0,0],this.bomIndex+=1,this.state=Xn.BOM;continue}}case Xn.START:if(this.offset+=1,this.separatorBytes&&o===this.separatorBytes[0]){if(this.separatorBytes.length===1){this.state=Xn.START,this.onToken({token:Ud.SEPARATOR,value:this.separator,offset:this.offset+this.separatorBytes.length-1});continue}this.state=Xn.SEPARATOR;continue}if(o===qi.SPACE||o===qi.NEWLINE||o===qi.CARRIAGE_RETURN||o===qi.TAB)continue;if(o===qi.LEFT_CURLY_BRACKET){this.onToken({token:Ud.LEFT_BRACE,value:"{",offset:this.offset});continue}if(o===qi.RIGHT_CURLY_BRACKET){this.onToken({token:Ud.RIGHT_BRACE,value:"}",offset:this.offset});continue}if(o===qi.LEFT_SQUARE_BRACKET){this.onToken({token:Ud.LEFT_BRACKET,value:"[",offset:this.offset});continue}if(o===qi.RIGHT_SQUARE_BRACKET){this.onToken({token:Ud.RIGHT_BRACKET,value:"]",offset:this.offset});continue}if(o===qi.COLON){this.onToken({token:Ud.COLON,value:":",offset:this.offset});continue}if(o===qi.COMMA){this.onToken({token:Ud.COMMA,value:",",offset:this.offset});continue}if(o===qi.LATIN_SMALL_LETTER_T){this.state=Xn.TRUE1;continue}if(o===qi.LATIN_SMALL_LETTER_F){this.state=Xn.FALSE1;continue}if(o===qi.LATIN_SMALL_LETTER_N){this.state=Xn.NULL1;continue}if(o===qi.QUOTATION_MARK){this.bufferedString.reset(),this.escapedCharsByteLength=0,this.state=Xn.STRING_DEFAULT;continue}if(o>=qi.DIGIT_ONE&&o<=qi.DIGIT_NINE){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_NON_ZERO;continue}if(o===qi.DIGIT_ZERO){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_ZERO;continue}if(o===qi.HYPHEN_MINUS){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_MINUS;continue}break;case Xn.STRING_DEFAULT:if(o===qi.QUOTATION_MARK){let a=this.bufferedString.toString();this.state=Xn.START,this.onToken({token:Ud.STRING,value:a,offset:this.offset}),this.offset+=this.escapedCharsByteLength+this.bufferedString.byteLength+1;continue}if(o===qi.REVERSE_SOLIDUS){this.state=Xn.STRING_AFTER_BACKSLASH;continue}if(o>=128){if(o>=194&&o<=223?this.bytes_in_sequence=2:o<=239?this.bytes_in_sequence=3:this.bytes_in_sequence=4,this.bytes_in_sequence<=n.length-i){this.bufferedString.appendBuf(n,i,i+this.bytes_in_sequence),i+=this.bytes_in_sequence-1;continue}this.bytes_remaining=i+this.bytes_in_sequence-n.length,this.char_split_buffer.set(n.subarray(i)),i=n.length-1,this.state=Xn.STRING_INCOMPLETE_CHAR;continue}if(o>=qi.SPACE){this.bufferedString.appendChar(o);continue}break;case Xn.STRING_INCOMPLETE_CHAR:this.char_split_buffer.set(n.subarray(i,i+this.bytes_remaining),this.bytes_in_sequence-this.bytes_remaining),this.bufferedString.appendBuf(this.char_split_buffer,0,this.bytes_in_sequence),i=this.bytes_remaining-1,this.state=Xn.STRING_DEFAULT;continue;case Xn.STRING_AFTER_BACKSLASH:let s=Dal[o];if(s){this.bufferedString.appendChar(s),this.escapedCharsByteLength+=1,this.state=Xn.STRING_DEFAULT;continue}if(o===qi.LATIN_SMALL_LETTER_U){this.unicode="",this.state=Xn.STRING_UNICODE_DIGIT_1;continue}break;case Xn.STRING_UNICODE_DIGIT_1:case Xn.STRING_UNICODE_DIGIT_2:case Xn.STRING_UNICODE_DIGIT_3:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE||o>=qi.LATIN_CAPITAL_LETTER_A&&o<=qi.LATIN_CAPITAL_LETTER_F||o>=qi.LATIN_SMALL_LETTER_A&&o<=qi.LATIN_SMALL_LETTER_F){this.unicode+=String.fromCharCode(o),this.state+=1;continue}break;case Xn.STRING_UNICODE_DIGIT_4:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE||o>=qi.LATIN_CAPITAL_LETTER_A&&o<=qi.LATIN_CAPITAL_LETTER_F||o>=qi.LATIN_SMALL_LETTER_A&&o<=qi.LATIN_SMALL_LETTER_F){let a=parseInt(this.unicode+String.fromCharCode(o),16),u;if(this.highSurrogate===void 0)if(a>=55296&&a<=56319){this.highSurrogate=a,this.state=Xn.STRING_DEFAULT;continue}else u=String.fromCharCode(a);else a>=56320&&a<=57343?u=String.fromCharCode(this.highSurrogate,a):u=String.fromCharCode(this.highSurrogate),this.highSurrogate=void 0;let p=this.encoder.encode(u);this.bufferedString.appendBuf(p),this.escapedCharsByteLength+=6-p.byteLength,this.state=Xn.STRING_DEFAULT;continue}break;case Xn.NUMBER_AFTER_INITIAL_MINUS:if(o===qi.DIGIT_ZERO){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_ZERO;continue}if(o>=qi.DIGIT_ONE&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_NON_ZERO;continue}break;case Xn.NUMBER_AFTER_INITIAL_ZERO:if(o===qi.FULL_STOP){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_FULL_STOP;continue}if(o===qi.LATIN_SMALL_LETTER_E||o===qi.LATIN_CAPITAL_LETTER_E){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E;continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.NUMBER_AFTER_INITIAL_NON_ZERO:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o);continue}if(o===qi.FULL_STOP){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_FULL_STOP;continue}if(o===qi.LATIN_SMALL_LETTER_E||o===qi.LATIN_CAPITAL_LETTER_E){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E;continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.NUMBER_AFTER_FULL_STOP:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_DECIMAL;continue}break;case Xn.NUMBER_AFTER_DECIMAL:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o);continue}if(o===qi.LATIN_SMALL_LETTER_E||o===qi.LATIN_CAPITAL_LETTER_E){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E;continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.NUMBER_AFTER_E:if(o===qi.PLUS_SIGN||o===qi.HYPHEN_MINUS){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E_AND_SIGN;continue}case Xn.NUMBER_AFTER_E_AND_SIGN:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E_AND_DIGIT;continue}break;case Xn.NUMBER_AFTER_E_AND_DIGIT:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o);continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.TRUE1:if(o===qi.LATIN_SMALL_LETTER_R){this.state=Xn.TRUE2;continue}break;case Xn.TRUE2:if(o===qi.LATIN_SMALL_LETTER_U){this.state=Xn.TRUE3;continue}break;case Xn.TRUE3:if(o===qi.LATIN_SMALL_LETTER_E){this.state=Xn.START,this.onToken({token:Ud.TRUE,value:!0,offset:this.offset}),this.offset+=3;continue}break;case Xn.FALSE1:if(o===qi.LATIN_SMALL_LETTER_A){this.state=Xn.FALSE2;continue}break;case Xn.FALSE2:if(o===qi.LATIN_SMALL_LETTER_L){this.state=Xn.FALSE3;continue}break;case Xn.FALSE3:if(o===qi.LATIN_SMALL_LETTER_S){this.state=Xn.FALSE4;continue}break;case Xn.FALSE4:if(o===qi.LATIN_SMALL_LETTER_E){this.state=Xn.START,this.onToken({token:Ud.FALSE,value:!1,offset:this.offset}),this.offset+=4;continue}break;case Xn.NULL1:if(o===qi.LATIN_SMALL_LETTER_U){this.state=Xn.NULL2;continue}break;case Xn.NULL2:if(o===qi.LATIN_SMALL_LETTER_L){this.state=Xn.NULL3;continue}break;case Xn.NULL3:if(o===qi.LATIN_SMALL_LETTER_L){this.state=Xn.START,this.onToken({token:Ud.NULL,value:null,offset:this.offset}),this.offset+=3;continue}break;case Xn.SEPARATOR:if(this.separatorIndex+=1,!this.separatorBytes||o!==this.separatorBytes[this.separatorIndex])break;this.separatorIndex===this.separatorBytes.length-1&&(this.state=Xn.START,this.onToken({token:Ud.SEPARATOR,value:this.separator,offset:this.offset+this.separatorIndex}),this.separatorIndex=0);continue;case Xn.BOM:if(o===this.bom[this.bomIndex]){if(this.bomIndex===this.bom.length-1){this.state=Xn.START,this.bom=void 0,this.bomIndex=0;continue}this.bomIndex+=1;continue}break;case Xn.ENDED:if(o===qi.SPACE||o===qi.NEWLINE||o===qi.CARRIAGE_RETURN||o===qi.TAB)continue}throw new het(`Unexpected "${String.fromCharCode(o)}" at position "${i}" in state ${Bal(this.state)}`)}if(this.emitPartialTokens)switch(this.state){case Xn.TRUE1:case Xn.TRUE2:case Xn.TRUE3:this.onToken({token:Ud.TRUE,value:!0,offset:this.offset,partial:!0});break;case Xn.FALSE1:case Xn.FALSE2:case Xn.FALSE3:case Xn.FALSE4:this.onToken({token:Ud.FALSE,value:!1,offset:this.offset,partial:!0});break;case Xn.NULL1:case Xn.NULL2:case Xn.NULL3:this.onToken({token:Ud.NULL,value:null,offset:this.offset,partial:!0});break;case Xn.STRING_DEFAULT:{let i=this.bufferedString.toString();this.onToken({token:Ud.STRING,value:i,offset:this.offset,partial:!0});break}case Xn.NUMBER_AFTER_INITIAL_ZERO:case Xn.NUMBER_AFTER_INITIAL_NON_ZERO:case Xn.NUMBER_AFTER_DECIMAL:case Xn.NUMBER_AFTER_E_AND_DIGIT:try{this.onToken({token:Ud.NUMBER,value:this.parseNumber(this.bufferedNumber.toString()),offset:this.offset,partial:!0})}catch{}}}catch(n){this.error(n)}}emitNumber(){this.onToken({token:Ud.NUMBER,value:this.parseNumber(this.bufferedNumber.toString()),offset:this.offset}),this.offset+=this.bufferedNumber.byteLength-1}parseNumber(t){return Number(t)}error(t){this.state!==Xn.ENDED&&(this.state=Xn.ERROR),this.onError(t)}end(){switch(this.state){case Xn.NUMBER_AFTER_INITIAL_ZERO:case Xn.NUMBER_AFTER_INITIAL_NON_ZERO:case Xn.NUMBER_AFTER_DECIMAL:case Xn.NUMBER_AFTER_E_AND_DIGIT:this.state=Xn.ENDED,this.emitNumber(),this.onEnd();break;case Xn.BOM_OR_START:case Xn.START:case Xn.ERROR:case Xn.SEPARATOR:this.state=Xn.ENDED,this.onEnd();break;default:this.error(new het(`Tokenizer ended in the middle of a token (state: ${Bal(this.state)}). Either not all the data was received or the data was invalid.`))}}onToken(t){throw new het(`Can't emit tokens before the "onToken" callback has been set up.`)}onError(t){throw t}onEnd(){}};var cO;(function(r){r[r.OBJECT=0]="OBJECT",r[r.ARRAY=1]="ARRAY"})(cO||(cO={}));var tA;(function(r){r[r.VALUE=0]="VALUE",r[r.KEY=1]="KEY",r[r.COLON=2]="COLON",r[r.COMMA=3]="COMMA",r[r.ENDED=4]="ENDED",r[r.ERROR=5]="ERROR",r[r.SEPARATOR=6]="SEPARATOR"})(tA||(tA={}));function Lal(r){return["VALUE","KEY","COLON","COMMA","ENDED","ERROR","SEPARATOR"][r]}var BD1={paths:void 0,keepStack:!0,separator:void 0,emitPartialValues:!1},W5e=class r extends Error{constructor(t){super(t),Object.setPrototypeOf(this,r.prototype)}},Aet=class{constructor(t){this.state=tA.VALUE,this.mode=void 0,this.key=void 0,this.value=void 0,this.stack=[],t=Object.assign(Object.assign({},BD1),t),t.paths&&(this.paths=t.paths.map(n=>{if(n===void 0||n==="$*")return;if(!n.startsWith("$"))throw new W5e(`Invalid selector "${n}". Should start with "$".`);let i=n.split(".").slice(1);if(i.includes(""))throw new W5e(`Invalid selector "${n}". ".." syntax not supported.`);return i})),this.keepStack=t.keepStack||!1,this.separator=t.separator,t.emitPartialValues||(this.emitPartial=()=>{})}shouldEmit(){return this.paths?this.paths.some(t=>{var n;if(t===void 0)return!0;if(t.length!==this.stack.length)return!1;for(let o=0;o<t.length-1;o++){let s=t[o],a=this.stack[o+1].key;if(s!=="*"&&s!==a?.toString())return!1}let i=t[t.length-1];return i==="*"?!0:i===((n=this.key)===null||n===void 0?void 0:n.toString())}):!0}push(){this.stack.push({key:this.key,value:this.value,mode:this.mode,emit:this.shouldEmit()})}pop(){let t=this.value,n;({key:this.key,value:this.value,mode:this.mode,emit:n}=this.stack.pop()),this.state=this.mode!==void 0?tA.COMMA:tA.VALUE,this.emit(t,n)}emit(t,n){!this.keepStack&&this.value&&this.stack.every(i=>!i.emit)&&delete this.value[this.key],n&&this.onValue({value:t,key:this.key,parent:this.value,stack:this.stack}),this.stack.length===0&&(this.separator?this.state=tA.SEPARATOR:this.separator===void 0&&this.end())}emitPartial(t){if(this.shouldEmit()){if(this.state===tA.KEY){this.onValue({value:void 0,key:t,parent:this.value,stack:this.stack,partial:!0});return}this.onValue({value:t,key:this.key,parent:this.value,stack:this.stack,partial:!0})}}get isEnded(){return this.state===tA.ENDED}write({token:t,value:n,partial:i}){try{if(i){this.emitPartial(n);return}if(this.state===tA.VALUE){if(t===Ud.STRING||t===Ud.NUMBER||t===Ud.TRUE||t===Ud.FALSE||t===Ud.NULL){this.mode===cO.OBJECT?(this.value[this.key]=n,this.state=tA.COMMA):this.mode===cO.ARRAY&&(this.value.push(n),this.state=tA.COMMA),this.emit(n,this.shouldEmit());return}if(t===Ud.LEFT_BRACE){if(this.push(),this.mode===cO.OBJECT)this.value=this.value[this.key]={};else if(this.mode===cO.ARRAY){let o={};this.value.push(o),this.value=o}else this.value={};this.mode=cO.OBJECT,this.state=tA.KEY,this.key=void 0,this.emitPartial();return}if(t===Ud.LEFT_BRACKET){if(this.push(),this.mode===cO.OBJECT)this.value=this.value[this.key]=[];else if(this.mode===cO.ARRAY){let o=[];this.value.push(o),this.value=o}else this.value=[];this.mode=cO.ARRAY,this.state=tA.VALUE,this.key=0,this.emitPartial();return}if(this.mode===cO.ARRAY&&t===Ud.RIGHT_BRACKET&&this.value.length===0){this.pop();return}}if(this.state===tA.KEY){if(t===Ud.STRING){this.key=n,this.state=tA.COLON,this.emitPartial();return}if(t===Ud.RIGHT_BRACE&&Object.keys(this.value).length===0){this.pop();return}}if(this.state===tA.COLON&&t===Ud.COLON){this.state=tA.VALUE;return}if(this.state===tA.COMMA){if(t===Ud.COMMA){if(this.mode===cO.ARRAY){this.state=tA.VALUE,this.key+=1;return}if(this.mode===cO.OBJECT){this.state=tA.KEY;return}}if(t===Ud.RIGHT_BRACE&&this.mode===cO.OBJECT||t===Ud.RIGHT_BRACKET&&this.mode===cO.ARRAY){this.pop();return}}if(this.state===tA.SEPARATOR&&t===Ud.SEPARATOR&&n===this.separator){this.state=tA.VALUE;return}if(t===Ud.SEPARATOR&&this.state!==tA.SEPARATOR&&Array.from(n).map(o=>o.charCodeAt(0)).every(o=>o===qi.SPACE||o===qi.NEWLINE||o===qi.CARRIAGE_RETURN||o===qi.TAB))return;throw new W5e(`Unexpected ${Ud[t]} (${JSON.stringify(n)}) in state ${Lal(this.state)}`)}catch(o){this.error(o)}}error(t){this.state!==tA.ENDED&&(this.state=tA.ERROR),this.onError(t)}end(){this.state!==tA.VALUE&&this.state!==tA.SEPARATOR||this.stack.length>0?this.error(new Error(`Parser ended in mid-parsing (state: ${Lal(this.state)}). Either not all the data was received or the data was invalid.`)):(this.state=tA.ENDED,this.onEnd())}onValue(t){throw new W5e(`Can't emit data before the "onValue" callback has been set up.`)}onError(t){throw t}onEnd(){}};var met=class{constructor(t={}){this.tokenizer=new get(t),this.tokenParser=new Aet(t),this.tokenizer.onToken=this.tokenParser.write.bind(this.tokenParser),this.tokenizer.onEnd=()=>{this.tokenParser.isEnded||this.tokenParser.end()},this.tokenParser.onError=this.tokenizer.error.bind(this.tokenizer),this.tokenParser.onEnd=()=>{this.tokenizer.isEnded||this.tokenizer.end()}}get isEnded(){return this.tokenizer.isEnded&&this.tokenParser.isEnded}write(t){this.tokenizer.write(t)}end(){this.tokenizer.end()}set onToken(t){this.tokenizer.onToken=n=>{t(n),this.tokenParser.write(n)}}set onValue(t){this.tokenParser.onValue=t}set onError(t){this.tokenizer.onError=t}set onEnd(t){this.tokenParser.onEnd=()=>{this.tokenizer.isEnded||this.tokenizer.end(),t.call(this.tokenParser)}}};var kal=Je("PLAN"),qal=async r=>new Promise((t,n)=>{let i=new met,o;i.onValue=({value:s,stack:a})=>{a.length===0&&(o=s)},i.onError=s=>{kal.error("streaming-json-parser","Error parsing JSON with streaming parser",s),n(s)},i.onEnd=()=>{t(o)};try{i.write(r),i.end()}catch(s){let a=s instanceof Error?s:new Error(String(s));kal.error("streaming-json-parser","Error writing to streaming parser",a),n(a)}});var _pe=Je("PLAN"),Ual=async(r,t,n,i,o,s,a,u)=>{let p="[sendCreatePlanRequest]",{measure:c,printSummary:l}=Bf(p,u),{branchName:d,clientWarnIssues:f,disablePresync:h,loadWarehouseComments:A,useRenderCache:E,userContext:v}=r;try{let T=(G,H)=>c(`store ${G} workspace data (parallelized)`,()=>Mal(G,t,i,o,n,H,u)),[w,N]=await Promise.all([T("current",a.currentWorkspaceData),T("desired",a.desiredWorkspaceData)]),{createPlan:k,getPlan:L}=D3(Db(),Xc.instance.getFirebaseRefreshToken);return await c("create plan request roundtrip",()=>k({parameters:s,runDetails:{branchName:d,currentWorkspaceDataFilePath:w,desiredWorkspaceDataFilePath:N,disablePresync:h,environmentID:o.toString(),issues:f,loadWarehouseComments:A,planID:n,skippedBeforeCollection:!!a.skippedBeforeCollection,useRenderCache:E},userCredentials:Oal(v)})),await c("poll for completed plan",async()=>{let G,H=3e5,V=0;do{let W=LD1(V);H-=W,await kG(W),V+=W,_pe.appContext(u,p,"Polling");let F=await L({params:{environmentID:o.toString(),planID:n}});if(rol(F)){let{planStorageFilePath:J}=F;_pe.appContext(u,p,`Received response for plan at ${J}; downloading`);let Y=await t.storage().downloadFile(J),z=typeof Y=="string",X;if(z?await c("decompress completed plan",async()=>{let Z=(0,Fal.inflate)(Y,{to:"string"});X=await qal(Z)}):X=Y,_pe.appContext(u,p,`Downloaded ${z?"":"un"}compressed plan:`,X),eol(X)){_pe.appContext(u,p,"Plan found in-flight; continuing to poll");continue}else if(Xil(X))G=X;else if(Zil(X)){let{error:Z}=X;throw _pe.appContext(u,p,"Plan found failed with error:",Z),Z}else throw _pe.errorContext(u,p,"Downloaded plan with unexpected shape",X),new nt("Plan was of unrecognized shape")}else throw H<=0?(_pe.errorContext(u,p,"Planning exceeded maximum wait time; last received response was:",F),new nt("Planning exceeded maximum wait time")):(_pe.errorContext(u,p,"Plan received unexpected response",F),new nt("Plan received unexpected response"))}while(!G);return G})}finally{l()}},LD1=r=>r===0?2e3:Math.min(Math.round(1e3+r*.1),6e4),zal=(r,t,n,i,o,s,a,u)=>{_pe.appContext(u,"[createDeployRequestObject]","Creating deploy request");let{id:c,phasedDependencies:l,phasedNodeEdits:d,targetEnvironment:f,version:h}=r;if(h!==2)throw new nt(`Deployment is not supported for plan version '${h}'`);let A={...t},{oid:E,commit:v}=n,{clearTargetEnvironment:T,forceDeployment:w,workspaceIDOverride:N}=a,k=N??f,L=0;Object.values(d).forEach(H=>{L+=Object.keys(H).length}),A.steps=HWo(A.steps,d,u);let q={deployCommit:E,deployCommitMessage:v.message,environmentID:`${k}`,fromWorkspaceData:A,phasedDependencies:l,phasedNodeEdits:d,planID:c,stepsInRun:L,version:h,...T&&{clearTargetEnvironment:T},...w&&{forcedDeployment:w}},G=null;return i&&(G=Mmr(i)),new vWe({runDetails:q,userCredentials:o,parameters:G,origin:s})};var Qal=async(r,t)=>{let n="[watchWorkspaceStatus]",i=[],o;try{let{status:s,updatedAt:a,updatedBy:u}=await r.fetch();i.push({status:s,updatedAt:a,updatedBy:u});let p=s;o=r.listen(c=>{(c.type==="added"||c.type==="modified")&&c.value.status!==p&&(i.push({status:c.value.status,updatedAt:c.value.updatedAt,updatedBy:c.value.updatedBy}),p=c.value.status)})}catch(s){Je("PLAN").errorContext(t,n,"Error setting up workspace status listener:",s)}return{unsubscribe:o,workspaceStatusChangelog:i}};var jk1=yt(vul()),ES=yt(DYo()),Gk1=yt(odl()),Hk1=yt(adl());var udl=Pb({id:SR(),name:ld(),steps:Dze(N7([SR(),ld()])),subgraphs:Dze(N7([SR(),ld()]))}),dL1=Pb({jobCounter:SR(),name:ld(),includeSelector:ld(),excludeSelector:ld()}),fL1=Mr("JobV2",dL1);var hL1=Pb({jobs:RA(udl),locations:Ukc,macros:RA(Nq),stepTypes:imc,subgraphs:RA(VPe.omit({id:!0}))}),cdl=Pb({jobs:RA(l$.omit({jobCounter:!0})),locations:k3o,macros:RA(Nq.omit({macroCounter:!0})),stepTypes:RA(Ace),subgraphs:RA(VPe),defaultStorageMapping:ld(),version:SR()}),lgC=N7([hL1,cdl]),gL1=Mr("DataYaml V1",cdl),ldl=Pb({username:ld(),gitAccountId:ld()}),pdl=Mr("GitCredentials",ldl);var ddl=Pb({steps:kAc,stepTypes:RA(la(Ace.omit({id:!0}))),jobs:RA(la(l$.omit({id:!0}))),folders:RA(la(EWe)),macros:RA(la(Nq)).optional(),userConnections:RA(Nze()).optional(),locations:RA(Nze()).optional(),defaultStorageMapping:ld().nullable(),version:SR().optional(),packageNamespaces:RA(Nze()).optional(),packages:RA(Nze()).optional(),installedPackages:RA(la(mce)).optional(),platformKind:jh.optional()}),AL1=ddl.extend({installedPackages:RA(la(xme)).optional()}),mL1=Mr("WorkspaceData",ddl),fdl=Mr("WorkspaceDataFromGit",AL1);var KYo=yt(Tze());var WMr=class{client;constructor(t,n){this.client=D3(t,n)}Exists=async(t,n)=>await this.client.SecretExists({params:{context:t.EncodeContext(n),secretType:t.typeName}});Set=async(t,n,i)=>await this.client.SetSecret({secretValue:i.sensitiveValue},{params:{context:t.EncodeContext(n),secretType:t.typeName}});Delete=async(t,n)=>await this.client.DeleteSecret(void 0,{params:{context:t.EncodeContext(n),secretType:t.typeName}});Upgrade=async(t,n)=>await this.Exists(t,n)?(await this.client.UpgradeSecret(void 0,{params:{context:t.EncodeContext(n),secretType:t.typeName}}),!0):!1};var zd=class r{constructor(t){this.value=t}value;static representation="[REDACTED]";get sensitiveValue(){return this.value}toString(){return r.representation}toJSON(){return r.representation}[Symbol.for("nodejs.util.inspect.custom")](){return r.representation}},vgC=new zgr("tag:yaml.org,2002:str",{kind:"scalar",instanceOf:zd,represent:r=>r.toString()});var hdl=B.string().brand(Symbol("SantizedString"));function Adl(r){return!!r&&typeof r=="object"&&"orgId"in r&&typeof r.orgId=="string"}function mdl(r){return Adl(r)&&"userId"in r&&typeof r.userId=="string"}function yL1(r){return mdl(r)&&"workspaceId"in r&&typeof r.workspaceId=="string"}function bL1(r){if(!mdl(r)){let t=fv(Nb(r,"orgId","userId"),n=>typeof n);throw new nt(`Secret got an invalid context type at runtime (got: ${t}, expected orgId & userId) - cannot create name`)}}function EL1(r){if(!yL1(r)){let t=fv(Nb(r,"orgId","userId","workspaceId"),n=>typeof n);throw new nt(`Secret got an invalid context type at runtime (got: ${t}, expected orgId & userId & workspaceId) - cannot create name`)}}function CL1(r){if(!Adl(r)){let t=fv(Nb(r,"orgId"),n=>typeof n);throw new nt(`Secret got an invalid context type at runtime (got: ${t}, expected orgId) - cannot create name`)}}function SL1(r){return bL1(r),r}function vL1(r){return CL1(r),r}function gdl(r){return EL1(r),r}var TL1=/[^a-zA-Z0-9/-]/gu,_L1=r=>{let t="-".codePointAt(0).toString(16);return r.replaceAll("--",`--${t}---${t}-`).replaceAll(TL1,n=>`--${n.codePointAt(0).toString(16)}-`)},KMr=r=>hdl.parse(r.map(_L1).join("_")),YMr=(r,t)=>{if(r.secretNameFormat==="orgId"){let n=vL1(t);return KMr([n.orgId,r.typeName])}else if(r.secretNameFormat==="orgIdAndUserId"){let n=SL1(t);return KMr([n.orgId,n.userId,r.typeName])}else if(r.secretNameFormat==="orgIdAndWorkspaceId"){let n=gdl(t);return KMr([n.orgId,n.workspaceId,r.typeName])}else if(r.secretNameFormat==="orgIdAndWorkspaceIdAndUserId"){let n=gdl(t);return KMr([n.orgId,n.workspaceId,n.userId,r.typeName])}else{let n=r.secretNameFormat;throw new nt(`Got an unknown secret name format "${n}" - cannot create name`)}},IL1=r=>{let t=/\-\-([0-9a-f]+)\-/g,n=r.replaceAll(t,i=>String.fromCodePoint(parseInt(i.replaceAll("-",""),16)));if(n!==r)return n},JMr=r=>{let t=IL1(r);if(!(t===void 0||t.match(/[^a-zA-Z0-9/_-]/g)))return t};var ket=class{constructor(t){this.secretStore=t}secretStore;Get=async(t,n)=>{let i=await this.secretStore.Get(YMr(t,n));if(i===null)return null;let o=new zd(t.dataValidator.assert(JSON.parse(i.sensitiveValue)));return t.GetEntry(n,o)};Set=async(t,n,i)=>{let o=YMr(t,n),s=null,a=await this.secretStore.Get(o);a!==null&&(s=new zd(t.dataValidator.assert(JSON.parse(a.sensitiveValue))));let u=t.SetEntry(n,s,i);await this.secretStore.Set(o,new zd(JSON.stringify(u.sensitiveValue)))};Delete=async(t,n)=>{let i=YMr(t,n),o=await this.secretStore.Get(i);if(o===null)return;let s=new zd(t.dataValidator.assert(JSON.parse(o.sensitiveValue))),a=t.DeleteEntry(n,s);a===null?await this.secretStore.Delete(i):await this.secretStore.Set(i,new zd(JSON.stringify(a.sensitiveValue)))};Upgrade=async(t,n,i,o,s)=>{let a=await this.Get(t,n);if(!a)return;await this.Get(i,o)||await this.Set(i,o,new zd(s(a.sensitiveValue))),await this.Delete(t,n)}};var $Mr=class{backend;constructor(t){this.backend=new ket(t)}Exists=async(t,n)=>await this.backend.Get(t,n)!==null;Set=async(t,n,i)=>await this.backend.Set(t,n,i);Delete=async(t,n)=>await this.backend.Delete(t,n);Upgrade=async(t,n)=>{if(!await this.Exists(t,n))return!1;let i=t.UpgradeTarget;if(!i)throw new Vi("Cannot upgrade this secret type",`Secret type ${t.typeName} as no upgrade target`);return await this.backend.Upgrade(t,n,i,n,o=>o),!0}};var XMr=class{injectError=null;data={};InjectErrorIfNeeded=()=>{if(this.injectError!==null)throw this.injectError};Get=async t=>{this.InjectErrorIfNeeded();let n=this.data[t];return n===void 0?null:new zd(n)};Set=async(t,n)=>{this.InjectErrorIfNeeded(),this.data[t]=n.sensitiveValue};Delete=async t=>{this.InjectErrorIfNeeded(),delete this.data[t]}};var S2e=yt(Mq());var kNt=S2e.Record({orgId:S2e.String}),qNt=S2e.Intersect(kNt,S2e.Record({userId:S2e.String})),ZMr=(r,t,n,i)=>({DecodeContext:o=>r.assert({[t]:o}),EncodeContext:o=>(r.assert(o),encodeURIComponent(o[t])),GetEntry:(o,s)=>{r.assert(o),n.assert(s.sensitiveValue);let a=s.sensitiveValue[o[t]];return a?new zd(i.assert(a)):null},SetEntry:(o,s,a)=>{r.assert(o);let u=s?ep(n.assert(s.sensitiveValue)):{};return u[o[t]]=i.assert(a.sensitiveValue),new zd(u)},DeleteEntry:(o,s)=>{r.assert(o),n.assert(s.sensitiveValue);let a=s?ep(n.assert(s.sensitiveValue)):{};return delete a[o[t]],typeof a=="object"&&(a===null||Object.keys(a).length===0)?null:a?new zd(a):null}}),ydl=(r,t,n)=>({DecodeContext:i=>r.assert({[t]:i}),EncodeContext:i=>(r.assert(i),encodeURIComponent(i[t])),GetEntry:(i,o)=>(r.assert(i),o),SetEntry:(i,o,s)=>(r.assert(i),n.assert(s.sensitiveValue),s),DeleteEntry:(i,o)=>(r.assert(i),n.assert(o.sensitiveValue),null)});var qet=yt(Mq());var bdl=qet.Record({gitAccountId:qet.String}),RL1=qet.Intersect(qNt,bdl),OL1=TM("SecretContextGitAccount",bdl),Edl=(r,t)=>ZMr(OL1,"gitAccountId",r,t);var Fet=yt(Mq());var Cdl=Fet.Record({workspaceId:Fet.String}),wL1=Fet.Intersect(qNt,Cdl),Sdl=TM("SecretContextWorkspace",Cdl),a2=(r,t)=>ZMr(Sdl,"workspaceId",r,t),v2e=r=>ydl(Sdl,"workspaceId",r);var ML1=et.object({clientID:et.string(),clientSecret:et.string()}),kYo=Mr("BigQueryOAuth",ML1),Uet={typeName:"BigQueryOAuth",dataValidator:kYo,entryValidator:kYo,secretNameFormat:"orgIdAndWorkspaceId",...v2e(kYo),UpgradeTarget:void 0};var _dl=et.object({access_token:et.string(),refresh_token:et.string()}),xL1=et.record(et.string(),_dl),vdl=Mr("BigQueryOAuthTokens",xL1),Tdl=Mr("BigQueryOAuthTokensEntry",_dl),zet={typeName:"BigQueryOAuthTokens",dataValidator:vdl,entryValidator:Tdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(vdl,Tdl),UpgradeTarget:void 0};var qYo=et.object({serviceAccountKey:et.string()}),PL1=et.record(qYo),Idl=Mr("BigQueryServiceAccount",PL1),Rdl=Mr("BigQueryServiceAccountEntry",qYo),Qet={typeName:"BigQueryServiceAccount",dataValidator:Idl,entryValidator:Rdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Idl,Rdl),UpgradeTarget:void 0};var NL1=et.object({clientID:et.string(),clientSecret:et.string()}),FYo=Mr("DatabricksOAuthM2M",NL1),e6e={typeName:"DatabricksOAuthM2M",dataValidator:FYo,entryValidator:FYo,secretNameFormat:"orgIdAndWorkspaceId",...v2e(FYo),UpgradeTarget:void 0};var DL1=et.object({clientId:et.string(),clientSecret:et.string()}),UYo=Mr("DatabricksOAuthU2M",DL1),jet={typeName:"DatabricksOAuthU2M",dataValidator:UYo,entryValidator:UYo,secretNameFormat:"orgIdAndWorkspaceId",...v2e(UYo),UpgradeTarget:void 0};var BL1=RA(ld(),ld()),Odl=Mr("GitTokens",BL1),wdl=Mr("string",ld()),exr={typeName:"GitTokens",dataValidator:Odl,entryValidator:wdl,secretNameFormat:"orgIdAndUserId",...Edl(Odl,wdl),UpgradeTarget:void 0};var zYo=et.object({token:et.string()}),LL1=et.record(zYo),Mdl=Mr("DatabricksCredentials",LL1),xdl=Mr("DatabricksCredentialsEntry",zYo),Get={typeName:"DatabricksCredentials",dataValidator:Mdl,entryValidator:xdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Mdl,xdl),UpgradeTarget:void 0};var Ddl=et.object({clientID:et.string(),clientSecret:et.string()}),kL1=et.record(Ddl),Pdl=Mr("FabricCredentials",kL1),Ndl=Mr("FabricCredentialsEntry",Ddl),QYo={typeName:"FabricCredentials",dataValidator:Pdl,entryValidator:Ndl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Pdl,Ndl),UpgradeTarget:void 0};var jYo=B.object({password:B.string()}),qL1=B.record(B.string(),jYo),txr=Mr("SnowflakeCredentials",qL1),rxr=Mr("SnowflakeCredentialsEntry",jYo),FNt={typeName:"SnowflakeCredentialsV2",dataValidator:txr,entryValidator:rxr,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(txr,rxr),UpgradeTarget:void 0},Het={typeName:"SnowflakeCredentials",dataValidator:txr,entryValidator:rxr,secretNameFormat:"orgIdAndUserId",...a2(txr,rxr),UpgradeTarget:FNt};var GYo=B.object({key:B.string(),passphrase:B.string().nullable().optional(),savePassphrase:B.boolean().optional()}).superRefine((r,t)=>{if((r.passphrase===void 0||r.passphrase===null)&&r.savePassphrase!==void 0)return t.addIssue({code:B.ZodIssueCode.custom,message:"Can't have passphrase unset and savePassphrase set at the same time",fatal:!0,path:["passphrase"]}),B.NEVER;r.savePassphrase||(delete r.passphrase,delete r.savePassphrase)}),FL1=B.record(B.string(),GYo),nxr=Mr("SnowflakeKeyPairSecret",FL1),ixr=Mr("SnowflakeKeyPairEntry",GYo),Bdl="SnowflakeKeyPair",UL1=Bdl+"V2",UNt={typeName:UL1,dataValidator:nxr,entryValidator:ixr,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(nxr,ixr),UpgradeTarget:void 0},Vet={typeName:Bdl,dataValidator:nxr,entryValidator:ixr,secretNameFormat:"orgIdAndUserId",...a2(nxr,ixr),UpgradeTarget:UNt};var kdl=B.object({clientId:B.string(),clientSecret:B.string()}),zL1=B.record(B.string(),kdl),Ldl=Mr("SnowflakeOAuthForWorkspaces",zL1),zNt=Mr("SnowflakeOAuth",kdl),QNt={typeName:"SnowflakeOAuthV2",dataValidator:zNt,entryValidator:zNt,secretNameFormat:"orgIdAndWorkspaceId",...v2e(zNt),UpgradeTarget:void 0},Wet={typeName:"SnowflakeOAuth",dataValidator:Ldl,entryValidator:zNt,secretNameFormat:"orgId",...a2(Ldl,zNt),UpgradeTarget:QNt};var HYo=et.object({access_token:et.string(),refresh_token:et.string()}),QL1=et.record(et.string(),HYo),oxr=Mr("SnowflakeTokens",QL1),sxr=Mr("SnowflakeTokensEntry",HYo),t6e={typeName:"SnowflakeTokensV2",dataValidator:oxr,entryValidator:sxr,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(oxr,sxr),UpgradeTarget:void 0},xpe={typeName:"SnowflakeTokens",dataValidator:oxr,entryValidator:sxr,secretNameFormat:"orgIdAndUserId",...a2(oxr,sxr),UpgradeTarget:t6e};var axr=TM("SecretContextOrg",kNt),qdl=r=>({DecodeContext:t=>({}),EncodeContext:t=>(axr.assert(t),"_"),GetEntry:(t,n)=>(axr.assert(t),n),SetEntry:(t,n,i)=>(axr.assert(t),r.assert(i.sensitiveValue),i),DeleteEntry:(t,n)=>(axr.assert(t),r.assert(n.sensitiveValue),null)});var jL1=et.object({clientSecret:et.string()}),VYo=Mr("SSOClientSecret",jL1),GL1={typeName:"SSOClientSecret",dataValidator:VYo,entryValidator:VYo,secretNameFormat:"orgId",...qdl(VYo),UpgradeTarget:void 0};var zdl=et.object({access_token:et.string(),refresh_token:et.string()}),HL1=et.record(et.string(),zdl),Fdl=Mr("DatabricksOAuthU2MTokens",HL1),Udl=Mr("DatabricksOAuthU2MTokensEntry",zdl),T2e={typeName:"DatabricksOAuthU2MTokens",dataValidator:Fdl,entryValidator:Udl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Fdl,Udl),UpgradeTarget:void 0};var VL1={[exr.typeName]:exr,[Het.typeName]:Het,[FNt.typeName]:FNt,[Vet.typeName]:Vet,[UNt.typeName]:UNt,[Wet.typeName]:Wet,[QNt.typeName]:QNt,[xpe.typeName]:xpe,[t6e.typeName]:t6e,[Get.typeName]:Get,[jet.typeName]:jet,[T2e.typeName]:T2e,[e6e.typeName]:e6e,[QYo.typeName]:QYo,[Qet.typeName]:Qet,[Uet.typeName]:Uet,[zet.typeName]:zet};var Gdl=et.object({clientID:et.string(),clientSecret:et.string()}),WL1=et.record(Gdl),Qdl=Mr("FabricCredentials",WL1),jdl=Mr("FabricCredentialsEntry",Gdl),WYo={typeName:"FabricCredentials",dataValidator:Qdl,entryValidator:jdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Qdl,jdl),UpgradeTarget:void 0};var YL1=Je("SECRETS"),YYo=(0,KYo.default)(async()=>(YL1.app("Selected Memory secret store."),new XMr)),_mC=(0,KYo.default)(async()=>Hg().isTest?new $Mr(await YYo()):new WMr(Db(),Xc.resolveAuthToken));var JL1="Environment",_2e=Pb({name:ld(),id:ld(),type:Fj(JL1),fileVersion:SR().int(),mappingDefinitions:zkc}).strict(),Hdl=Mr("Environment File",_2e),$L1=RA(_2e),Vdl=Mr("Environment File Dictionary",$L1);var XL1="Job",WH=l$.pick({excludeSelector:!0,includeSelector:!0,name:!0}).extend({id:SWe,type:et.literal(XL1),fileVersion:et.literal(1)}).strict(),Wdl=Mr("GitJob",WH),tyC=et.record(WH),Kdl=Mr("Job Files with Passthrough",et.record(la(WH)));var ZL1="Macro",TZ=Nq.pick({macroString:!0}).extend({id:et.string(),name:et.string(),packageInfo:gce.optional(),type:et.literal(ZL1),fileVersion:et.literal(1)}),Ydl=Mr("GitMacro",TZ),ek1=et.record(la(TZ)),Jdl=Mr("MacroDictionary",ek1);var tk1="Node",rk1=r=>et.object({name:et.string(),id:et.string(),fileVersion:et.number().int(),type:et.literal(tk1),operation:r?I3o:_3o}).strict(),_Z=rk1(!1),JYo=Mr("Node File",_Z),nk1=et.record(_Z),$dl=Mr("Git Nodes",la(nk1));var ik1="NodeType",Xdl=et.union([la(AWe.omit({templates:!0})),la(N3o.omit({templates:!0}))]),uxr=la(mWe.pick({isDisabled:!0,name:!0,id:!0}).extend({metadata:Xdl,fileVersion:et.union([et.literal(1),et.literal(2)]).default(1),type:et.literal(ik1)})),$Yo=Mr("NodeType Unparsed Metadata",Xdl),XYo=Mr("NodeType Definition file",uxr),ZYo=et.object({nodeType:uxr,create:et.string().optional(),run:et.string().optional()}).strict(),ok1=et.record(ZYo),Zdl=Mr("NodeTypesDictionary",ok1);var cxr=1,lxr="Subgraph",IZ=EWe.omit({folderCounter:!0,version:!0}).extend({type:B.literal(lxr),fileVersion:B.literal(cxr),id:B.string()}).strict(),eJo=Mr("Subgraph (YAML)",la(IZ)),e0l=Mr("Subgraph (YAML)",IZ);var ak1=Je("GIT");var uk1=r=>{let t={},n=$dl.assert(r);return Object.values(n).forEach(i=>{let{operation:o,id:s}=i;t[s]={operation:o}}),t},ck1=r=>{let t={};return Object.entries(r).forEach(n=>{let[i,o]=n,s=eJo.assert(o,{errorMessage:`Subgraph ${i} is invalid`}),{type:a,id:u,fileVersion:p,...c}=s,l=sTt.assert({id:u,...c});t[u]=l}),t},lk1=r=>{let t={},n=Kdl.assert(r);return Object.values(n).forEach(i=>{let{id:o,fileVersion:s,type:a,...u}=i;t[o]={...u,jobCounter:Number(o),id:Number(o),version:c$}}),t},pk1=r=>{let t={},n=Jdl.assert(r);return Object.values(n).forEach(i=>{let{id:o,fileVersion:s,type:a,...u}=i;t[o]={...u,id:o,version:gh}}),t},tJo=r=>{let{nodeType:t,create:n,run:i}=r,{id:o,type:s,fileVersion:a,...u}=t,{defaultStorageLocation:p}=u.metadata,c=p??null,l=a??gWe;return D3o.assert({...u,version:l,metadata:{...u.metadata,defaultStorageLocation:c,templates:{create:{templateString:n||""},run:{templateString:i||""}}},id:o})},dk1=(r,t)=>{let n={},i=Zdl.assert(t);return Object.values(i).forEach(o=>{n[o.nodeType.id]=tJo(o)}),n.Source=lNe(r).Source,n},fk1=(r,t)=>{let n={};for(let i of t)n[i]={mappingDefinitions:{}};if(r){let i=Vdl.assert(r);Object.values(i).forEach(o=>{let{mappingDefinitions:s,id:a}=o;Object.entries(s).forEach(([u,p])=>{let c=n[u];c||(c={mappingDefinitions:{}},n[u]=c),c.mappingDefinitions[a]=p})})}return n},hk1=r=>r?Object.fromEntries(Object.entries(r).map(([t,n])=>[t,{releaseID:n.releaseID,packageID:n.packageID,config:n.config}])):{},rJo=(r,t,n)=>{try{let{nodes:i,subgraphs:o,jobs:s,macros:a,nodeTypes:u,environments:p,packages:c,locationManifest:l,dataYML:d}=r;return{defaultStorageMapping:l.defaultStorageMapping??d.defaultStorageMapping,steps:uk1(i),stepTypes:dk1(t,u),folders:ck1(o),jobs:lk1(s),locations:fk1(p,l.locations),macros:pk1(a),installedPackages:hk1(c),platformKind:t}}catch(i){throw ak1.errorContext(n,"Failed to validate and convert the Repo to AllWorkspaceData.",i),i}},t0l=()=>({nodes:{},nodeTypes:{},macros:{},jobs:{},subgraphs:{},environments:{},dataYML:{fileVersion:3,defaultStorageMapping:null},locationManifest:{defaultStorageMapping:null,locations:[],fileVersion:1}});var JH=yt(DYo()),UF=yt(require("path"));var r6e=class extends nt{code;result;constructor(t,n,i=400){super(t,"Parsing error occurred"),this.result=n,this.code=i}statusCode(){return this.code}get parsingResult(){return this.result}get failureDetails(){return`${this.message}: ${this.result.length} error(s) in these file(s) ${this.result.map(t=>t.fileName).join(", ")}`}};var r0l=(r,t)=>typeof r=="object"&&r!==null&&r.code===t;function pxr(r,t,n){let i=[],o=new Map;for(let s of Object.values(n))s.nodeType&&o.set(s.nodeType.id,s.nodeType.fileVersion);for(let[s,a]of r){let u=t[s],p=u?.operation.sqlType,c=o.get(p??"");if(!u||!p||!c)continue;let l=c===2;l&&a!==".sql"?i.push({path:`nodes.${s}.outOfBandEdit`,message:`Node "${u.name}" (${u.operation.locationName}) uses a .yml file but its node type "${p}" requires a .sql file (v2 node type)`}):!l&&a!==".yml"&&i.push({path:`nodes.${s}.outOfBandEdit`,message:`Node "${u.name}" (${u.operation.locationName}) uses a .sql file but its node type "${p}" requires a .yml file (v1 node type)`})}return i}function n0l(r){let t=[];for(let[n,i]of r)if(i.size>1){let o=[...i].join(", ");t.push({path:`nodes.${n}.outOfBandEdit`,message:`Duplicate node ID "${n}": Node IDs must be unique within a workspace. Found in: ${o}`})}return t}function i0l(r){let t=[];for(let[n,i]of Object.entries(r)){let o=i.operation?.metadata?.columns;if(!Array.isArray(o))continue;let s=new Map,a=new Set;for(let c of o){let l=c?.columnReference?.columnCounter;if(l.length===0){t.push({path:`nodes.${n}.outOfBandEdit`,message:`Column ID is empty for column "${c.name}" in node "${i.name}"`});continue}let d=s.get(l);d?(d.push(c.name),a.add(l)):s.set(l,[c.name])}if(a.size===0)continue;let u=typeof i.operation?.locationName=="string"?i.operation.locationName:"",p=u?` (${u})`:"";for(let c of a){let l=s.get(c);t.push({path:`nodes.${n}.outOfBandEdit`,message:`Duplicate column ID "${c}" in node "${i.name}"${p}: Column IDs must be unique within a node. Found columns (sharing column ID "${c}"): ${l?.join(", ")??"<ERROR reading column names>"}`})}}return t}var KH=(d=>(d.node="nodes",d.subgraph="subgraphs",d.job="jobs",d.environment="environments",d.dataYML="dataYML",d.packagesV1="packagesV1",d.packages="packages",d.macro="macros",d.nodeType="nodeTypes",d.jinja="jinja",d.locations="locations",d))(KH||{}),n6e="packagesV1.yml",lO="data.yml",I2e="locations.yml";var jNt="create.sql.j2",GNt="run.sql.j2";var YH=yt(require("path"));var ex=(r,t,n,i=[".yml"])=>{let o=YH.default.normalize(t),s=r?YH.default.join(r,n):n;return o.startsWith(s)&&i.some(a=>t.endsWith(a))},Ket=(r,t="")=>[ex(t,r,"nodeTypes",[".yml",".sql.j2"]),ex(t,r,"nodes",[".yml",".sql"]),ex(t,r,"environments"),ex(t,r,"subgraphs"),ex(t,r,"jobs"),ex(t,r,"macros"),ex(t,r,"packages"),YH.default.normalize(r)===YH.default.join(t,lO),YH.default.normalize(r)===YH.default.join(t,n6e),YH.default.normalize(r)===YH.default.join(t,I2e)].some(n=>!!n),nJo=r=>!!r.promises.writeFiles&&!!r.promises.readFiles,HNt=(r,t)=>T9o(r,"",t.operation),dxr=(r,t,n)=>YH.default.normalize(r)===YH.default.join(t,n),o0l=r=>{!r.id&&r.folderCounter!=null&&(r.id=String(r.folderCounter))};var s0l=(r,t,n)=>{Bm("RUNNER",!!r[t],`Step ${t} doesn't exist`);let i=r[t].operation.name,o=gk1(i,!1);return n&&(o.runExecutionSequenceID=n),o},gk1=(r,t)=>({dataResult:null,runState:"waiting",stepRunState:"None",queryResultSequence:{name:r,queryResults:[],isRunning:t}});var Ak1=Je("VERSION_CONTROL_ACTIONS"),mk1=(r,t)=>Object.fromEntries(Object.entries(i6e(r)).map(([n,i])=>(i[t]=i.id,delete i.id,[n,i]))),o6e=(r,t,n,i,o)=>{let s=[],a={},u=[];r.forEach(E=>{let{filePath:v,fileData:T}=E;try{let N=Sp(`Node ${v}`,T).steps;for(let k in N){let L=g1(k,N,"unserializedNodes"),{stepCounter:q}=L;a[q]&&u.push(q),a[q]=L}}catch(w){let k=v.split("/").pop();s.push({fileName:k,type:"nodes",parsingError:w.errorString})}}),u.length&&hh("GIT",!1,n,`Encountered node files using the same stepCounter on commit: ${i||"Current Live Files"}`,"nodeIDs: ",u);let p={environments:{},locations:{},subgraphs:{},jobs:{},macros:{},stepTypes:{},defaultStorageMapping:"",projects:{},packages:{},installedPackages:{},platformKind:o};if(t)try{p={...p,...Sp(lO,t)}}catch(E){Ak1.error("(getReduxStateFromYaml) failed to parse data.yml",E),s.push({fileName:"data.yml",type:"otherData",parsingError:E.errorString})}if(s.length)throw new r6e("Error parsing repo files",s);let c=mk1(p.jobs,"jobCounter"),l=kEr(i6e(p.subgraphs)),d=Object.fromEntries(Object.keys(p.projects).map(E=>[E,p.projects[E]])),f=Object.fromEntries(Object.keys(a).map(E=>[E,s0l(a,E)])),{mappings:h,defaultStorageMapping:A}=bk1(p);return{jobs:c,steps:a,folders:l,mappings:h,runResults:f,packageNamespaces:d,defaultStorageMapping:A,locations:h,macros:i6e(p.macros),stepTypes:i6e(p.stepTypes),packages:i6e(p.packages),installedPackages:p.installedPackages,platformKind:o}},lbC=C3o.extend({mappings:RA(ld(),B3o),deployedWorkspaces:RA(Pb({})),version:Fj(0)}).strict(),yk1=(r,t)=>{let n={};return Object.keys(r).forEach(i=>{let o=r[i].locationName;n[o]||(n[o]=Vkc()),Object.values(t).forEach(s=>{let a=s.mappings?.[i]??null;a?n[o].mappingDefinitions[s.id]={database:a.database,schema:a.schema}:n[o].mappingDefinitions[s.id]=W6o()})}),n},bk1=r=>{let t=r.environments||{},n=i6e(t),i=r.locations||{},o={},s=r.defaultStorageMapping??null;if(Object.keys(i).length)if(Gkc(i)){let a=i6e(i);o=yk1(a,n),s=Hkc(i)}else o=i;return{mappings:o,defaultStorageMapping:s}},i6e=r=>{let t={};for(let n in r){let i=r[n].id;if(!i){console.warn(`Missing id for entity ${n}!`);continue}t[i]=r[n]}return t};var VNt=et.object({defaultStorageMapping:et.string().nullable(),locations:et.array(et.string()),fileVersion:et.literal(1)}),a0l=Mr("LocationsFile",la(VNt));var Ck1=B.object({name:B.string()}).strict(),u0l=Ri.merge(Ck1).strict();var Sk1=B.union([B.object({seconds:B.number(),nanoseconds:B.number()}),B.object({_seconds:B.number(),_nanoseconds:B.number()})]),c0l=B.union([Sk1,B.date()]);var l0l=(o=>(o.adding="adding",o.added="added",o.removing="removing",o.error="error",o))(l0l||{}),vk1=B.object({filePath:B.string()}),Tk1=B.object({commit:B.string()}),p0l=Ri.extend({version:B.string(),versionInfo:B.union([Tk1,vk1]),status:B.nativeEnum(l0l),addedBy:B.string(),createdAt:c0l.nullable(),manifest:B.record(B.record(B.object({id:B.string(),name:B.string()})))}).strict();var d0l=B.object({packages:B.union([B.record(p0l),B.object({})]),packageNamespaces:B.union([B.record(u0l),B.object({})]),fileVersion:B.number()}).strict();var fxr=et.object({defaultStorageMapping:et.string().nullable().default(null),fileVersion:et.number().int(),platformKind:jh.optional()}),f0l=Mr("DataYmlV2",la(fxr)),_k1=et.object({dataYML:la(fxr),locationManifest:la(VNt).default({defaultStorageMapping:null,locations:[],fileVersion:1}),nodes:et.record(la(_Z)),nodeTypes:et.record(la(ZYo)),environments:et.record(la(_2e)),subgraphs:et.record(la(IZ)),jobs:et.record(la(WH)),macros:et.record(la(TZ)),packagesV1:la(d0l).optional(),packages:et.record(la(tbe)).optional()}),Ik1=(r,t)=>(r.issues=r.issues.map(n=>{if(n.path[0]==="nodes"){let o=n.path[1]||"",s=t.nodes[o];if(s?.name)return{...n,message:`Problem with node "${s.name}": ${n.message}`}}return n}),r),h0l=Mr("CoalesceRepo",_k1,[Ik1]);var iJo=yt(require("path"));var Rk1=Je("GIT"),hxr=async(r,t,n)=>{let{fileData:i,filePath:o}=r,{refs:s,topLevelAnnotations:a,errorMessage:u}=await t.extractRefs(i,n,o,{skipCache:!0});u&&Rk1.warn(`Error extracting refs from ${o}: ${u}`);let p=NWo(a);if(p.errorMessage)throw new Error(`Failed to extract metadata from ${o}: ${p.errorMessage}`);if(!p.id)throw new Error(`Missing required annotation @id in ${o}`);let l=iJo.default.basename(o,".sql").split("-"),d=l[0]??"",f=l.slice(1).join("-"),h={name:f,locationName:d,type:"sql",sqlType:p.nodeType,description:p.description,database:"",schema:"",version:1,materializationType:p.materializationType,isMultisource:!1,deployEnabled:!0,config:{},metadata:{sourceMapping:[{name:f,join:{joinCondition:""},dependencies:s,noLinkRefs:[],aliases:{},customSQL:{customSQL:i}}],columns:[],appliedNodeTests:[],enabledColumnTestIDs:[]}};return{id:p.id,name:f,type:"Node",fileVersion:1,operation:h}},g0l=async(r,t,n,i,o,s)=>{let{filePath:a}=r,{unknownFileList:u,nodeSourceExtensions:p,nodeSourceFiles:c}=s;if(!ex(t,a,"nodes",[".sql"])){u.push(a);return}let l=await hxr(r,i,o),d=iJo.default.basename(a),f=c.get(l.id)??new Set;f.add(d),c.set(l.id,f),!n.nodes[l.id]&&(n.nodes[l.id]=l,p.set(l.id,".sql"))};var pO=Je("GIT");var oJo=(r,t="")=>({filePath:r,fileData:t,type:"File"}),Yet=async(r,t,n,i=!0)=>{let o="",s=0,a;if(t)try{await JH.log({...r,ref:t})}catch(u){throw pO.error("Error getting data.yaml info from commit",u),u}try{o=t?await A0l(r,t,lO,{}):(await Jet(r,r.dir,lO)).fileData;let u=Sp(lO,o);s=Number(u?.version??u?.fileVersion)||0;let p=u?.platformKind;p?a=p:a=i?n:"snowflake"}catch(u){return pO.error("Error getting data.yaml info from commit",u),0}try{uNt.checkPlatformMismatch(n,a)}catch(u){throw pO.error("Error platform mismatch:",u),u}return s};var A0l=(r,t,n,i)=>{let o={...r,oid:t,filepath:n,cache:i??void 0};return JH.readBlob(o).then(({blob:s})=>Buffer.from(s).toString("utf-8")).catch(s=>{throw new Error(`Error reading file ${n} from commit ${t}: ${s.toString()}`)})};var WNt=async(r,t,n)=>{let i="[ReadAllFilesFromCommit]";try{let s=(await JH.readTree({...r,oid:t})).oid;return JH.walk({...r,trees:[JH.TREE({ref:s})],map:async(a,u)=>{let p=oJo(a);if(u[0])try{let c=await u[0].content();c&&typeof c=="object"?p.fileData=Buffer.from(c).toString("utf8"):p.type="Directory"}catch(c){if(r0l(c,"NotFoundError"))return pO.infoContext(n,`${i}: skipping file ${a}: blob missing due to partial clone filtering (blob:limit)`),null;throw c}return p}})}catch(o){throw pO.errorContext(n,`${i} commit ${t}. An error occurred: `,o),o}};var Jet=async(r,t,n)=>{try{return await m0l(r,t,n)}catch{return{...oJo(n),exists:!1}}},m0l=async(r,t,n)=>{let i=UF.default.join(t,n),o=await r.fs.promises.readFile(i),s=new TextDecoder("utf-8").decode(o);return{...oJo(n,s),exists:!0}},Ok1=async(r,t)=>{if(nJo(r.fs))return(await r.fs.promises.readFiles(t,{encoding:"utf8"})).map((i,o)=>({fileData:i,filePath:t[o],exists:!0,type:"File"}));{let n=t.map(i=>async()=>await Jet(r,"",i));return await dce(n,8)}},y0l=async(r,t)=>{let n=(await r.fs.promises.readdir(r.dir)).map(o=>UF.default.join(r.dir,o)),i=[];for(;n.length>0;){let o=n.pop();if(o&&!o.includes(".git")){let s=await r.fs.promises.stat(o);if(s.isFile()&&(!t||t(o)))i.push({filePath:o,size:s.size});else{let a=(await r.fs.promises.readdir(o)).map(u=>UF.default.join(o,u));n.push(...a)}}}return i},Axr=async r=>{let t=await y0l(r);return await Ok1(r,t.map(n=>n.filePath))},b0l=r=>{let n=UF.default.normalize(r).split(`nodeTypes${UF.default.sep}`),[i,o]=n[1].split(UF.default.sep);return{nodeTypeID:i,fileName:o}},wk1=(r,t,n,i,o,s,a)=>{if(ex(n,r.filePath,s)){let u=t.id;i[a][u]=t}else o.push(r.filePath)},Mk1=r=>{r&&r.operation&&(r.operation.description??="")},xk1=(r,t,n,i,o)=>{let{unknownFileList:s,nodeSourceExtensions:a,nodeSourceFiles:u}=o,{fileData:p,filePath:c}=r,l=Sp(c,p),{type:d}=l,f=(h,A)=>wk1(r,l,t,n,s,h,A);switch(d){case"Node":if(ex(t,c,"nodes")){let A=l.id,E=UF.default.basename(c),v=u.get(A)??new Set;v.add(E),u.set(A,v),Mk1(l),n.nodes[A]=l,a.set(A,".yml")}else s.push(c);break;case"NodeType":let{nodeTypeID:h}=b0l(c);i[h]||(i[h]={}),i[h].nodeType=l;break;case"Environment":f("environments","environments");break;case"Job":f("jobs","jobs");break;case"Macro":f("macros","macros");break;case"Subgraph":o0l(l),f("subgraphs","subgraphs");break;case"Package":if(ex(t,c,"packages")){let{name:A,id:E}=l;pO.info(`HandleCoalesceYamlFile: using package alias "${A}" for package with id "${E}"`),n.packages||(n.packages={}),n.packages[A]=l}else s.push(c);break;default:dxr(c,t,lO)?n.dataYML=l:dxr(c,t,n6e)?n.packagesV1=l:dxr(c,t,I2e)?n.locationManifest=l:s.push(c);break}},Pk1=(r,t,n)=>{let{fileData:i,filePath:o}=r,{nodeTypeID:s,fileName:a}=b0l(o);switch(t[s]||(t[s]={}),a){case jNt:t[s].create=i;break;case GNt:t[s].run=i;break;default:n.push(o)}},Nk1=async(r,t,n,i,o,s)=>{let a=t0l(),u=[],p={},c={unknownFileList:[],nodeSourceExtensions:new Map,nodeSourceFiles:new Map};for(let l of r)try{let{filePath:d}=l;d.endsWith(".yml")?xk1(l,n,a,p,c):d.endsWith(".sql.j2")?Pk1(l,p,c.unknownFileList):d.endsWith(".sql")?await g0l(l,n,a,i,o,c):pO.debugContext(t,`Ignoring file ${d} as it is using an extension unused by Coalesce`)}catch(d){if(pO.errorContext(t,`Error parsing file ${n}/${l?.filePath}: `,d,"File data: ",l?.fileData),Ket(l.filePath,n)){let f=yg(d),A=UF.default.normalize(l.filePath).split(UF.default.sep),v=A.length<2?"otherData":A[0]??"otherData",T=v==="nodeTypes"?`${A[A.length-2]}${UF.default.sep}${A[A.length-1]}`:A.pop();if(u.push({fileName:T,type:v,parsingError:f.message}),s){let w=UF.default.extname(l.filePath),N=w===".sql"||w===".yml"?w:".unknown";s({filePath:l.filePath,fileName:T,type:v,extension:N,message:f.message})}}}if(u.length&&!s)throw new r6e("Error parsing repo files",u);return a.nodeTypes=p,{repo:a,auditContext:c,parsingErrors:u}},E0l=async(r,t,n,i,o="",s,a,u,p={})=>{let c=t?"":o,{repo:l,auditContext:d,parsingErrors:f}=await Nk1(r,n,c,s,a,u);pO.infoContext(n,"GetRepoFromFileReads Patching nodes collection");for(let[h,A]of Object.entries(l.nodes))HNt(h,{operation:A.operation});if(p.onAuditContext?.(d),i){d.unknownFileList.length&&pO.infoContext(n,"Found some files in unexpected places while reading repository files",d.unknownFileList);let h=[...pxr(d.nodeSourceExtensions,l.nodes,l.nodeTypes),...n0l(d.nodeSourceFiles),...i0l(l.nodes)];if(h.length&&!p.suppressOutOfBandThrow)throw new FP(`Out-of-band editing issues detected for commit: ${t||"Current Live Files"}`,new r$(l,h));return f.length?l:h0l.assert(l)}return l},Dk1=async(r,t,n)=>{let i=[];try{i=await r.fs.promises.readdir(`${r.dir}/nodes`)}catch(p){pO.errorContext(n,"Error during GetAllWorkspaceDataFromFileSystemDirectory: ",p)}let o=i.map(p=>Ah(`file: ${p}`,n,"GIT",async()=>await Jet(r,`${r.dir}/nodes`,p))),s=await Promise.all(o),{steps:a}=o6e(s,"",n,null,t),u;try{let{fileData:p}=await Ah("PromiseifiedReadFile data.yml",n,"GIT",()=>m0l(r,r.dir,lO)),{folders:c,jobs:l,macros:d,stepTypes:f,mappings:h,defaultStorageMapping:A,packageNamespaces:E,packages:v,installedPackages:T}=o6e([],p,n,null,t);u={steps:sJo(a),jobs:l,folders:c,stepTypes:f,locations:h,packages:v,packageNamespaces:E,defaultStorageMapping:A,macros:d,installedPackages:T||{},platformKind:t}}catch(p){if(pO.errorContext(n,"Error during GetAllWorkspaceDataFromFileSystemDirectory: ",p),p.message.startsWith("Failed to parse"))throw p;u={...d$e(t),steps:a}}pO.infoContext(n,"GetAllWorkspaceDataFromFileSystemDirectoryOld Patching nodes collection");for(let[p,c]of Object.entries(u.steps))HNt(p,{operation:c.operation});return u},C0l=async(r,t,n)=>{try{pO.infoContext(n,"Hydrating SQL dependencies for .sql files");let i=await Q4t(r.steps,r.stepTypes,r.platformKind,t,void 0);return{...r,steps:i}}catch(i){return pO.warnContext(n,"Error hydrating SQL dependencies:",i),r}},Bk1=(r,t,n,i,o,s,a={})=>Ah("GetAllWorkspaceDataFromFileSystemDirectory",n,"GIT",async()=>{if(await Yet(r,null,t)<3)return await Dk1(r,t,n);{let p=await Axr(r),c=await E0l(p,null,n,i,r.dir,o,t,s,a),l=rJo(c,t,n);return await C0l(l,o,n)}}),Lk1=async(r,t,n,i)=>{let o=r.find(u=>u.filePath===lO),s=r.filter(u=>u.filePath.includes("nodes/")),a;if(o){let u=o6e(s,o?.fileData,n,i,t);a={...u,locations:u.mappings,platformKind:t}}else{let{steps:u}=o6e(s,"",n,i,t);a={...d$e(t),steps:sJo(u)}}pO.infoContext(n,"GetAllWorkspaceDataFromGitCommitInternalOld Patching nodes collection");for(let[u,p]of Object.entries(a.steps))HNt(u,{operation:p.operation});return a},kk1=async(r,t,n,i,o,s,a,u={})=>{let p=await Yet(r,t,n),c=await Ah(`GetAllWorkspaceDataFromGitCommitInternal::ReadAllFilesFromCommit ${t}`,i,"GIT",()=>WNt(r,t,i));if(p<3)return await Lk1(c,n,i,t);{let l=await Ah(`GetAllWorkspaceDataFromGitCommitInternal::GetRepoFromFileReads ${t}`,i,"GIT",()=>E0l(c,t,i,o,r.dir,s,n,a,u)),d=rJo(l,n,i);return await C0l(d,s,i)}},$et=async(r,t,n,i,o,s)=>{let a="GetAllWorkspaceDataFromGitCommit",u,p={onAuditContext:o.onAuditContext,suppressOutOfBandThrow:o.suppressOutOfBandThrow};if(t?u=await Ah(`${a} for commit: ${t}`,i||{},"GIT",()=>kk1(r,t,n,i,!!o.validateData,s,o.onFileLoadError,p),"info"):u=await Ah(`${a} when a commitOID does not exist`,i||{},"GIT",()=>Bk1(r,n,i,!!o.validateData,s,o.onFileLoadError,p),"info"),o.validateData){let c=fdl.validate(u);c.valid||pO.errorContext(i,`Content from commit ${t} was invalid. Errors: `,c.failureMessage)}return u};var aJo=Je("GIT"),Xet=async(r,t,n,i,o,s,a)=>{let u=await $et(r,t,n,o,i,s),p=u.installedPackages||{},c={};return Object.keys(p).length?(aJo.infoContext(o,"Attempting to hydrate from stored packages"),c=await cf(()=>kIt(p,a),3,aJo,o,{retryStrategy:{name:"backoff",base:1},logOnRetry:"Retrying to hydrate packages",logOnFailure:"Failed to hydrate packages"})):aJo.infoContext(o,"No packages to hydrate"),i.installPackageEntities?k5e(u,c):{...u,installedPackages:c}};var OEC=Je("STEPS");var XEC=Je("GIT");var r2C=new aL(20);var cJo="remotes/origin";var j2C=Je("GIT");var lJo=async(r,t,n=!1)=>{let i=await mxr(r,t,n);if(!i.length)throw`No commits are available in the git log of branch ${t}`;return i[0]};var pJo=r=>ES.currentBranch({...r}).catch(t=>{throw new Error(`Error retrieving branch information: ${t}`)});var mxr=async(r,t,n=!1,i=void 0)=>{pd(!!t,"(GitLog) expected to have target branch","GIT");let o=n?`${cJo}/${t}`:t;return ES.log({...r,ref:o,depth:i})};var sJo=r=>fv(r,t=>({operation:t.operation}));var G2C=Je("GIT");var Z2C=Je("GIT");var $k1=yt(mYe());var Vk1=["step","job","graph","subgraph","columnGraph","buildSettings","workspaceSettings","templateEditor","apps"],nCC=B.object({tabID:B.string(),tabType:B.enum(Vk1),lastOpenedTimestamp:B.coerce.date().optional()});var iCC=B.string(),Wk1=Pb({filePath:ld(),fileData:ld()}),Kk1=Mr("FileReadResult",Wk1);var oCC=B.object({x:B.number(),y:B.number(),initialX:B.number().optional(),initialY:B.number().optional()}),sCC=B.object({x:B.number().int(),y:B.number().int()});var PCC=Je("GIT");var qCC=Je("GIT");var XCC=Je("GIT");var dJo=Je("PLAN"),u91=async(r,t)=>{let n="[getWorkspaceDataWithRetry]",i=await r();if(n3(i.steps)===0){dJo.infoContext(t,`${n}: no nodes in current workspace data. This is a potentially valid state. Checking for consistency in followup query...`),await kG(2e3);let o=await r(),s=n3(o.steps);s!==0&&(dJo.alertContext(t,`${n}: followup query returned ${s} nodes. Data is not consistent between identical calls to currentWorkspaceDataGetter(). Returning data containing steps...`),i=o)}return i},c91=async(r,t,n)=>{let i=await t.workspace(r).fetch(),o=qIt(i);return{...FEr(n),locations:o}},O0l=async(r,t,n,i,o,s,a,u,p,c,l=!1)=>{let d="[getCurrentAndDesiredWorkspaceDataWithPackages]";return Ah(`${d} fetching current and desired workspace data (${r})`,c,"APP",async()=>{let f;l?f=Promise.resolve(c91(n,i,s)):f=u91(()=>UEr(n,i,o??new tk,void 0,c),c);let[h,A]=await Promise.all([f,Xet(a,u,s,{installPackageEntities:!0,validateData:!0},{...c,orgID:t},aO,p)]);dJo.infoContext(c,`${d} current workspace data contains ${n3(h.steps)} nodes;`,`desired workspace data contains ${n3(A.steps)} nodes`);let E={currentWorkspaceData:{...k5e(h,h.installedPackages||{}),platformKind:s},desiredWorkspaceData:{...k5e(A,A.installedPackages||{}),platformKind:s}};return l&&(E.skippedBeforeCollection=!0),E},"info")};var fJo=Je("PLAN"),w0l=(r,t)=>{let n=[];for(let i=1;i<r.length;i++){let o=r[i];if(r[i-1]==="columns"&&typeof o=="number"){let a=t[o];n.push(a?.name??`[${o}]`)}else n.push(String(o))}return n.join(" > ")},yxr=r=>r==null?`<${r}>`:typeof r=="function"?"<function>":typeof r=="object"?r:String(r),hJo=(r,t)=>{let n=[];for(let i of r)!i.path||i.path.length===0||(i.kind==="A"?n.push(l91(i,t)):n.push(p91(i,t)));return n},l91=(r,t)=>{let n=r.path,{item:i}=r,o=[...n,r.index],s=w0l(o,t),a=i.path?.length?`${s} > ${i.path.join(" > ")}`:s,u=i.kind==="N"?"added":i.kind==="D"?"removed":"changed",c={path:`${a} (${u})`,rawPath:o,kind:"A"};return"lhs"in i&&i.lhs!==void 0&&(c.lhs=yxr(i.lhs)),"rhs"in i&&i.rhs!==void 0&&(c.rhs=yxr(i.rhs)),c},p91=(r,t)=>{let n=r.path,o={path:w0l(n,t),rawPath:n,kind:r.kind};return"lhs"in r&&r.lhs!==void 0&&(o.lhs=yxr(r.lhs)),"rhs"in r&&r.rhs!==void 0&&(o.rhs=yxr(r.rhs)),o},bxr=class{summaries=new Map;capturedPaths=new Map;addReason(t,n){let i=this.summaries.get(t);i?i.push(n):this.summaries.set(t,[n])}pathKey(t){return t.path?t.kind==="A"?`${t.path.join(".")}.${t.index}`:t.path.join("."):""}recordPaths(t,n){let i=this.capturedPaths.get(t);i||(i=new Set,this.capturedPaths.set(t,i));for(let o of n){let s=this.pathKey(o);s&&i.add(s)}}dedup(t,n){let i=this.capturedPaths.get(t);return i?.size?n.filter(o=>{let s=this.pathKey(o);return!s||!i.has(s)}):n}checkDDLDiff(t,n,i,o){let s=[],a=yol(n,i,o,u=>{s=u});if(a&&s.length>0){this.recordPaths(t,s);try{this.addReason(t,{kind:"ddl",summary:"Structural changes detected",changes:hJo(s,i.operation.metadata.columns)})}catch(u){fJo.warnContext(o,"Failed to humanize DDL diffs for change summary",{error:u})}}return a}checkMetadataDiff(t,n,i,o){let s=[],a=Lol(n,i,o,u=>{s=u});if(a&&s.length>0){let u=this.dedup(t,s);if(u.length>0){this.recordPaths(t,u);try{this.addReason(t,{kind:"metadata",summary:"Metadata changes detected",changes:hJo(u,i.operation.metadata.columns)})}catch(p){fJo.warnContext(o,"Failed to humanize metadata diffs for change summary",{error:p})}}}return a}captureFullDiff(t,n,i,o){let s=[];if(KZe(n,i,()=>!0,()=>{},o,"captureFullDiff",a=>{s=a}),s.length>0){this.recordPaths(t,s);try{this.addReason(t,{kind:"ddl",summary:"Changes detected",changes:hJo(s,i.operation.metadata.columns)})}catch(a){fJo.warnContext(o,"Failed to humanize diffs for advanced deploy change summary",{error:a})}}}checkSourceMappingDiff(t,n,i,o){let s=mol(t,n,i,o);return s&&this.addReason(t,{kind:"sourceMapping",summary:"Upstream dependency location mappings changed"}),s}recordLocationChange(t,n,i){this.addReason(t,{kind:"locationChange",summary:"Location mapping changed",from:n,to:i})}recordTransient(t){this.addReason(t,{kind:"transient",summary:"Transient deploy strategy \u2014 full recreate"})}recordViewDependencyRecreate(t){this.addReason(t,{kind:"viewDependencyRecreate",summary:"View recreated due to dependency location change"})}getSummaries(){let t={};for(let[n,i]of this.summaries)t[n]={reasons:i};return t}};var gJo=(r,t,n)=>{let i=t[r];i?i.workspaceEdits.push(...n.workspaceEdits):t[r]=n},Exr=class{adds={};alters={};deletes={};add(t,n){gJo(t,this.adds,n)}alter(t,n){gJo(t,this.alters,n)}delete(t,n){gJo(t,this.deletes,n)}getAlterStep(t){return this.alters[t]}finalize=()=>({addedTable:this.adds,alteredTable:this.alters,deletedTable:this.deletes})};var Rp=Je("PLAN"),M0l=r=>r==="table"||r==="view",$H=(r,t,n,i)=>({workspaceEdits:r,operation:t,nodeMetadata:{...n,...i}}),RZ=class{constructor(t,n,i,o,s,a,u,p,c){this.name=t;this.workspaceEditBuilder=n;this.renderer=i;this.currentState=o;this.desiredState=s;this.runTimeParameters=a;this.schemas=u;this.renderCacheManager=p;this.logContext=c}name;workspaceEditBuilder;renderer;currentState;desiredState;runTimeParameters;schemas;renderCacheManager;logContext;result=new Exr;diffCollector=new bxr;dependencyRefLookup={};get nodeChangeSummaries(){return this.diffCollector.getSummaries()}test_setResult(t){this.result=t}getNodeEdits=async()=>{let t="[BaseNodeEditBuidler.getNodeEdits()]",{measure:n,printSummary:i}=Bf(t,this.logContext),o=Bf("[Getting Dependency Refs]",this.logContext),s=wv(this.currentState.nodes),a=wv(this.desiredState.nodes),{deletedEntityIDs:u,addedEntityIDs:p,entitiesWithPossibleEdits:c}=j4e(this.desiredState.nodes,this.currentState.nodes);return Rp.debugContext(this.logContext,"getNodeEditsInternal -",`deletedEntityIDs:
|
|
10489
|
+
Total objects from all schemas: `,u)}catch(a){m2e.errorContext(n,i,"failed to log object list details",a)}return{objectLookup:this.buildObjectsByLocationLookup(o),missingLocations:s}}catch(o){throw m2e.errorContext(n,i,'Error when building object by location name lookup for objectType "objects"',o),o}},"info")}async getObjectAndColumnLookups(t,n,i){try{let[{objectLookup:o,missingLocations:s},{columnLookup:a,missingLocations:u}]=await Promise.all([this.getDataWarehouseObjectsByLocation(t,i),this.getDataWarehouseColumns(t,i)]),p={tables:{},views:{}},c={},l=T6o(t),d=T6o(n),f={};for(let[N,k]of Object.entries(d)){let q=l[N]?.[0];if(q){let G=o.tables[q]??new Set,H=o.views[q]??new Set,V=a[q]??[];for(let W of k)p.tables[W]=G,p.views[W]=H,c[W]=V}else for(let G of k){let H=n[G];H&&(f[G]=H)}}let[{objectLookup:h,missingLocations:A},{columnLookup:E,missingLocations:v}]=await Promise.all([this.getDataWarehouseObjectsByLocation(f,i),this.getDataWarehouseColumns(f,i)]),T={tables:{...p.tables,...h.tables},views:{...p.views,...h.views}},w={...c,...E};return{currentLookup:{objectLookup:o,columnLookup:a},updatedLookup:{objectLookup:T,columnLookup:w},missingLocations:{current:new Map([...s,...u]),updated:new Map([...A,...v])}}}catch(o){throw m2e.errorContext(i,"getting object and column lookups failed",o),yg(o,"Could not get object and column lookups: ")}}wrapSQLWithTest=t=>`SELECT 1 WHERE EXISTS (${t})`;getTemplateString=(t,n,i)=>{let o=t;return i&&(o=this.wrapSQLWithTest(o)),n&&(o=this.wrapSQLWithExplain(o)),o}};var det=class extends nt{noRoleFound;noWarehouseFound;isWarehouseInvalid;constructor(t,n){let i="Snowflake user authentication unsuccessful: ";t.invalidWarehouseInfo?i+=`Warehouse not found, is invalid, or the user with current role ${t.invalidWarehouseInfo.role} does not have permission.`:i+=`${t.noRoleFound?`Role${t.noWarehouseFound?" and Warehouse":""}`:"Warehouse"} must be provided.`,super(i,n),this.noRoleFound=!!t.noRoleFound,this.noWarehouseFound=!!t.noWarehouseFound,this.isWarehouseInvalid=!!t.invalidWarehouseInfo}},_al=r=>typeof r=="object"&&r instanceof det;var uMr=Je("PLATFORM"),lNt=class{constructor(t,n,i,o){this.runner=i;if(t.toLowerCase().includes("limit")||t.toLowerCase().includes("offset")||t.toLowerCase().includes("order by"))throw new nt("[BatchedQuery] Base query must not contain 'LIMIT', 'OFFSET', or 'ORDER BY', which are reserved for batching");this.queryParams.orderBy.push(...n),this.sql=`${t} ORDER BY ${n.join(", ")}`,this.logContext={...o,queryParams:this.queryParams,sql:t}}runner;aggregateRows=[];batchCount=0;isComplete=!1;logContext;meta=new Map;queryParams={limit:0,offset:0,orderBy:[]};sql;async runOneBatch(){let t="[BatchedQuery.runOneBatch()]";uMr.infoContext({...this.logContext,batch:this.batchCount},t,"Running batch query");try{let{data:{rows:n,status:i},runDetails:{queryID:o}}=await this.runner(this.batchCount===1?this.sql:`${this.sql} LIMIT ${this.queryParams.limit} OFFSET ${this.queryParams.offset}`);switch(this.aggregateRows.push(...n),this.meta.set(this.batchCount,{queryID:o,queryParams:{...this.queryParams},rowCount:n.length,status:i}),i){case"Canceled":case"Failure":throw new nt(`${t} Query finished with status '${i}'`);case"Success":this.isComplete=!this.queryParams.limit||n.length<this.queryParams.limit;break;case dL:{let s=Math.floor(n.length*(1-.1));if(s<1e3)throw new nt(`Unable to project a safe row count limit - query ${o?`'${o}'`:"(no ID)"} unexpectedly truncated at ${n.length} rows. Row data may be unusually large.`);this.queryParams.limit=s;break}}this.queryParams.offset+=n.length}catch(n){uMr.errorContext(this.logContext,t,"Batch failed",n);let i=this.meta.get(this.batchCount);throw this.meta.set(this.batchCount,{...i,error:n}),n}}async run(){let t="[BatchedQuery.run()]",{measure:n,printSummary:i}=Bf(t,this.logContext);uMr.infoContext(this.logContext,t,"Starting");try{do this.batchCount++,await n(`batch ${this.batchCount}`,()=>this.runOneBatch());while(!this.isComplete)}finally{i(),uMr.infoContext(this.logContext,t,`Finished all batches with ${this.aggregateRows.length} total rows; query metadata:`,Object.fromEntries([...this.meta.entries()]))}}checkForDuplicates(t){let n="[BatchedQuery.checkForDuplicates()]",i=new Set,o=new Set;for(let s of this.aggregateRows){let a=t.map(u=>s[u]).join(".");i.has(a)?o.add(a):i.add(a)}if(o.size)throw new nt(`${n} Found ${o.size} duplicate row(s) in query '${this.sql}'`,`Duplicate rows: ${JSON.stringify([...o])}`)}};var Ial=(r,t,n,i)=>{let o=i?` ORDER BY ${i}`:"";return`SELECT * FROM TABLE(RESULT_SCAN('${r}'))${o} LIMIT ${t} OFFSET ${n}`};var XM=Je("PLATFORM"),vD1=B.object({TABLE_NAME:B.string(),COMMENT:B.string().nullable(),TABLE_TYPE:B.string()}),cMr=class extends fZ{validator=Mr("InformationSchemaTablesRow",vD1);query(t){return`SELECT TABLE_NAME, TABLE_TYPE, COMMENT from "${t.database}".INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${t.schema}';`}convert(t){let{TABLE_NAME:n,COMMENT:i,...o}=t;return{kind:o.TABLE_TYPE.match(/^(.+\s)?TABLE$/)?"TABLE":o.TABLE_TYPE.match(/^(.+\s)?VIEW$/)?"VIEW":"<unknown>",name:n,comment:i??"",extra:o}}},TD1=B.object({TABLE_NAME:B.string(),COMMENT:B.string().nullable(),COLUMN_NAME:B.string(),IS_NULLABLE:B.union([B.literal("YES"),B.literal("NO")]),COLUMN_DEFAULT:B.string().nullable()}),lMr=class extends hZ{_logTag="log-tag-not-set";setLogTag(t){this._logTag=t}get logTag(){return this._logTag}validator=Mr("InformationSchemaColumnsRow",TD1);get columnsString(){return"TABLE_NAME, COLUMN_NAME, IS_NULLABLE, COMMENT, COLUMN_DEFAULT"}query(t){return`SELECT ${this.columnsString} from "${t.database}".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${t.schema}' ORDER BY TABLE_NAME, COLUMN_NAME`}convert(t){let{TABLE_NAME:n,COLUMN_NAME:i,COMMENT:o,...s}=t;return{name:i,objectName:n,comment:o??"",extra:s}}async runQuery(t,n,i){let o="[SnowflakeInformationSchemaColumnsImplementation] ";if(!t.toUpperCase().includes("ORDER BY TABLE_NAME, COLUMN_NAME")){let f="INFORMATION_SCHEMA.COLUMNS query missing required ORDER BY TABLE_NAME, COLUMN_NAME clause. This can lead to non-deterministic results when Snowflake truncates large result sets. Add ORDER BY TABLE_NAME, COLUMN_NAME clause to ensure consistent behavior. SQL text: "+t;throw XM.errorContext(i,o,f),new nt(f)}let s=await n(t),{status:a,rows:u}=s.data,{queryID:p}=s.runDetails;if(!p)throw XM.fatalContext(i,o,`query ID was unexpectedly ${p}`),new nt(`Query ID was unexpectedly ${p} when querying warehouse columns`);let c={...i,initialQueryID:p};if(this.setLogTag(`${o}[initial query ID=${p}] `),u.length===0)return XM.infoContext(c,this.logTag,"initial query returned 0 rows. No pagination needed. Returning empty array."),[];if(a!==dL)return XM.infoContext(c,this.logTag,`initial query returned all ${u.length} rows without truncation. No pagination needed.`),u.map(f=>this.validateAndConvert(f));let l=this.initializePaginationStateForTruncatedResponse(u,a,p,c),d=await this.paginateResults(p,l,n,c);return this.auditPaginatedResultsForDuplicates(d,c),XM.infoContext(c,this.logTag,`finished querying ${d.length} rows in ${l.batchNumber} pagination ${l.batchNumber===1?"batch":"batches"}.`),d}initializePaginationStateForTruncatedResponse(t,n,i,o){if(n!==dL)throw new nt(`Programming error: initializePaginationStateForTruncatedResponse called with non-truncated initial status ${n} for query ${i}`);let s=t.length,a=Math.floor(s*.9),u=0;return XM.infoContext(o,this.logTag,`initial query truncated - applying 10% safety margin to max batch size of ${a}. Discarding initial results and fetching all data via RESULT_SCAN. batchSize=${a},maxBatchSize=${a},offset=${u}`),{aggregateRows:[],offset:u,batchSize:a,maxBatchSize:a,batchNumber:1,failedBatchSize:void 0}}async paginateResults(t,n,i,o){let s=!1;for(;!s;){let a=n.batchSize,{paginatedRows:u,batchStatus:p,batchQueryID:c}=await this.fetchBatch(t,n.batchSize,n.offset,n.batchNumber,i,o);XM.infoContext(o,this.logTag,`[batch query ID=${c}] for batch ${n.batchNumber} completed with status "${p}" returned ${u.length} records`);let l=p===dL;l?(n.batchSize=this.adjustBatchSizeAfterTruncation(n.batchNumber,n.batchSize,u.length,o),n.failedBatchSize=n.batchSize):u.length===a&&n.failedBatchSize===void 0&&(n.batchSize=this.adjustBatchSizeAfterSuccess(n.batchNumber,n.batchSize,n.maxBatchSize,o));for(let d of u)n.aggregateRows.push(d);s=u.length<a&&!l,s||(n.offset+=u.length,n.batchNumber++)}return n.aggregateRows}async fetchBatch(t,n,i,o,s,a){try{let u=Ial(t,n,i,"TABLE_NAME, COLUMN_NAME"),{data:{rows:p,status:c},runDetails:{queryID:l}}=await s(u);return{paginatedRows:p.map(f=>this.validateAndConvert(f)),batchStatus:c,batchQueryID:l}}catch(u){throw XM.errorContext(a,this.logTag,`query for batch ${o} failed with error`,u),u}}adjustBatchSizeAfterTruncation(t,n,i,o){let u=Math.floor(i*.75);if(n<=1e3&&u<1e3)throw XM.fatalContext(o,this.logTag,`[batch=${t}]: already at minimum batch size 1000 and still truncating at ${i} rows. Cannot reduce batch size any further.`,{batch_number:t,paginated_request_batch_size:n,truncated_row_count:i,min_batch_size:1e3,calculated_size:u}),new nt("Already at minimum batch size of 1000 and still experiencing truncation. Cannot paginate this query - even 1000 rows exceed data limits.");let p=Math.max(1e3,u);return XM.infoContext(o,this.logTag,`[batch=${t}]: reducing batch size by factor ${.75}. From ${n} -> ${p}. Min batch size 1000`),p}adjustBatchSizeAfterSuccess(t,n,i,o){if(n<i){let a=Math.min(i,Math.floor(n*1.25));return XM.infoContext(o,this.logTag,`[batch=${t}]: increasing batch size by ${1.25}. From ${n} -> ${a}. Max batch size ${i}`),a}else if(n>i)return XM.infoContext(o,this.logTag,`[batch=${t}]: current batch size ${n} exceeds max batch size ${i}. Scaling down.`),i;return n}auditPaginatedResultsForDuplicates(t,n){try{XM.infoContext(n,this.logTag,`Auditing ${t.length} paginated results for duplicates...`);let i=new Map,o=new Map,s=0;for(let a of t){let u=`${a.objectName}.${a.name}`,p=i.get(u);p?(p.count++,o.set(u,p),s++):i.set(u,{table:a.objectName,column:a.name,count:1})}s?XM.errorContext(n,this.logTag,"Duplicate rows detected after pagination! This indicates RESULT_SCAN ordering issue.",{total_rows:t.length,unique_rows:i.size,duplicate_count:s,first_10_duplicates:Array.from(o.values()).slice(0,10)}):XM.infoContext(n,this.logTag,`Audit passed: all ${t.length} rows are unique by (TABLE_NAME, COLUMN_NAME).`)}catch(i){XM.errorContext(n,this.logTag,"Audit of paginated results for duplicates failed with error",i)}}},_D1=B.object({name:B.string(),owner:B.string(),comment:B.string(),budget:B.string().nullable().optional(),is_default:B.union([B.literal("Y"),B.literal("N")]),is_current:B.union([B.literal("Y"),B.literal("N")]),retention_time:B.string(),created_on:B.union([B.date(),B.string()]),options:B.string(),owner_role_type:B.string(),database_name:B.string()}),pMr=class extends gZ{validator=Mr("SnowflakeShowSchemaRow",_D1);convert(t){let{name:n,options:i,...o}=t;return{name:n,extra:{...o,options:new Set(i.length?i.split(", "):[])}}}query(t){return`SHOW SCHEMAS IN DATABASE "${t.database}"`}};var ID1=["002003","002043"],RD1=r=>{let t=r instanceof cet?r.coalesceCause:r;if(t instanceof yle){let n=String(t.getSnowflakeErrorCode()??"");return ID1.includes(n)}return!1},pNt=class extends AZ{constructor(n){super("snowflake");this.userContext=n}userContext;log(n,...i){Je("PLATFORM")[n]({orgID:this.userContext.orgID,workspaceID:this.userContext.environmentID,...i})}getObjectsImplementation=new cMr;getColumnsImplementation=new lMr;getSchemasImplementation=new pMr;isMissingLocationError(n){return RD1(n)}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n?.data?.status||"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data){let a=n.data.columns.map(c=>c.Name),u=n.data.rows.map(c=>({values:YYe(a,c)})),p=n.data.columns.map(c=>({name:c.Name,type:c.DataType||""}));s.fields=p,s.rows=u}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}validateUserContext(){let n="In your environment settings, verify that you have";if(!this.userContext)throw new nt(`Missing ${this.name} connection information! ${n} selected and authenticated a connection type.`);if(pd(this.userContext.kind==="snowflake",`Expected snowflake user context but received kind ${this.userContext.kind}`,"PLATFORM"),!this.userContext.accountName?.trim())throw new nt(`Missing ${this.name} account information! ${n} added an account.`);let i=PKo(this.userContext),o=`Missing ${this.name} credentials! ${n} added a`,s=Dme(i,a=>a.snowflakeUsername.trim()&&a.snowflakePassword?null:`${o} username and password.`,()=>null,()=>null,a=>a.snowflakeUsername?.trim()?null:`${o} username.`);if(s)throw new nt(s)}async testConnection(n=!1){if(n)try{this.validateUserContext();let i=(await this.getRows("select current_role()"))[0]?.["CURRENT_ROLE()"],o=(await this.getRows("select current_warehouse()"))[0]?.["CURRENT_WAREHOUSE()"],s=!1,a=!1;if(!o){if(this.userContext.warehouse)throw new det({invalidWarehouseInfo:{warehouse:this.userContext.warehouse,role:i??""}});a=!0}if((!i||i==="PUBLIC")&&!this.userContext.role&&(s=!0),a||s)throw new det({noRoleFound:s,noWarehouseFound:a})}catch(i){throw _al(i)?i:LE(i)?new nt(`${TD(this.name)} user authentication unsuccessful: ${i.message}`,i.detail):new nt(`${TD(this.name)} user authentication unsuccessful:`,aa(i).error.errorDetail)}else try{await this.runSQL({sql:h5})}catch(i){throw LE(i)?new nt(`Could not validate connection to ${this.name}: ${i.message}`,i.detail):new nt(`Could not validate connection to ${this.name}`,aa(i).error.errorDetail)}}async getDatabaseNames(){return(await this.getRows("SHOW DATABASES")).map(i=>i.name)}async getSchemaNames(n){return(await this.getRows(`SHOW SCHEMAS IN "${n}"`)).map(o=>o.name)}async getVariantRows(n,i,o,s){let a=this.getName(s,o),u=`SELECT "${n}" FROM ${a} SAMPLE (${i} ROWS)`;return this.getSQLQueryResult({sql:u})}async getObjectRows(n,i,o){let s=`SELECT * FROM ${this.getName(n,i)} LIMIT 100`;return o&&(s=this.wrapSQLWithExplain(s)),this.getSQLQueryResult({sql:s})}createColumnMetadata(n,i){return{name:n.name,dataType:n.type,transform:"",nullable:n["null?"]==="Y",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},primaryKey:n["primary key"]==="Y",uniqueKey:n["unique key"]==="Y",description:n.comment||"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async describeObject(n,i,o,s){let a=`DESC ${o.toUpperCase()} ${this.getName(n,i)}`;return(await this.runSQL({sql:a,overrideRequestID:mu()})).data.rows.map(p=>this.createColumnMetadata(p,s))}convertObjectRowsToMaterializationKinds(n){let i="convertObjectRowsToMaterializationKinds:",o=[],s=[];for(let a of n)a.kind==="TABLE"?o.push(a.name):a.kind==="VIEW"?s.push(a.name):this.log("emergContext",i,`table ${a.name} is of unexpected table type ${a.kind}`);return{tables:o,views:s}}createState(n,i,o,s){return new JZe(s,o,i,n)}wrapSQLWithExplain(n){return`EXPLAIN USING text ${n}`}},PKo=r=>({platformKind:"snowflake",snowflakeAccount:r.accountName||"",snowflakeAccessUrl:r.accessUrl,snowflakeUsername:r.user||"",snowflakePassword:r.password||"",snowflakeKeyPairKey:r.keyPairKey,snowflakeRole:r.role||"",snowflakeWarehouse:r.warehouse||"",snowflakeAuthType:r.authenticator,snowflakeKeyPairPass:r.keyPairPass??void 0});function V5e(r){if(r==="ApplicationDefault")throw new Vi("BigQuery ApplicationDefault auth is local-CLI-only and has no cloud connection type.");return r}var Ral=Je("RUNNER");var OD1=r=>{if(r.authenticator==="Token")return{token:r.token??"",path:r.path,host:r.host,databricksAuthType:r.authenticator,platformKind:"databricks"};if(r.authenticator==="Cloud")return{path:r.path,databricksAuthType:r.authenticator,host:r.host,platformKind:"databricks"};if(r.authenticator==="OAuthU2M")return{path:r.path,databricksAuthType:r.authenticator,host:r.host,platformKind:"databricks",accessToken:r.accessToken};if(r.authenticator==="OAuthM2M")return{path:r.path,databricksAuthType:r.authenticator,host:r.host,clientID:r.clientID??"",clientSecret:r.secret??"",platformKind:"databricks"};{let t=r.authenticator;throw new nt(`Databricks authenticator not supported: ${t}`)}},wD1=r=>({platformKind:"bigquery",bigQueryAuthType:V5e(r.authenticator),serviceAccountKey:r.serviceAccountKey}),MD1=r=>{if(r.authenticator==="oauth")return{credentials:r.credentials,connectionString:r.connectionString,fabricAuthType:r.authenticator,platformKind:"fabric"};{let t=r.authenticator;throw new nt(`Fabric authenticator not supported: ${t}`)}},Oal=r=>fL(r,{snowflake:t=>PKo(t),databricks:t=>OD1(t),fabric:t=>MD1(t),bigquery:t=>wD1(t)}),fet=(r,t)=>fL(t,{snowflake:n=>{if(!CWe(r))throw new Vi("Provided credentials are not Snowflake credentials");let i=Dme(r,()=>{},o=>o.snowflakeKeyPairKey,()=>{},()=>{},()=>{});return{snowflakeAccount:n.accountName,snowflakeAccessUrl:n.accessUrl,snowflakeKeyPairKey:i,snowflakeUsername:n.user,snowflakeRole:n.role,snowflakeWarehouse:n.warehouse,snowflakeAuthType:n.authenticator}},databricks:n=>{if(!w0r(r))throw new Vi("Provided credentials are not Databricks credentials");let i=r.databricksAuthType==="Token"?r.token:void 0;return{databricksAuthType:r.databricksAuthType,databricksPath:r.path,databricksHost:n.host,databricksToken:i,platformKind:"databricks"}},fabric:n=>{if(!M0r(r))throw new Vi("Provided credentials are not Fabric credentials");return{fabricAuthType:r.fabricAuthType,fabricConnectionString:n.connectionString,platformKind:"fabric"}},bigquery:n=>{if(!x0r(r))throw new Vi("Provided credentials are not BigQuery credentials");let i=r.bigQueryAuthType,o=i==="ServiceAccount"?r.serviceAccountKey||n.serviceAccountKey:void 0;if(i==="ServiceAccount"&&!o)throw new Vi("Missing required BigQuery credentials: serviceAccountKey");return{bigQueryAuthType:i,bigQueryServiceAccountKey:o,platformKind:"bigquery"}}});var wal=async(r,t=Xc.resolveAuthToken)=>{Ral.app("Attempting to cancel run",r);try{await rJe("/scheduler/cancelRun",r,t)}catch(n){let i=aa(n);throw Ral.error(i),i}};var NKo=Je("PLAN");var Mal=(r,t,n,i,o,s,a)=>dMr(`${r} workspace data`,t,n,i,o,`${r}WorkspaceData`,s,a),xal=async(r,t,n,i,o,s)=>{await dMr("plan context",r,t,n,i,"context",o,s)},Pal=async(r,t,n,i,o,s)=>await dMr("plan (completed)",r,t,n,i,"plan",o,s),Nal=async(r,t,n,i,o,s)=>await dMr("plan (unrealized)",r,t,n,i,"plan",o,s),dMr=async(r,t,n,i,o,s,a,u)=>{let p="[storePlanData]",c=PD1(n,i,o,s);return await Ah(`${p} (${r})`,u,"PLAN",async()=>{try{return NKo.infoContext(u,p,`Storing ${r} (${typeof a}) to ${c}`),await t.storage().uploadFile(c,a),NKo.infoContext(u,p,`Successfully stored ${r} (${typeof a}) to ${c}`),c}catch(l){throw NKo.errorContext(u,p,`Failed to store ${r} (${typeof a}) to ${c}`,l),l}},"info")},PD1=(r,t,n,i)=>`user/${r}/environment/${t}/planContext/${n}.${i}`;var qi;(function(r){r[r.BACKSPACE=8]="BACKSPACE",r[r.FORM_FEED=12]="FORM_FEED",r[r.NEWLINE=10]="NEWLINE",r[r.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",r[r.TAB=9]="TAB",r[r.SPACE=32]="SPACE",r[r.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",r[r.QUOTATION_MARK=34]="QUOTATION_MARK",r[r.NUMBER_SIGN=35]="NUMBER_SIGN",r[r.DOLLAR_SIGN=36]="DOLLAR_SIGN",r[r.PERCENT_SIGN=37]="PERCENT_SIGN",r[r.AMPERSAND=38]="AMPERSAND",r[r.APOSTROPHE=39]="APOSTROPHE",r[r.LEFT_PARENTHESIS=40]="LEFT_PARENTHESIS",r[r.RIGHT_PARENTHESIS=41]="RIGHT_PARENTHESIS",r[r.ASTERISK=42]="ASTERISK",r[r.PLUS_SIGN=43]="PLUS_SIGN",r[r.COMMA=44]="COMMA",r[r.HYPHEN_MINUS=45]="HYPHEN_MINUS",r[r.FULL_STOP=46]="FULL_STOP",r[r.SOLIDUS=47]="SOLIDUS",r[r.DIGIT_ZERO=48]="DIGIT_ZERO",r[r.DIGIT_ONE=49]="DIGIT_ONE",r[r.DIGIT_TWO=50]="DIGIT_TWO",r[r.DIGIT_THREE=51]="DIGIT_THREE",r[r.DIGIT_FOUR=52]="DIGIT_FOUR",r[r.DIGIT_FIVE=53]="DIGIT_FIVE",r[r.DIGIT_SIX=54]="DIGIT_SIX",r[r.DIGIT_SEVEN=55]="DIGIT_SEVEN",r[r.DIGIT_EIGHT=56]="DIGIT_EIGHT",r[r.DIGIT_NINE=57]="DIGIT_NINE",r[r.COLON=58]="COLON",r[r.SEMICOLON=59]="SEMICOLON",r[r.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",r[r.EQUALS_SIGN=61]="EQUALS_SIGN",r[r.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",r[r.QUESTION_MARK=63]="QUESTION_MARK",r[r.COMMERCIAL_AT=64]="COMMERCIAL_AT",r[r.LATIN_CAPITAL_LETTER_A=65]="LATIN_CAPITAL_LETTER_A",r[r.LATIN_CAPITAL_LETTER_B=66]="LATIN_CAPITAL_LETTER_B",r[r.LATIN_CAPITAL_LETTER_C=67]="LATIN_CAPITAL_LETTER_C",r[r.LATIN_CAPITAL_LETTER_D=68]="LATIN_CAPITAL_LETTER_D",r[r.LATIN_CAPITAL_LETTER_E=69]="LATIN_CAPITAL_LETTER_E",r[r.LATIN_CAPITAL_LETTER_F=70]="LATIN_CAPITAL_LETTER_F",r[r.LATIN_CAPITAL_LETTER_G=71]="LATIN_CAPITAL_LETTER_G",r[r.LATIN_CAPITAL_LETTER_H=72]="LATIN_CAPITAL_LETTER_H",r[r.LATIN_CAPITAL_LETTER_I=73]="LATIN_CAPITAL_LETTER_I",r[r.LATIN_CAPITAL_LETTER_J=74]="LATIN_CAPITAL_LETTER_J",r[r.LATIN_CAPITAL_LETTER_K=75]="LATIN_CAPITAL_LETTER_K",r[r.LATIN_CAPITAL_LETTER_L=76]="LATIN_CAPITAL_LETTER_L",r[r.LATIN_CAPITAL_LETTER_M=77]="LATIN_CAPITAL_LETTER_M",r[r.LATIN_CAPITAL_LETTER_N=78]="LATIN_CAPITAL_LETTER_N",r[r.LATIN_CAPITAL_LETTER_O=79]="LATIN_CAPITAL_LETTER_O",r[r.LATIN_CAPITAL_LETTER_P=80]="LATIN_CAPITAL_LETTER_P",r[r.LATIN_CAPITAL_LETTER_Q=81]="LATIN_CAPITAL_LETTER_Q",r[r.LATIN_CAPITAL_LETTER_R=82]="LATIN_CAPITAL_LETTER_R",r[r.LATIN_CAPITAL_LETTER_S=83]="LATIN_CAPITAL_LETTER_S",r[r.LATIN_CAPITAL_LETTER_T=84]="LATIN_CAPITAL_LETTER_T",r[r.LATIN_CAPITAL_LETTER_U=85]="LATIN_CAPITAL_LETTER_U",r[r.LATIN_CAPITAL_LETTER_V=86]="LATIN_CAPITAL_LETTER_V",r[r.LATIN_CAPITAL_LETTER_W=87]="LATIN_CAPITAL_LETTER_W",r[r.LATIN_CAPITAL_LETTER_X=88]="LATIN_CAPITAL_LETTER_X",r[r.LATIN_CAPITAL_LETTER_Y=89]="LATIN_CAPITAL_LETTER_Y",r[r.LATIN_CAPITAL_LETTER_Z=90]="LATIN_CAPITAL_LETTER_Z",r[r.LEFT_SQUARE_BRACKET=91]="LEFT_SQUARE_BRACKET",r[r.REVERSE_SOLIDUS=92]="REVERSE_SOLIDUS",r[r.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",r[r.CIRCUMFLEX_ACCENT=94]="CIRCUMFLEX_ACCENT",r[r.LOW_LINE=95]="LOW_LINE",r[r.GRAVE_ACCENT=96]="GRAVE_ACCENT",r[r.LATIN_SMALL_LETTER_A=97]="LATIN_SMALL_LETTER_A",r[r.LATIN_SMALL_LETTER_B=98]="LATIN_SMALL_LETTER_B",r[r.LATIN_SMALL_LETTER_C=99]="LATIN_SMALL_LETTER_C",r[r.LATIN_SMALL_LETTER_D=100]="LATIN_SMALL_LETTER_D",r[r.LATIN_SMALL_LETTER_E=101]="LATIN_SMALL_LETTER_E",r[r.LATIN_SMALL_LETTER_F=102]="LATIN_SMALL_LETTER_F",r[r.LATIN_SMALL_LETTER_G=103]="LATIN_SMALL_LETTER_G",r[r.LATIN_SMALL_LETTER_H=104]="LATIN_SMALL_LETTER_H",r[r.LATIN_SMALL_LETTER_I=105]="LATIN_SMALL_LETTER_I",r[r.LATIN_SMALL_LETTER_J=106]="LATIN_SMALL_LETTER_J",r[r.LATIN_SMALL_LETTER_K=107]="LATIN_SMALL_LETTER_K",r[r.LATIN_SMALL_LETTER_L=108]="LATIN_SMALL_LETTER_L",r[r.LATIN_SMALL_LETTER_M=109]="LATIN_SMALL_LETTER_M",r[r.LATIN_SMALL_LETTER_N=110]="LATIN_SMALL_LETTER_N",r[r.LATIN_SMALL_LETTER_O=111]="LATIN_SMALL_LETTER_O",r[r.LATIN_SMALL_LETTER_P=112]="LATIN_SMALL_LETTER_P",r[r.LATIN_SMALL_LETTER_Q=113]="LATIN_SMALL_LETTER_Q",r[r.LATIN_SMALL_LETTER_R=114]="LATIN_SMALL_LETTER_R",r[r.LATIN_SMALL_LETTER_S=115]="LATIN_SMALL_LETTER_S",r[r.LATIN_SMALL_LETTER_T=116]="LATIN_SMALL_LETTER_T",r[r.LATIN_SMALL_LETTER_U=117]="LATIN_SMALL_LETTER_U",r[r.LATIN_SMALL_LETTER_V=118]="LATIN_SMALL_LETTER_V",r[r.LATIN_SMALL_LETTER_W=119]="LATIN_SMALL_LETTER_W",r[r.LATIN_SMALL_LETTER_X=120]="LATIN_SMALL_LETTER_X",r[r.LATIN_SMALL_LETTER_Y=121]="LATIN_SMALL_LETTER_Y",r[r.LATIN_SMALL_LETTER_Z=122]="LATIN_SMALL_LETTER_Z",r[r.LEFT_CURLY_BRACKET=123]="LEFT_CURLY_BRACKET",r[r.VERTICAL_LINE=124]="VERTICAL_LINE",r[r.RIGHT_CURLY_BRACKET=125]="RIGHT_CURLY_BRACKET",r[r.TILDE=126]="TILDE"})(qi||(qi={}));var Dal={[qi.QUOTATION_MARK]:qi.QUOTATION_MARK,[qi.REVERSE_SOLIDUS]:qi.REVERSE_SOLIDUS,[qi.SOLIDUS]:qi.SOLIDUS,[qi.LATIN_SMALL_LETTER_B]:qi.BACKSPACE,[qi.LATIN_SMALL_LETTER_F]:qi.FORM_FEED,[qi.LATIN_SMALL_LETTER_N]:qi.NEWLINE,[qi.LATIN_SMALL_LETTER_R]:qi.CARRIAGE_RETURN,[qi.LATIN_SMALL_LETTER_T]:qi.TAB};var dNt=class{constructor(){this.decoder=new TextDecoder("utf-8"),this.strings=[],this.byteLength=0}appendChar(t){this.strings.push(String.fromCharCode(t)),this.byteLength+=1}appendBuf(t,n=0,i=t.length){this.strings.push(this.decoder.decode(t.subarray(n,i))),this.byteLength+=i-n}reset(){this.strings=[],this.byteLength=0}toString(){return this.strings.join("")}},fNt=class{constructor(t){this.decoder=new TextDecoder("utf-8"),this.bufferOffset=0,this.string="",this.byteLength=0,this.buffer=new Uint8Array(t)}appendChar(t){this.bufferOffset>=this.buffer.length&&this.flushStringBuffer(),this.buffer[this.bufferOffset++]=t,this.byteLength+=1}appendBuf(t,n=0,i=t.length){let o=i-n;this.bufferOffset+o>this.buffer.length&&this.flushStringBuffer(),this.buffer.set(t.subarray(n,i),this.bufferOffset),this.bufferOffset+=o,this.byteLength+=o}flushStringBuffer(){this.string+=this.decoder.decode(this.buffer.subarray(0,this.bufferOffset)),this.bufferOffset=0}reset(){this.string="",this.bufferOffset=0,this.byteLength=0}toString(){return this.flushStringBuffer(),this.string}};var DKo;(function(r){r[r.LEFT_BRACE=0]="LEFT_BRACE",r[r.RIGHT_BRACE=1]="RIGHT_BRACE",r[r.LEFT_BRACKET=2]="LEFT_BRACKET",r[r.RIGHT_BRACKET=3]="RIGHT_BRACKET",r[r.COLON=4]="COLON",r[r.COMMA=5]="COMMA",r[r.TRUE=6]="TRUE",r[r.FALSE=7]="FALSE",r[r.NULL=8]="NULL",r[r.STRING=9]="STRING",r[r.NUMBER=10]="NUMBER",r[r.SEPARATOR=11]="SEPARATOR"})(DKo||(DKo={}));var Ud=DKo;var Xn;(function(r){r[r.START=0]="START",r[r.ENDED=1]="ENDED",r[r.ERROR=2]="ERROR",r[r.TRUE1=3]="TRUE1",r[r.TRUE2=4]="TRUE2",r[r.TRUE3=5]="TRUE3",r[r.FALSE1=6]="FALSE1",r[r.FALSE2=7]="FALSE2",r[r.FALSE3=8]="FALSE3",r[r.FALSE4=9]="FALSE4",r[r.NULL1=10]="NULL1",r[r.NULL2=11]="NULL2",r[r.NULL3=12]="NULL3",r[r.STRING_DEFAULT=13]="STRING_DEFAULT",r[r.STRING_AFTER_BACKSLASH=14]="STRING_AFTER_BACKSLASH",r[r.STRING_UNICODE_DIGIT_1=15]="STRING_UNICODE_DIGIT_1",r[r.STRING_UNICODE_DIGIT_2=16]="STRING_UNICODE_DIGIT_2",r[r.STRING_UNICODE_DIGIT_3=17]="STRING_UNICODE_DIGIT_3",r[r.STRING_UNICODE_DIGIT_4=18]="STRING_UNICODE_DIGIT_4",r[r.STRING_INCOMPLETE_CHAR=19]="STRING_INCOMPLETE_CHAR",r[r.NUMBER_AFTER_INITIAL_MINUS=20]="NUMBER_AFTER_INITIAL_MINUS",r[r.NUMBER_AFTER_INITIAL_ZERO=21]="NUMBER_AFTER_INITIAL_ZERO",r[r.NUMBER_AFTER_INITIAL_NON_ZERO=22]="NUMBER_AFTER_INITIAL_NON_ZERO",r[r.NUMBER_AFTER_FULL_STOP=23]="NUMBER_AFTER_FULL_STOP",r[r.NUMBER_AFTER_DECIMAL=24]="NUMBER_AFTER_DECIMAL",r[r.NUMBER_AFTER_E=25]="NUMBER_AFTER_E",r[r.NUMBER_AFTER_E_AND_SIGN=26]="NUMBER_AFTER_E_AND_SIGN",r[r.NUMBER_AFTER_E_AND_DIGIT=27]="NUMBER_AFTER_E_AND_DIGIT",r[r.SEPARATOR=28]="SEPARATOR",r[r.BOM_OR_START=29]="BOM_OR_START",r[r.BOM=30]="BOM"})(Xn||(Xn={}));function Bal(r){return["START","ENDED","ERROR","TRUE1","TRUE2","TRUE3","FALSE1","FALSE2","FALSE3","FALSE4","NULL1","NULL2","NULL3","STRING_DEFAULT","STRING_AFTER_BACKSLASH","STRING_UNICODE_DIGIT_1","STRING_UNICODE_DIGIT_2","STRING_UNICODE_DIGIT_3","STRING_UNICODE_DIGIT_4","STRING_INCOMPLETE_CHAR","NUMBER_AFTER_INITIAL_MINUS","NUMBER_AFTER_INITIAL_ZERO","NUMBER_AFTER_INITIAL_NON_ZERO","NUMBER_AFTER_FULL_STOP","NUMBER_AFTER_DECIMAL","NUMBER_AFTER_E","NUMBER_AFTER_E_AND_SIGN","NUMBER_AFTER_E_AND_DIGIT","SEPARATOR","BOM_OR_START","BOM"][r]}var DD1={stringBufferSize:0,numberBufferSize:0,separator:void 0,emitPartialTokens:!1},het=class r extends Error{constructor(t){super(t),Object.setPrototypeOf(this,r.prototype)}},get=class{constructor(t){this.state=Xn.BOM_OR_START,this.bomIndex=0,this.separatorIndex=0,this.escapedCharsByteLength=0,this.bytes_remaining=0,this.bytes_in_sequence=0,this.char_split_buffer=new Uint8Array(4),this.encoder=new TextEncoder,this.offset=-1,t=Object.assign(Object.assign({},DD1),t),this.emitPartialTokens=t.emitPartialTokens===!0,this.bufferedString=t.stringBufferSize&&t.stringBufferSize>4?new fNt(t.stringBufferSize):new dNt,this.bufferedNumber=t.numberBufferSize&&t.numberBufferSize>0?new fNt(t.numberBufferSize):new dNt,this.separator=t.separator,this.separatorBytes=t.separator?this.encoder.encode(t.separator):void 0}get isEnded(){return this.state===Xn.ENDED}write(t){try{let n;if(t instanceof Uint8Array)n=t;else if(typeof t=="string")n=this.encoder.encode(t);else if(Array.isArray(t))n=Uint8Array.from(t);else if(ArrayBuffer.isView(t))n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else throw new TypeError("Unexpected type. The `write` function only accepts Arrays, TypedArrays and Strings.");for(let i=0;i<n.length;i+=1){let o=n[i];switch(this.state){case Xn.BOM_OR_START:if(t instanceof Uint8Array&&o===239){this.bom=[239,187,191],this.bomIndex+=1,this.state=Xn.BOM;continue}if(t instanceof Uint16Array){if(o===254){this.bom=[254,255],this.bomIndex+=1,this.state=Xn.BOM;continue}if(o===255){this.bom=[255,254],this.bomIndex+=1,this.state=Xn.BOM;continue}}if(t instanceof Uint32Array){if(o===0){this.bom=[0,0,254,255],this.bomIndex+=1,this.state=Xn.BOM;continue}if(o===255){this.bom=[255,254,0,0],this.bomIndex+=1,this.state=Xn.BOM;continue}}case Xn.START:if(this.offset+=1,this.separatorBytes&&o===this.separatorBytes[0]){if(this.separatorBytes.length===1){this.state=Xn.START,this.onToken({token:Ud.SEPARATOR,value:this.separator,offset:this.offset+this.separatorBytes.length-1});continue}this.state=Xn.SEPARATOR;continue}if(o===qi.SPACE||o===qi.NEWLINE||o===qi.CARRIAGE_RETURN||o===qi.TAB)continue;if(o===qi.LEFT_CURLY_BRACKET){this.onToken({token:Ud.LEFT_BRACE,value:"{",offset:this.offset});continue}if(o===qi.RIGHT_CURLY_BRACKET){this.onToken({token:Ud.RIGHT_BRACE,value:"}",offset:this.offset});continue}if(o===qi.LEFT_SQUARE_BRACKET){this.onToken({token:Ud.LEFT_BRACKET,value:"[",offset:this.offset});continue}if(o===qi.RIGHT_SQUARE_BRACKET){this.onToken({token:Ud.RIGHT_BRACKET,value:"]",offset:this.offset});continue}if(o===qi.COLON){this.onToken({token:Ud.COLON,value:":",offset:this.offset});continue}if(o===qi.COMMA){this.onToken({token:Ud.COMMA,value:",",offset:this.offset});continue}if(o===qi.LATIN_SMALL_LETTER_T){this.state=Xn.TRUE1;continue}if(o===qi.LATIN_SMALL_LETTER_F){this.state=Xn.FALSE1;continue}if(o===qi.LATIN_SMALL_LETTER_N){this.state=Xn.NULL1;continue}if(o===qi.QUOTATION_MARK){this.bufferedString.reset(),this.escapedCharsByteLength=0,this.state=Xn.STRING_DEFAULT;continue}if(o>=qi.DIGIT_ONE&&o<=qi.DIGIT_NINE){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_NON_ZERO;continue}if(o===qi.DIGIT_ZERO){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_ZERO;continue}if(o===qi.HYPHEN_MINUS){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_MINUS;continue}break;case Xn.STRING_DEFAULT:if(o===qi.QUOTATION_MARK){let a=this.bufferedString.toString();this.state=Xn.START,this.onToken({token:Ud.STRING,value:a,offset:this.offset}),this.offset+=this.escapedCharsByteLength+this.bufferedString.byteLength+1;continue}if(o===qi.REVERSE_SOLIDUS){this.state=Xn.STRING_AFTER_BACKSLASH;continue}if(o>=128){if(o>=194&&o<=223?this.bytes_in_sequence=2:o<=239?this.bytes_in_sequence=3:this.bytes_in_sequence=4,this.bytes_in_sequence<=n.length-i){this.bufferedString.appendBuf(n,i,i+this.bytes_in_sequence),i+=this.bytes_in_sequence-1;continue}this.bytes_remaining=i+this.bytes_in_sequence-n.length,this.char_split_buffer.set(n.subarray(i)),i=n.length-1,this.state=Xn.STRING_INCOMPLETE_CHAR;continue}if(o>=qi.SPACE){this.bufferedString.appendChar(o);continue}break;case Xn.STRING_INCOMPLETE_CHAR:this.char_split_buffer.set(n.subarray(i,i+this.bytes_remaining),this.bytes_in_sequence-this.bytes_remaining),this.bufferedString.appendBuf(this.char_split_buffer,0,this.bytes_in_sequence),i=this.bytes_remaining-1,this.state=Xn.STRING_DEFAULT;continue;case Xn.STRING_AFTER_BACKSLASH:let s=Dal[o];if(s){this.bufferedString.appendChar(s),this.escapedCharsByteLength+=1,this.state=Xn.STRING_DEFAULT;continue}if(o===qi.LATIN_SMALL_LETTER_U){this.unicode="",this.state=Xn.STRING_UNICODE_DIGIT_1;continue}break;case Xn.STRING_UNICODE_DIGIT_1:case Xn.STRING_UNICODE_DIGIT_2:case Xn.STRING_UNICODE_DIGIT_3:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE||o>=qi.LATIN_CAPITAL_LETTER_A&&o<=qi.LATIN_CAPITAL_LETTER_F||o>=qi.LATIN_SMALL_LETTER_A&&o<=qi.LATIN_SMALL_LETTER_F){this.unicode+=String.fromCharCode(o),this.state+=1;continue}break;case Xn.STRING_UNICODE_DIGIT_4:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE||o>=qi.LATIN_CAPITAL_LETTER_A&&o<=qi.LATIN_CAPITAL_LETTER_F||o>=qi.LATIN_SMALL_LETTER_A&&o<=qi.LATIN_SMALL_LETTER_F){let a=parseInt(this.unicode+String.fromCharCode(o),16),u;if(this.highSurrogate===void 0)if(a>=55296&&a<=56319){this.highSurrogate=a,this.state=Xn.STRING_DEFAULT;continue}else u=String.fromCharCode(a);else a>=56320&&a<=57343?u=String.fromCharCode(this.highSurrogate,a):u=String.fromCharCode(this.highSurrogate),this.highSurrogate=void 0;let p=this.encoder.encode(u);this.bufferedString.appendBuf(p),this.escapedCharsByteLength+=6-p.byteLength,this.state=Xn.STRING_DEFAULT;continue}break;case Xn.NUMBER_AFTER_INITIAL_MINUS:if(o===qi.DIGIT_ZERO){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_ZERO;continue}if(o>=qi.DIGIT_ONE&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_INITIAL_NON_ZERO;continue}break;case Xn.NUMBER_AFTER_INITIAL_ZERO:if(o===qi.FULL_STOP){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_FULL_STOP;continue}if(o===qi.LATIN_SMALL_LETTER_E||o===qi.LATIN_CAPITAL_LETTER_E){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E;continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.NUMBER_AFTER_INITIAL_NON_ZERO:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o);continue}if(o===qi.FULL_STOP){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_FULL_STOP;continue}if(o===qi.LATIN_SMALL_LETTER_E||o===qi.LATIN_CAPITAL_LETTER_E){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E;continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.NUMBER_AFTER_FULL_STOP:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_DECIMAL;continue}break;case Xn.NUMBER_AFTER_DECIMAL:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o);continue}if(o===qi.LATIN_SMALL_LETTER_E||o===qi.LATIN_CAPITAL_LETTER_E){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E;continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.NUMBER_AFTER_E:if(o===qi.PLUS_SIGN||o===qi.HYPHEN_MINUS){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E_AND_SIGN;continue}case Xn.NUMBER_AFTER_E_AND_SIGN:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o),this.state=Xn.NUMBER_AFTER_E_AND_DIGIT;continue}break;case Xn.NUMBER_AFTER_E_AND_DIGIT:if(o>=qi.DIGIT_ZERO&&o<=qi.DIGIT_NINE){this.bufferedNumber.appendChar(o);continue}i-=1,this.state=Xn.START,this.emitNumber();continue;case Xn.TRUE1:if(o===qi.LATIN_SMALL_LETTER_R){this.state=Xn.TRUE2;continue}break;case Xn.TRUE2:if(o===qi.LATIN_SMALL_LETTER_U){this.state=Xn.TRUE3;continue}break;case Xn.TRUE3:if(o===qi.LATIN_SMALL_LETTER_E){this.state=Xn.START,this.onToken({token:Ud.TRUE,value:!0,offset:this.offset}),this.offset+=3;continue}break;case Xn.FALSE1:if(o===qi.LATIN_SMALL_LETTER_A){this.state=Xn.FALSE2;continue}break;case Xn.FALSE2:if(o===qi.LATIN_SMALL_LETTER_L){this.state=Xn.FALSE3;continue}break;case Xn.FALSE3:if(o===qi.LATIN_SMALL_LETTER_S){this.state=Xn.FALSE4;continue}break;case Xn.FALSE4:if(o===qi.LATIN_SMALL_LETTER_E){this.state=Xn.START,this.onToken({token:Ud.FALSE,value:!1,offset:this.offset}),this.offset+=4;continue}break;case Xn.NULL1:if(o===qi.LATIN_SMALL_LETTER_U){this.state=Xn.NULL2;continue}break;case Xn.NULL2:if(o===qi.LATIN_SMALL_LETTER_L){this.state=Xn.NULL3;continue}break;case Xn.NULL3:if(o===qi.LATIN_SMALL_LETTER_L){this.state=Xn.START,this.onToken({token:Ud.NULL,value:null,offset:this.offset}),this.offset+=3;continue}break;case Xn.SEPARATOR:if(this.separatorIndex+=1,!this.separatorBytes||o!==this.separatorBytes[this.separatorIndex])break;this.separatorIndex===this.separatorBytes.length-1&&(this.state=Xn.START,this.onToken({token:Ud.SEPARATOR,value:this.separator,offset:this.offset+this.separatorIndex}),this.separatorIndex=0);continue;case Xn.BOM:if(o===this.bom[this.bomIndex]){if(this.bomIndex===this.bom.length-1){this.state=Xn.START,this.bom=void 0,this.bomIndex=0;continue}this.bomIndex+=1;continue}break;case Xn.ENDED:if(o===qi.SPACE||o===qi.NEWLINE||o===qi.CARRIAGE_RETURN||o===qi.TAB)continue}throw new het(`Unexpected "${String.fromCharCode(o)}" at position "${i}" in state ${Bal(this.state)}`)}if(this.emitPartialTokens)switch(this.state){case Xn.TRUE1:case Xn.TRUE2:case Xn.TRUE3:this.onToken({token:Ud.TRUE,value:!0,offset:this.offset,partial:!0});break;case Xn.FALSE1:case Xn.FALSE2:case Xn.FALSE3:case Xn.FALSE4:this.onToken({token:Ud.FALSE,value:!1,offset:this.offset,partial:!0});break;case Xn.NULL1:case Xn.NULL2:case Xn.NULL3:this.onToken({token:Ud.NULL,value:null,offset:this.offset,partial:!0});break;case Xn.STRING_DEFAULT:{let i=this.bufferedString.toString();this.onToken({token:Ud.STRING,value:i,offset:this.offset,partial:!0});break}case Xn.NUMBER_AFTER_INITIAL_ZERO:case Xn.NUMBER_AFTER_INITIAL_NON_ZERO:case Xn.NUMBER_AFTER_DECIMAL:case Xn.NUMBER_AFTER_E_AND_DIGIT:try{this.onToken({token:Ud.NUMBER,value:this.parseNumber(this.bufferedNumber.toString()),offset:this.offset,partial:!0})}catch{}}}catch(n){this.error(n)}}emitNumber(){this.onToken({token:Ud.NUMBER,value:this.parseNumber(this.bufferedNumber.toString()),offset:this.offset}),this.offset+=this.bufferedNumber.byteLength-1}parseNumber(t){return Number(t)}error(t){this.state!==Xn.ENDED&&(this.state=Xn.ERROR),this.onError(t)}end(){switch(this.state){case Xn.NUMBER_AFTER_INITIAL_ZERO:case Xn.NUMBER_AFTER_INITIAL_NON_ZERO:case Xn.NUMBER_AFTER_DECIMAL:case Xn.NUMBER_AFTER_E_AND_DIGIT:this.state=Xn.ENDED,this.emitNumber(),this.onEnd();break;case Xn.BOM_OR_START:case Xn.START:case Xn.ERROR:case Xn.SEPARATOR:this.state=Xn.ENDED,this.onEnd();break;default:this.error(new het(`Tokenizer ended in the middle of a token (state: ${Bal(this.state)}). Either not all the data was received or the data was invalid.`))}}onToken(t){throw new het(`Can't emit tokens before the "onToken" callback has been set up.`)}onError(t){throw t}onEnd(){}};var cO;(function(r){r[r.OBJECT=0]="OBJECT",r[r.ARRAY=1]="ARRAY"})(cO||(cO={}));var tA;(function(r){r[r.VALUE=0]="VALUE",r[r.KEY=1]="KEY",r[r.COLON=2]="COLON",r[r.COMMA=3]="COMMA",r[r.ENDED=4]="ENDED",r[r.ERROR=5]="ERROR",r[r.SEPARATOR=6]="SEPARATOR"})(tA||(tA={}));function Lal(r){return["VALUE","KEY","COLON","COMMA","ENDED","ERROR","SEPARATOR"][r]}var BD1={paths:void 0,keepStack:!0,separator:void 0,emitPartialValues:!1},W5e=class r extends Error{constructor(t){super(t),Object.setPrototypeOf(this,r.prototype)}},Aet=class{constructor(t){this.state=tA.VALUE,this.mode=void 0,this.key=void 0,this.value=void 0,this.stack=[],t=Object.assign(Object.assign({},BD1),t),t.paths&&(this.paths=t.paths.map(n=>{if(n===void 0||n==="$*")return;if(!n.startsWith("$"))throw new W5e(`Invalid selector "${n}". Should start with "$".`);let i=n.split(".").slice(1);if(i.includes(""))throw new W5e(`Invalid selector "${n}". ".." syntax not supported.`);return i})),this.keepStack=t.keepStack||!1,this.separator=t.separator,t.emitPartialValues||(this.emitPartial=()=>{})}shouldEmit(){return this.paths?this.paths.some(t=>{var n;if(t===void 0)return!0;if(t.length!==this.stack.length)return!1;for(let o=0;o<t.length-1;o++){let s=t[o],a=this.stack[o+1].key;if(s!=="*"&&s!==a?.toString())return!1}let i=t[t.length-1];return i==="*"?!0:i===((n=this.key)===null||n===void 0?void 0:n.toString())}):!0}push(){this.stack.push({key:this.key,value:this.value,mode:this.mode,emit:this.shouldEmit()})}pop(){let t=this.value,n;({key:this.key,value:this.value,mode:this.mode,emit:n}=this.stack.pop()),this.state=this.mode!==void 0?tA.COMMA:tA.VALUE,this.emit(t,n)}emit(t,n){!this.keepStack&&this.value&&this.stack.every(i=>!i.emit)&&delete this.value[this.key],n&&this.onValue({value:t,key:this.key,parent:this.value,stack:this.stack}),this.stack.length===0&&(this.separator?this.state=tA.SEPARATOR:this.separator===void 0&&this.end())}emitPartial(t){if(this.shouldEmit()){if(this.state===tA.KEY){this.onValue({value:void 0,key:t,parent:this.value,stack:this.stack,partial:!0});return}this.onValue({value:t,key:this.key,parent:this.value,stack:this.stack,partial:!0})}}get isEnded(){return this.state===tA.ENDED}write({token:t,value:n,partial:i}){try{if(i){this.emitPartial(n);return}if(this.state===tA.VALUE){if(t===Ud.STRING||t===Ud.NUMBER||t===Ud.TRUE||t===Ud.FALSE||t===Ud.NULL){this.mode===cO.OBJECT?(this.value[this.key]=n,this.state=tA.COMMA):this.mode===cO.ARRAY&&(this.value.push(n),this.state=tA.COMMA),this.emit(n,this.shouldEmit());return}if(t===Ud.LEFT_BRACE){if(this.push(),this.mode===cO.OBJECT)this.value=this.value[this.key]={};else if(this.mode===cO.ARRAY){let o={};this.value.push(o),this.value=o}else this.value={};this.mode=cO.OBJECT,this.state=tA.KEY,this.key=void 0,this.emitPartial();return}if(t===Ud.LEFT_BRACKET){if(this.push(),this.mode===cO.OBJECT)this.value=this.value[this.key]=[];else if(this.mode===cO.ARRAY){let o=[];this.value.push(o),this.value=o}else this.value=[];this.mode=cO.ARRAY,this.state=tA.VALUE,this.key=0,this.emitPartial();return}if(this.mode===cO.ARRAY&&t===Ud.RIGHT_BRACKET&&this.value.length===0){this.pop();return}}if(this.state===tA.KEY){if(t===Ud.STRING){this.key=n,this.state=tA.COLON,this.emitPartial();return}if(t===Ud.RIGHT_BRACE&&Object.keys(this.value).length===0){this.pop();return}}if(this.state===tA.COLON&&t===Ud.COLON){this.state=tA.VALUE;return}if(this.state===tA.COMMA){if(t===Ud.COMMA){if(this.mode===cO.ARRAY){this.state=tA.VALUE,this.key+=1;return}if(this.mode===cO.OBJECT){this.state=tA.KEY;return}}if(t===Ud.RIGHT_BRACE&&this.mode===cO.OBJECT||t===Ud.RIGHT_BRACKET&&this.mode===cO.ARRAY){this.pop();return}}if(this.state===tA.SEPARATOR&&t===Ud.SEPARATOR&&n===this.separator){this.state=tA.VALUE;return}if(t===Ud.SEPARATOR&&this.state!==tA.SEPARATOR&&Array.from(n).map(o=>o.charCodeAt(0)).every(o=>o===qi.SPACE||o===qi.NEWLINE||o===qi.CARRIAGE_RETURN||o===qi.TAB))return;throw new W5e(`Unexpected ${Ud[t]} (${JSON.stringify(n)}) in state ${Lal(this.state)}`)}catch(o){this.error(o)}}error(t){this.state!==tA.ENDED&&(this.state=tA.ERROR),this.onError(t)}end(){this.state!==tA.VALUE&&this.state!==tA.SEPARATOR||this.stack.length>0?this.error(new Error(`Parser ended in mid-parsing (state: ${Lal(this.state)}). Either not all the data was received or the data was invalid.`)):(this.state=tA.ENDED,this.onEnd())}onValue(t){throw new W5e(`Can't emit data before the "onValue" callback has been set up.`)}onError(t){throw t}onEnd(){}};var met=class{constructor(t={}){this.tokenizer=new get(t),this.tokenParser=new Aet(t),this.tokenizer.onToken=this.tokenParser.write.bind(this.tokenParser),this.tokenizer.onEnd=()=>{this.tokenParser.isEnded||this.tokenParser.end()},this.tokenParser.onError=this.tokenizer.error.bind(this.tokenizer),this.tokenParser.onEnd=()=>{this.tokenizer.isEnded||this.tokenizer.end()}}get isEnded(){return this.tokenizer.isEnded&&this.tokenParser.isEnded}write(t){this.tokenizer.write(t)}end(){this.tokenizer.end()}set onToken(t){this.tokenizer.onToken=n=>{t(n),this.tokenParser.write(n)}}set onValue(t){this.tokenParser.onValue=t}set onError(t){this.tokenizer.onError=t}set onEnd(t){this.tokenParser.onEnd=()=>{this.tokenizer.isEnded||this.tokenizer.end(),t.call(this.tokenParser)}}};var kal=Je("PLAN"),qal=async r=>new Promise((t,n)=>{let i=new met,o;i.onValue=({value:s,stack:a})=>{a.length===0&&(o=s)},i.onError=s=>{kal.error("streaming-json-parser","Error parsing JSON with streaming parser",s),n(s)},i.onEnd=()=>{t(o)};try{i.write(r),i.end()}catch(s){let a=s instanceof Error?s:new Error(String(s));kal.error("streaming-json-parser","Error writing to streaming parser",a),n(a)}});var _pe=Je("PLAN"),Ual=async(r,t,n,i,o,s,a,u)=>{let p="[sendCreatePlanRequest]",{measure:c,printSummary:l}=Bf(p,u),{branchName:d,clientWarnIssues:f,disablePresync:h,loadWarehouseComments:A,useRenderCache:E,userContext:v}=r;try{let T=(G,H)=>c(`store ${G} workspace data (parallelized)`,()=>Mal(G,t,i,o,n,H,u)),[w,N]=await Promise.all([T("current",a.currentWorkspaceData),T("desired",a.desiredWorkspaceData)]),{createPlan:k,getPlan:L}=D3(Db(),Xc.instance.getFirebaseRefreshToken);return await c("create plan request roundtrip",()=>k({parameters:s,runDetails:{branchName:d,currentWorkspaceDataFilePath:w,desiredWorkspaceDataFilePath:N,disablePresync:h,environmentID:o.toString(),issues:f,loadWarehouseComments:A,planID:n,skippedBeforeCollection:!!a.skippedBeforeCollection,useRenderCache:E},userCredentials:Oal(v)})),await c("poll for completed plan",async()=>{let G,H=3e5,V=0;do{let W=LD1(V);H-=W,await kG(W),V+=W,_pe.appContext(u,p,"Polling");let F=await L({params:{environmentID:o.toString(),planID:n}});if(rol(F)){let{planStorageFilePath:J}=F;_pe.appContext(u,p,`Received response for plan at ${J}; downloading`);let Y=await t.storage().downloadFile(J),z=typeof Y=="string",X;if(z?await c("decompress completed plan",async()=>{let Z=(0,Fal.inflate)(Y,{to:"string"});X=await qal(Z)}):X=Y,_pe.appContext(u,p,`Downloaded ${z?"":"un"}compressed plan:`,X),eol(X)){_pe.appContext(u,p,"Plan found in-flight; continuing to poll");continue}else if(Xil(X))G=X;else if(Zil(X)){let{error:Z}=X;throw _pe.appContext(u,p,"Plan found failed with error:",Z),Z}else throw _pe.errorContext(u,p,"Downloaded plan with unexpected shape",X),new nt("Plan was of unrecognized shape")}else throw H<=0?(_pe.errorContext(u,p,"Planning exceeded maximum wait time; last received response was:",F),new nt("Planning exceeded maximum wait time")):(_pe.errorContext(u,p,"Plan received unexpected response",F),new nt("Plan received unexpected response"))}while(!G);return G})}finally{l()}},LD1=r=>r===0?2e3:Math.min(Math.round(1e3+r*.1),6e4),zal=(r,t,n,i,o,s,a,u)=>{_pe.appContext(u,"[createDeployRequestObject]","Creating deploy request");let{id:c,phasedDependencies:l,phasedNodeEdits:d,targetEnvironment:f,version:h}=r;if(h!==2)throw new nt(`Deployment is not supported for plan version '${h}'`);let A={...t},{oid:E,commit:v}=n,{clearTargetEnvironment:T,forceDeployment:w,workspaceIDOverride:N}=a,k=N??f,L=0;Object.values(d).forEach(H=>{L+=Object.keys(H).length}),A.steps=HWo(A.steps,d,u);let q={deployCommit:E,deployCommitMessage:v.message,environmentID:`${k}`,fromWorkspaceData:A,phasedDependencies:l,phasedNodeEdits:d,planID:c,stepsInRun:L,version:h,...T&&{clearTargetEnvironment:T},...w&&{forcedDeployment:w}},G=null;return i&&(G=Mmr(i)),new vWe({runDetails:q,userCredentials:o,parameters:G,origin:s})};var Qal=async(r,t)=>{let n="[watchWorkspaceStatus]",i=[],o;try{let{status:s,updatedAt:a,updatedBy:u}=await r.fetch();i.push({status:s,updatedAt:a,updatedBy:u});let p=s;o=r.listen(c=>{(c.type==="added"||c.type==="modified")&&c.value.status!==p&&(i.push({status:c.value.status,updatedAt:c.value.updatedAt,updatedBy:c.value.updatedBy}),p=c.value.status)})}catch(s){Je("PLAN").errorContext(t,n,"Error setting up workspace status listener:",s)}return{unsubscribe:o,workspaceStatusChangelog:i}};var jk1=yt(vul()),ES=yt(DYo()),Gk1=yt(odl()),Hk1=yt(adl());var udl=Pb({id:SR(),name:ld(),steps:Dze(N7([SR(),ld()])),subgraphs:Dze(N7([SR(),ld()]))}),dL1=Pb({jobCounter:SR(),name:ld(),includeSelector:ld(),excludeSelector:ld()}),fL1=Mr("JobV2",dL1);var hL1=Pb({jobs:RA(udl),locations:Ukc,macros:RA(Nq),stepTypes:imc,subgraphs:RA(VPe.omit({id:!0}))}),cdl=Pb({jobs:RA(l$.omit({jobCounter:!0})),locations:k3o,macros:RA(Nq.omit({macroCounter:!0})),stepTypes:RA(Ace),subgraphs:RA(VPe),defaultStorageMapping:ld(),version:SR()}),lgC=N7([hL1,cdl]),gL1=Mr("DataYaml V1",cdl),ldl=Pb({username:ld(),gitAccountId:ld()}),pdl=Mr("GitCredentials",ldl);var ddl=Pb({steps:kAc,stepTypes:RA(la(Ace.omit({id:!0}))),jobs:RA(la(l$.omit({id:!0}))),folders:RA(la(EWe)),macros:RA(la(Nq)).optional(),userConnections:RA(Nze()).optional(),locations:RA(Nze()).optional(),defaultStorageMapping:ld().nullable(),version:SR().optional(),packageNamespaces:RA(Nze()).optional(),packages:RA(Nze()).optional(),installedPackages:RA(la(mce)).optional(),platformKind:jh.optional()}),AL1=ddl.extend({installedPackages:RA(la(xme)).optional()}),mL1=Mr("WorkspaceData",ddl),fdl=Mr("WorkspaceDataFromGit",AL1);var KYo=yt(Tze());var WMr=class{client;constructor(t,n){this.client=D3(t,n)}Exists=async(t,n)=>await this.client.SecretExists({params:{context:t.EncodeContext(n),secretType:t.typeName}});Set=async(t,n,i)=>await this.client.SetSecret({secretValue:i.sensitiveValue},{params:{context:t.EncodeContext(n),secretType:t.typeName}});Delete=async(t,n)=>await this.client.DeleteSecret(void 0,{params:{context:t.EncodeContext(n),secretType:t.typeName}});Upgrade=async(t,n)=>await this.Exists(t,n)?(await this.client.UpgradeSecret(void 0,{params:{context:t.EncodeContext(n),secretType:t.typeName}}),!0):!1};var zd=class r{constructor(t){this.value=t}value;static representation="[REDACTED]";get sensitiveValue(){return this.value}toString(){return r.representation}toJSON(){return r.representation}[Symbol.for("nodejs.util.inspect.custom")](){return r.representation}},vgC=new zgr("tag:yaml.org,2002:str",{kind:"scalar",instanceOf:zd,represent:r=>r.toString()});var hdl=B.string().brand(Symbol("SantizedString"));function Adl(r){return!!r&&typeof r=="object"&&"orgId"in r&&typeof r.orgId=="string"}function mdl(r){return Adl(r)&&"userId"in r&&typeof r.userId=="string"}function yL1(r){return mdl(r)&&"workspaceId"in r&&typeof r.workspaceId=="string"}function bL1(r){if(!mdl(r)){let t=fv(Nb(r,"orgId","userId"),n=>typeof n);throw new nt(`Secret got an invalid context type at runtime (got: ${t}, expected orgId & userId) - cannot create name`)}}function EL1(r){if(!yL1(r)){let t=fv(Nb(r,"orgId","userId","workspaceId"),n=>typeof n);throw new nt(`Secret got an invalid context type at runtime (got: ${t}, expected orgId & userId & workspaceId) - cannot create name`)}}function CL1(r){if(!Adl(r)){let t=fv(Nb(r,"orgId"),n=>typeof n);throw new nt(`Secret got an invalid context type at runtime (got: ${t}, expected orgId) - cannot create name`)}}function SL1(r){return bL1(r),r}function vL1(r){return CL1(r),r}function gdl(r){return EL1(r),r}var TL1=/[^a-zA-Z0-9/-]/gu,_L1=r=>{let t="-".codePointAt(0).toString(16);return r.replaceAll("--",`--${t}---${t}-`).replaceAll(TL1,n=>`--${n.codePointAt(0).toString(16)}-`)},KMr=r=>hdl.parse(r.map(_L1).join("_")),YMr=(r,t)=>{if(r.secretNameFormat==="orgId"){let n=vL1(t);return KMr([n.orgId,r.typeName])}else if(r.secretNameFormat==="orgIdAndUserId"){let n=SL1(t);return KMr([n.orgId,n.userId,r.typeName])}else if(r.secretNameFormat==="orgIdAndWorkspaceId"){let n=gdl(t);return KMr([n.orgId,n.workspaceId,r.typeName])}else if(r.secretNameFormat==="orgIdAndWorkspaceIdAndUserId"){let n=gdl(t);return KMr([n.orgId,n.workspaceId,n.userId,r.typeName])}else{let n=r.secretNameFormat;throw new nt(`Got an unknown secret name format "${n}" - cannot create name`)}},IL1=r=>{let t=/\-\-([0-9a-f]+)\-/g,n=r.replaceAll(t,i=>String.fromCodePoint(parseInt(i.replaceAll("-",""),16)));if(n!==r)return n},JMr=r=>{let t=IL1(r);if(!(t===void 0||t.match(/[^a-zA-Z0-9/_-]/g)))return t};var ket=class{constructor(t){this.secretStore=t}secretStore;Get=async(t,n)=>{let i=await this.secretStore.Get(YMr(t,n));if(i===null)return null;let o=new zd(t.dataValidator.assert(JSON.parse(i.sensitiveValue)));return t.GetEntry(n,o)};Set=async(t,n,i)=>{let o=YMr(t,n),s=null,a=await this.secretStore.Get(o);a!==null&&(s=new zd(t.dataValidator.assert(JSON.parse(a.sensitiveValue))));let u=t.SetEntry(n,s,i);await this.secretStore.Set(o,new zd(JSON.stringify(u.sensitiveValue)))};Delete=async(t,n)=>{let i=YMr(t,n),o=await this.secretStore.Get(i);if(o===null)return;let s=new zd(t.dataValidator.assert(JSON.parse(o.sensitiveValue))),a=t.DeleteEntry(n,s);a===null?await this.secretStore.Delete(i):await this.secretStore.Set(i,new zd(JSON.stringify(a.sensitiveValue)))};Upgrade=async(t,n,i,o,s)=>{let a=await this.Get(t,n);if(!a)return;await this.Get(i,o)||await this.Set(i,o,new zd(s(a.sensitiveValue))),await this.Delete(t,n)}};var $Mr=class{backend;constructor(t){this.backend=new ket(t)}Exists=async(t,n)=>await this.backend.Get(t,n)!==null;Set=async(t,n,i)=>await this.backend.Set(t,n,i);Delete=async(t,n)=>await this.backend.Delete(t,n);Upgrade=async(t,n)=>{if(!await this.Exists(t,n))return!1;let i=t.UpgradeTarget;if(!i)throw new Vi("Cannot upgrade this secret type",`Secret type ${t.typeName} as no upgrade target`);return await this.backend.Upgrade(t,n,i,n,o=>o),!0}};var XMr=class{injectError=null;data={};InjectErrorIfNeeded=()=>{if(this.injectError!==null)throw this.injectError};Get=async t=>{this.InjectErrorIfNeeded();let n=this.data[t];return n===void 0?null:new zd(n)};Set=async(t,n)=>{this.InjectErrorIfNeeded(),this.data[t]=n.sensitiveValue};Delete=async t=>{this.InjectErrorIfNeeded(),delete this.data[t]}};var S2e=yt(Mq());var kNt=S2e.Record({orgId:S2e.String}),qNt=S2e.Intersect(kNt,S2e.Record({userId:S2e.String})),ZMr=(r,t,n,i)=>({DecodeContext:o=>r.assert({[t]:o}),EncodeContext:o=>(r.assert(o),encodeURIComponent(o[t])),GetEntry:(o,s)=>{r.assert(o),n.assert(s.sensitiveValue);let a=s.sensitiveValue[o[t]];return a?new zd(i.assert(a)):null},SetEntry:(o,s,a)=>{r.assert(o);let u=s?ep(n.assert(s.sensitiveValue)):{};return u[o[t]]=i.assert(a.sensitiveValue),new zd(u)},DeleteEntry:(o,s)=>{r.assert(o),n.assert(s.sensitiveValue);let a=s?ep(n.assert(s.sensitiveValue)):{};return delete a[o[t]],typeof a=="object"&&(a===null||Object.keys(a).length===0)?null:a?new zd(a):null}}),ydl=(r,t,n)=>({DecodeContext:i=>r.assert({[t]:i}),EncodeContext:i=>(r.assert(i),encodeURIComponent(i[t])),GetEntry:(i,o)=>(r.assert(i),o),SetEntry:(i,o,s)=>(r.assert(i),n.assert(s.sensitiveValue),s),DeleteEntry:(i,o)=>(r.assert(i),n.assert(o.sensitiveValue),null)});var qet=yt(Mq());var bdl=qet.Record({gitAccountId:qet.String}),RL1=qet.Intersect(qNt,bdl),OL1=TM("SecretContextGitAccount",bdl),Edl=(r,t)=>ZMr(OL1,"gitAccountId",r,t);var Fet=yt(Mq());var Cdl=Fet.Record({workspaceId:Fet.String}),wL1=Fet.Intersect(qNt,Cdl),Sdl=TM("SecretContextWorkspace",Cdl),a2=(r,t)=>ZMr(Sdl,"workspaceId",r,t),v2e=r=>ydl(Sdl,"workspaceId",r);var ML1=et.object({clientID:et.string(),clientSecret:et.string()}),kYo=Mr("BigQueryOAuth",ML1),Uet={typeName:"BigQueryOAuth",dataValidator:kYo,entryValidator:kYo,secretNameFormat:"orgIdAndWorkspaceId",...v2e(kYo),UpgradeTarget:void 0};var _dl=et.object({access_token:et.string(),refresh_token:et.string()}),xL1=et.record(et.string(),_dl),vdl=Mr("BigQueryOAuthTokens",xL1),Tdl=Mr("BigQueryOAuthTokensEntry",_dl),zet={typeName:"BigQueryOAuthTokens",dataValidator:vdl,entryValidator:Tdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(vdl,Tdl),UpgradeTarget:void 0};var qYo=et.object({serviceAccountKey:et.string()}),PL1=et.record(qYo),Idl=Mr("BigQueryServiceAccount",PL1),Rdl=Mr("BigQueryServiceAccountEntry",qYo),Qet={typeName:"BigQueryServiceAccount",dataValidator:Idl,entryValidator:Rdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Idl,Rdl),UpgradeTarget:void 0};var NL1=et.object({clientID:et.string(),clientSecret:et.string()}),FYo=Mr("DatabricksOAuthM2M",NL1),e6e={typeName:"DatabricksOAuthM2M",dataValidator:FYo,entryValidator:FYo,secretNameFormat:"orgIdAndWorkspaceId",...v2e(FYo),UpgradeTarget:void 0};var DL1=et.object({clientId:et.string(),clientSecret:et.string()}),UYo=Mr("DatabricksOAuthU2M",DL1),jet={typeName:"DatabricksOAuthU2M",dataValidator:UYo,entryValidator:UYo,secretNameFormat:"orgIdAndWorkspaceId",...v2e(UYo),UpgradeTarget:void 0};var BL1=RA(ld(),ld()),Odl=Mr("GitTokens",BL1),wdl=Mr("string",ld()),exr={typeName:"GitTokens",dataValidator:Odl,entryValidator:wdl,secretNameFormat:"orgIdAndUserId",...Edl(Odl,wdl),UpgradeTarget:void 0};var zYo=et.object({token:et.string()}),LL1=et.record(zYo),Mdl=Mr("DatabricksCredentials",LL1),xdl=Mr("DatabricksCredentialsEntry",zYo),Get={typeName:"DatabricksCredentials",dataValidator:Mdl,entryValidator:xdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Mdl,xdl),UpgradeTarget:void 0};var Ddl=et.object({clientID:et.string(),clientSecret:et.string()}),kL1=et.record(Ddl),Pdl=Mr("FabricCredentials",kL1),Ndl=Mr("FabricCredentialsEntry",Ddl),QYo={typeName:"FabricCredentials",dataValidator:Pdl,entryValidator:Ndl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Pdl,Ndl),UpgradeTarget:void 0};var jYo=B.object({password:B.string()}),qL1=B.record(B.string(),jYo),txr=Mr("SnowflakeCredentials",qL1),rxr=Mr("SnowflakeCredentialsEntry",jYo),FNt={typeName:"SnowflakeCredentialsV2",dataValidator:txr,entryValidator:rxr,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(txr,rxr),UpgradeTarget:void 0},Het={typeName:"SnowflakeCredentials",dataValidator:txr,entryValidator:rxr,secretNameFormat:"orgIdAndUserId",...a2(txr,rxr),UpgradeTarget:FNt};var GYo=B.object({key:B.string(),passphrase:B.string().nullable().optional(),savePassphrase:B.boolean().optional()}).superRefine((r,t)=>{if((r.passphrase===void 0||r.passphrase===null)&&r.savePassphrase!==void 0)return t.addIssue({code:B.ZodIssueCode.custom,message:"Can't have passphrase unset and savePassphrase set at the same time",fatal:!0,path:["passphrase"]}),B.NEVER;r.savePassphrase||(delete r.passphrase,delete r.savePassphrase)}),FL1=B.record(B.string(),GYo),nxr=Mr("SnowflakeKeyPairSecret",FL1),ixr=Mr("SnowflakeKeyPairEntry",GYo),Bdl="SnowflakeKeyPair",UL1=Bdl+"V2",UNt={typeName:UL1,dataValidator:nxr,entryValidator:ixr,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(nxr,ixr),UpgradeTarget:void 0},Vet={typeName:Bdl,dataValidator:nxr,entryValidator:ixr,secretNameFormat:"orgIdAndUserId",...a2(nxr,ixr),UpgradeTarget:UNt};var kdl=B.object({clientId:B.string(),clientSecret:B.string()}),zL1=B.record(B.string(),kdl),Ldl=Mr("SnowflakeOAuthForWorkspaces",zL1),zNt=Mr("SnowflakeOAuth",kdl),QNt={typeName:"SnowflakeOAuthV2",dataValidator:zNt,entryValidator:zNt,secretNameFormat:"orgIdAndWorkspaceId",...v2e(zNt),UpgradeTarget:void 0},Wet={typeName:"SnowflakeOAuth",dataValidator:Ldl,entryValidator:zNt,secretNameFormat:"orgId",...a2(Ldl,zNt),UpgradeTarget:QNt};var HYo=et.object({access_token:et.string(),refresh_token:et.string()}),QL1=et.record(et.string(),HYo),oxr=Mr("SnowflakeTokens",QL1),sxr=Mr("SnowflakeTokensEntry",HYo),t6e={typeName:"SnowflakeTokensV2",dataValidator:oxr,entryValidator:sxr,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(oxr,sxr),UpgradeTarget:void 0},xpe={typeName:"SnowflakeTokens",dataValidator:oxr,entryValidator:sxr,secretNameFormat:"orgIdAndUserId",...a2(oxr,sxr),UpgradeTarget:t6e};var axr=TM("SecretContextOrg",kNt),qdl=r=>({DecodeContext:t=>({}),EncodeContext:t=>(axr.assert(t),"_"),GetEntry:(t,n)=>(axr.assert(t),n),SetEntry:(t,n,i)=>(axr.assert(t),r.assert(i.sensitiveValue),i),DeleteEntry:(t,n)=>(axr.assert(t),r.assert(n.sensitiveValue),null)});var jL1=et.object({clientSecret:et.string()}),VYo=Mr("SSOClientSecret",jL1),GL1={typeName:"SSOClientSecret",dataValidator:VYo,entryValidator:VYo,secretNameFormat:"orgId",...qdl(VYo),UpgradeTarget:void 0};var zdl=et.object({access_token:et.string(),refresh_token:et.string()}),HL1=et.record(et.string(),zdl),Fdl=Mr("DatabricksOAuthU2MTokens",HL1),Udl=Mr("DatabricksOAuthU2MTokensEntry",zdl),T2e={typeName:"DatabricksOAuthU2MTokens",dataValidator:Fdl,entryValidator:Udl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Fdl,Udl),UpgradeTarget:void 0};var VL1={[exr.typeName]:exr,[Het.typeName]:Het,[FNt.typeName]:FNt,[Vet.typeName]:Vet,[UNt.typeName]:UNt,[Wet.typeName]:Wet,[QNt.typeName]:QNt,[xpe.typeName]:xpe,[t6e.typeName]:t6e,[Get.typeName]:Get,[jet.typeName]:jet,[T2e.typeName]:T2e,[e6e.typeName]:e6e,[QYo.typeName]:QYo,[Qet.typeName]:Qet,[Uet.typeName]:Uet,[zet.typeName]:zet};var Gdl=et.object({clientID:et.string(),clientSecret:et.string()}),WL1=et.record(Gdl),Qdl=Mr("FabricCredentials",WL1),jdl=Mr("FabricCredentialsEntry",Gdl),WYo={typeName:"FabricCredentials",dataValidator:Qdl,entryValidator:jdl,secretNameFormat:"orgIdAndWorkspaceIdAndUserId",...a2(Qdl,jdl),UpgradeTarget:void 0};var YL1=Je("SECRETS"),YYo=(0,KYo.default)(async()=>(YL1.app("Selected Memory secret store."),new XMr)),_mC=(0,KYo.default)(async()=>Hg().isTest?new $Mr(await YYo()):new WMr(Db(),Xc.resolveAuthToken));var JL1="Environment",_2e=Pb({name:ld(),id:ld(),type:Fj(JL1),fileVersion:SR().int(),mappingDefinitions:zkc}).strict(),Hdl=Mr("Environment File",_2e),$L1=RA(_2e),Vdl=Mr("Environment File Dictionary",$L1);var XL1="Job",WH=l$.pick({excludeSelector:!0,includeSelector:!0,name:!0}).extend({id:SWe,type:et.literal(XL1),fileVersion:et.literal(1)}).strict(),Wdl=Mr("GitJob",WH),tyC=et.record(WH),Kdl=Mr("Job Files with Passthrough",et.record(la(WH)));var ZL1="Macro",TZ=Nq.pick({macroString:!0}).extend({id:et.string(),name:et.string(),packageInfo:gce.optional(),type:et.literal(ZL1),fileVersion:et.literal(1)}),Ydl=Mr("GitMacro",TZ),ek1=et.record(la(TZ)),Jdl=Mr("MacroDictionary",ek1);var tk1="Node",rk1=r=>et.object({name:et.string(),id:et.string(),fileVersion:et.number().int(),type:et.literal(tk1),operation:r?I3o:_3o}).strict(),_Z=rk1(!1),JYo=Mr("Node File",_Z),nk1=et.record(_Z),$dl=Mr("Git Nodes",la(nk1));var ik1="NodeType",Xdl=et.union([la(AWe.omit({templates:!0})),la(N3o.omit({templates:!0}))]),uxr=la(mWe.pick({isDisabled:!0,name:!0,id:!0}).extend({metadata:Xdl,fileVersion:et.union([et.literal(1),et.literal(2)]).default(1),type:et.literal(ik1)})),$Yo=Mr("NodeType Unparsed Metadata",Xdl),XYo=Mr("NodeType Definition file",uxr),ZYo=et.object({nodeType:uxr,create:et.string().optional(),run:et.string().optional()}).strict(),ok1=et.record(ZYo),Zdl=Mr("NodeTypesDictionary",ok1);var cxr=1,lxr="Subgraph",IZ=EWe.omit({folderCounter:!0,version:!0}).extend({type:B.literal(lxr),fileVersion:B.literal(cxr),id:B.string()}).strict(),eJo=Mr("Subgraph (YAML)",la(IZ)),e0l=Mr("Subgraph (YAML)",IZ);var ak1=Je("GIT");var uk1=r=>{let t={},n=$dl.assert(r);return Object.values(n).forEach(i=>{let{operation:o,id:s}=i;t[s]={operation:o}}),t},ck1=r=>{let t={};return Object.entries(r).forEach(n=>{let[i,o]=n,s=eJo.assert(o,{errorMessage:`Subgraph ${i} is invalid`}),{type:a,id:u,fileVersion:p,...c}=s,l=sTt.assert({id:u,...c});t[u]=l}),t},lk1=r=>{let t={},n=Kdl.assert(r);return Object.values(n).forEach(i=>{let{id:o,fileVersion:s,type:a,...u}=i;t[o]={...u,jobCounter:Number(o),id:Number(o),version:c$}}),t},pk1=r=>{let t={},n=Jdl.assert(r);return Object.values(n).forEach(i=>{let{id:o,fileVersion:s,type:a,...u}=i;t[o]={...u,id:o,version:gh}}),t},tJo=r=>{let{nodeType:t,create:n,run:i}=r,{id:o,type:s,fileVersion:a,...u}=t,{defaultStorageLocation:p}=u.metadata,c=p??null,l=a??gWe;return D3o.assert({...u,version:l,metadata:{...u.metadata,defaultStorageLocation:c,templates:{create:{templateString:n||""},run:{templateString:i||""}}},id:o})},dk1=(r,t)=>{let n={},i=Zdl.assert(t);return Object.values(i).forEach(o=>{n[o.nodeType.id]=tJo(o)}),n.Source=lNe(r).Source,n},fk1=(r,t)=>{let n={};for(let i of t)n[i]={mappingDefinitions:{}};if(r){let i=Vdl.assert(r);Object.values(i).forEach(o=>{let{mappingDefinitions:s,id:a}=o;Object.entries(s).forEach(([u,p])=>{let c=n[u];c||(c={mappingDefinitions:{}},n[u]=c),c.mappingDefinitions[a]=p})})}return n},hk1=r=>r?Object.fromEntries(Object.entries(r).map(([t,n])=>[t,{releaseID:n.releaseID,packageID:n.packageID,config:n.config}])):{},rJo=(r,t,n)=>{try{let{nodes:i,subgraphs:o,jobs:s,macros:a,nodeTypes:u,environments:p,packages:c,locationManifest:l,dataYML:d}=r;return{defaultStorageMapping:l.defaultStorageMapping??d.defaultStorageMapping,steps:uk1(i),stepTypes:dk1(t,u),folders:ck1(o),jobs:lk1(s),locations:fk1(p,l.locations),macros:pk1(a),installedPackages:hk1(c),platformKind:t}}catch(i){throw ak1.errorContext(n,"Failed to validate and convert the Repo to AllWorkspaceData.",i),i}},t0l=()=>({nodes:{},nodeTypes:{},macros:{},jobs:{},subgraphs:{},environments:{},dataYML:{fileVersion:3,defaultStorageMapping:null},locationManifest:{defaultStorageMapping:null,locations:[],fileVersion:1}});var JH=yt(DYo()),UF=yt(require("path"));var r6e=class extends nt{code;result;constructor(t,n,i=400){super(t,"Parsing error occurred"),this.result=n,this.code=i}statusCode(){return this.code}get parsingResult(){return this.result}get failureDetails(){return`${this.message}: ${this.result.length} error(s) in these file(s) ${this.result.map(t=>t.fileName).join(", ")}`}};var r0l=(r,t)=>typeof r=="object"&&r!==null&&r.code===t;function pxr(r,t,n){let i=[],o=new Map;for(let s of Object.values(n))s.nodeType&&o.set(s.nodeType.id,s.nodeType.fileVersion);for(let[s,a]of r){let u=t[s],p=u?.operation.sqlType,c=o.get(p??"");if(!u||!p||!c)continue;let l=c===2;l&&a!==".sql"?i.push({path:`nodes.${s}.outOfBandEdit`,message:`Node "${u.name}" (${u.operation.locationName}) uses a .yml file but its node type "${p}" requires a .sql file (v2 node type)`}):!l&&a!==".yml"&&i.push({path:`nodes.${s}.outOfBandEdit`,message:`Node "${u.name}" (${u.operation.locationName}) uses a .sql file but its node type "${p}" requires a .yml file (v1 node type)`})}return i}function n0l(r){let t=[];for(let[n,i]of r)if(i.size>1){let o=[...i].join(", ");t.push({path:`nodes.${n}.outOfBandEdit`,message:`Duplicate node ID "${n}": Node IDs must be unique within a workspace. Found in: ${o}`})}return t}function i0l(r){let t=[];for(let[n,i]of Object.entries(r)){let o=i.operation?.metadata?.columns;if(!Array.isArray(o))continue;let s=new Map,a=new Set;for(let c of o){let l=c?.columnReference?.columnCounter;if(l.length===0){t.push({path:`nodes.${n}.outOfBandEdit`,message:`Column ID is empty for column "${c.name}" in node "${i.name}"`});continue}let d=s.get(l);d?(d.push(c.name),a.add(l)):s.set(l,[c.name])}if(a.size===0)continue;let u=typeof i.operation?.locationName=="string"?i.operation.locationName:"",p=u?` (${u})`:"";for(let c of a){let l=s.get(c);t.push({path:`nodes.${n}.outOfBandEdit`,message:`Duplicate column ID "${c}" in node "${i.name}"${p}: Column IDs must be unique within a node. Found columns (sharing column ID "${c}"): ${l?.join(", ")??"<ERROR reading column names>"}`})}}return t}var KH=(d=>(d.node="nodes",d.subgraph="subgraphs",d.job="jobs",d.environment="environments",d.dataYML="dataYML",d.packagesV1="packagesV1",d.packages="packages",d.macro="macros",d.nodeType="nodeTypes",d.jinja="jinja",d.locations="locations",d))(KH||{}),n6e="packagesV1.yml",lO="data.yml",I2e="locations.yml";var jNt="create.sql.j2",GNt="run.sql.j2";var YH=yt(require("path"));var ex=(r,t,n,i=[".yml"])=>{let o=YH.default.normalize(t),s=r?YH.default.join(r,n):n;return o.startsWith(s)&&i.some(a=>t.endsWith(a))},Ket=(r,t="")=>[ex(t,r,"nodeTypes",[".yml",".sql.j2"]),ex(t,r,"nodes",[".yml",".sql"]),ex(t,r,"environments"),ex(t,r,"subgraphs"),ex(t,r,"jobs"),ex(t,r,"macros"),ex(t,r,"packages"),YH.default.normalize(r)===YH.default.join(t,lO),YH.default.normalize(r)===YH.default.join(t,n6e),YH.default.normalize(r)===YH.default.join(t,I2e)].some(n=>!!n),nJo=r=>!!r.promises.writeFiles&&!!r.promises.readFiles,HNt=(r,t)=>T9o(r,"",t.operation),dxr=(r,t,n)=>YH.default.normalize(r)===YH.default.join(t,n),o0l=r=>{!r.id&&r.folderCounter!=null&&(r.id=String(r.folderCounter))};var s0l=(r,t,n)=>{Bm("RUNNER",!!r[t],`Step ${t} doesn't exist`);let i=r[t].operation.name,o=gk1(i,!1);return n&&(o.runExecutionSequenceID=n),o},gk1=(r,t)=>({dataResult:null,runState:"waiting",stepRunState:"None",queryResultSequence:{name:r,queryResults:[],isRunning:t}});var Ak1=Je("VERSION_CONTROL_ACTIONS"),mk1=(r,t)=>Object.fromEntries(Object.entries(i6e(r)).map(([n,i])=>(i[t]=i.id,delete i.id,[n,i]))),o6e=(r,t,n,i,o)=>{let s=[],a={},u=[];r.forEach(E=>{let{filePath:v,fileData:T}=E;try{let N=Sp(`Node ${v}`,T).steps;for(let k in N){let L=g1(k,N,"unserializedNodes"),{stepCounter:q}=L;a[q]&&u.push(q),a[q]=L}}catch(w){let k=v.split("/").pop();s.push({fileName:k,type:"nodes",parsingError:w.errorString})}}),u.length&&hh("GIT",!1,n,`Encountered node files using the same stepCounter on commit: ${i||"Current Live Files"}`,"nodeIDs: ",u);let p={environments:{},locations:{},subgraphs:{},jobs:{},macros:{},stepTypes:{},defaultStorageMapping:"",projects:{},packages:{},installedPackages:{},platformKind:o};if(t)try{p={...p,...Sp(lO,t)}}catch(E){Ak1.error("(getReduxStateFromYaml) failed to parse data.yml",E),s.push({fileName:"data.yml",type:"otherData",parsingError:E.errorString})}if(s.length)throw new r6e("Error parsing repo files",s);let c=mk1(p.jobs,"jobCounter"),l=kEr(i6e(p.subgraphs)),d=Object.fromEntries(Object.keys(p.projects).map(E=>[E,p.projects[E]])),f=Object.fromEntries(Object.keys(a).map(E=>[E,s0l(a,E)])),{mappings:h,defaultStorageMapping:A}=bk1(p);return{jobs:c,steps:a,folders:l,mappings:h,runResults:f,packageNamespaces:d,defaultStorageMapping:A,locations:h,macros:i6e(p.macros),stepTypes:i6e(p.stepTypes),packages:i6e(p.packages),installedPackages:p.installedPackages,platformKind:o}},lbC=C3o.extend({mappings:RA(ld(),B3o),deployedWorkspaces:RA(Pb({})),version:Fj(0)}).strict(),yk1=(r,t)=>{let n={};return Object.keys(r).forEach(i=>{let o=r[i].locationName;n[o]||(n[o]=Vkc()),Object.values(t).forEach(s=>{let a=s.mappings?.[i]??null;a?n[o].mappingDefinitions[s.id]={database:a.database,schema:a.schema}:n[o].mappingDefinitions[s.id]=W6o()})}),n},bk1=r=>{let t=r.environments||{},n=i6e(t),i=r.locations||{},o={},s=r.defaultStorageMapping??null;if(Object.keys(i).length)if(Gkc(i)){let a=i6e(i);o=yk1(a,n),s=Hkc(i)}else o=i;return{mappings:o,defaultStorageMapping:s}},i6e=r=>{let t={};for(let n in r){let i=r[n].id;if(!i){console.warn(`Missing id for entity ${n}!`);continue}t[i]=r[n]}return t};var VNt=et.object({defaultStorageMapping:et.string().nullable(),locations:et.array(et.string()),fileVersion:et.literal(1)}),a0l=Mr("LocationsFile",la(VNt));var Ck1=B.object({name:B.string()}).strict(),u0l=Ri.merge(Ck1).strict();var Sk1=B.union([B.object({seconds:B.number(),nanoseconds:B.number()}),B.object({_seconds:B.number(),_nanoseconds:B.number()})]),c0l=B.union([Sk1,B.date()]);var l0l=(o=>(o.adding="adding",o.added="added",o.removing="removing",o.error="error",o))(l0l||{}),vk1=B.object({filePath:B.string()}),Tk1=B.object({commit:B.string()}),p0l=Ri.extend({version:B.string(),versionInfo:B.union([Tk1,vk1]),status:B.nativeEnum(l0l),addedBy:B.string(),createdAt:c0l.nullable(),manifest:B.record(B.record(B.object({id:B.string(),name:B.string()})))}).strict();var d0l=B.object({packages:B.union([B.record(p0l),B.object({})]),packageNamespaces:B.union([B.record(u0l),B.object({})]),fileVersion:B.number()}).strict();var fxr=et.object({defaultStorageMapping:et.string().nullable().default(null),fileVersion:et.number().int(),platformKind:jh.optional()}),f0l=Mr("DataYmlV2",la(fxr)),_k1=et.object({dataYML:la(fxr),locationManifest:la(VNt).default({defaultStorageMapping:null,locations:[],fileVersion:1}),nodes:et.record(la(_Z)),nodeTypes:et.record(la(ZYo)),environments:et.record(la(_2e)),subgraphs:et.record(la(IZ)),jobs:et.record(la(WH)),macros:et.record(la(TZ)),packagesV1:la(d0l).optional(),packages:et.record(la(tbe)).optional()}),Ik1=(r,t)=>(r.issues=r.issues.map(n=>{if(n.path[0]==="nodes"){let o=n.path[1]||"",s=t.nodes[o];if(s?.name)return{...n,message:`Problem with node "${s.name}": ${n.message}`}}return n}),r),h0l=Mr("CoalesceRepo",_k1,[Ik1]);var iJo=yt(require("path"));var Rk1=Je("GIT"),hxr=async(r,t,n)=>{let{fileData:i,filePath:o}=r,{refs:s,topLevelAnnotations:a,errorMessage:u}=await t.extractRefs(i,n,o,{skipCache:!0});u&&Rk1.warn(`Error extracting refs from ${o}: ${u}`);let p=NWo(a);if(p.errorMessage)throw new Error(`Failed to extract metadata from ${o}: ${p.errorMessage}`);if(!p.id)throw new Error(`Missing required annotation @id in ${o}`);let l=iJo.default.basename(o,".sql").split("-"),d=l[0]??"",f=l.slice(1).join("-"),h={name:f,locationName:d,type:"sql",sqlType:p.nodeType,description:p.description,database:"",schema:"",version:1,materializationType:p.materializationType,isMultisource:!1,deployEnabled:!0,config:{},metadata:{sourceMapping:[{name:f,join:{joinCondition:""},dependencies:s,noLinkRefs:[],aliases:{},customSQL:{customSQL:i}}],columns:[],appliedNodeTests:[],enabledColumnTestIDs:[]}};return{id:p.id,name:f,type:"Node",fileVersion:1,operation:h}},g0l=async(r,t,n,i,o,s)=>{let{filePath:a}=r,{unknownFileList:u,nodeSourceExtensions:p,nodeSourceFiles:c}=s;if(!ex(t,a,"nodes",[".sql"])){u.push(a);return}let l=await hxr(r,i,o),d=iJo.default.basename(a),f=c.get(l.id)??new Set;f.add(d),c.set(l.id,f),!n.nodes[l.id]&&(n.nodes[l.id]=l,p.set(l.id,".sql"))};var pO=Je("GIT");var oJo=(r,t="")=>({filePath:r,fileData:t,type:"File"}),Yet=async(r,t,n,i=!0)=>{let o="",s=0,a;if(t)try{await JH.log({...r,ref:t})}catch(u){throw pO.error("Error getting data.yaml info from commit",u),u}try{o=t?await A0l(r,t,lO,{}):(await Jet(r,r.dir,lO)).fileData;let u=Sp(lO,o);s=Number(u?.version??u?.fileVersion)||0;let p=u?.platformKind;p?a=p:a=i?n:"snowflake"}catch(u){return pO.error("Error getting data.yaml info from commit",u),0}try{uNt.checkPlatformMismatch(n,a)}catch(u){throw pO.error("Error platform mismatch:",u),u}return s};var A0l=(r,t,n,i)=>{let o={...r,oid:t,filepath:n,cache:i??void 0};return JH.readBlob(o).then(({blob:s})=>Buffer.from(s).toString("utf-8")).catch(s=>{throw new Error(`Error reading file ${n} from commit ${t}: ${s.toString()}`)})};var WNt=async(r,t,n)=>{let i="[ReadAllFilesFromCommit]";try{let s=(await JH.readTree({...r,oid:t})).oid;return JH.walk({...r,trees:[JH.TREE({ref:s})],map:async(a,u)=>{let p=oJo(a);if(u[0])try{let c=await u[0].content();c&&typeof c=="object"?p.fileData=Buffer.from(c).toString("utf8"):p.type="Directory"}catch(c){if(r0l(c,"NotFoundError"))return pO.infoContext(n,`${i}: skipping file ${a}: blob missing due to partial clone filtering (blob:limit)`),null;throw c}return p}})}catch(o){throw pO.errorContext(n,`${i} commit ${t}. An error occurred: `,o),o}};var Jet=async(r,t,n)=>{try{return await m0l(r,t,n)}catch{return{...oJo(n),exists:!1}}},m0l=async(r,t,n)=>{let i=UF.default.join(t,n),o=await r.fs.promises.readFile(i),s=new TextDecoder("utf-8").decode(o);return{...oJo(n,s),exists:!0}},Ok1=async(r,t)=>{if(nJo(r.fs))return(await r.fs.promises.readFiles(t,{encoding:"utf8"})).map((i,o)=>({fileData:i,filePath:t[o],exists:!0,type:"File"}));{let n=t.map(i=>async()=>await Jet(r,"",i));return await dce(n,8)}},y0l=async(r,t)=>{let n=(await r.fs.promises.readdir(r.dir)).map(o=>UF.default.join(r.dir,o)),i=[];for(;n.length>0;){let o=n.pop();if(o&&!o.includes(".git")){let s=await r.fs.promises.stat(o);if(s.isFile()&&(!t||t(o)))i.push({filePath:o,size:s.size});else{let a=(await r.fs.promises.readdir(o)).map(u=>UF.default.join(o,u));n.push(...a)}}}return i},Axr=async r=>{let t=await y0l(r);return await Ok1(r,t.map(n=>n.filePath))},b0l=r=>{let n=UF.default.normalize(r).split(`nodeTypes${UF.default.sep}`),[i,o]=n[1].split(UF.default.sep);return{nodeTypeID:i,fileName:o}},wk1=(r,t,n,i,o,s,a)=>{if(ex(n,r.filePath,s)){let u=t.id;i[a][u]=t}else o.push(r.filePath)},Mk1=r=>{r&&r.operation&&(r.operation.description??="")},xk1=(r,t,n,i,o)=>{let{unknownFileList:s,nodeSourceExtensions:a,nodeSourceFiles:u}=o,{fileData:p,filePath:c}=r,l=Sp(c,p),{type:d}=l,f=(h,A)=>wk1(r,l,t,n,s,h,A);switch(d){case"Node":if(ex(t,c,"nodes")){let A=l.id,E=UF.default.basename(c),v=u.get(A)??new Set;v.add(E),u.set(A,v),Mk1(l),n.nodes[A]=l,a.set(A,".yml")}else s.push(c);break;case"NodeType":let{nodeTypeID:h}=b0l(c);i[h]||(i[h]={}),i[h].nodeType=l;break;case"Environment":f("environments","environments");break;case"Job":f("jobs","jobs");break;case"Macro":f("macros","macros");break;case"Subgraph":o0l(l),f("subgraphs","subgraphs");break;case"Package":if(ex(t,c,"packages")){let{name:A,id:E}=l;pO.info(`HandleCoalesceYamlFile: using package alias "${A}" for package with id "${E}"`),n.packages||(n.packages={}),n.packages[A]=l}else s.push(c);break;default:dxr(c,t,lO)?n.dataYML=l:dxr(c,t,n6e)?n.packagesV1=l:dxr(c,t,I2e)?n.locationManifest=l:s.push(c);break}},Pk1=(r,t,n)=>{let{fileData:i,filePath:o}=r,{nodeTypeID:s,fileName:a}=b0l(o);switch(t[s]||(t[s]={}),a){case jNt:t[s].create=i;break;case GNt:t[s].run=i;break;default:n.push(o)}},Nk1=async(r,t,n,i,o,s)=>{let a=t0l(),u=[],p={},c={unknownFileList:[],nodeSourceExtensions:new Map,nodeSourceFiles:new Map};for(let l of r)try{let{filePath:d}=l;d.endsWith(".yml")?xk1(l,n,a,p,c):d.endsWith(".sql.j2")?Pk1(l,p,c.unknownFileList):d.endsWith(".sql")?await g0l(l,n,a,i,o,c):pO.debugContext(t,`Ignoring file ${d} as it is using an extension unused by Coalesce`)}catch(d){if(pO.errorContext(t,`Error parsing file ${n}/${l?.filePath}: `,d,"File data: ",l?.fileData),Ket(l.filePath,n)){let f=yg(d),A=UF.default.normalize(l.filePath).split(UF.default.sep),v=A.length<2?"otherData":A[0]??"otherData",T=v==="nodeTypes"?`${A[A.length-2]}${UF.default.sep}${A[A.length-1]}`:A.pop();if(u.push({fileName:T,type:v,parsingError:f.message}),s){let w=UF.default.extname(l.filePath),N=w===".sql"||w===".yml"?w:".unknown";s({filePath:l.filePath,fileName:T,type:v,extension:N,message:f.message})}}}if(u.length&&!s)throw new r6e("Error parsing repo files",u);return a.nodeTypes=p,{repo:a,auditContext:c,parsingErrors:u}},E0l=async(r,t,n,i,o="",s,a,u,p={})=>{let c=t?"":o,{repo:l,auditContext:d,parsingErrors:f}=await Nk1(r,n,c,s,a,u);pO.infoContext(n,"GetRepoFromFileReads Patching nodes collection");for(let[h,A]of Object.entries(l.nodes))HNt(h,{operation:A.operation});if(p.onAuditContext?.(d),i){d.unknownFileList.length&&pO.infoContext(n,"Found some files in unexpected places while reading repository files",d.unknownFileList);let h=[...pxr(d.nodeSourceExtensions,l.nodes,l.nodeTypes),...n0l(d.nodeSourceFiles),...i0l(l.nodes)];if(h.length&&!p.suppressOutOfBandThrow)throw new FP(`Out-of-band editing issues detected for commit: ${t||"Current Live Files"}`,new r$(l,h));return f.length?l:h0l.assert(l)}return l},Dk1=async(r,t,n)=>{let i=[];try{i=await r.fs.promises.readdir(`${r.dir}/nodes`)}catch(p){pO.errorContext(n,"Error during GetAllWorkspaceDataFromFileSystemDirectory: ",p)}let o=i.map(p=>Ah(`file: ${p}`,n,"GIT",async()=>await Jet(r,`${r.dir}/nodes`,p))),s=await Promise.all(o),{steps:a}=o6e(s,"",n,null,t),u;try{let{fileData:p}=await Ah("PromiseifiedReadFile data.yml",n,"GIT",()=>m0l(r,r.dir,lO)),{folders:c,jobs:l,macros:d,stepTypes:f,mappings:h,defaultStorageMapping:A,packageNamespaces:E,packages:v,installedPackages:T}=o6e([],p,n,null,t);u={steps:sJo(a),jobs:l,folders:c,stepTypes:f,locations:h,packages:v,packageNamespaces:E,defaultStorageMapping:A,macros:d,installedPackages:T||{},platformKind:t}}catch(p){if(pO.errorContext(n,"Error during GetAllWorkspaceDataFromFileSystemDirectory: ",p),p.message.startsWith("Failed to parse"))throw p;u={...d$e(t),steps:a}}pO.infoContext(n,"GetAllWorkspaceDataFromFileSystemDirectoryOld Patching nodes collection");for(let[p,c]of Object.entries(u.steps))HNt(p,{operation:c.operation});return u},C0l=async(r,t,n)=>{try{pO.infoContext(n,"Hydrating SQL dependencies for .sql files");let i=await Q4t(r.steps,r.stepTypes,r.platformKind,t,void 0);return{...r,steps:i}}catch(i){return pO.warnContext(n,"Error hydrating SQL dependencies:",i),r}},Bk1=(r,t,n,i,o,s,a={})=>Ah("GetAllWorkspaceDataFromFileSystemDirectory",n,"GIT",async()=>{if(await Yet(r,null,t)<3)return await Dk1(r,t,n);{let p=await Axr(r),c=await E0l(p,null,n,i,r.dir,o,t,s,a),l=rJo(c,t,n);return await C0l(l,o,n)}}),Lk1=async(r,t,n,i)=>{let o=r.find(u=>u.filePath===lO),s=r.filter(u=>u.filePath.includes("nodes/")),a;if(o){let u=o6e(s,o?.fileData,n,i,t);a={...u,locations:u.mappings,platformKind:t}}else{let{steps:u}=o6e(s,"",n,i,t);a={...d$e(t),steps:sJo(u)}}pO.infoContext(n,"GetAllWorkspaceDataFromGitCommitInternalOld Patching nodes collection");for(let[u,p]of Object.entries(a.steps))HNt(u,{operation:p.operation});return a},kk1=async(r,t,n,i,o,s,a,u={})=>{let p=await Yet(r,t,n),c=await Ah(`GetAllWorkspaceDataFromGitCommitInternal::ReadAllFilesFromCommit ${t}`,i,"GIT",()=>WNt(r,t,i));if(p<3)return await Lk1(c,n,i,t);{let l=await Ah(`GetAllWorkspaceDataFromGitCommitInternal::GetRepoFromFileReads ${t}`,i,"GIT",()=>E0l(c,t,i,o,r.dir,s,n,a,u)),d=rJo(l,n,i);return await C0l(d,s,i)}},$et=async(r,t,n,i,o,s)=>{let a="GetAllWorkspaceDataFromGitCommit",u,p={onAuditContext:o.onAuditContext,suppressOutOfBandThrow:o.suppressOutOfBandThrow};if(t?u=await Ah(`${a} for commit: ${t}`,i||{},"GIT",()=>kk1(r,t,n,i,!!o.validateData,s,o.onFileLoadError,p),"info"):u=await Ah(`${a} when a commitOID does not exist`,i||{},"GIT",()=>Bk1(r,n,i,!!o.validateData,s,o.onFileLoadError,p),"info"),o.validateData){let c=fdl.validate(u);c.valid||pO.errorContext(i,`Content from commit ${t} was invalid. Errors: `,c.failureMessage)}return u};var aJo=Je("GIT"),Xet=async(r,t,n,i,o,s,a)=>{let u=await $et(r,t,n,o,i,s),p=u.installedPackages||{},c={};return Object.keys(p).length?(aJo.infoContext(o,"Attempting to hydrate from stored packages"),c=await cf(()=>kIt(p,a),3,aJo,o,{retryStrategy:{name:"backoff",base:1},logOnRetry:"Retrying to hydrate packages",logOnFailure:"Failed to hydrate packages"})):aJo.infoContext(o,"No packages to hydrate"),i.installPackageEntities?k5e(u,c):{...u,installedPackages:c}};var OEC=Je("STEPS");var XEC=Je("GIT");var r2C=new aL(20);var cJo="remotes/origin";var j2C=Je("GIT");var lJo=async(r,t,n=!1)=>{let i=await mxr(r,t,n);if(!i.length)throw`No commits are available in the git log of branch ${t}`;return i[0]};var pJo=r=>ES.currentBranch({...r}).catch(t=>{throw new Error(`Error retrieving branch information: ${t}`)});var mxr=async(r,t,n=!1,i=void 0)=>{pd(!!t,"(GitLog) expected to have target branch","GIT");let o=n?`${cJo}/${t}`:t;return ES.log({...r,ref:o,depth:i})};var sJo=r=>fv(r,t=>({operation:t.operation}));var G2C=Je("GIT");var Z2C=Je("GIT");var $k1=yt(mYe());var Vk1=["step","job","graph","subgraph","columnGraph","buildSettings","workspaceSettings","templateEditor","apps"],nCC=B.object({tabID:B.string(),tabType:B.enum(Vk1),lastOpenedTimestamp:B.coerce.date().optional()});var iCC=B.string(),Wk1=Pb({filePath:ld(),fileData:ld()}),Kk1=Mr("FileReadResult",Wk1);var oCC=B.object({x:B.number(),y:B.number(),initialX:B.number().optional(),initialY:B.number().optional()}),sCC=B.object({x:B.number().int(),y:B.number().int()});var PCC=Je("GIT");var qCC=Je("GIT");var XCC=Je("GIT");var dJo=Je("PLAN"),u91=async(r,t)=>{let n="[getWorkspaceDataWithRetry]",i=await r();if(n3(i.steps)===0){dJo.infoContext(t,`${n}: no nodes in current workspace data. This is a potentially valid state. Checking for consistency in followup query...`),await kG(2e3);let o=await r(),s=n3(o.steps);s!==0&&(dJo.alertContext(t,`${n}: followup query returned ${s} nodes. Data is not consistent between identical calls to currentWorkspaceDataGetter(). Returning data containing steps...`),i=o)}return i},c91=async(r,t,n)=>{let i=await t.workspace(r).fetch(),o=qIt(i);return{...FEr(n),locations:o}},O0l=async(r,t,n,i,o,s,a,u,p,c,l=!1)=>{let d="[getCurrentAndDesiredWorkspaceDataWithPackages]";return Ah(`${d} fetching current and desired workspace data (${r})`,c,"APP",async()=>{let f;l?f=Promise.resolve(c91(n,i,s)):f=u91(()=>UEr(n,i,o??new tk,void 0,c),c);let[h,A]=await Promise.all([f,Xet(a,u,s,{installPackageEntities:!0,validateData:!0},{...c,orgID:t},aO,p)]);dJo.infoContext(c,`${d} current workspace data contains ${n3(h.steps)} nodes;`,`desired workspace data contains ${n3(A.steps)} nodes`);let E={currentWorkspaceData:{...k5e(h,h.installedPackages||{}),platformKind:s},desiredWorkspaceData:{...k5e(A,A.installedPackages||{}),platformKind:s}};return l&&(E.skippedBeforeCollection=!0),E},"info")};var fJo=Je("PLAN"),w0l=(r,t)=>{let n=[];for(let i=1;i<r.length;i++){let o=r[i];if(r[i-1]==="columns"&&typeof o=="number"){let a=t[o];n.push(a?.name??`[${o}]`)}else n.push(String(o))}return n.join(" > ")},yxr=r=>r==null?`<${r}>`:typeof r=="function"?"<function>":typeof r=="object"?r:String(r),hJo=(r,t)=>{let n=[];for(let i of r)!i.path||i.path.length===0||(i.kind==="A"?n.push(l91(i,t)):n.push(p91(i,t)));return n},l91=(r,t)=>{let n=r.path,{item:i}=r,o=[...n,r.index],s=w0l(o,t),a=i.path?.length?`${s} > ${i.path.join(" > ")}`:s,u=i.kind==="N"?"added":i.kind==="D"?"removed":"changed",c={path:`${a} (${u})`,rawPath:o,kind:"A"};return"lhs"in i&&i.lhs!==void 0&&(c.lhs=yxr(i.lhs)),"rhs"in i&&i.rhs!==void 0&&(c.rhs=yxr(i.rhs)),c},p91=(r,t)=>{let n=r.path,o={path:w0l(n,t),rawPath:n,kind:r.kind};return"lhs"in r&&r.lhs!==void 0&&(o.lhs=yxr(r.lhs)),"rhs"in r&&r.rhs!==void 0&&(o.rhs=yxr(r.rhs)),o},bxr=class{summaries=new Map;capturedPaths=new Map;addReason(t,n){let i=this.summaries.get(t);i?i.push(n):this.summaries.set(t,[n])}pathKey(t){return t.path?t.kind==="A"?`${t.path.join(".")}.${t.index}`:t.path.join("."):""}recordPaths(t,n){let i=this.capturedPaths.get(t);i||(i=new Set,this.capturedPaths.set(t,i));for(let o of n){let s=this.pathKey(o);s&&i.add(s)}}dedup(t,n){let i=this.capturedPaths.get(t);return i?.size?n.filter(o=>{let s=this.pathKey(o);return!s||!i.has(s)}):n}checkDDLDiff(t,n,i,o){let s=[],a=yol(n,i,o,u=>{s=u});if(a&&s.length>0){this.recordPaths(t,s);try{this.addReason(t,{kind:"ddl",summary:"Structural changes detected",changes:hJo(s,i.operation.metadata.columns)})}catch(u){fJo.warnContext(o,"Failed to humanize DDL diffs for change summary",{error:u})}}return a}checkMetadataDiff(t,n,i,o){let s=[],a=Lol(n,i,o,u=>{s=u});if(a&&s.length>0){let u=this.dedup(t,s);if(u.length>0){this.recordPaths(t,u);try{this.addReason(t,{kind:"metadata",summary:"Metadata changes detected",changes:hJo(u,i.operation.metadata.columns)})}catch(p){fJo.warnContext(o,"Failed to humanize metadata diffs for change summary",{error:p})}}}return a}captureFullDiff(t,n,i,o){let s=[];if(KZe(n,i,()=>!0,()=>{},o,"captureFullDiff",a=>{s=a}),s.length>0){this.recordPaths(t,s);try{this.addReason(t,{kind:"ddl",summary:"Changes detected",changes:hJo(s,i.operation.metadata.columns)})}catch(a){fJo.warnContext(o,"Failed to humanize diffs for advanced deploy change summary",{error:a})}}}checkSourceMappingDiff(t,n,i,o){let s=mol(t,n,i,o);return s&&this.addReason(t,{kind:"sourceMapping",summary:"Upstream dependency location mappings changed"}),s}recordLocationChange(t,n,i){this.addReason(t,{kind:"locationChange",summary:"Location mapping changed",from:n,to:i})}recordTransient(t){this.addReason(t,{kind:"transient",summary:"Transient deploy strategy \u2014 full recreate"})}recordViewDependencyRecreate(t){this.addReason(t,{kind:"viewDependencyRecreate",summary:"View recreated due to dependency location change"})}getSummaries(){let t={};for(let[n,i]of this.summaries)t[n]={reasons:i};return t}};var gJo=(r,t,n)=>{let i=t[r];i?i.workspaceEdits.push(...n.workspaceEdits):t[r]=n},Exr=class{adds={};alters={};deletes={};add(t,n){gJo(t,this.adds,n)}alter(t,n){gJo(t,this.alters,n)}delete(t,n){gJo(t,this.deletes,n)}getAlterStep(t){return this.alters[t]}finalize=()=>({addedTable:this.adds,alteredTable:this.alters,deletedTable:this.deletes})};var Rp=Je("PLAN"),M0l=r=>r==="table"||r==="view",$H=(r,t,n,i)=>({workspaceEdits:r,operation:t,nodeMetadata:{...n,...i}}),RZ=class{constructor(t,n,i,o,s,a,u,p,c){this.name=t;this.workspaceEditBuilder=n;this.renderer=i;this.currentState=o;this.desiredState=s;this.runTimeParameters=a;this.schemas=u;this.renderCacheManager=p;this.logContext=c}name;workspaceEditBuilder;renderer;currentState;desiredState;runTimeParameters;schemas;renderCacheManager;logContext;result=new Exr;diffCollector=new bxr;dependencyRefLookup={};get nodeChangeSummaries(){return this.diffCollector.getSummaries()}test_setResult(t){this.result=t}getNodeEdits=async()=>{let t="[BaseNodeEditBuidler.getNodeEdits()]",{measure:n,printSummary:i}=Bf(t,this.logContext),o=Bf("[Getting Dependency Refs]",this.logContext),s=wv(this.currentState.nodes),a=wv(this.desiredState.nodes),{deletedEntityIDs:u,addedEntityIDs:p,entitiesWithPossibleEdits:c}=j4e(this.desiredState.nodes,this.currentState.nodes);return Rp.debugContext(this.logContext,"getNodeEditsInternal -",`deletedEntityIDs:
|
|
10490
10490
|
`,u,`addedEntityIDs:
|
|
10491
10491
|
`,p,`entitiesWithPossibleEdits:
|
|
10492
10492
|
`,c),Rp.appContext(this.logContext,t,`Processing "delete" phase edits (${u.length})`),await n("deletes",()=>{u.forEach(l=>{let d={...this.logContext,nodeID:l};this.result.delete(l,this.getStepWithEditsForRemoveNode(l,s,d))})}),Rp.appContext(this.logContext,t,`Processing "add" phase edits (${p.length})`),await n("adds",()=>{p.forEach(l=>{let d={...this.logContext,nodeID:l};this.result.add(l,this.getStepWithWorkspaceEditsForCreateNode(l,a,d))})}),Rp.appContext(this.logContext,t,`Processing "alter" phase edits (${c.length})`),await n("alters",async()=>{let l=c.map(d=>async()=>{let f={...this.logContext,nodeID:d};try{return await this.getWorkspaceEditsForPossiblyEditedNode(d,s,a,f,o.measure)}catch(h){let A=y2r({type:"delta",current:this.currentState.getNode(d).operation,desired:this.desiredState.getNode(d).operation});throw yg(h,A)}});await Jgc(l,12,"Could not generate plan for the following nodes");try{let d=await this.renderCacheManager?.syncCache();d!==void 0&&Rp.infoContext(this.logContext,`Synced ${d} ref usages to cache`)}catch(d){Rp.errorContext(this.logContext,"syncCache","Failed to sync ref cache",{error:d})}}),i(),o.printSummary(),this.result.finalize()};getAlteredTableData(t,n){return{oldName:t,oldLocation:this.currentState.getNodePartialLocationString(n)}}getStepWithEditsForRemoveNode(t,n,i){let o=this.currentState.getNode(t),s=o.operation.name,a={...i,nodeName:s},u=xIt(o.operation,this.currentState.stepTypes,a),p={};try{p=this.getAlteredTableData(s,t)}catch{Rp.errorContext(a,`Mappings for node: ${s} don't exist`)}return i0(o,a)&&u?(Rp.infoContext(a,`getting advanced edit for remove node for ${s}...`),this.getAdvancedStepWithEditForRemoveNode(t,n,a)):i0(o,a)&&"oldLocation"in p?(Rp.debugContext(a,`getting standard edit for remove node for ${s}...`),this.getStepWithEditsForRemoveStandardNode(t,p,a)):(Rp.debugContext(a,`getting metadata edit for remove node for ${s}...`),this.getStepWithEditsForRemoveMetadata(t,a))}async getWorkspaceEditsForPossiblyEditedNode(t,n,i,o,s){let a=this.currentState.getNode(t),u=this.desiredState.getNode(t),p={...o,nodeID:t,currentNodeName:a.operation.name,updatedNodeName:u.operation.name};if(Rp.debugContext(p,`getting node edits for possibly edited node with updated name "${u.operation.name}"...`),$P(u,p)&&$P(a,p))return Rp.debugContext(p,`getting metadata edit for edited node "${u.operation.name}"`),this.getStepWithWorkspaceEditsForAlterSourceNode(t,i,p);if(i0(a,p)&&i0(u,p))return xIt(u.operation,this.desiredState.stepTypes,p)?(Rp.debugContext(p,`getting advanced edit for edited node "${u.operation.name}"`),await this.getStepWithWorkspaceEditsForAlterAdvancedDeployNode(t,n,i,s,{...p,nodeID:t})):(Rp.debugContext(p,`getting standard edit for edited node "${u.operation.name}"`),await this.getStepWithWorkspaceEditsForAlterNonSourceNode(t,i,s,p));{let c=`Source node cannot be converted to SQL node and vice versa. Node name: ${u.operation.name}, Node id: ${t}`;throw Rp.alertContext(p,c,a,u),new nt(c)}}generateStepDataWithMetadataUpdateEdit=(t,n,i)=>{let o=this.desiredState.getNode(t),s={operationName:o.operation.name,destinationName:o.operation.locationName,mapping:this.desiredState.physicalLocs},a=Mv(o.operation,t,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,this.runTimeParameters,n,i,this.name,{throwOnMissingSource:!0}),u=this.workspaceEditBuilder.metadataUpdate(t,o,a);return $H([u],o.operation,s,a)};getStepWithEditsForRemoveMetadata=(t,n)=>{Rp.infoContext(n,"Getting metadata drop edit for node");let i=this.currentState.getNode(t),o={operationName:i.operation.name,destinationName:i.operation.locationName,mapping:this.currentState.physicalLocs};return $H([this.workspaceEditBuilder.metadataDelete(t,i)],i.operation,o,{})};getStepWithWorkspaceEditsForCreateNode=(t,n,i)=>{Rp.debugContext(i,`getting node create requirements for node "${t}"`);let o=this.desiredState.getNode(t),s={operationName:o.operation.name,destinationName:o.operation.locationName,mapping:this.desiredState.physicalLocs,parameters:this.runTimeParameters},a=Mv(o.operation,t,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,this.runTimeParameters,n,i,this.name,{throwOnMissingSource:!0}),u=i0(o,i),p=u?Omr(this.desiredState.stepTypes,o.operation.sqlType):"",c;u?xIt(o.operation,this.desiredState.stepTypes,i)?(c=`Advanced Deployment: Created node ${o.operation.name}`,a={currentState:void 0,desiredState:a,currentMapping:void 0,desiredMapping:this.desiredState.physicalLocs}):c=`Created node ${o.operation.name}`:c=`Adding metadata for ${o.operation.name}`,Rp.debugContext({...i,nodeName:o.operation.name},`getting create edit for node "${o.operation.name}"`);let l=this.workspaceEditBuilder.createNode(t,c,p);return $H([l],o.operation,s,a)};getAdvancedStepWithEditForRemoveNode(t,n,i){let o=this.currentState.getSqlNode(t);Rp.infoContext(i,`Getting advanced deploy drop edit for ${o.operation.name}`);let s=this.currentState.getUdn(o.operation.sqlType).metadata.templates.create.templateString,a=s.length?`Advanced Deployment: Deleted node ${o.operation.name}`:`Advanced Deployment: No SQL available for ${o.operation.name}`,u={operationName:o.operation.name,destinationName:o.operation.locationName,mapping:this.currentState.physicalLocs,parameters:this.runTimeParameters},c={currentState:Mv(o.operation,t,this.currentState.nodes,this.currentState.stepTypes,this.currentState.physicalLocs,this.runTimeParameters,n,i,this.name,{throwOnMissingSource:!0}),desiredState:void 0,currentMapping:this.currentState.physicalLocs,desiredMapping:void 0};pd(!!n3(c),"hydratedMetadata for advanced deploy was missing data when creating workspace edits","PLAN",i);let l=this.workspaceEditBuilder.dropAdvancedDeploy(t,a,s);return $H([l],o.operation,u,c)}getStepWithEditsForRemoveStandardNode(t,n,i){let o=this.currentState.getSqlNode(t),s={operationName:o.operation.name,destinationName:o.operation.locationName,mapping:this.currentState.physicalLocs},a=`Deleted node ${o.operation.name}`,u,p=o.operation.materializationType==="view",c=o.operation.sqlType==="View";return p||c?(Rp.infoContext(i,`Node ${o.operation.name} is a view, getting delete template...`),u=[this.workspaceEditBuilder.dropMaterialization(t,a,n,"view")]):(Rp.infoContext(i,`Node ${o.operation.name} is a table, getting delete template...`),u=[this.workspaceEditBuilder.dropClone(t,n),this.workspaceEditBuilder.dropMaterialization(t,a,n,"table")]),$H(u,o.operation,s,{})}async getStepWithWorkspaceEditsForAlterAdvancedDeployNode(t,n,i,o,s){let a=this.currentState.getNode(t),u=this.desiredState.getNode(t),{name:p}=u.operation;if(Rp.debugContext(s,`getting alter advanced deploy workspace edits for node ${p}`),!i0(a,s)||!i0(u,s))throw new nt(`Node ${p} is not a SQL node, cannot get advanced deploy workspace edits for non-SQL nodes`);let c=this.desiredState.getUdn(u.operation.sqlType).metadata.templates.create.templateString,{advancedHydratedMetadata:l,nodeMetadata:d,renderResult:{compiledSQL:f,ref_usage:h}}=await this.renderAdvancedDeployNode(t,c,n,i,s),A=[],E=[],v=[],T=tJe(f);if(this.diffCollector.captureFullDiff(t,a,u,s),T.length){Rp.debugContext(s,`parsed sql stages for advanced deploy node ${p}`,T);for(let q of T){let{deployPhaseOverride:G}=q;G==="create"?E.push(this.workspaceEditBuilder.alterAdvancedDeploy(t,"addedTable",q)):G==="drop"?A.push(this.workspaceEditBuilder.alterAdvancedDeploy(t,"deletedTable",q)):v.push(this.workspaceEditBuilder.alterAdvancedDeploy(t,"alteredTable",q))}this.addToDependencyRefLookup(t,h,s)}else{if(this.diffCollector.checkMetadataDiff(t,a,u,s)){Rp.debugContext(s,`Advanced deploy node ${p} will have metadata update`);let q=Mv(u.operation,t,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,this.runTimeParameters,i,s,this.name,{throwOnMissingSource:!0}),G=this.workspaceEditBuilder.metadataUpdate(t,u,q);E.push(G)}Rp.debugContext(s,`Advanced deploy node ${p} had no parsed stages. Force rendering create template to gather refs...`),await o(`Advanced: ${t}`,async()=>{let q=await this.forceRenderedRefsAdvancedDeployNode(t,c,i,s);this.addToDependencyRefLookup(t,q,s)})}let w=q=>$H(q,u.operation,d,l),N=i$(E);N&&this.result.add(t,w(N));let k=i$(v);k&&this.result.alter(t,w(k));let L=i$(A);return L&&this.result.delete(t,w(L)),this}getStepWithWorkspaceEditsForAlterSourceNode(t,n,i){let o=this.currentState.getNode(t),s=this.desiredState.getNode(t),a={operationName:s.operation.name,destinationName:s.operation.locationName,mapping:this.desiredState.physicalLocs},u=Mv(s.operation,t,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,this.runTimeParameters,n,i,this.name,{throwOnMissingSource:!0});Rp.debugContext(i,`getting alter src workspace edits for node with updated name "${s.operation.name}"...`);let p=this.currentState.getNodePartialLocationString(t),c=this.desiredState.getNodePartialLocationString(t),l=p!==c;if(l&&this.diffCollector.recordLocationChange(t,p,c),!this.diffCollector.checkDDLDiff(t,o,s,i)&&!l)return Rp.debugContext(i,`No metadata diff detected for source node ${s.operation.name}`),this;Rp.infoContext(i,`Metadata diff detected for source node ${s.operation.name}, getting workspace edits...`);let d=this.workspaceEditBuilder.metadataUpdate(t,s,u),f=$H([d],s.operation,a,u);return this.result.alter(t,f),this}async getStepWithWorkspaceEditsForAlterNonSourceNode(t,n,i,o){let s=this.currentState.getSqlNode(t),a=this.desiredState.getSqlNode(t);this.throwOnInvalidStandardSQLNode(s,a,o);let u=this.currentState.getNodePartialLocationString(t),p=this.desiredState.getNodePartialLocationString(t),c=u!==p;c&&this.diffCollector.recordLocationChange(t,u,p);let d=this.diffCollector.checkDDLDiff(t,s,a,o)||c,f=this.nodeIs(a,"view")&&this.diffCollector.checkSourceMappingDiff(t,this.currentState,this.desiredState,o),h=this.diffCollector.checkMetadataDiff(t,s,a,o);if(!d&&!f)return h&&this.result.add(t,this.generateStepDataWithMetadataUpdateEdit(t,n,o)),this.nodeIs(a,"view")&&await i(`Standard: ${t}`,async()=>{let k=this.desiredState.getUdn(a.operation.sqlType).metadata.templates.create.templateString,L=await this.getRefUsageForStandardDeployNode(t,k,this.desiredState,n,o);this.addToDependencyRefLookup(t,L,o)}),this;let A=_kc(a.operation,this.desiredState.stepTypes,o);A&&d&&this.diffCollector.recordTransient(t),f&&this.diffCollector.recordViewDependencyRecreate(t);let E=d&&this.nodeIs(s,"table")&&this.nodeIs(a,"table")&&!A,v=f||d||A&&d,T=Mv(a.operation,t,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,this.runTimeParameters,n,o,this.name,{throwOnMissingSource:!0}),w=this.getAlteredTableData(s.operation.name,t);if(E)return this.getWorkspaceEditsForAlteredTable(t,s,a,this.desiredState.physicalLocs,w,T,c,o);if(v)return this.getStepWithEditBlobsForDropAndRecreate(t,w,s.operation,a.operation,T,"",o);let N=`Reached dropthrough case for step ${t} when attempting to create workspace edits - one or both materialization types are invalid. Original materialization type: ${s.operation.materializationType}; updated materialization type: ${a.operation.materializationType}.`;throw Rp.emergContext(o,N+"This should never happen."),new nt(N)}getCloneTableEdit(t,n,i,o,s){let a=this.schemas.current[n.operation.locationName],u=this.schemas.updated[i.operation.locationName];if(!a||!u){let c=!a&&!u?"Current and updated":a?"Updated":"Current";throw Rp.errorContext(s,`${c} schema missing for node. currentLoc:`,n.operation.locationName,"updatedLoc:",i.operation.locationName,"schemas:",this.schemas),new nt(`${c} schema is missing for node ${i.operation.name} (updated name)`)}return this.workspaceEditBuilder.cloneTable(t,o,a,u,s)}getRenameEdits(t,n,i,o,s,a){let u=n.operation.name!==i.operation.name;if(u||s){Rp.infoContext(a,`Node ${i.operation.name} is a table and has a name or location mapping difference. getting workspace edits for rename or swap...`,`
|
|
10493
10493
|
hasNodeNameDifference: ${u}, hasLocationMappingDifference: ${s}`);let p=this.workspaceEditBuilder.renameTable(t,o),c=this.workspaceEditBuilder.dropMaterialization(t,"Deleting table",o,"table");return[p,c]}return[]}getEditsToRunAgainstClone(t,n,i,o,s){return[...this.workspaceEditBuilder.alteredTable(t,n,i,o,s),...o.hasNodeDescriptionChange?[this.workspaceEditBuilder.updateTableDescription(t,i)]:[]]}getEditsToCloneAlterSwapDrop(t,n,i,o,s,a,u){let p=this.getEditsToRunAgainstClone(t,i,o,a,u),c=this.getRenameEdits(t,n,i,o,s,u);return c.length?[this.getCloneTableEdit(t,n,i,o,u),...p,...c]:p.length?[this.getCloneTableEdit(t,n,i,o,u),...p,this.workspaceEditBuilder.handleSwapOrReplace(t,o),this.workspaceEditBuilder.dropClone(t,o)]:[]}getEditsToRunAgainstFinal(t,n,i,o){return[]}getWorkspaceEditsForAlteredTable(t,n,i,o,s,a,u,p){Rp.infoContext(p,`Node ${i.operation.name} is a table. getting workspace edits for alter table...`);let c={operationName:i.operation.name,destinationName:i.operation.locationName,mapping:o},l=v=>$H(v,i.operation,c,a),d=this.workspaceEditBuilder.getNodeChanges(n,i),f=this.getEditsToCloneAlterSwapDrop(t,n,i,s,u,d,p),h=this.getEditsToRunAgainstFinal(t,n.operation,i.operation,s);if(!f.length&&!h.length){Rp.infoContext(p,`No actual edits generated for node ${i.operation.name}. Creating metadata only update for add phase.`);let v=this.workspaceEditBuilder.metadataUpdate(t,i,a);return this.result.add(t,l([v])),this}let E=i$([...f,...h]);if(!E)throw new nt(`No alters generated for node ${i.operation.name}. This should never happen.`);return this.result.alter(t,l(E)),this}getStepWithEditBlobsForDropAndRecreate=(t,n,i,o,s,a,u)=>{let p={operationName:i.name,destinationName:i.locationName,mapping:this.currentState.physicalLocs},c={operationName:o.name,destinationName:o.locationName,mapping:this.desiredState.physicalLocs};Rp.infoContext(u,"Getting workspace edits for drop and recreate");let{dropEdit:l,createEdit:d}=this.workspaceEditBuilder.dropAndRecreate(t,n,this.desiredState.stepTypes,i,o,a),f=(h,A,E)=>$H([h],A,E,s);return this.result.delete(t,f(l,i,p)),this.result.add(t,f(d,o,c)),this};addToDependencyRefLookup=(t,n,i)=>{this.dependencyRefLookup[t]&&Rp.emergContext(i,`Overwriting existing view ref lookup for node ${t}. This really shouldn't have happened. Proceeding anyway...`),this.dependencyRefLookup[t]=n};getRefUsageForStandardDeployNode=async(t,n,i,o,s)=>{let a=i.getSqlNode(t),u=c4(this.name,Sle(this.name,i.macros),n,i.installedPackages||{},i.getUdn(a.operation.sqlType),s),c={nodeMetadata:{...Mv(a.operation,t,i.nodes,i.stepTypes,i.physicalLocs,this.runTimeParameters,o,s,this.name,{throwOnMissingSource:!0}),...LIt(a.operation,i.physicalLocs)},macrosString:u.macrosString,templateString:n,runTimeParameters:this.runTimeParameters,packages:u.packages};if(this.renderCacheManager){let d=await this.renderCacheManager.getCachedRef(t,c);if(d)return Rp.infoContext(s,"getRefUsageForStandardDeployNode","Cache hit for ref",{nodeID:t}),d;Rp.infoContext(s,"getRefUsageForStandardDeployNode","Cache miss for ref",{nodeID:t})}let{ref_usage:l}=await this.renderAndCache(t,c,s);return l};getRefUsageForAdvancedDeployNode=async(t,n,i,o,s,a)=>{let u={nodeMetadata:o,macrosString:i,templateString:n,runTimeParameters:o.parameters,packages:s};if(this.renderCacheManager){let c=await this.renderCacheManager.getCachedRef(t,u);if(c)return Rp.infoContext(a,"getRefUsageForAdvancedDeployNode","Cache hit for ref",{nodeID:t}),c;Rp.infoContext(a,"getRefUsageForAdvancedDeployNode","Cache miss for ref",{nodeID:t})}let{ref_usage:p}=await this.renderAndCache(t,u,a);return p};renderStandardDeployNode=async(t,n,i,o,s)=>{let a=i.getSqlNode(t),u=c4(this.name,Sle(this.name,i.macros),n,i.installedPackages||{},i.getUdn(a.operation.sqlType),s),c={nodeMetadata:{...Mv(a.operation,t,i.nodes,i.stepTypes,i.physicalLocs,this.runTimeParameters,o,s,this.name,{throwOnMissingSource:!0}),...LIt(a.operation,i.physicalLocs)},macrosString:u.macrosString,templateString:n,runTimeParameters:this.runTimeParameters,packages:u.packages};return this.renderAndCache(t,c,s)};async renderAndCache(t,n,i){let o=await IOt(this.renderer,n.templateString,n.macrosString,n.nodeMetadata,n.packages,this.name,i,void 0,!0);return this.renderCacheManager&&this.renderCacheManager.updateCache(t,o.ref_usage,this.renderCacheManager.hashRenderPlan(n)),o}renderAdvancedDeployNode=async(t,n,i,o,s)=>{let a=this.currentState.getSqlNode(t),u=this.currentState;if(Uwr(a)){let T=a.operation.locationName,w={...this.currentState.locations,[T]:{mappingDefinitions:{[this.currentState.workspaceID]:{database:a.operation.database,schema:a.operation.schema}}}};u=new L5e(this.currentState.workspaceID,{locations:w,stepTypes:this.currentState.stepTypes,steps:this.currentState.nodes,installedPackages:this.currentState.installedPackages,macros:this.currentState.macros},this.currentState.platformKind,s),Rp.debugContext(s,`updated locations data for location ${T} for node ${t} to include the presynced node's location data. was:`,this.currentState.locations[T],"is now:",w[T])}let p=this.desiredState.getSqlNode(t),c={operationName:p.operation.name,destinationName:p.operation.locationName,mapping:this.desiredState.physicalLocs,parameters:this.runTimeParameters},l=(T,w,N,k,L)=>Mv(T,t,w,N,k,this.runTimeParameters,L,s,this.name,{throwOnMissingSource:!0}),d=l(a.operation,u.nodes,u.stepTypes,u.physicalLocs,i),f=l(p.operation,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,o),h={currentState:d,desiredState:f,currentMapping:u.physicalLocs,desiredMapping:this.desiredState.physicalLocs},A=c4(this.name,Sle(this.name,this.desiredState.macros),n,this.desiredState.installedPackages||{},this.desiredState.getUdn(p.operation.sqlType),s),E={nodeMetadata:{...c,...h},macrosString:A.macrosString,templateString:n,runTimeParameters:this.runTimeParameters,packages:A.packages},v=await this.renderAndCache(t,E,s);return{advancedHydratedMetadata:h,nodeMetadata:c,renderResult:v}};forceRenderedRefsAdvancedDeployNode=async(t,n,i,o)=>{let s=this.desiredState.getSqlNode(t),a=c4(this.name,Sle(this.name,this.desiredState.macros),n,this.desiredState.installedPackages||{},this.desiredState.getUdn(s.operation.sqlType),o),u={operationName:s.operation.name,destinationName:s.operation.locationName,mapping:this.desiredState.physicalLocs,parameters:this.runTimeParameters},c={currentState:void 0,desiredState:Mv(s.operation,t,this.desiredState.nodes,this.desiredState.stepTypes,this.desiredState.physicalLocs,this.runTimeParameters,i,o,this.name,{throwOnMissingSource:!0}),currentMapping:void 0,desiredMapping:this.desiredState.physicalLocs},l=await this.getRefUsageForAdvancedDeployNode(t,n,a.macrosString,{...u,...c},a.packages,o),{ref:d,ref_no_link:f}=l;return[...d,...f].filter(({node_name:A,location_name:E})=>!(A===s.operation.name&&E===s.operation.locationName)).length||Rp.warnContext(o,`Forced render of create case for advanced deploy node ${s.operation.name} did not return any refs.`),l};throwOnInvalidStandardSQLNode=(t,n,i)=>{let o=i0(n,i),s=M0l(t.operation.materializationType),a=M0l(n.operation.materializationType);if(!o||!s||!a){let{name:u,locationName:p}=n.operation,c=[`Node ${u} (${p}) is not a valid standard SQL node.`];throw n?o||c.push("Desired state was a Source node instead of a SQL node."):c.push("Desired state was missing."),a||c.push(`Desired materialization type (should be Table or View) but was: ${n.operation.materializationType}.`),s||c.push(`Current materialization type (should be Table or View) but was: ${t.operation.materializationType}.`),new nt(c.join(`
|
|
10494
10494
|
- `))}};nodeIs=(t,n)=>t.operation.materializationType===n};var AJo=Je("PLAN"),Cxr=class extends RZ{constructor(t,n,i,o,s,a,u){let p=new Pwr;super("bigquery",p,t,n,i,o,s,u,a)}getAlteredTableData(t,n){return{oldName:t,oldLocation:this.currentState.getNodePartialLocationString(n),desiredLocation:this.getDesiredLocation(n)}}getDesiredLocation(t){try{return this.desiredState.getNodePartialLocationString(t)}catch{return}}getStepWithEditsForRemoveStandardNode(t,n,i){let o=this.currentState.getSqlNode(t),s={operationName:o.operation.name,destinationName:o.operation.locationName,mapping:this.currentState.physicalLocs},a=`Deleted node ${o.operation.name}`,u,p=o.operation.materializationType==="view",c=o.operation.sqlType==="View";return p||c?(AJo.infoContext(i,`Node ${o.operation.name} is a view, getting delete template...`),u=[this.workspaceEditBuilder.dropMaterialization(t,a,n,"view")]):(AJo.infoContext(i,`Node ${o.operation.name} is a table, getting delete template...`),u=[this.workspaceEditBuilder.dropMaterialization(t,a,n,"table")],n.desiredLocation&&u.push(this.workspaceEditBuilder.dropClone(t,n))),$H(u,o.operation,s,{})}getEditsToCloneAlterSwapDrop(t,n,i,o,s,a,u){let{hasOnlyDescriptionChanges:p,hasNodeDescriptionChange:c,alteredColumnData:l}=a,d=n.operation.name!==i.operation.name;if(p&&!s&&!d){AJo.infoContext(u,`Node ${i.operation.name} has only description/label changes. Using in-place alter instead of clone.`);let h=[];return l.length>0&&h.push(...this.workspaceEditBuilder.inPlaceAlterColumnEdits(o,t,l)),c&&h.push(this.workspaceEditBuilder.inPlaceUpdateTableDescription(t,o)),h}return super.getEditsToCloneAlterSwapDrop(t,n,i,o,s,a,u)}};var Sxr=class extends sZ{constructor(){super("databricks",new GZe)}handleSwapOrReplace=(t,n)=>E1(t,"Replacing table with clone","replaceTable",n,this.templateProvider.replaceWithCloneTemplate);getCloneTableTemplate(){return this.templateProvider.getCloneTableTemplate()}};var vxr=class extends sZ{constructor(){super("fabric",new HZe)}updateTableDescription=()=>{throw new d1};handleSwapOrReplace=(t,n)=>E1(t,"Replacing table with clone","replaceTable",n,this.templateProvider.replaceWithCloneTemplate);getCloneTableTemplate(){return this.templateProvider.getCloneTableTemplate()}alterColumnEdits(t,n,i){return i.length?[E1(n,"Altered Columns","alteredColumn",{...t,alteredColumns:i},this.templateProvider.alterColumnTemplate)]:[]}};var Txr=class extends sZ{constructor(){super("snowflake",new VZe)}handleSwapOrReplace=(t,n)=>E1(t,"Swapping cloned table","swapClone",n,this.templateProvider.swapClonedTableTemplate);getCloneTableTemplate(t,n,i){return this.templateProvider.getCloneTableTemplate(t,n,i)}alterColumnEdits(t,n,i){return i.length?[E1(n,"Altered Columns","alteredColumn",{...t,alteredColumns:i},this.templateProvider.alterColumnTemplate)]:[]}};var _xr=class extends RZ{constructor(t,n,i,o,s,a,u){let p=new Sxr;super("databricks",p,t,n,i,o,s,u,a)}getEditsToRunAgainstClone(t,n,i,o,s){return[...this.workspaceEditBuilder.alteredTable(t,n,i,o,s)]}getEditsToRunAgainstFinal(t,n,i,o){return n.description!==i.description?[this.workspaceEditBuilder.updateTableDescription(t,o)]:[]}};var Ixr=class extends RZ{constructor(t,n,i,o,s,a,u){let p=new vxr;super("fabric",p,t,n,i,o,s,u,a)}getEditsToRunAgainstClone(t,n,i,o,s){return[...this.workspaceEditBuilder.alteredTable(t,n,i,o,s)]}};var Rxr=class extends RZ{constructor(t,n,i,o,s,a,u){let p=new Txr;super("snowflake",p,t,n,i,o,s,u,a)}};var KNt=async(r,t,n,i,o,s,a,u,p)=>{let c="[getNodeEdits]",{measure:l,printSummary:d}=Bf(c,u);if(!n.locations||!t.locations)throw new nt("Locations are required to calculate node edits");let f=d91(r,o,new L5e(i,t,o,u),new L5e(i,n,o,u),s,a,u,p),h=await l("editBuilder.getNodeEdits",()=>f.getNodeEdits());return d(),{edits:h,dependencies:f.dependencyRefLookup,nodeChangeSummaries:f.nodeChangeSummaries}},d91=(r,t,n,i,o,s,a,u)=>$g({snowflake:()=>new Rxr(r,n,i,o,s,a,u),databricks:()=>new _xr(r,n,i,o,s,a,u),fabric:()=>new Ixr(r,n,i,o,s,a,u),bigquery:()=>new Cxr(r,n,i,o,s,a,u)},t,"getNodeEditBuilder");var dO=Je("PLAN"),x0l=(r,t,n,i,o,s)=>{o.size!==0&&r.scan(new iZ(t,n,i,o),["sqlNodeParseErrors"],[],{workspaceState:"desired",shouldThrow:s})},P0l=async(r,t,n,i,o,s,a,u,p,c,l)=>{let d="[createPlan]",f=mu(),h={...l,planID:f,workspaceID:o,planOptions:{...r,platform:u.desiredWorkspaceData.platformKind}},{unsubscribe:A,workspaceStatusChangelog:E}=await Qal(p.org(i).workspace(o),h);try{dO.appContext(h,d,"Making plan workspace data plan ready");let v=new G4t,T=await v.monitor(l,async()=>{if(!o)throw dO.emergContext(l,d,"no workspaceID specified"),new nt("no environmentID specified");let{platformKind:w}=u.desiredWorkspaceData,N=["invalidStorageMappings","invalidStorageLocations","invalidNodeTypes","missingNodeTypes","emptyColumnNames"];w==="databricks"&&N.push("databricksUppercaseNodeNames"),v.scan(new iZ(u.desiredWorkspaceData,o,a),N,["invalidColumnSources","invalidParameterReferences"],{jobSchedules:c??void 0,workspaceState:"desired",shouldThrow:!1}),v.scan(new iZ(u.currentWorkspaceData,o),["invalidNodeTypes"],[],{workspaceState:"current",shouldThrow:!1}),hol(o,u,h),v.scan(new iZ(u.currentWorkspaceData,o),["invalidNodeLocationData","missingNodeTypes"],[],{workspaceState:"current"});let k=new Map;if(u.desiredWorkspaceData.steps=await Q4t(u.desiredWorkspaceData.steps,u.desiredWorkspaceData.stepTypes,_G(u.desiredWorkspaceData.platformKind),aO,void 0,k),x0l(v,u.desiredWorkspaceData,o,a,k,!1),r.usePlanAPI)return Ual({...r,clientWarnIssues:[...v.warn]},p,f,s,o,a,u,h);{let{platform:L,...q}=r;return await L.testConnection(),mJo({...q,clientWarnIssues:[...v.warn]},t,n,f,o,s,L,a,u,p,h,k)}});return v.foldWarnIssues(T.issues,h),{plan:T,issues:v}}finally{E.some(({status:v})=>v==="Deploying")&&dO.warnContext(h,d,"Workspace had a 'Deploying' status during plan",E),A?.()}},mJo=async(r,t,n,i,o,s,a,u,p,c,l,d)=>{let f="[createPlanInternal]",{clientWarnIssues:h,...A}=r,E={...l,planOptions:A},{measure:v,printSummary:T}=Bf("[createPlanInternal] \u2014 breakdown of operations WITHIN the parent 'plan calculation (total)' measurement",E),{disablePresync:w,skipPlanContextUpload:N}=r,k=new sS(dO,E),L=new Zvr({context:E,logger:dO}),q=async(W,F)=>{L.startPhase(W);let J=await v(W,F);return L.endPhase(W),J},G={workspaceContext:{before:p.currentWorkspaceData,after:p.desiredWorkspaceData,runTimeParameters:u,schemas:void 0,workspaceID:o,skippedBeforeCollection:!!p.skippedBeforeCollection},presyncContext:void 0},H,V={id:i,presyncDetails:{},targetEnvironment:o,version:2};p.skippedBeforeCollection&&(V.skippedBeforeCollection=!0),r.branchName&&(V.branchName=r.branchName);try{if(!d){let ce=await v("re-hydrate to detect SQL parse errors",async()=>{let de=new Map;return p.desiredWorkspaceData.steps=await Q4t(p.desiredWorkspaceData.steps,p.desiredWorkspaceData.stepTypes,a.name,aO,void 0,de),de});x0l(new G4t,p.desiredWorkspaceData,o,u,ce,!0)}let W={...p.currentWorkspaceData},F;try{let ce=!w&&!yrl.includes(a.name),de=[],pe=[];if(new Set(["snowflake","databricks","bigquery"]).has(a.name)&&r.loadWarehouseComments&&(pe=await QWo(a,W.steps,p.desiredWorkspaceData.steps,E)),ce){let Ne=await q("presync",()=>Dol(a,W,p.desiredWorkspaceData,u,t,E));dO.appContext(E,f,"Finished with presync"),W.steps=Ne.nodes,V.presyncDetails=Ne.details,G.presyncContext=Ne,de=Ne.missingLocations}F=await q("schemas",()=>zwr(a,W.steps,p.desiredWorkspaceData.steps,E)),dO.appContext(E,f,"Finished getting schemas"),G.workspaceContext.schemas=ep(F),V.issues=f91(de,pe,F,h)}catch(ce){throw dO.errorContext(E,f,"Presync/schemas failed! Error:",Gdr(ce)),ce}finally{dO.appContext(E,f,"Finished getting schemas"),G.workspaceContext.schemas&&(GWo(G.workspaceContext.schemas.current),GWo(G.workspaceContext.schemas.updated)),N||(H=q("store plan context",()=>xal(c,s,o,i,G,E).catch(ce=>dO.errorContext(E,f,"storePlanContext failed. This is non-critical and can be ignored.",ce))))}let{edits:J,dependencies:Y,nodeChangeSummaries:z}=await q("node edits",()=>KNt(t,W,p.desiredWorkspaceData,o,a.name,u,F,E,n));dO.appContext(E,f,"Rendering");let X=await v("init deploy renderer",()=>new _2r(t,a.name,E,R2e(J),u,p.desiredWorkspaceData.macros,p.desiredWorkspaceData.installedPackages||{},new cNe(p.desiredWorkspaceData.steps),J,new tk)),Z=await q("render nodes",()=>X.renderAllNodes(X$(p.desiredWorkspaceData.stepTypes)));dO.appContext(E,f,"Building dependencies");let{phasedDependencies:re,phasedNodeEdits:oe}=await q("build dependencies & edits",async()=>({phasedDependencies:new Obe(p.desiredWorkspaceData.steps,Z,Y,E).build(),phasedNodeEdits:Z.toEdits().toRecord()})),ee={...V,phasedDependencies:re,phasedNodeEdits:oe,nodeChangeSummaries:z};return pd(!!wwr(ee),`${f} Malformed plan!`,"PLAN",E),dO.appContext(E,f,`finished creating plan (version ${ee.version})`),ee}finally{H?r.skipAwaitPlanContext?dO.infoContext(E,f,"Skipping await of plan context upload"):await H:dO.errorContext(E,f,"storePlanContextPromise was never set"),k.logMetric("plan-execution",{orgID:l.orgID,workspaceID:o,planID:i,version:2}),await v("write plan analytics",async()=>{try{let W=L.toPlanAnalytics(o.toString());await c.org(l.orgID).writePlanAnalytics(i,W),dO.infoContext(E,f,"Successfully wrote plan analytics to Firestore")}catch(W){dO.errorContext(E,f,"Failed to write plan analytics to Firestore. This is non-critical.",W)}}),T()}},f91=(r,t,n,i)=>{let o=new Set,a=uol((u=>u.filter(({locationName:p,workspaceState:c})=>{let l=`${c}:${p}`;return o.has(l)?!1:(o.add(l),!0)}))([...r,...t,...n.missingLocations??[]]));return{stop:[],warn:[...i??[],...a]}};var __C=Je("DEBUG");var h91=Je("RUNNER_BACKEND"),N0l=async(r,t,n,i,o,s,a)=>{let u=d$e(t.name),p=await zwr(t,u.steps,n.steps,a),{edits:c}=await KNt(r,u,{...n,steps:Nb(n.steps,[...s])},+o,t.name,i,p,a),l=Object.keys(c.deletedTable),d=Object.keys(c.alteredTable);return hh("RUNNER_BACKEND",!l.length&&!d.length,a,"GetWorkspaceEditsForDevRun: found edits of unexpected type for nodes; ","deleted: ",l,"altered: ",d),h91.infoContext(a,"GetWorkspaceEditsForDevRun: done constructing edits ",Object.keys(c.addedTable)),c};var V_C=Je("PIPELINE");var g91=Je("PIPELINE"),D0l=async(r,t,n)=>{let i="createRun:",o={...A91(r),version:3},{runType:s}=o,a;switch(s){case"deploy":a=t.runs.createDeployRun(o);break;case"refresh":a=t.runs.createRefreshRun(o);break;case"devRun":a=t.devRuns.createDevRun(o);break;default:{let p=s;throw g91.emergContext(n,i,"unexpected run type",p),new nt(`${i} unexpected run type ${p}`)}}let u=await Ah(`${i} runRepository creation`,n,"PIPELINE",()=>a,"info");return{runRepository:u,logContext:{...n,runID:u.id}}},A91=r=>{if(!r.userCredentials)return r;let t={...r.userCredentials};return $g({snowflake:()=>{if(t.platformKind==="snowflake"||t.platformKind===void 0)for(let n of T0r)t[n]&&(t[n]="<REDACTED>")},databricks:()=>{if(t.platformKind==="databricks")for(let n of $dr)t[n]&&(t[n]="<REDACTED>")},bigquery:()=>{if(t.platformKind==="bigquery")for(let n of Jdr)t[n]&&(t[n]="<REDACTED>")},fabric:()=>{}},t.platformKind,"redactSensitiveRunInfo"),{...r,userCredentials:t}};var Zet=Je("PIPELINE"),Oxr=async(r,t)=>{let{logContext:n,runInfo:{runDetails:i,runDetails:{deployCommit:o,environmentID:s,fromWorkspaceData:a,clearTargetEnvironment:u}},teamInfoAndFirebase:{rootRepository:p,teamInfo:{fbTeamID:c}},platform:l}=r;Zet.infoContext(n,"[buildDeployPipeline] Starting");let{measure:d,printSummary:f}=Bf("[buildDeployPipeline] (version=2)",n),h=p.org(c).workspace(+s),A=Arl(h,a,n);Zet.infoContext(n,"[buildDeployPipeline] Getting supplemental node data");let E=await ZRt(async()=>{let v=await d("query nodes",()=>qEr(h)),T=Object.keys(i.phasedNodeEdits.deletedTable);return Object.fromEntries(Object.entries(v).filter(([w])=>T.includes(w)))},{attempts:3,tags:["[buildDeployPipeline] get supplemental node data"],waitSeconds:1});return f(),_De(dKc,{...r,supplementalNodeData:E},{beforeRun:async()=>{let v="[buildPipeline Deploy beforeRun]";u&&await grl(h,l.name,["nodes","macros","nodeTypes","subgraphs","jobs","installedPackages"],n),Zet.infoContext(n,v,"Writing workspace entities pre-deploy"),await mrl(h,a.locations,n),await A("macros"),await A("nodeTypes","update"),await A("installedPackages","update"),Zet.infoContext(n,v,"Wrote workspace entities pre-deploy")},afterRun:async()=>{let v="[buildPipeline Deploy afterRun]";Zet.infoContext(n,v,"Writing workspace entities post-deploy");let T=Pme.assert(a.locations||{});await h.merge({mappingsV1:UA(T),lastCommit:o}),await A("subgraphs"),await A("jobs"),await A("nodeTypes","delete"),await A("installedPackages","delete"),Zet.infoContext(n,v,"Wrote workspace entities post-deploy")},onCleanup:t})};var m91=Je("PIPELINE"),B0l=async(r,t)=>{let n="buildDevRunPipeline:",{allWorkspaceData:i,logContext:o,nodesInRun:s,platform:a,renderer:u,runID:p,runInfo:c,workspaceID:l}=r;switch(c.runDetails.operationType){case"create":{let d=await N0l(u,a,i,c.runTimeParameters||{},l,s,o),f={...c,runDetails:{...c.runDetails,dividedStepDataWithWorkspaceEdits:d}};await y91({...r,nodesInRun:R2e(d),runInfo:f},t);break}case"run":{await b91(r,t);break}default:{m91.errorContext(o,n,`received unrecognized operation type ${c.runDetails.operationType} for run ${p}`);break}}},y91=async(r,t)=>_De(hKc,r,{beforeRun:void 0,afterRun:void 0,onCleanup:t}),b91=async(r,t)=>_De(gKc,r,{beforeRun:void 0,afterRun:void 0,onCleanup:t});var ett=async(r,t)=>_De(fKc,r,{beforeRun:void 0,afterRun:void 0,onCleanup:t});var yJo=Je("RUN_RESULTS"),E91=(r,t,n,i)=>{let o={},s={};return r.forEach(({id:a,...u})=>{let p=[],c=u.history;!u.queryResultSequence&&Array.isArray(c)&&(p.push(`Patching 'queryResultSequence' from 'history' for step ${a}`),u.queryResultSequence=c[c.length-1]?.queryResultSequence),u.runResultVersion||(p.push(`Patching 'version' to zero for step ${a}`),u.runResultVersion=0),u.runExecutionSequenceID||(p.push(`Patching 'runExecutionSequenceID' to zero for step ${a}`),u.runExecutionSequenceID=0),u.name||(p.push(`Patching 'name' to 'unknown' for step ${a}`),u.name="unknown"),u.queryResultSequence?.queryResults?.map((d,f)=>{d.status||(p.push(`Patching 'status' to 'Failure' for step ${a} query result ${f}`),d.status="Failure"),d.exportedRefs||(p.push(`Patching 'exportedRefs' for step ${a} query result ${f}`),d.exportedRefs=[]),d.invalidExportedRefs||(p.push(`Patching 'invalidExportedRefs' for step ${a} query result ${f}`),d.invalidExportedRefs=[]),d.fields?.map(h=>{h.type||(p.push(`Patching 'type' to 'unknown' for step ${a} field ${h.name} of query result ${f}`),h.type="unknown")})}),p.length&&n&&i&&yJo.infoContext(n,i,p);let l=_Hc.assert(u);s[a]=l,o[a]={nodeID:a,hasTestFailures:u.hasTestFailures,queryResultSequence:l.queryResultSequence,runState:l.runState},u.hasTestFailures!==void 0&&(t.runResults.hasFailedTest=u.hasTestFailures)}),{runResults:o,fullRunResults:s}},C91=r=>Object.entries(r).map(([i,o])=>(Bm("RUN_RESULTS",o.runExecutionSequenceID!==void 0,"runExecutionSequenceID was undefined!"),{stepID:i,runExecutionSequenceID:o.runExecutionSequenceID})).sort((i,o)=>i.runExecutionSequenceID-o.runExecutionSequenceID).map(i=>i.stepID),L0l=async(r,t)=>{let n=[];for(;r;){let i=parseInt(r);if(isNaN(i))break;n.push(i);try{r=(await t.run(i).fetch()).reRunID}catch{throw new Du(`Run ${i} does not exist`,"404: Specify a valid runCounter")}}return n},S91=r=>{let{id:t,runDetails:{environmentID:n}}=r,i={runResults:{runStartTime:r.runStartTime,runEndTime:r.runEndTime,runType:r.runType,runStatus:r.runStatus,runID:t||0,runResults:[],runTimeParameters:r.runTimeParameters,environmentID:n||"n/a"}};if(r.userCredentials&&"snowflakeAuthType"in r.userCredentials&&(i.runResults.snowflakeAccount=r.userCredentials.snowflakeAccount,i.runResults.snowflakeWarehouse=r.userCredentials.snowflakeWarehouse),r.runType==="refresh"){let{jobID:o,includeNodesSelector:s,excludeNodesSelector:a}=r.runDetails;i.runResults.jobID=o===void 0?void 0:+o,i.runResults.includeNodesSelector=s,i.runResults.excludeNodesSelector=a}return typeof i.runResults.jobID=="string"&&(yJo.error(`Patching jobID from string to number for run ${r.id}`),i.runResults.jobID=parseInt(i.runResults.jobID)),WEr.assert(i)},k0l=async(r,t)=>{let n="[formatRunOutput]";t?pd(t.id===r.id,`in formatRunOutput, run.id (${t.id}) !== runRepository.id (${r.id})`,"RUN_RESULTS"):t=await r.fetch();let i=S91(t),o=[],s=await r.runResults.select(void 0,{ignoreDataTransformErrors:!0,onDataTransformError:(c,l)=>o.push(`
|
|
10495
|
-
${c}`,l)});o.length&&yJo.infoContext(r.logContext,n,"Error(s) transforming results from storage",...o);let{runResults:a,fullRunResults:u}=E91(s,i,r.logContext,n),p=C91(u);return i.runResults.runResults=p.map(c=>a[c]),i};var lrl=(r,t)=>{let n="--",i="--",o="--";if(!("rows"in t))return t.rowsInserted&&(n=t.rowsInserted),t.rowsUpdated&&(i=t.rowsUpdated),t.rowsDeleted&&(o=t.rowsDeleted),{rowsInserted:n,rowsUpdated:i,rowsDeleted:o};if(r==="refresh")if(!t.rows[0])n=0,i=0,o=0;else{let s=t.fields.findIndex(p=>p.name==="number of rows inserted"),a=t.fields.findIndex(p=>p.name==="number of rows updated"),u=t.fields.findIndex(p=>p.name==="number of rows deleted");n=s===-1?0:t.rows[0].values[s],i=a===-1?0:t.rows[0].values[a],o=u===-1?0:t.rows[0].values[u]}return{rowsInserted:n,rowsUpdated:i,rowsDeleted:o}};var v91=["nodes","subgraphs","jobs"],J3C=[...v91,"docs","problems","subfolders","git"];var $3C=B.object({hierarchy:B.array(B.string()),key:B.string(),type:B.string(),value:B.string(),stepCounter:B.string().optional(),tagColor:B.string().optional()}),X3C=B.object({selectedNodeIDs:B.object({nodes:B.record(B.boolean()),subgraphs:B.record(B.boolean()),jobs:B.record(B.boolean()),docs:B.record(B.boolean()),problems:B.record(B.boolean()),subfolders:B.record(B.boolean()),git:B.record(B.boolean())})});var uIC=Je("GRAPH"),wxr=async(r,t,n)=>{let i=await T91(r,t);return ttt(t.runDetails,n,i)},T91=async(r,t)=>{let n=new Set,i=await L0l(t.reRunID,r);for(let o of i){let s=await r.run(o).runResults.select();for(let{id:a,runState:u}of s)u==="complete"&&n.add(a)}return n},ttt=(r,t,n)=>_91(r,t,n||new Set)||new Set(Object.keys(t.steps)),bJo=(r,t,n,i)=>({steps:r,allStepTypesYAML:VEr(n,t),allSubgraphs:i}),_91=(r,t,n)=>{let i=null,o="",s="";if(r.jobID?{includeSelector:o,excludeSelector:s}=CHc(t,+r.jobID):(r.includeNodesSelector||r.excludeNodesSelector)&&(o=r.includeNodesSelector||"",s=r.excludeNodesSelector||""),o||s||n.size){let a=bJo(t.steps,t.stepTypes,t.installedPackages??{},t.folders);i=new Set(I91(o,s,a).filter(u=>!n.has(u)))}return i},I91=(r,t,n)=>{let i=RIt(n.steps);n.graphInformation=i;let o=HEr(r,t,n);return Object.keys(o.stepsResult)},R2e=r=>{let t=new Set;for(let n of Object.values(r))for(let i in n)t.add(i);return t};var R91=(r,t)=>{if(t=t===void 0?oAc:t,r<=1||t<=1)return 1;let s=r<=4?r:Math.floor((r-4)/2)+4;return Math.min(s,t)},Ppe=(r,t)=>{let n=R91(r,t),i=sAc,o=i<n?i:n;return o>0?o:1};var q0l=async(r,t)=>{let n=await r.fetch({ignoreDataTransformErrors:!0}),i={fbEmail:t?.emptyEmail?"":n.email,fbUserID:r.id,fbTeamID:n.currentTeam,fbFullName:`${n.firstName} ${n.lastName}`,fbFirstName:n.firstName,fbLastName:n.lastName,fbHasSuperUserAccess:n.hasSuperUserAccess,fbActivated:n.activated??!0};return t?.populateProvisioningAccess&&(i.hasProvisioningAccess=n.hasProvisioningAccess),i},F0l=async(r,t)=>(await r.org(t).fetch()).superDebugEnabled;var HKp=yt(a3l());var VKp=yt(fYe());var zsp=yt(Tze());var Fsp=yt(Tze());var Twl=yt(vwl());var LLr=yt(bU());var X0s=require("perf_hooks");function $Eg(r){let t=X0s.performance.now()*.001,n=Math.floor(t),i=Math.floor(t%1*1e9);return r!=null&&(n=n-r[0],i=i-r[1],i<0&&(n--,i+=1e9)),[n,i]}function dBe(){let[r,t]=$Eg();return r*1e3+Math.floor(t/1e6)}function PLr(r){return new Promise(t=>setTimeout(t,r))}var NLr=class{constructor({bucketSize:t,tokensPerInterval:n,interval:i,parentBucket:o}){if(this.bucketSize=t,this.tokensPerInterval=n,typeof i=="string")switch(i){case"sec":case"second":this.interval=1e3;break;case"min":case"minute":this.interval=1e3*60;break;case"hr":case"hour":this.interval=1e3*60*60;break;case"day":this.interval=1e3*60*60*24;break;default:throw new Error("Invalid interval "+i)}else this.interval=i;this.parentBucket=o,this.content=0,this.lastDrip=dBe()}async removeTokens(t){if(this.bucketSize===0)return Number.POSITIVE_INFINITY;if(t>this.bucketSize)throw new Error(`Requested tokens ${t} exceeds bucket size ${this.bucketSize}`);this.drip();let n=async()=>{let i=Math.ceil((t-this.content)*(this.interval/this.tokensPerInterval));return await PLr(i),this.removeTokens(t)};if(t>this.content)return n();if(this.parentBucket!=null){let i=await this.parentBucket.removeTokens(t);return t>this.content?n():(this.content-=t,Math.min(i,this.content))}else return this.content-=t,this.content}tryRemoveTokens(t){return this.bucketSize?t>this.bucketSize||(this.drip(),t>this.content)||this.parentBucket&&!this.parentBucket.tryRemoveTokens(t)?!1:(this.content-=t,!0):!0}drip(){if(this.tokensPerInterval===0){let s=this.content;return this.content=this.bucketSize,this.content>s}let t=dBe(),n=Math.max(t-this.lastDrip,0);this.lastDrip=t;let i=n*(this.tokensPerInterval/this.interval),o=this.content;return this.content=Math.min(this.content+i,this.bucketSize),Math.floor(this.content)>Math.floor(o)}};var fit=class{constructor({tokensPerInterval:t,interval:n,fireImmediately:i}){this.tokenBucket=new NLr({bucketSize:t,tokensPerInterval:t,interval:n}),this.tokenBucket.content=t,this.curIntervalStart=dBe(),this.tokensThisInterval=0,this.fireImmediately=i??!1}async removeTokens(t){if(t>this.tokenBucket.bucketSize)throw new Error(`Requested tokens ${t} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);let n=dBe();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),t>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)return-1;{let o=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-n);await PLr(o);let s=await this.tokenBucket.removeTokens(t);return this.tokensThisInterval+=t,s}}let i=await this.tokenBucket.removeTokens(t);return this.tokensThisInterval+=t,i}tryRemoveTokens(t){if(t>this.tokenBucket.bucketSize)return!1;let n=dBe();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),t>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;let i=this.tokenBucket.tryRemoveTokens(t);return i&&(this.tokensThisInterval+=t),i}getTokensRemaining(){return this.tokenBucket.drip(),this.tokenBucket.content}};var Z0s=r=>r;var vee=Je("SECRETS");function tfs(r,t){return!!r&&typeof r=="object"&&"code"in r&&r.code===t}function XEg(r){return tfs(r,LLr.Status.INVALID_ARGUMENT)&&"details"in r&&typeof r.details=="string"&&r.details.startsWith("Secret payload data length must be at most")}function hit(r){return tfs(r,LLr.Status.NOT_FOUND)||ZEg(r)}function ZEg(r){return tfs(r,LLr.Status.FAILED_PRECONDITION)&&typeof r?.message=="string"&&r.message.includes("is in DESTROYED state")}function efs(r){if(!r)return null;let t=r.split("/").pop();if(!t)return null;let n=parseInt(t);return Number.isNaN(n)?null:n}var e2g=9e4,t2g=600,r2g=600,rfs=10,n2g=new fit({tokensPerInterval:e2g/rfs,interval:"minute"}),i2g=new fit({tokensPerInterval:t2g/rfs,interval:"minute"}),DLr=new fit({tokensPerInterval:r2g/rfs,interval:"minute"}),o2g=new aL(1),BLr=class{constructor(t,n=new Twl.SecretManagerServiceClient){this.projectId=t;this.client=n}projectId;client;shouldUpgradeLegacyResultsToNewName(){return!1}BuildSecretName=t=>`projects/${this.projectId}/secrets/${t}`;BuildSecretNameLatestVersion=t=>`${this.BuildSecretName(t)}/versions/latest`;getByName=async t=>{await n2g.removeTokens(1);let n=await this.client.accessSecretVersion({name:this.BuildSecretNameLatestVersion(t)}),[i]=n,o=i.payload?.data?.toString();return o?new zd(o):null};makeAddVersionData=(t,n)=>({parent:this.BuildSecretName(t),payload:{data:Z0s(Buffer.from(n.sensitiveValue))}});addVersionByName=async(t,n)=>{let i=this.makeAddVersionData(t,n);await DLr.removeTokens(1),await this.client.addSecretVersion(i),this.PruneInaccessibleVersions(t).catch(o=>{vee.error("Could not prune versions for",t,o)})};setByName=async(t,n)=>{await DLr.removeTokens(2);let i=this.makeAddVersionData(t,n);await this.client.createSecret({parent:`projects/${this.projectId}`,secretId:t,secret:{replication:{automatic:{}}}}),await this.client.addSecretVersion(i)};listSecretVersions=async t=>{await i2g.removeTokens(1);let[n]=await this.client.listSecretVersions({parent:this.BuildSecretName(t)});return n};destroySecretVersion=async t=>{await DLr.removeTokens(1),await this.client.destroySecretVersion({name:t})};getMissingSecret=async t=>{let n=JMr(t);if(n)try{let i=await this.getByName(n);return i&&this.shouldUpgradeLegacyResultsToNewName()&&(await this.setByName(t,i),await this.deleteByName(n)),i}catch(i){if(!hit(i))throw i}return null};Get=async t=>{try{return await this.getByName(t)}catch(n){if(hit(n))return this.getMissingSecret(t);throw n}};setMissingSecret=async(t,n)=>{let i=JMr(t);if(!i)await this.setByName(t,n);else if(this.shouldUpgradeLegacyResultsToNewName())await this.setByName(t,n),await this.deleteByName(i,{ignoreMissing:!0});else try{await this.addVersionByName(i,n)}catch(o){if(hit(o)){await this.setByName(t,n);return}throw o}};Set=async(t,n)=>{try{await this.addVersionByName(t,n);return}catch(i){if(hit(i)){await this.setMissingSecret(t,n);return}throw XEg(i)&&vee.emerg("Payload exceeded for: ",t,"Reach out to support to determine if feature flags to adjust secret storage are appropriate next steps",i),i}};deleteByName=async(t,n)=>{try{await DLr.removeTokens(1),await this.client.deleteSecret({name:this.BuildSecretName(t)})}catch(i){if(n?.ignoreMissing&&hit(i))return;throw i}};Delete=async t=>{let n=JMr(t),i=[t];n&&i.push(n),await UP(i.map(o=>this.deleteByName(o,{ignoreMissing:!0})))};async PruneInaccessibleVersions(t){try{vee.info("Begin pruning inaccessible versions for secret",t),await o2g.runExclusive(async()=>{vee.info("Got lock for pruning inaccessible versions for secret",t);let i=(await this.listSecretVersions(t)).filter(o=>o.state==="ENABLED"&&!!efs(o.name)).sort((o,s)=>efs(s.name)-efs(o.name)).slice(1);for(let o of i)try{vee.info("Destroying secret version",o.name),await this.destroySecretVersion(o.name),vee.info("Successfully destroyed secret version",o.name)}catch(s){hit(s)?vee.error("Tried to prune secret",o.name,"but it was not found"):vee.alert("Error trying to prune inaccessible secret version",o.name,". Error: ",s)}},1)}catch(n){vee.alert("Fatal error trying to prune inaccessible secret versions for secret",t,". Error: ",n)}finally{vee.info("Completed pruning inaccessible versions for secret",t)}}};var rjl=yt(tjl());var p7r=class r{client;constructor(t){this.client=(0,rjl.createClient)({url:t})}static Create=async t=>{let n=new r(t);return await n.client.connect(),n};Get=async t=>{let n=await this.client.get(t);return n===null?null:new zd(n)};Set=async(t,n)=>{await this.client.set(t,n.sensitiveValue)};Delete=async t=>{await this.client.del(t)}};vr();var duA=yt(HQr());var ouA=B.enum(["org-settings-read","org-settings-write","org-users-read","org-users-write","org-users-create","org-users-delete","org-userRoles-read","org-userRoles-write","org-projects-create","org-tags-create","org-tags-delete","org-tags-write","org-tags-read"]),suA=B.enum(["project-settings-read","project-summary-read","project-settings-write","project-delete","project-members-read","project-members-add","project-members-write","project-members-remove","project-userRoles-read","project-workspaces-create","project-documentation-read","project-environments-create","project-workspace-settings-read","project-workspace-settings-write","project-workspaces-delete","project-workspace-jobs-create","project-workspace-jobs-read","project-workspace-jobs-write","project-workspace-jobs-delete","project-workspace-macros-create","project-workspace-macros-read","project-workspace-macros-write","project-workspace-macros-delete","project-workspace-node-types-create","project-workspace-node-types-read","project-workspace-node-types-write","project-workspace-node-types-delete","project-workspace-nodes-create","project-workspace-nodes-read","project-workspace-nodes-write","project-workspace-nodes-delete","project-workspace-packages-create","project-workspace-packages-read","project-workspace-packages-write","project-workspace-packages-delete","project-workspace-sql-run","project-workspace-subgraphs-create","project-workspace-subgraphs-read","project-workspace-subgraphs-write","project-workspace-subgraphs-delete"]),auA=B.enum(["env-run-results-read","env-run-job","env-delete","env-deploy","env-refresh","env-settings-read","env-summary-read","env-settings-write","env-documentation-read","env-members-read","env-members-add","env-members-write","env-members-remove","env-userRoles-read","env-job-schedule-write","env-job-schedule-read"]),uuA={reader:{permissions:["env-run-results-read","env-summary-read","env-documentation-read","env-job-schedule-read"],inheritedEnvironmentRoles:[]},admin:{permissions:[...auA.options],inheritedEnvironmentRoles:["reader"]}},cuA={member:{permissions:["project-summary-read","project-members-read","project-workspace-sql-run","project-workspace-nodes-read"],inheritedProjectRoles:[],inheritedEnvironmentRoles:[]},contributor:{permissions:["project-settings-read","project-members-read","project-workspaces-create","project-workspace-settings-read","project-workspace-settings-write","project-workspaces-delete","project-workspace-jobs-read","project-workspace-jobs-create","project-workspace-jobs-write","project-workspace-jobs-delete","project-workspace-macros-read","project-workspace-node-types-read","project-workspace-nodes-create","project-workspace-nodes-write","project-workspace-nodes-delete","project-workspace-packages-read","project-workspace-subgraphs-read","project-workspace-subgraphs-create","project-workspace-subgraphs-write","project-workspace-subgraphs-delete","project-documentation-read","env-delete","env-documentation-read"],inheritedProjectRoles:["member"],inheritedEnvironmentRoles:["reader"]},architect:{permissions:["project-workspace-macros-create","project-workspace-macros-write","project-workspace-macros-delete","project-workspace-node-types-create","project-workspace-node-types-write","project-workspace-node-types-delete","project-workspace-packages-create","project-workspace-packages-write","project-workspace-packages-delete"],inheritedProjectRoles:["contributor"],inheritedEnvironmentRoles:["reader"]},admin:{permissions:[...suA.options],inheritedProjectRoles:["architect"],inheritedEnvironmentRoles:["admin"]}},luA={member:{permissions:["org-tags-read"],inheritedOrganizationRoles:[],inheritedProjectRoles:[]},contributor:{permissions:["org-projects-create"],inheritedOrganizationRoles:["member"],inheritedProjectRoles:[]},admin:{permissions:[...ouA.options],inheritedOrganizationRoles:["contributor"],inheritedProjectRoles:["admin"]}},WQr=r=>{let t=uuA[r],n=new Set(t.permissions);for(let i of t.inheritedEnvironmentRoles)WQr(i).forEach(o=>n.add(o));return Array.from(n)},Uct=r=>{let t=cuA[r],n=new Set(t.permissions);for(let i of t.inheritedProjectRoles)Uct(i).forEach(o=>n.add(o));for(let i of t.inheritedEnvironmentRoles)WQr(i).forEach(o=>n.add(o));return Array.from(n)},VQr=r=>{let t=luA[r],n=new Set(t.permissions);for(let i of t.inheritedOrganizationRoles)VQr(i).forEach(o=>n.add(o));for(let i of t.inheritedProjectRoles)Uct(i).forEach(o=>n.add(o));return Array.from(n)},_sp={admin:VQr("admin"),contributor:VQr("contributor"),member:VQr("member")},Isp={admin:Uct("admin"),architect:Uct("architect"),contributor:Uct("contributor"),member:Uct("member")},Rsp={admin:WQr("admin"),reader:WQr("reader")};var puA=Je("USER_MANAGEMENT"),rvs=class{throwIfOrgPermissionDenied(t,n=!1){if(!this.hasOrgPermission(t))throw n?new Du("The requested resource is unavailable"):new Ww("Permission denied",`Permission '${t}' is required to perform this operation.`)}throwIfProjectPermissionDenied(t,n,i=!1){if(!this.hasProjectPermission(t,n))throw i?new Du("The requested resource is unavailable"):new Ww("Permission denied",`Permission '${t}' is required to perform this operation.`)}throwIfEnvironmentPermissionDenied(t,n,i,o=!1){if(!this.hasEnvironmentPermission(t,n,i))throw o?new Du("The requested resource is unavailable"):new Ww("Permission denied",`'Permission ${t}' is required to perform this operation.`)}},KQr=class r extends rvs{constructor(n,i){super();this.userRoles=n;this.hasSuperUserAccess=i;this.userPermissions=this.ConstructPermissionsFromRoles(n)}userRoles;hasSuperUserAccess;userPermissions;get orgRoles(){return this.userRoles?.organizationRoles??[]}hasOrgPermissionInternal(n){return this.userPermissions.organizationPermissions?.has(n)}hasOrgPermission(n){return this.hasSuperUserAccess||this.hasOrgPermissionInternal(n)}hasProjectPermissionInternal(n,i){return this.userPermissions.projects[i]?.projectPermissions?.has(n)}hasProjectPermission(n,i){return this.hasSuperUserAccess||this.hasOrgPermissionInternal(n)||this.hasProjectPermissionInternal(n,i)}hasEnvironmentPermissionInternal(n,i,o){return this.userPermissions.projects[i]?.environments[o]?.environmentPermissions?.has(n)}hasEnvironmentPermission(n,i,o){return this.hasSuperUserAccess||this.hasOrgPermissionInternal(n)||this.hasProjectPermissionInternal(n,i)||this.hasEnvironmentPermissionInternal(n,i,o)}ConstructPermissionsFromRoles(n){return n?(n.projects||(puA.warn(`userRoles.projects is undefined for user ${n.id}, defaulting to empty object`),n.projects={}),{organizationPermissions:r.ConstructOrgPermissionsFromRoles(n.organizationRoles),projects:r.ConstructProjectsPermissionsFromRoles(n.projects)}):{organizationPermissions:new Set,projects:{}}}static ConstructEnvironmentPermissionsFromRoles(n){let i=new Set;return n.environmentRoles.forEach(o=>{Rsp[o].forEach(s=>{i.add(s)})}),i}static ConstructEnvironmentPermissionObjectsFromRoles(n){let i={};return Object.entries(n).forEach(([o,s])=>{i[o]={environmentPermissions:r.ConstructEnvironmentPermissionsFromRoles(s)}}),i}static ConstructProjectPermissionsFromRoles(n){let i=new Set;return n.projectRoles.forEach(s=>{Isp[s].forEach(a=>{i.add(a)})}),{projectPermissions:i,environments:r.ConstructEnvironmentPermissionObjectsFromRoles(n.environments)}}static ConstructProjectsPermissionsFromRoles(n){let i={};return Object.keys(n).forEach(o=>{i[o]=this.ConstructProjectPermissionsFromRoles(n[o])}),i}static ConstructOrgPermissionsFromRoles(n){let i=new Set;return n.forEach(o=>{_sp[o].forEach(s=>{i.add(s)})}),i}};var Osp=Je("AUTH"),RKC=Je("USER_MANAGEMENT"),fuA=async(r,t,n,i,o)=>{let s={};try{let a=await r(),{context:{userID:u},token:p}=await t(a);s.userID=u;let c=o||await n(a,p),l=await q0l(c.user(u),{emptyEmail:!0,populateProvisioningAccess:!0});s.orgID=l.fbTeamID;let d=K8.getActiveSpan();d&&(d.setAttribute("userID",u),d.setAttribute("orgID",l.fbTeamID));let f=await i({org:{id:l.fbTeamID},user:{id:u},...Dv&&{version:{id:Dv.version}}},c,p),h=await c.org(l.fbTeamID).userRole(u).fetch(),A=new KQr(h,!!l.fbHasSuperUserAccess);return{teamInfo:l,firebase:a,rootRepository:c,token:p,featureFlags:f,userPermissions:A}}catch(a){if(Osp.errorContext(s,"AuthenticateTokenAndRetrieveTeamInfo",a),a instanceof KY)throw a;let u=a?.message||a?.error?.errorString;throw new nt("Unable to authenticate, please check your network connection and ensure your token is valid",u)}},wsp=async(r,t,n,i,o)=>{let s="[AuthenticateTokenAndRetrieveTeamInfo]",a={};return cf(async()=>Ah(s,a,"AUTH",()=>fuA(r,t,n,i,o),"info"),4,Osp,a,{alterRetryStrategy:p=>({name:"backoff",base:oWe(ua(p,!0),"QUOTA_EXCEEDED")||oWe(ua(p,!0),"Unable to authenticate")?60:1}),checkError:p=>{if(p instanceof KY)return p;let c=ua(p,!0);if(["INVALID_REFRESH_TOKEN","EXPIRED_TOKEN","Missing or invalid OAuth refresh token","OAuth access token expired","Invalid Token","JWT ID token expired","Decoding Firebase ID token failed","Token expired","User not found","User disabled"].some(d=>oWe(c,d)))return p},logOnRetry:`${s} retrying`,logOnFailure:`${s} failed, exhausted allotted retry attempts`})};var Bsp=yt(Tze()),Lsp=require("node:fs/promises");vr();var Msp;var Cre=(r,t={},n=1)=>{Msp&&Msp.increment(r,t,n)};var huA=B.object({auth:B.string(),firestore:B.string(),storage:B.string()}),guA=B.object({apiKey:B.string(),authDomain:B.string(),projectId:B.string(),storageBucket:B.string(),messagingSenderId:B.string(),appId:B.string(),measurementId:B.string(),emulatorInfo:huA.optional()}),xsp=Mr("FirebaseConfig",guA);var nvs=r=>{Cre("firestore.delete",{path:r})},YQr=r=>{Cre("firestore.set",{path:r})},ivs=r=>{Cre("firestore.update",{path:r})};var ovs=r=>{Cre("firestore.get",{path:r})},svs=r=>{Cre("firestore.transaction.get",{path:r})},avs=r=>{Cre("firestore.transaction.set",{path:r})},uvs=r=>{Cre("firestore.transaction.update",{path:r})},cvs=r=>{Cre("firestore.transaction.delete",{path:r})},lvs=()=>{Cre("firestore.batch")};var FKC=K8.getTracer("firestore");var Psp=async(r,t=1e3)=>{let n=()=>{},i=new Promise(o=>{n=r.onSnapshot(s=>{s.metadata.hasPendingWrites||o(s)})});return await JR(t,`Timed out in GetDocumentNoPendingWrites after ${t} ms`,i).finally(n)};var Nsp=yt(AXt());async function Dsp(r){let t=new Nsp.ProxyAgent;r.httpProxy=t,r.httpsProxy=t}var ksp=(0,Bsp.default)(async()=>{if(ZG)return Je("RUNNER_BACKEND").info("WARNING: API using Firebase emulator!"),{apiKey:"none",authDomain:"none",projectId:"coalesce",storageBucket:"coalesce.appspot.com",messagingSenderId:"none",appId:"none",measurementId:"none",emulatorInfo:ZG};{let r=await(0,Lsp.readFile)(process.env.FIREBASE_CONFIG_PATH??"/firebase.json"),t=xsp.assert(JSON.parse(r.toString()));return Je("RUNNER_BACKEND").info("API using Firebase config:",t),t}});async function qsp(){return oQe()||Kyu()?await ksp():Gh.app().options}var pvs=async(r,t)=>{await Dsp(r),await SGc(r,t)};var dvs=Je("SECRETS"),Usp=(0,Fsp.default)(async()=>{switch(process.env.COALESCE_SECRET_STORE_TYPE){case"redis":if(dvs.app("Selected Redis secret store."),!process.env.COALESCE_SECRET_STORE_REDIS_URL)throw new Error("The redis secret store is configured, but no COALESCE_SECRET_STORE_REDIS_URL was defined.");return await p7r.Create(process.env.COALESCE_SECRET_STORE_REDIS_URL);case"memory":return dvs.app("Selected Memory secret store."),YYo();default:return dvs.app("Selected Google Secrets Manager secret store."),new BLr((await qsp()).projectId)}});var hI=(0,zsp.default)(async()=>new ket(await Usp()));var AuA=Je("SECRETS"),zct=async(r,t,n,i)=>{let o={userID:t.userId,orgID:t.orgId,workspaceID:+t.workspaceId},s=n.UpgradeTarget;if(i&&s){let a=await r.Get(s,t);return a||(a=await r.Get(n,t),a&&(AuA.infoContext(o,`v2 Snowflake secrets feature flag was set, found v1 credentials. Upgrading v1 to v2 for ${n.typeName}`),await r.Set(s,t,a),await r.Delete(n,t))),a}else return await r.Get(n,t)};var Qsp=async(r,t,n)=>{let i=n.isFeatureEnabled("enableSnowflakeOAuthSecretsV2");return zct(r,t,Wet,i)},jsp=async(r,t)=>await r.Get(jet,t);var Gsp=async(r,t)=>await r.Get(Qet,t),Hsp=async(r,t)=>await r.Get(Uet,t),Vsp=async(r,t,n)=>zct(r,t,Het,n),Wsp=async(r,t,n)=>{let i=n.isFeatureEnabled("enableSnowflakeSecretsV2");return zct(r,t,xpe,i)},Ksp=async r=>await(await hI()).Get(zet,r),Ysp=async r=>await(await hI()).Get(T2e,r);var muA=async(r,t,n)=>await r.Set(T2e,t,n),JQr=async(r,t)=>{let n=await hI(),i={orgId:r.orgID,userId:r.userID,workspaceId:r.workspaceID.toString()};await muA(n,i,new zd(t))},Jsp=async(r,t,n,i)=>{if(!i.isFeatureEnabled("enableSnowflakeSecretsV2"))return await r.Set(xpe,t,n);await r.Get(xpe,t)&&await r.Delete(xpe,t),await r.Set(t6e,t,n)};var $sp;var gI=(r,t={},n=1)=>{if($sp){let o={appContext:PZt()??"unknown"};ZG&&(o.emulated="true"),$sp.increment(r,{...o,...t},n)}};var yuA="20428800",s3e=()=>parseInt(process.env.MAX_RESPONSE_SIZE||yuA);var buA=Je("CONNECTION"),a3e=class{constructor(t,n,i,o,s=2){this.handle=t;this.queryParams=n;this.logContext=i;this.resetFunc=o;this.maxAttempts=s;this.queryParams.requestId=this.coalesceQueryID=this.queryParams.requestId??mu()}handle;queryParams;logContext;resetFunc;maxAttempts;_promise=null;coalesceQueryID;get promise(){if(this.Start(),!this._promise)throw new DA("Internal consistency error: _promise cannot be null after Start()!");return this._promise}Cancel=async()=>{buA.infoContext(this.logContext,"Canceling the running query, CQID=",this.coalesceQueryID),await this.tryCancel()};Start=()=>{this._promise||(this._promise=this.queryWithRetries())};attachThen=t=>{this._promise=this.promise.then(n=>(t(n),n))}};var Sre=Je("CONNECTION"),e9t=class extends a3e{constructor(n,i,o,s,a,u=5){let p={...s,snowflakeRequestID:o.requestId};super(i,o,p,a,u);this.completion=n}completion;get sqlText(){return this.queryParams.statement}mapRowCountColumns(n,i){let o=i.trim().toUpperCase(),s;return o.startsWith("UPDATE")?s="UPDATE":o.startsWith("DELETE")&&(s="DELETE"),n.map(a=>{if(a.columnName==="num_inserted_rows")return{...a,columnName:"number of rows inserted"};if(a.columnName==="num_updated_rows")return{...a,columnName:"number of rows updated"};if(a.columnName==="num_deleted_rows")return{...a,columnName:"number of rows deleted"};if(a.columnName==="num_affected_rows"){if(s==="UPDATE")return{...a,columnName:"number of rows updated"};if(s==="DELETE")return{...a,columnName:"number of rows deleted"}}return a})}shouldResetConnection=n=>CuA(n)?!0:!!ua(n).error.errorString.match(/(network ?error|econnreset)/i);handleRetry=async(n,i)=>{if(this.shouldResetConnection(n))try{this.handle=await this.resetFunc()}catch(o){throw Sre.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",o),n.coalesceCause}return i};async ensureSession(){if(!this.handle.session){let o=this.getSessionOptions();return this.handle.session=await this.handle.client.openSession(o),this.handle.sessionOptions=o,this.handle.session}let n=this.getSessionOptions(),i=this.handle.sessionOptions;if(n.initialCatalog!==i.initialCatalog||n.initialSchema!==i.initialSchema){try{await this.handle.session.close()}catch(o){Sre.errorContext(this.logContext,"Error closing previous session for CQID=",this.coalesceQueryID,o)}finally{this.handle.session=void 0}this.handle.session=await this.handle.client.openSession(n),this.handle.sessionOptions=n}return this.handle.session}getSessionOptions(){return{initialCatalog:this.queryParams.initialCatalog,initialSchema:this.queryParams.initialSchema}}async queryWithRetries(){let n=`[TrackedPendingDatabricksQuery.queryWithRetries() - '${this.queryParams.statement}']`;try{Sre.debugContext(this.logContext,"Making request for CQID=",this.coalesceQueryID);let i=async()=>{gI("databricks.runQuery.attempt",this.logContext);let l={columns:[],rows:[],status:"Success"};try{let f=await(await this.ensureSession()).executeStatement(this.queryParams.statement,this.queryParams.queryOptions),h=(await f.getSchema())?.columns;h&&(l.columns=h);let A=0;do{let v=await f.fetchChunk({maxRows:1e3});if(A+=lWe(v,!0),l.rows.push(...v),A>s3e())throw new Yvt(A,s3e())}while(await f.hasMoreRows());l.columns=this.mapRowCountColumns(l.columns,this.queryParams.statement);let E=await f.status();gI("databricks.runQuery.finished",{...this.logContext,statusCode:E.status.statusCode??-1})}catch(d){if(gI("databricks.runQuery.error",{...this.logContext,errorString:ua(d).error.errorString}),d instanceof Yvt)return l.status=dL,Sre.errorContext(this.logContext,n,d.detail,`; returning partial set of rows (${l.rows.length})`),l;throw Sre.errorContext(this.logContext,"Error in databricks query",d),new bX(this.queryParams,d)}return Sre.debugContext(this.logContext,"Successfully got result for CQID=",this.coalesceQueryID),l},o=(l,d)=>{if(!(typeof l=="object"&&l instanceof bX))return Sre.errorContext(this.logContext,"Not retrying request CQID=",this.coalesceQueryID,"attempt=",d,"error=",l,"was unrecognized and not retryable"),l;if(Qct(l))return Sre.infoContext(this.logContext,"Not retrying request, auth error detected CQID=",this.coalesceQueryID,"attempt=",d),l;if(l.isCancel())return Sre.infoContext(this.logContext,"Not retrying request, it was canceled CQID=",this.coalesceQueryID,"error=",l.coalesceCause?l.coalesceCause:l),l},s=l=>["CQID=",this.coalesceQueryID,"error=",l.cause?l.cause:l],a={name:"backoff",base:5},u={name:"nowait"},p=async l=>{typeof l=="object"&&l instanceof bX&&await this.handleRetry(l,this.queryParams)},c=(l,d)=>{let f=JSON.stringify(ua(l,!0).error);return f.match(/network ?error/i)||f.match(/bad HTTP status code: 5/)||f.match(/bad HTTP status code: 400/)?a:d||u};return await cf(i,this.maxAttempts,Sre,this.logContext,{beforeRetry:p,alterRetryStrategy:c,checkError:o,retryStrategy:u,retryLogLevel:"info",logOnRetry:"Retrying databricks request",customErrorOnRetry:s,logOnFailure:"Out of retries for request",customErrorOnFailure:s})}catch(i){throw i instanceof bX?i:new bX(this.queryParams,i)}finally{this.completion(this.coalesceQueryID)}}async tryCancel(){try{await this.handle.session?.close()}catch(n){throw new nt("Error canceling Databricks session",JSON.stringify(ua(n).error))}finally{this.handle.session=void 0}}},fvs=r=>{if(typeof r!="object"||r===null)return[];let t=r,n=typeof t.statusCode=="number"?[t.statusCode]:[];return t.coalesceCause!==void 0&&n.push(...fvs(t.coalesceCause)),n};var EuA=/Invalid SessionHandle|SESSION_CLOSED|SESSION_NOT_FOUND|SESSION_CHANGED|session was closed or has expired/i,CuA=r=>{if(fvs(r).includes(400))return!0;let t=ua(r,!0).error.errorString;return/bad HTTP status code: 400/i.test(t)||EuA.test(t)},Qct=r=>fvs(r).includes(403);var U8e=require("perf_hooks");var $Qr=class{logTag;gcStats;performanceObserver;isActive=!1;trackingStartTime;gcTypeMap={1:"scavenge",2:"mark_sweep_compact",4:"incremental_marking",8:"process_weak_callbacks",15:"all"};constructor(t={}){this.logTag="[GCTracker]: "+(t.logTag||""),this.gcStats=this.initializeGCStats(),t.autoStart!==!1&&this.start()}initializeGCStats(){return{scavenge:{count:0,totalDuration:0,maxPause:0},mark_sweep_compact:{count:0,totalDuration:0,maxPause:0},incremental_marking:{count:0,totalDuration:0,maxPause:0},process_weak_callbacks:{count:0,totalDuration:0,maxPause:0},all:{count:0,totalDuration:0,maxPause:0},unknown:{count:0,totalDuration:0,maxPause:0}}}start(){if(!(this.isActive||this.performanceObserver))try{if(typeof U8e.PerformanceObserver>"u"||typeof U8e.performance>"u"){Je("PERFORMANCE").app(`${this.logTag} PerformanceObserver not available in this environment`);return}this.performanceObserver=new U8e.PerformanceObserver(t=>{for(let n of t.getEntries())if(n.entryType==="gc"){let o=n.detail.kind||0,s=this.gcTypeMap[o]||"unknown",a=n.duration,u=this.gcStats[s],p=this.gcStats.all,c=U8e.performance.timeOrigin+n.startTime;u.firstGCTime||(u.firstGCTime=c),p.firstGCTime||(p.firstGCTime=c),u.count++,p.count++,u.totalDuration+=a,p.totalDuration+=a,u.lastGCTime=c,p.lastGCTime=c,u.maxPause=Math.max(u.maxPause,a),p.maxPause=Math.max(p.maxPause,a)}}),this.performanceObserver.observe({entryTypes:["gc"]}),this.isActive=!0,this.trackingStartTime=Date.now(),Je("PERFORMANCE").debug(`${this.logTag} GC performance monitoring enabled`)}catch(t){Je("PERFORMANCE").error(`${this.logTag} Failed to initialize GC monitoring:`,t)}}stop(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=void 0,this.isActive=!1)}analyzePatterns(){let t=[],n=[];if(!this.performanceObserver||!this.trackingStartTime)return{statistics:n,warnings:t};let s=(U8e.performance.now()-this.trackingStartTime)/6e4,a=Object.entries(this.gcStats);for(let[p,c]of a)if(!(p!=="scavenge"&&p!=="mark_sweep_compact")&&(p==="scavenge"&&c.maxPause>100?t.push(`Long ${p} GC pause: ${c.maxPause.toFixed(1)}ms where typical is <10ms`):p==="mark_sweep_compact"&&c.maxPause>400&&t.push(`Long ${p} GC pause: ${c.maxPause.toFixed(1)}ms where typical is 10-100ms`),s>0)){let l=c.count/s;n.push(`${p} GC frequency: ${l.toFixed(1)} GCs/minute`)}let u=this.gcStats.mark_sweep_compact;if(u.count>0&&s>0){let p=u.count/s;n.push(`Full GCs (mark_sweep_compact): ${p.toFixed(1)}/minute`)}return{statistics:n,warnings:t}}};var t9t=yt(require("fs")),Xsp=yt(require("v8"));var nW=class extends zZe{logTag="[MemoryMonitor]: ";gcTracker;threshold=75;memoryLimit;constructor(){super(),this.memoryLimit=this.getMemoryLimit(),this.suppress||(this.gcTracker=new $Qr({logTag:this.logTag}))}cleanup(){this.gcTracker?.stop()}getLogContextWithMetrics(t,n,i){let o={metric_type:"memory_telemetry",operation:i,rss_bytes:n.memUsage.rss,heap_used_bytes:n.memUsage.heapUsed,heap_total_bytes:n.memUsage.heapTotal,external_bytes:n.memUsage.external,warnings_count:n.warnings.length};try{if(this.memoryLimit){let s=n.memUsage.rss/this.memoryLimit[0]*100;o.limit_bytes=this.memoryLimit[0],o.oom_risk=s>=90?1:0}try{o.v8_available_bytes=n.heapStats.total_available_size,o.v8_heap_size_limit_bytes=n.heapStats.heap_size_limit}catch{}n.deltaData&&(o.rss_delta_bytes=n.deltaData.rssDelta,o.heap_delta_bytes=n.deltaData.heapDelta,o.external_delta_bytes=n.deltaData.externalDelta)}catch(s){Je("PERFORMANCE").errorContext(t,`${this.logTag} Error getting metrics: ${s}`)}return{...t,memoryMetrics:o}}getMemoryUsage(t){if(typeof process<"u"&&process.memoryUsage!==void 0)return process.memoryUsage();Je("PERFORMANCE").infoContext(t,`${this.logTag} Cannot get memory usage in browser environment`)}getMemoryLimit(){try{let t=this.getContainerCgroupLimit();if(t)return[t,"container"];let n=this.getNodeMemoryInfo();if(n)return[n,"node"]}catch{}}getContainerCgroupLimit(){try{let t=["/sys/fs/cgroup/memory.max"],n=["/sys/fs/cgroup/memory/memory.limit_in_bytes"];for(let i of[...t,...n])if(t9t.default.existsSync(i)){let o=t9t.default.readFileSync(i,"utf8").trim();if(o!=="max"){let s=parseInt(o,10);if(s>=67108864&&s<=1099511627776)return s}}}catch{}}getNodeMemoryInfo(){try{if(t9t.default.existsSync("/proc/meminfo")){let n=t9t.default.readFileSync("/proc/meminfo","utf8").match(/^MemTotal:\s+(\d+)\s+kB$/m);if(n&&n[1]){let o=parseInt(n[1],10)*1024;if(o>=1073741824&&o<=1099511627776)return o}}}catch{}}formatBytes(t){if(t===0)return"0B";let n=1024,i=["B","KB","MB","GB","TB"],o=Math.floor(Math.log(t)/Math.log(n));return`${parseFloat((t/Math.pow(n,o)).toFixed(1))}${i[o]}`}getMemoryWarnings(t){let n=[];if(this.memoryLimit){let[a,u]=this.memoryLimit,p=t.rss/a*100,c=a-t.rss,l=u==="container"?"container limit":"node memory",d=u==="container"?"OOM kill":"node memory exhaustion";p>=90?n.push(`\u{1F6A8} K8S ${u==="container"?"OOM":"MEMORY"} RISK: RSS at ${p.toFixed(1)}% of ${l} - Only ${this.formatBytes(c)} remaining before ${d}`):p>=this.threshold&&n.push(`\u26A0\uFE0F K8S MEMORY PRESSURE: RSS at ${p.toFixed(1)}% of ${l} - ${this.formatBytes(c)} remaining`)}let i=Xsp.default.getHeapStatistics(),o=i.total_available_size/(1024*1024);o<50?n.push(`\u{1F6A8} V8 CRITICAL: Only ${this.formatBytes(i.total_available_size)} heap space available`):o<100&&n.push(`\u26A0\uFE0F V8 WARNING: Only ${this.formatBytes(i.total_available_size)} heap space available`);let s=(t.heapTotal-t.heapUsed)/t.heapTotal*100;return s>60&&n.push(`\u26A0\uFE0F High heap fragmentation: ${s.toFixed(1)}% - consider restart`),{warnings:n,heapStats:i}}formatMemoryUsage(t){let n=t.heapUsed/t.heapTotal*100,i=`RSS: ${this.formatBytes(t.rss)}`;if(this.memoryLimit){let[o,s]=this.memoryLimit,a=t.rss/o*100;i+=` (${a.toFixed(1)}% of ${s})`}return i+=` | Heap: ${this.formatBytes(t.heapUsed)}/${this.formatBytes(t.heapTotal)} (${n.toFixed(1)}% used)`,i+=` | External: ${this.formatBytes(t.external)}`,i}analyzeDeltaConcerns(t,n,i,o){let s=[];if(t>500*1024*1024)if(this.memoryLimit){let[a]=this.memoryLimit,u=o/a*100,p=t/a*100,c=u+p;c>95?s.push(`\u{1F6A8} CRITICAL: RSS +${p.toFixed(1)}% (${this.formatBytes(t)}) \u2192 ${c.toFixed(1)}% of ${this.memoryLimit[1]} limit - OOM risk if pattern continues`):c>85?s.push(`\u26A0\uFE0F HIGH RISK: RSS +${p.toFixed(1)}% (${this.formatBytes(t)}) \u2192 ${c.toFixed(1)}% of ${this.memoryLimit[1]} limit - Monitor closely`):u>70&&s.push(`\u26A0\uFE0F LARGE INCREASE while at ${u.toFixed(1)}%: +${this.formatBytes(t)} - Watch for continued growth`)}else s.push(`\u26A0\uFE0F LARGE RSS INCREASE: +${this.formatBytes(t)} - Cannot assess OOM risk (container limit unknown)`);return n>200*1024*1024&&s.push(`\u26A0\uFE0F LARGE HEAP GROWTH: +${this.formatBytes(n)} - Check for memory leaks`),i>200*1024*1024&&s.push(`\u26A0\uFE0F LARGE EXTERNAL MEMORY: +${this.formatBytes(i)} - Check buffers`),s}getMemoryReport(t,n){let{warnings:i,heapStats:o}=this.getMemoryWarnings(t),s=this.formatMemoryUsage(t);if(this.gcTracker){let{warnings:a,statistics:u}=this.gcTracker.analyzePatterns();a.length&&a.push(`~~ GC Warnings ~~: ${a.join(" | ")}`),u.length&&(s+=` | ~~ GC Stats ~~: ${u.join(" | ")}`)}for(let a of n??[])i.push(a);return{summary:s,warnings:i,heapStats:o,memUsage:t}}logMemorySnapshot(t,n,i,o=[],s=!1){if(this.suppress||s)return;let a=this.getMemoryUsage(t);if(a)try{let u=this.getMemoryReport(a,o),p=this.getLogContextWithMetrics(t,u,i);this.logMemory(p,n,u.summary,u.warnings);return}catch(u){Je("PERFORMANCE").errorContext(t,`${this.logTag} Error logging memory snapshot: ${u}`);return}}logDeltaMetrics(t,n,i,o,s=!1){if(this.suppress||!n||s)return;let a=process.memoryUsage(),u={rssDelta:a.rss-n.rss,heapDelta:a.heapUsed-n.heapUsed,externalDelta:a.external-n.external},p=this.analyzeDeltaConcerns(u.rssDelta,u.heapDelta,u.externalDelta,a.rss),c=this.getMemoryReport(a,p);c.deltaData=u;let l=this.getLogContextWithMetrics(t,c,i);this.logMemory(l,o,c.summary,c.warnings)}};var E_=Je("CONNECTION"),XQr=r=>t=>{E_.assert(`Got error in cannot-reject function "${r}":`,t)},vre=class{constructor(t,n,i,o){this.userContext=t;this.teamInfo=n;this.logContext=i;this.maximumConnections=o;this.slots=[],this.shutdown=!1,this.canceled=!1,hh("CONNECTION",o>0,this.logContext,"At least one connection is required!")}userContext;teamInfo;logContext;maximumConnections;slots;shutdown;canceled;queued=[];memoryMonitor=new nW;totalExecutions=0;incrementExecutions(t){E_.infoContext(this.logContext,`Incrementing executions for ${t}. Total executions: ${this.totalExecutions}`),this.totalExecutions++}get executions(){return this.totalExecutions}setup=async()=>{let t="[ConnectionManager.setup()]";E_.infoContext(this.logContext,"Setting up",this.maximumConnections,"connections - for large values this may take some time");let n="ConnectionManager.setup()";await this.memoryMonitor.measureOperationAsync(this.logContext,`${t}: Before setup initialization`,`${t}: Setup completed`,n,async()=>{for(let i=0;i<this.maximumConnections;i++){let o=this.NewSlotMember(i,mu());i===0&&(E_.infoContext(this.logContext,`${t}: first slot awaiting initialization`),await this.memoryMonitor.measureOperationAsync(this.logContext,`${t}: Before first connection initialization`,`${t}: First connection initialization completed`,n,async()=>{await o.isInitialized()}),E_.infoContext(this.logContext,`${t}: first slot done initializing`)),E_.infoContext(this.logContext,`${t}: initializing slot ${o.slotID}`),o.isInitialized().then(()=>{E_.infoContext(this.logContext,`${t}: slot ${o.slotID} initialized, marking unused`,o.connectionID),this.handleNextQueued(o.markUsed()).catch(XQr("handleNextQueued"))},s=>{E_.errorContext(this.logContext,`${t}: slot ${o.slotID} failed to initialize, error: `,o.connectionID,s),o.markErrored()}),this.slots.push(o)}})};teardown=async()=>{this.memoryMonitor.cleanup(),this.shutdown=!0,await UP(this.slots.map(t=>t.teardown()))};getFirstAvailableSlot=()=>this.slots.find(t=>t.state==="unused")?.markUsed()??null;handleNextQueued=async t=>{let n=this.queued.pop();if(n===void 0){E_.debug("connection pool queue empty, freeing slot"),t.markUnused();return}await this.handleItem(t,n).catch(XQr("handleItem"))};handleItem=async(t,n)=>{let{slotID:i}=t;E_.debugContext(this.logContext,"using connection: ",i);let{callback:o,promise:s,resolve:a,reject:u}=n;try{if(this.shutdown)throw new nt("Can't run on shutdown");if(this.canceled)return u(new BA(`Connection was canceled, aborting on slot ${i}`)),this.handleNextQueued(t).catch(XQr("handleNextQueued")),s;await t.acquire();let p=await t.unwrap(),c=await o(p);a(c)}catch(p){u(p)}finally{await t.release()}return this.handleNextQueued(t).catch(XQr("handleNextQueued")),s};withConnection=async t=>{let n="[ConnectionManager.withConnection()]";if(this.shutdown)throw E_.errorContext(this.logContext,`${n}: can't run on shutdown`),new nt("Can't run on shutdown");if(this.canceled)throw E_.errorContext(this.logContext,`${n}: connection canceled before item was handled or queued`),new BA("Connection canceled before item was handled or queued");let i={...TR(),callback:t};E_.infoContext(this.logContext,`${n}: attempting to acquire a connection slot`);let o=this.getFirstAvailableSlot();return o!==null?(E_.infoContext(this.logContext,`${n}: slot ${o.slotID} found ${o.state}`),await this.handleItem(o,i)):(E_.infoContext(this.logContext,`${n}:`,this.slots.length,"connections in use, couldn't find available slot, enqueueing item"),this.queued.push(i),this.queued.length>5&&this.memoryMonitor.logMemorySnapshot(this.logContext,`${n}: Queued connection pool size: ${this.queued.length}`,"withConnection")),i.promise};getConnection=()=>({execute:n=>this.withConnection(i=>i.execute(n)),teardown:()=>Promise.resolve(),logContext:this.logContext});async cancel(){try{if(E_.infoContext(this.logContext,"Begin canceling all connections in the ConnectionManager"),this.canceled)return E_.infoContext(this.logContext,"ConnectionManager already canceled"),Promise.resolve();this.canceled=!0;let t=this.slots.map(n=>n.cancel());await UP(t)}catch(t){throw E_.errorContext(this.logContext,"Error canceling all connections in the ConnectionManager",t),t}finally{E_.infoContext(this.logContext,"Completed canceling all connections in the ConnectionManager")}}showQueued=()=>this.queued};var jct=Je("CONNECTION"),Tre=class{constructor(t,n,i,o,s,a){this.slotID=t;this.connectionID=n;this.userContext=i;this.teamInfoAndFirebase=o;this.logContext=s;this.managerQueryStats=a;this.initPromise=this.initialize(),this.firstInitPromise=this.initPromise.then(()=>this.setup())}slotID;connectionID;userContext;teamInfoAndFirebase;logContext;managerQueryStats;handle=null;state="initializing";connection=null;firstInitPromise;initPromise;useCount=0;canceled=!1;async initialize(){this.handle=await this.createConnection()}async postReInitialization(){}reinitialize=async()=>{let t=this.createConnection();return this.initPromise=t.then(n=>{this.handle=n}),await this.postReInitialization(),t};async acquire(t){if(this.state!=="in use")throw new DA(`Expected slot to be in use, but it was ${this.state}`);if(!t&&this.connection)throw hh("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new DA(`Cannot acquire in-use connection ${this.connectionID}`);if(this.canceled)throw new BA("Attempting to acquire canceled connection slot entry",this.connectionID);if(this.connection=await this.newConnection(),this.useCount++,this.canceled)throw this.connection=null,new BA("Attempting to acquire canceled connection slot entry",this.connectionID)}async release(){this.connection=null}async unwrap(){if(this.state!=="in use")throw new DA(`Expected slot to be in use, but it was ${this.state}`);return await this.assertConnected(),this.connection}async isInitialized(){return this.firstInitPromise}async assertConnected(){if(!this.connection)throw hh("CONNECTION",!1,this.logContext,"Connection was not acquired before connection check!"),new DA("Connection was not acquired before connection check!");await this.initPromise}async execute(t){return(await Ah("Waiting for connection",this.logContext,"CONNECTION",()=>this.unwrap())).execute(t)}async cancel(){try{if(jct.infoContext(this.logContext,"Begin canceling connection slot entry",this.connectionID),this.canceled){jct.infoContext(this.logContext,"Connection slot entry already canceled",this.connectionID);return}if(this.canceled=!0,this.connection){let t=this.connection;this.connection=null,await t.cancel()}else jct.infoContext(this.logContext,"Canceling connection slot entry",this.connectionID,"no-op")}catch(t){throw jct.errorContext(this.logContext,"Error canceling connection slot entry",this.connectionID,t),t}finally{jct.infoContext(this.logContext,"Completed canceling managed connection",this.connectionID)}}async teardown(){jct.infoContext(this.logContext,`[ConnectionManagerSlotMember]: Tearing down ${this.userContext.kind} connection`,this.connectionID),await this.initPromise.catch(()=>{}),await this.firstInitPromise.catch(()=>{}),this.handle&&await(this.connection||this.newConnection()).teardown()}markUsed(){return this.state="in use",this}markUnused(){return this.state="unused",this}markErrored(){return this.state="error",this}};var r9t=Je("CONNECTION"),gvs=async(r,t,n)=>{let{rootRepository:i,teamInfo:o,teamInfo:{fbTeamID:s,fbUserID:a}}=t,{environmentID:u}=r;if(!u)throw new nt(`No environmentID provided for org ${s} by user ${a}`);if(r.authenticator!=="OAuthU2M")throw new eH(`Cannot reset oauth connection on a non-oauth connection type: ${r.authenticator}`,"OAuthU2M");let p=await Hct(i.org(s),o,u,jh.Values.databricks),c=await tjr(n);if(!c.refresh_token)throw new eH("Missing or invalid OAuth refresh token, please reauthenticate.","OAuthU2M");let l=c.refresh_token,d=await rjr(p,l,n);return await JQr(n,{access_token:d,refresh_token:l}),d},hvs=class extends Tre{name="databricks";async createConnection(){let t=this.userContext.authenticator==="OAuthU2M"?Zsp(this.userContext,this.teamInfoAndFirebase,this.logContext):void 0,n=await ejr(this.userContext,t);return Avs(n)}async updateFromResult(t){}async setup(){await this.connectAndValidate()}async assertConnected(){if(await super.assertConnected(),this.handle===null)throw hh("CONNECTION",!1,this.logContext,"Connection was null after initPromise!"),new DA("Connection was null after initPromise!")}async postReInitialization(){await this.connectAndValidate(),await this.acquire(!0)}async connect(){if(!this.handle){r9t.alertContext(this.logContext,"No handle found in DatabricksConnectionManagerSlotMember.connect");return}return this.handle.session||(this.handle.session=await this.handle.client.openSession(),this.handle.sessionOptions={}),this.handle.session}async resetOauth(){let t=await gvs(this.userContext,this.teamInfoAndFirebase,this.logContext);this.userContext.accessToken=t}async connectAndValidate(){await this.initPromise;try{await this.connect()}catch(t){if(this.userContext.authenticator==="OAuthU2M"&&Qct(t)){await this.resetOauth();try{this.initPromise=this.initialize(),await this.initPromise,await this.connect()}catch(n){if(r9t.errorContext(this.logContext,"Just refreshed oauth tokens, shouldn't have gotten here unless another process did it at the same time: ",n),Qct(n))this.initPromise=this.initialize(),await this.initPromise,await this.connect();else throw n}}else throw t}}async teardown(){r9t.infoContext(this.logContext,`Tearing down ${this.name} connection`,this.connectionID),await this.initPromise.catch(()=>{}),await this.firstInitPromise.catch(()=>{}),this.handle&&await mvs(this.handle,this.logContext)}async acquire(t){if(!t&&this.connection)throw hh("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new DA(`Cannot acquire in-use connection ${this.connectionID}`);if(this.canceled)throw new BA("Attempting to acquire canceled connection slot entry",this.connectionID);if(this.connection=new Gct(this.handle,this.logContext,this.connectionID,this.useCount,this),this.useCount++,this.canceled)throw this.connection=null,new BA("Attempting to acquire canceled connection slot entry",this.connectionID)}newConnection(){return new Gct(this.handle,this.logContext,this.connectionID,this.useCount,this)}},ZQr=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new hvs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}async test(){let t="DatabricksConnectionManager.test:",n=Nb(this.userContext,"authenticator","kind","role","user","warehouse");r9t.appContext(this.logContext,t,"testing connection",n),await this.withConnection(async i=>i.execute({statement:h5})),r9t.appContext(this.logContext,t,"connection successfully established",n)}};var LKp=yt(fYe()),bnn=yt(cWp());function lWp(r,t=null){return t??`https://${r}.snowflakecomputing.com`}var DKp=yt(NKp());var ymS=Je("JSON_PARSER");var M2m=Je("XML_PARSER");var BKp=r=>{let t=new DKp.Parser({attrkey:"@",charkey:"#",explicitArray:!1}),n;return t.parseString(r,(i,o)=>{if(i)throw i;n=o}),M2m.debug("$Parsed JSON",JSON.stringify(n,null,2)),n};var r1t=Je("CONNECTION"),x2m=()=>{let r=process.env.COALESCE_SNOWFLAKE_LOG_LEVEL?.toUpperCase(),t=r==="ERROR"||r==="WARN"||r==="INFO"||r==="DEBUG"||r==="TRACE"?r:"OFF",n=process.env.COALESCE_SNOWFLAKE_LOG_FILE;bnn.configure({xmlColumnVariantParser:BKp,keepAlive:!1,logLevel:t,logFilePath:n})};x2m();function P2m(r){return r.startsWith("https://")?r:`https://${r}`}var kKp={sfRetryMaxLoginRetries:4},Y7s=r=>!(!r.accountName||!r.user),J7s=r=>{let{accountName:t,accessUrl:n,user:i,warehouse:o}=r;return{account:t,username:i,application:"CoalesceIO_Coalesce",...n&&{accessUrl:P2m(n)},...o&&{warehouse:o}}},N2m=(r,t)=>{if(!Y7s(r))throw r1t.infoContext(t,"Error creating basic snowflake connection parameters (CreateSnowflakeConnectionBasic)",{user:Eme(r.user),accountName:Eme(r.accountName)}),new yX("Invalid Connection Information, please correct your account or username and proceed.","Basic");let{password:n,role:i}=r;return{...J7s(r),password:n,...i&&{role:i},...kKp}},D2m=(r,t)=>{if(!Y7s(r))throw r1t.infoContext(t,"Error creating basic snowflake connection (CreateSnowflakeConnectionKeyPair)",{user:Eme(r.user),accountName:Eme(r.accountName)}),new yX("Invalid Connection Information, please correct your account or username and proceed.","KeyPair");let{keyPairKey:n,keyPairPass:i,role:o}=r;return{...J7s(r),authenticator:"SNOWFLAKE_JWT",privateKey:n,privateKeyPass:i??void 0,...o&&{role:o},...kKp}},$7s=async(r,t)=>{let{workspaceID:n,orgID:i,userID:o}=r;try{let s=await hI(),a=await Wsp(s,{orgId:i,userId:o,workspaceId:n.toString()},t);if(r1t.infoContext(r,"get access token from secret (GetAccessTokenFromSecret)"),!a)throw new cWe("Invalid OAuth configuration.");return a.sensitiveValue}catch(s){throw r1t.errorContext(r,"Error getting access token from secret (GetAccessTokenFromSecret)",s),s}},B2m=async(r,t,n)=>{if(!Y7s(r))throw r1t.infoContext(t,"Error creating basic snowflake connection (CreateSnowflakeConnectionOAuth)",{user:Eme(r.user),accountName:Eme(r.accountName)}),new yX("Invalid Connection Information, please correct your account or username and proceed.","OAuth");let i=await $7s(t,n);return{...J7s(r),authenticator:"OAUTH",token:i.access_token??void 0}},L2m=r=>{try{return bnn.createConnection(r)}catch(t){throw new yle(t)}},Enn=async(r,t,n)=>{let i;switch(r.authenticator){case"Basic":case"Cloud":i=N2m(r,t);break;case"KeyPair":i=D2m(r,t);break;case"OAuth":i=await B2m(r,t,n);break;default:throw new DA(`authenticator type of ${r.authenticator} not supported`)}return L2m(i)},k2m=r=>`${r.response?.data?.error}: ${r.response?.data?.message}`,qKp=async(r,t,n)=>{let i=LKp.default.stringify({grant_type:"refresh_token",refresh_token:t}),s=`${lWp(r.connectionAccount,r.accessUrl)}/oauth/token-request`,a=Buffer.from(`${r.oauthClientID}:${r.oauthClientSecret}`).toString("base64"),u={method:"post",url:s,headers:{Authorization:`Basic ${a}`,"Content-Type":"application/x-www-form-urlencoded"},data:i};try{return(await dc(u)).data.access_token}catch(p){let c=p instanceof Sao?k2m(p):"unknown";throw r1t.errorContext(n,`RefreshAccessToken: ${c}`,p),new yX("An error occured refreshing your OAuth refresh_token. Please ensure your OAuth Security Integration is still valid or reauthenticate.","OAuth",p)}};var SRe=Je("CONNECTION"),Bne=class{constructor(t,n,i,o,s,a){this.handle=t;this.logContext=n;this.connectionID=i;this.useCounter=o;this.parent=s;a?this.resetConnectionHandle=()=>a():s?this.resetConnectionHandle=()=>s.reinitialize():this.resetConnectionHandle=()=>{throw new DA("Cannot reset the connection, no reset function provided")}}handle;logContext;connectionID;useCounter;parent;runningQueries=new Map;wasCanceled=!1;resetConnectionHandle;get memoryMonitor(){return this.parent?this.parent.managerQueryStats.memoryMonitor:(SRe.debugContext(this.logContext,"Could not get memory monitor from parent. This may be expected.",this.connectionID),{logDeltaMetrics:()=>{},getMemoryUsage:()=>{}})}async resetConnection(){if(this.wasCanceled)throw new BA("not resetting canceled connection");gI(`${this.name}.resetConnection`,this.logContext);let t=await this.resetConnectionHandle();return this.handle=t,t}async executeAndGetRunning(t){let n=this.parent?.managerQueryStats.executions,i=!n||n%50!==0,o=`(${this.name}) BaseConnection.executeAndGetRunning()`,s=this.memoryMonitor.getMemoryUsage(this.logContext),a=await this.makePendingQuery(t);return a.attachThen(u=>{this.parent&&this.parent.updateFromResult(u),this.memoryMonitor.logDeltaMetrics(this.logContext,s,o,`(connID: ${this.connectionID})[${this.name} executeAndGetRunning()]: completed pending query | total executions: ${n}`,i)}),this.parent&&this.parent.managerQueryStats.incrementExecutions(`[${this.name} executeAndGetRunning()]:${this.connectionID}`),a}execute=async t=>(await this.executeAndGetRunning(t)).promise;cancel=async()=>{try{if(SRe.infoContext(this.logContext,"Begin canceling connection",this.connectionID),this.wasCanceled)return SRe.infoContext(this.logContext,"Connection already canceled",this.connectionID),Promise.resolve();this.wasCanceled=!0;let t=Array.from(this.runningQueries.values()).map(async n=>{SRe.infoContext(this.logContext,"Begin canceling query",n.coalesceQueryID,"conn",this.connectionID);try{await n.Cancel()}catch(i){throw SRe.errorContext(this.logContext,"Error canceling query",n.coalesceQueryID,"conn",this.connectionID,i),i}finally{SRe.infoContext(this.logContext,"Completed canceling query",n.coalesceQueryID,"conn",this.connectionID)}});await UP(t)}catch(t){throw SRe.errorContext(this.logContext,"Error canceling connection",this.connectionID,t),t}finally{SRe.infoContext(this.logContext,"Completed canceling connection",this.connectionID)}}};var X7s=yt(require("v8"));var Lne=Je("CONNECTION"),Cnn=class extends Error{constructor(n,i,o,s){super("Heap size exceeded");this.heapStats=n;this.currentSize=i;this.stmt=o;this.rows=s}heapStats;currentSize;stmt;rows;makeResult=()=>{let n=this.stmt,i=n.getSessionState();return{rows:this.rows,stmt:this.stmt,status:dL,queryID:n.getStatementId(),warehouse:i?.getCurrentWarehouse?.()||null}};makeErrorMessage=n=>{let i=n$(this.heapStats.total_heap_size),o=n$(n.heap_size_limit),s=n$(this.currentSize),a=n$(s3e());return`Chunk limit reached,
|
|
10495
|
+
${c}`,l)});o.length&&yJo.infoContext(r.logContext,n,"Error(s) transforming results from storage",...o);let{runResults:a,fullRunResults:u}=E91(s,i,r.logContext,n),p=C91(u);return i.runResults.runResults=p.map(c=>a[c]),i};var lrl=(r,t)=>{let n="--",i="--",o="--";if(!("rows"in t))return t.rowsInserted&&(n=t.rowsInserted),t.rowsUpdated&&(i=t.rowsUpdated),t.rowsDeleted&&(o=t.rowsDeleted),{rowsInserted:n,rowsUpdated:i,rowsDeleted:o};if(r==="refresh")if(!t.rows[0])n=0,i=0,o=0;else{let s=t.fields.findIndex(p=>p.name==="number of rows inserted"),a=t.fields.findIndex(p=>p.name==="number of rows updated"),u=t.fields.findIndex(p=>p.name==="number of rows deleted");n=s===-1?0:t.rows[0].values[s],i=a===-1?0:t.rows[0].values[a],o=u===-1?0:t.rows[0].values[u]}return{rowsInserted:n,rowsUpdated:i,rowsDeleted:o}};var v91=["nodes","subgraphs","jobs"],J3C=[...v91,"docs","problems","subfolders","git"];var $3C=B.object({hierarchy:B.array(B.string()),key:B.string(),type:B.string(),value:B.string(),stepCounter:B.string().optional(),tagColor:B.string().optional()}),X3C=B.object({selectedNodeIDs:B.object({nodes:B.record(B.boolean()),subgraphs:B.record(B.boolean()),jobs:B.record(B.boolean()),docs:B.record(B.boolean()),problems:B.record(B.boolean()),subfolders:B.record(B.boolean()),git:B.record(B.boolean())})});var uIC=Je("GRAPH"),wxr=async(r,t,n)=>{let i=await T91(r,t);return ttt(t.runDetails,n,i)},T91=async(r,t)=>{let n=new Set,i=await L0l(t.reRunID,r);for(let o of i){let s=await r.run(o).runResults.select();for(let{id:a,runState:u}of s)u==="complete"&&n.add(a)}return n},ttt=(r,t,n)=>_91(r,t,n||new Set)||new Set(Object.keys(t.steps)),bJo=(r,t,n,i)=>({steps:r,allStepTypesYAML:VEr(n,t),allSubgraphs:i}),_91=(r,t,n)=>{let i=null,o="",s="";if(r.jobID?{includeSelector:o,excludeSelector:s}=CHc(t,+r.jobID):(r.includeNodesSelector||r.excludeNodesSelector)&&(o=r.includeNodesSelector||"",s=r.excludeNodesSelector||""),o||s||n.size){let a=bJo(t.steps,t.stepTypes,t.installedPackages??{},t.folders);i=new Set(I91(o,s,a).filter(u=>!n.has(u)))}return i},I91=(r,t,n)=>{let i=RIt(n.steps);n.graphInformation=i;let o=HEr(r,t,n);return Object.keys(o.stepsResult)},R2e=r=>{let t=new Set;for(let n of Object.values(r))for(let i in n)t.add(i);return t};var R91=(r,t)=>{if(t=t===void 0?oAc:t,r<=1||t<=1)return 1;let s=r<=4?r:Math.floor((r-4)/2)+4;return Math.min(s,t)},Ppe=(r,t)=>{let n=R91(r,t),i=sAc,o=i<n?i:n;return o>0?o:1};var q0l=async(r,t)=>{let n=await r.fetch({ignoreDataTransformErrors:!0}),i={fbEmail:t?.emptyEmail?"":n.email,fbUserID:r.id,fbTeamID:n.currentTeam,fbFullName:`${n.firstName} ${n.lastName}`,fbFirstName:n.firstName,fbLastName:n.lastName,fbHasSuperUserAccess:n.hasSuperUserAccess,fbActivated:n.activated??!0};return t?.populateProvisioningAccess&&(i.hasProvisioningAccess=n.hasProvisioningAccess),i},F0l=async(r,t)=>(await r.org(t).fetch()).superDebugEnabled;var HKp=yt(a3l());var VKp=yt(fYe());var zsp=yt(Tze());var Fsp=yt(Tze());var Twl=yt(vwl());var LLr=yt(bU());var X0s=require("perf_hooks");function $Eg(r){let t=X0s.performance.now()*.001,n=Math.floor(t),i=Math.floor(t%1*1e9);return r!=null&&(n=n-r[0],i=i-r[1],i<0&&(n--,i+=1e9)),[n,i]}function dBe(){let[r,t]=$Eg();return r*1e3+Math.floor(t/1e6)}function PLr(r){return new Promise(t=>setTimeout(t,r))}var NLr=class{constructor({bucketSize:t,tokensPerInterval:n,interval:i,parentBucket:o}){if(this.bucketSize=t,this.tokensPerInterval=n,typeof i=="string")switch(i){case"sec":case"second":this.interval=1e3;break;case"min":case"minute":this.interval=1e3*60;break;case"hr":case"hour":this.interval=1e3*60*60;break;case"day":this.interval=1e3*60*60*24;break;default:throw new Error("Invalid interval "+i)}else this.interval=i;this.parentBucket=o,this.content=0,this.lastDrip=dBe()}async removeTokens(t){if(this.bucketSize===0)return Number.POSITIVE_INFINITY;if(t>this.bucketSize)throw new Error(`Requested tokens ${t} exceeds bucket size ${this.bucketSize}`);this.drip();let n=async()=>{let i=Math.ceil((t-this.content)*(this.interval/this.tokensPerInterval));return await PLr(i),this.removeTokens(t)};if(t>this.content)return n();if(this.parentBucket!=null){let i=await this.parentBucket.removeTokens(t);return t>this.content?n():(this.content-=t,Math.min(i,this.content))}else return this.content-=t,this.content}tryRemoveTokens(t){return this.bucketSize?t>this.bucketSize||(this.drip(),t>this.content)||this.parentBucket&&!this.parentBucket.tryRemoveTokens(t)?!1:(this.content-=t,!0):!0}drip(){if(this.tokensPerInterval===0){let s=this.content;return this.content=this.bucketSize,this.content>s}let t=dBe(),n=Math.max(t-this.lastDrip,0);this.lastDrip=t;let i=n*(this.tokensPerInterval/this.interval),o=this.content;return this.content=Math.min(this.content+i,this.bucketSize),Math.floor(this.content)>Math.floor(o)}};var fit=class{constructor({tokensPerInterval:t,interval:n,fireImmediately:i}){this.tokenBucket=new NLr({bucketSize:t,tokensPerInterval:t,interval:n}),this.tokenBucket.content=t,this.curIntervalStart=dBe(),this.tokensThisInterval=0,this.fireImmediately=i??!1}async removeTokens(t){if(t>this.tokenBucket.bucketSize)throw new Error(`Requested tokens ${t} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);let n=dBe();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),t>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)return-1;{let o=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-n);await PLr(o);let s=await this.tokenBucket.removeTokens(t);return this.tokensThisInterval+=t,s}}let i=await this.tokenBucket.removeTokens(t);return this.tokensThisInterval+=t,i}tryRemoveTokens(t){if(t>this.tokenBucket.bucketSize)return!1;let n=dBe();if((n<this.curIntervalStart||n-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=n,this.tokensThisInterval=0),t>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;let i=this.tokenBucket.tryRemoveTokens(t);return i&&(this.tokensThisInterval+=t),i}getTokensRemaining(){return this.tokenBucket.drip(),this.tokenBucket.content}};var Z0s=r=>r;var vee=Je("SECRETS");function tfs(r,t){return!!r&&typeof r=="object"&&"code"in r&&r.code===t}function XEg(r){return tfs(r,LLr.Status.INVALID_ARGUMENT)&&"details"in r&&typeof r.details=="string"&&r.details.startsWith("Secret payload data length must be at most")}function hit(r){return tfs(r,LLr.Status.NOT_FOUND)||ZEg(r)}function ZEg(r){return tfs(r,LLr.Status.FAILED_PRECONDITION)&&typeof r?.message=="string"&&r.message.includes("is in DESTROYED state")}function efs(r){if(!r)return null;let t=r.split("/").pop();if(!t)return null;let n=parseInt(t);return Number.isNaN(n)?null:n}var e2g=9e4,t2g=600,r2g=600,rfs=10,n2g=new fit({tokensPerInterval:e2g/rfs,interval:"minute"}),i2g=new fit({tokensPerInterval:t2g/rfs,interval:"minute"}),DLr=new fit({tokensPerInterval:r2g/rfs,interval:"minute"}),o2g=new aL(1),BLr=class{constructor(t,n=new Twl.SecretManagerServiceClient){this.projectId=t;this.client=n}projectId;client;shouldUpgradeLegacyResultsToNewName(){return!1}BuildSecretName=t=>`projects/${this.projectId}/secrets/${t}`;BuildSecretNameLatestVersion=t=>`${this.BuildSecretName(t)}/versions/latest`;getByName=async t=>{await n2g.removeTokens(1);let n=await this.client.accessSecretVersion({name:this.BuildSecretNameLatestVersion(t)}),[i]=n,o=i.payload?.data?.toString();return o?new zd(o):null};makeAddVersionData=(t,n)=>({parent:this.BuildSecretName(t),payload:{data:Z0s(Buffer.from(n.sensitiveValue))}});addVersionByName=async(t,n)=>{let i=this.makeAddVersionData(t,n);await DLr.removeTokens(1),await this.client.addSecretVersion(i),this.PruneInaccessibleVersions(t).catch(o=>{vee.error("Could not prune versions for",t,o)})};setByName=async(t,n)=>{await DLr.removeTokens(2);let i=this.makeAddVersionData(t,n);await this.client.createSecret({parent:`projects/${this.projectId}`,secretId:t,secret:{replication:{automatic:{}}}}),await this.client.addSecretVersion(i)};listSecretVersions=async t=>{await i2g.removeTokens(1);let[n]=await this.client.listSecretVersions({parent:this.BuildSecretName(t)});return n};destroySecretVersion=async t=>{await DLr.removeTokens(1),await this.client.destroySecretVersion({name:t})};getMissingSecret=async t=>{let n=JMr(t);if(n)try{let i=await this.getByName(n);return i&&this.shouldUpgradeLegacyResultsToNewName()&&(await this.setByName(t,i),await this.deleteByName(n)),i}catch(i){if(!hit(i))throw i}return null};Get=async t=>{try{return await this.getByName(t)}catch(n){if(hit(n))return this.getMissingSecret(t);throw n}};setMissingSecret=async(t,n)=>{let i=JMr(t);if(!i)await this.setByName(t,n);else if(this.shouldUpgradeLegacyResultsToNewName())await this.setByName(t,n),await this.deleteByName(i,{ignoreMissing:!0});else try{await this.addVersionByName(i,n)}catch(o){if(hit(o)){await this.setByName(t,n);return}throw o}};Set=async(t,n)=>{try{await this.addVersionByName(t,n);return}catch(i){if(hit(i)){await this.setMissingSecret(t,n);return}throw XEg(i)&&vee.emerg("Payload exceeded for: ",t,"Reach out to support to determine if feature flags to adjust secret storage are appropriate next steps",i),i}};deleteByName=async(t,n)=>{try{await DLr.removeTokens(1),await this.client.deleteSecret({name:this.BuildSecretName(t)})}catch(i){if(n?.ignoreMissing&&hit(i))return;throw i}};Delete=async t=>{let n=JMr(t),i=[t];n&&i.push(n),await UP(i.map(o=>this.deleteByName(o,{ignoreMissing:!0})))};async PruneInaccessibleVersions(t){try{vee.info("Begin pruning inaccessible versions for secret",t),await o2g.runExclusive(async()=>{vee.info("Got lock for pruning inaccessible versions for secret",t);let i=(await this.listSecretVersions(t)).filter(o=>o.state==="ENABLED"&&!!efs(o.name)).sort((o,s)=>efs(s.name)-efs(o.name)).slice(1);for(let o of i)try{vee.info("Destroying secret version",o.name),await this.destroySecretVersion(o.name),vee.info("Successfully destroyed secret version",o.name)}catch(s){hit(s)?vee.error("Tried to prune secret",o.name,"but it was not found"):vee.alert("Error trying to prune inaccessible secret version",o.name,". Error: ",s)}},1)}catch(n){vee.alert("Fatal error trying to prune inaccessible secret versions for secret",t,". Error: ",n)}finally{vee.info("Completed pruning inaccessible versions for secret",t)}}};var rjl=yt(tjl());var p7r=class r{client;constructor(t){this.client=(0,rjl.createClient)({url:t})}static Create=async t=>{let n=new r(t);return await n.client.connect(),n};Get=async t=>{let n=await this.client.get(t);return n===null?null:new zd(n)};Set=async(t,n)=>{await this.client.set(t,n.sensitiveValue)};Delete=async t=>{await this.client.del(t)}};vr();var duA=yt(HQr());var ouA=B.enum(["org-settings-read","org-settings-write","org-users-read","org-users-write","org-users-create","org-users-delete","org-userRoles-read","org-userRoles-write","org-projects-create","org-tags-create","org-tags-delete","org-tags-write","org-tags-read"]),suA=B.enum(["project-settings-read","project-summary-read","project-settings-write","project-delete","project-members-read","project-members-add","project-members-write","project-members-remove","project-userRoles-read","project-workspaces-create","project-documentation-read","project-environments-create","project-workspace-settings-read","project-workspace-settings-write","project-workspaces-delete","project-workspace-jobs-create","project-workspace-jobs-read","project-workspace-jobs-write","project-workspace-jobs-delete","project-workspace-macros-create","project-workspace-macros-read","project-workspace-macros-write","project-workspace-macros-delete","project-workspace-node-types-create","project-workspace-node-types-read","project-workspace-node-types-write","project-workspace-node-types-delete","project-workspace-nodes-create","project-workspace-nodes-read","project-workspace-nodes-write","project-workspace-nodes-delete","project-workspace-packages-create","project-workspace-packages-read","project-workspace-packages-write","project-workspace-packages-delete","project-workspace-sql-run","project-workspace-subgraphs-create","project-workspace-subgraphs-read","project-workspace-subgraphs-write","project-workspace-subgraphs-delete"]),auA=B.enum(["env-run-results-read","env-run-job","env-delete","env-deploy","env-refresh","env-settings-read","env-summary-read","env-settings-write","env-documentation-read","env-members-read","env-members-add","env-members-write","env-members-remove","env-userRoles-read","env-job-schedule-write","env-job-schedule-read"]),uuA={reader:{permissions:["env-run-results-read","env-summary-read","env-documentation-read","env-job-schedule-read"],inheritedEnvironmentRoles:[]},admin:{permissions:[...auA.options],inheritedEnvironmentRoles:["reader"]}},cuA={member:{permissions:["project-summary-read","project-members-read","project-workspace-sql-run","project-workspace-nodes-read"],inheritedProjectRoles:[],inheritedEnvironmentRoles:[]},contributor:{permissions:["project-settings-read","project-members-read","project-workspaces-create","project-workspace-settings-read","project-workspace-settings-write","project-workspaces-delete","project-workspace-jobs-read","project-workspace-jobs-create","project-workspace-jobs-write","project-workspace-jobs-delete","project-workspace-macros-read","project-workspace-node-types-read","project-workspace-nodes-create","project-workspace-nodes-write","project-workspace-nodes-delete","project-workspace-packages-read","project-workspace-subgraphs-read","project-workspace-subgraphs-create","project-workspace-subgraphs-write","project-workspace-subgraphs-delete","project-documentation-read","env-delete","env-documentation-read"],inheritedProjectRoles:["member"],inheritedEnvironmentRoles:["reader"]},architect:{permissions:["project-workspace-macros-create","project-workspace-macros-write","project-workspace-macros-delete","project-workspace-node-types-create","project-workspace-node-types-write","project-workspace-node-types-delete","project-workspace-packages-create","project-workspace-packages-write","project-workspace-packages-delete"],inheritedProjectRoles:["contributor"],inheritedEnvironmentRoles:["reader"]},admin:{permissions:[...suA.options],inheritedProjectRoles:["architect"],inheritedEnvironmentRoles:["admin"]}},luA={member:{permissions:["org-tags-read"],inheritedOrganizationRoles:[],inheritedProjectRoles:[]},contributor:{permissions:["org-projects-create"],inheritedOrganizationRoles:["member"],inheritedProjectRoles:[]},admin:{permissions:[...ouA.options],inheritedOrganizationRoles:["contributor"],inheritedProjectRoles:["admin"]}},WQr=r=>{let t=uuA[r],n=new Set(t.permissions);for(let i of t.inheritedEnvironmentRoles)WQr(i).forEach(o=>n.add(o));return Array.from(n)},Uct=r=>{let t=cuA[r],n=new Set(t.permissions);for(let i of t.inheritedProjectRoles)Uct(i).forEach(o=>n.add(o));for(let i of t.inheritedEnvironmentRoles)WQr(i).forEach(o=>n.add(o));return Array.from(n)},VQr=r=>{let t=luA[r],n=new Set(t.permissions);for(let i of t.inheritedOrganizationRoles)VQr(i).forEach(o=>n.add(o));for(let i of t.inheritedProjectRoles)Uct(i).forEach(o=>n.add(o));return Array.from(n)},_sp={admin:VQr("admin"),contributor:VQr("contributor"),member:VQr("member")},Isp={admin:Uct("admin"),architect:Uct("architect"),contributor:Uct("contributor"),member:Uct("member")},Rsp={admin:WQr("admin"),reader:WQr("reader")};var puA=Je("USER_MANAGEMENT"),rvs=class{throwIfOrgPermissionDenied(t,n=!1){if(!this.hasOrgPermission(t))throw n?new Du("The requested resource is unavailable"):new Ww("Permission denied",`Permission '${t}' is required to perform this operation.`)}throwIfProjectPermissionDenied(t,n,i=!1){if(!this.hasProjectPermission(t,n))throw i?new Du("The requested resource is unavailable"):new Ww("Permission denied",`Permission '${t}' is required to perform this operation.`)}throwIfEnvironmentPermissionDenied(t,n,i,o=!1){if(!this.hasEnvironmentPermission(t,n,i))throw o?new Du("The requested resource is unavailable"):new Ww("Permission denied",`'Permission ${t}' is required to perform this operation.`)}},KQr=class r extends rvs{constructor(n,i){super();this.userRoles=n;this.hasSuperUserAccess=i;this.userPermissions=this.ConstructPermissionsFromRoles(n)}userRoles;hasSuperUserAccess;userPermissions;get orgRoles(){return this.userRoles?.organizationRoles??[]}hasOrgPermissionInternal(n){return this.userPermissions.organizationPermissions?.has(n)}hasOrgPermission(n){return this.hasSuperUserAccess||this.hasOrgPermissionInternal(n)}hasProjectPermissionInternal(n,i){return this.userPermissions.projects[i]?.projectPermissions?.has(n)}hasProjectPermission(n,i){return this.hasSuperUserAccess||this.hasOrgPermissionInternal(n)||this.hasProjectPermissionInternal(n,i)}hasEnvironmentPermissionInternal(n,i,o){return this.userPermissions.projects[i]?.environments[o]?.environmentPermissions?.has(n)}hasEnvironmentPermission(n,i,o){return this.hasSuperUserAccess||this.hasOrgPermissionInternal(n)||this.hasProjectPermissionInternal(n,i)||this.hasEnvironmentPermissionInternal(n,i,o)}ConstructPermissionsFromRoles(n){return n?(n.projects||(puA.warn(`userRoles.projects is undefined for user ${n.id}, defaulting to empty object`),n.projects={}),{organizationPermissions:r.ConstructOrgPermissionsFromRoles(n.organizationRoles),projects:r.ConstructProjectsPermissionsFromRoles(n.projects)}):{organizationPermissions:new Set,projects:{}}}static ConstructEnvironmentPermissionsFromRoles(n){let i=new Set;return n.environmentRoles.forEach(o=>{Rsp[o].forEach(s=>{i.add(s)})}),i}static ConstructEnvironmentPermissionObjectsFromRoles(n){let i={};return Object.entries(n).forEach(([o,s])=>{i[o]={environmentPermissions:r.ConstructEnvironmentPermissionsFromRoles(s)}}),i}static ConstructProjectPermissionsFromRoles(n){let i=new Set;return n.projectRoles.forEach(s=>{Isp[s].forEach(a=>{i.add(a)})}),{projectPermissions:i,environments:r.ConstructEnvironmentPermissionObjectsFromRoles(n.environments)}}static ConstructProjectsPermissionsFromRoles(n){let i={};return Object.keys(n).forEach(o=>{i[o]=this.ConstructProjectPermissionsFromRoles(n[o])}),i}static ConstructOrgPermissionsFromRoles(n){let i=new Set;return n.forEach(o=>{_sp[o].forEach(s=>{i.add(s)})}),i}};var Osp=Je("AUTH"),RKC=Je("USER_MANAGEMENT"),fuA=async(r,t,n,i,o)=>{let s={};try{let a=await r(),{context:{userID:u},token:p}=await t(a);s.userID=u;let c=o||await n(a,p),l=await q0l(c.user(u),{emptyEmail:!0,populateProvisioningAccess:!0});s.orgID=l.fbTeamID;let d=K8.getActiveSpan();d&&(d.setAttribute("userID",u),d.setAttribute("orgID",l.fbTeamID));let f=await i({org:{id:l.fbTeamID},user:{id:u},...Dv&&{version:{id:Dv.version}}},c,p),h=await c.org(l.fbTeamID).userRole(u).fetch(),A=new KQr(h,!!l.fbHasSuperUserAccess);return{teamInfo:l,firebase:a,rootRepository:c,token:p,featureFlags:f,userPermissions:A}}catch(a){if(Osp.errorContext(s,"AuthenticateTokenAndRetrieveTeamInfo",a),a instanceof KY)throw a;let u=a?.message||a?.error?.errorString;throw new nt("Unable to authenticate, please check your network connection and ensure your token is valid",u)}},wsp=async(r,t,n,i,o)=>{let s="[AuthenticateTokenAndRetrieveTeamInfo]",a={};return cf(async()=>Ah(s,a,"AUTH",()=>fuA(r,t,n,i,o),"info"),4,Osp,a,{alterRetryStrategy:p=>({name:"backoff",base:oWe(aa(p,!0),"QUOTA_EXCEEDED")||oWe(aa(p,!0),"Unable to authenticate")?60:1}),checkError:p=>{if(p instanceof KY)return p;let c=aa(p,!0);if(["INVALID_REFRESH_TOKEN","EXPIRED_TOKEN","Missing or invalid OAuth refresh token","OAuth access token expired","Invalid Token","JWT ID token expired","Decoding Firebase ID token failed","Token expired","User not found","User disabled"].some(d=>oWe(c,d)))return p},logOnRetry:`${s} retrying`,logOnFailure:`${s} failed, exhausted allotted retry attempts`})};var Bsp=yt(Tze()),Lsp=require("node:fs/promises");vr();var Msp;var Cre=(r,t={},n=1)=>{Msp&&Msp.increment(r,t,n)};var huA=B.object({auth:B.string(),firestore:B.string(),storage:B.string()}),guA=B.object({apiKey:B.string(),authDomain:B.string(),projectId:B.string(),storageBucket:B.string(),messagingSenderId:B.string(),appId:B.string(),measurementId:B.string(),emulatorInfo:huA.optional()}),xsp=Mr("FirebaseConfig",guA);var nvs=r=>{Cre("firestore.delete",{path:r})},YQr=r=>{Cre("firestore.set",{path:r})},ivs=r=>{Cre("firestore.update",{path:r})};var ovs=r=>{Cre("firestore.get",{path:r})},svs=r=>{Cre("firestore.transaction.get",{path:r})},avs=r=>{Cre("firestore.transaction.set",{path:r})},uvs=r=>{Cre("firestore.transaction.update",{path:r})},cvs=r=>{Cre("firestore.transaction.delete",{path:r})},lvs=()=>{Cre("firestore.batch")};var FKC=K8.getTracer("firestore");var Psp=async(r,t=1e3)=>{let n=()=>{},i=new Promise(o=>{n=r.onSnapshot(s=>{s.metadata.hasPendingWrites||o(s)})});return await JR(t,`Timed out in GetDocumentNoPendingWrites after ${t} ms`,i).finally(n)};var Nsp=yt(AXt());async function Dsp(r){let t=new Nsp.ProxyAgent;r.httpProxy=t,r.httpsProxy=t}var ksp=(0,Bsp.default)(async()=>{if(ZG)return Je("RUNNER_BACKEND").info("WARNING: API using Firebase emulator!"),{apiKey:"none",authDomain:"none",projectId:"coalesce",storageBucket:"coalesce.appspot.com",messagingSenderId:"none",appId:"none",measurementId:"none",emulatorInfo:ZG};{let r=await(0,Lsp.readFile)(process.env.FIREBASE_CONFIG_PATH??"/firebase.json"),t=xsp.assert(JSON.parse(r.toString()));return Je("RUNNER_BACKEND").info("API using Firebase config:",t),t}});async function qsp(){return oQe()||Kyu()?await ksp():Gh.app().options}var pvs=async(r,t)=>{await Dsp(r),await SGc(r,t)};var dvs=Je("SECRETS"),Usp=(0,Fsp.default)(async()=>{switch(process.env.COALESCE_SECRET_STORE_TYPE){case"redis":if(dvs.app("Selected Redis secret store."),!process.env.COALESCE_SECRET_STORE_REDIS_URL)throw new Error("The redis secret store is configured, but no COALESCE_SECRET_STORE_REDIS_URL was defined.");return await p7r.Create(process.env.COALESCE_SECRET_STORE_REDIS_URL);case"memory":return dvs.app("Selected Memory secret store."),YYo();default:return dvs.app("Selected Google Secrets Manager secret store."),new BLr((await qsp()).projectId)}});var hI=(0,zsp.default)(async()=>new ket(await Usp()));var AuA=Je("SECRETS"),zct=async(r,t,n,i)=>{let o={userID:t.userId,orgID:t.orgId,workspaceID:+t.workspaceId},s=n.UpgradeTarget;if(i&&s){let a=await r.Get(s,t);return a||(a=await r.Get(n,t),a&&(AuA.infoContext(o,`v2 Snowflake secrets feature flag was set, found v1 credentials. Upgrading v1 to v2 for ${n.typeName}`),await r.Set(s,t,a),await r.Delete(n,t))),a}else return await r.Get(n,t)};var Qsp=async(r,t,n)=>{let i=n.isFeatureEnabled("enableSnowflakeOAuthSecretsV2");return zct(r,t,Wet,i)},jsp=async(r,t)=>await r.Get(jet,t);var Gsp=async(r,t)=>await r.Get(Qet,t),Hsp=async(r,t)=>await r.Get(Uet,t),Vsp=async(r,t,n)=>zct(r,t,Het,n),Wsp=async(r,t,n)=>{let i=n.isFeatureEnabled("enableSnowflakeSecretsV2");return zct(r,t,xpe,i)},Ksp=async r=>await(await hI()).Get(zet,r),Ysp=async r=>await(await hI()).Get(T2e,r);var muA=async(r,t,n)=>await r.Set(T2e,t,n),JQr=async(r,t)=>{let n=await hI(),i={orgId:r.orgID,userId:r.userID,workspaceId:r.workspaceID.toString()};await muA(n,i,new zd(t))},Jsp=async(r,t,n,i)=>{if(!i.isFeatureEnabled("enableSnowflakeSecretsV2"))return await r.Set(xpe,t,n);await r.Get(xpe,t)&&await r.Delete(xpe,t),await r.Set(t6e,t,n)};var $sp;var gI=(r,t={},n=1)=>{if($sp){let o={appContext:PZt()??"unknown"};ZG&&(o.emulated="true"),$sp.increment(r,{...o,...t},n)}};var yuA="20428800",s3e=()=>parseInt(process.env.MAX_RESPONSE_SIZE||yuA);var buA=Je("CONNECTION"),a3e=class{constructor(t,n,i,o,s=2){this.handle=t;this.queryParams=n;this.logContext=i;this.resetFunc=o;this.maxAttempts=s;this.queryParams.requestId=this.coalesceQueryID=this.queryParams.requestId??mu()}handle;queryParams;logContext;resetFunc;maxAttempts;_promise=null;coalesceQueryID;get promise(){if(this.Start(),!this._promise)throw new DA("Internal consistency error: _promise cannot be null after Start()!");return this._promise}Cancel=async()=>{buA.infoContext(this.logContext,"Canceling the running query, CQID=",this.coalesceQueryID),await this.tryCancel()};Start=()=>{this._promise||(this._promise=this.queryWithRetries())};attachThen=t=>{this._promise=this.promise.then(n=>(t(n),n))}};var Sre=Je("CONNECTION"),e9t=class extends a3e{constructor(n,i,o,s,a,u=5){let p={...s,snowflakeRequestID:o.requestId};super(i,o,p,a,u);this.completion=n}completion;get sqlText(){return this.queryParams.statement}mapRowCountColumns(n,i){let o=i.trim().toUpperCase(),s;return o.startsWith("UPDATE")?s="UPDATE":o.startsWith("DELETE")&&(s="DELETE"),n.map(a=>{if(a.columnName==="num_inserted_rows")return{...a,columnName:"number of rows inserted"};if(a.columnName==="num_updated_rows")return{...a,columnName:"number of rows updated"};if(a.columnName==="num_deleted_rows")return{...a,columnName:"number of rows deleted"};if(a.columnName==="num_affected_rows"){if(s==="UPDATE")return{...a,columnName:"number of rows updated"};if(s==="DELETE")return{...a,columnName:"number of rows deleted"}}return a})}shouldResetConnection=n=>CuA(n)?!0:!!aa(n).error.errorString.match(/(network ?error|econnreset)/i);handleRetry=async(n,i)=>{if(this.shouldResetConnection(n))try{this.handle=await this.resetFunc()}catch(o){throw Sre.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",o),n.coalesceCause}return i};async ensureSession(){if(!this.handle.session){let o=this.getSessionOptions();return this.handle.session=await this.handle.client.openSession(o),this.handle.sessionOptions=o,this.handle.session}let n=this.getSessionOptions(),i=this.handle.sessionOptions;if(n.initialCatalog!==i.initialCatalog||n.initialSchema!==i.initialSchema){try{await this.handle.session.close()}catch(o){Sre.errorContext(this.logContext,"Error closing previous session for CQID=",this.coalesceQueryID,o)}finally{this.handle.session=void 0}this.handle.session=await this.handle.client.openSession(n),this.handle.sessionOptions=n}return this.handle.session}getSessionOptions(){return{initialCatalog:this.queryParams.initialCatalog,initialSchema:this.queryParams.initialSchema}}async queryWithRetries(){let n=`[TrackedPendingDatabricksQuery.queryWithRetries() - '${this.queryParams.statement}']`;try{Sre.debugContext(this.logContext,"Making request for CQID=",this.coalesceQueryID);let i=async()=>{gI("databricks.runQuery.attempt",this.logContext);let l={columns:[],rows:[],status:"Success"};try{let f=await(await this.ensureSession()).executeStatement(this.queryParams.statement,this.queryParams.queryOptions),h=(await f.getSchema())?.columns;h&&(l.columns=h);let A=0;do{let v=await f.fetchChunk({maxRows:1e3});if(A+=lWe(v,!0),l.rows.push(...v),A>s3e())throw new Yvt(A,s3e())}while(await f.hasMoreRows());l.columns=this.mapRowCountColumns(l.columns,this.queryParams.statement);let E=await f.status();gI("databricks.runQuery.finished",{...this.logContext,statusCode:E.status.statusCode??-1})}catch(d){if(gI("databricks.runQuery.error",{...this.logContext,errorString:aa(d).error.errorString}),d instanceof Yvt)return l.status=dL,Sre.errorContext(this.logContext,n,d.detail,`; returning partial set of rows (${l.rows.length})`),l;throw Sre.errorContext(this.logContext,"Error in databricks query",d),new bX(this.queryParams,d)}return Sre.debugContext(this.logContext,"Successfully got result for CQID=",this.coalesceQueryID),l},o=(l,d)=>{if(!(typeof l=="object"&&l instanceof bX))return Sre.errorContext(this.logContext,"Not retrying request CQID=",this.coalesceQueryID,"attempt=",d,"error=",l,"was unrecognized and not retryable"),l;if(Qct(l))return Sre.infoContext(this.logContext,"Not retrying request, auth error detected CQID=",this.coalesceQueryID,"attempt=",d),l;if(l.isCancel())return Sre.infoContext(this.logContext,"Not retrying request, it was canceled CQID=",this.coalesceQueryID,"error=",l.coalesceCause?l.coalesceCause:l),l},s=l=>["CQID=",this.coalesceQueryID,"error=",l.cause?l.cause:l],a={name:"backoff",base:5},u={name:"nowait"},p=async l=>{typeof l=="object"&&l instanceof bX&&await this.handleRetry(l,this.queryParams)},c=(l,d)=>{let f=JSON.stringify(aa(l,!0).error);return f.match(/network ?error/i)||f.match(/bad HTTP status code: 5/)||f.match(/bad HTTP status code: 400/)?a:d||u};return await cf(i,this.maxAttempts,Sre,this.logContext,{beforeRetry:p,alterRetryStrategy:c,checkError:o,retryStrategy:u,retryLogLevel:"info",logOnRetry:"Retrying databricks request",customErrorOnRetry:s,logOnFailure:"Out of retries for request",customErrorOnFailure:s})}catch(i){throw i instanceof bX?i:new bX(this.queryParams,i)}finally{this.completion(this.coalesceQueryID)}}async tryCancel(){try{await this.handle.session?.close()}catch(n){throw new nt("Error canceling Databricks session",JSON.stringify(aa(n).error))}finally{this.handle.session=void 0}}},fvs=r=>{if(typeof r!="object"||r===null)return[];let t=r,n=typeof t.statusCode=="number"?[t.statusCode]:[];return t.coalesceCause!==void 0&&n.push(...fvs(t.coalesceCause)),n};var EuA=/Invalid SessionHandle|SESSION_CLOSED|SESSION_NOT_FOUND|SESSION_CHANGED|session was closed or has expired/i,CuA=r=>{if(fvs(r).includes(400))return!0;let t=aa(r,!0).error.errorString;return/bad HTTP status code: 400/i.test(t)||EuA.test(t)},Qct=r=>fvs(r).includes(403);var U8e=require("perf_hooks");var $Qr=class{logTag;gcStats;performanceObserver;isActive=!1;trackingStartTime;gcTypeMap={1:"scavenge",2:"mark_sweep_compact",4:"incremental_marking",8:"process_weak_callbacks",15:"all"};constructor(t={}){this.logTag="[GCTracker]: "+(t.logTag||""),this.gcStats=this.initializeGCStats(),t.autoStart!==!1&&this.start()}initializeGCStats(){return{scavenge:{count:0,totalDuration:0,maxPause:0},mark_sweep_compact:{count:0,totalDuration:0,maxPause:0},incremental_marking:{count:0,totalDuration:0,maxPause:0},process_weak_callbacks:{count:0,totalDuration:0,maxPause:0},all:{count:0,totalDuration:0,maxPause:0},unknown:{count:0,totalDuration:0,maxPause:0}}}start(){if(!(this.isActive||this.performanceObserver))try{if(typeof U8e.PerformanceObserver>"u"||typeof U8e.performance>"u"){Je("PERFORMANCE").app(`${this.logTag} PerformanceObserver not available in this environment`);return}this.performanceObserver=new U8e.PerformanceObserver(t=>{for(let n of t.getEntries())if(n.entryType==="gc"){let o=n.detail.kind||0,s=this.gcTypeMap[o]||"unknown",a=n.duration,u=this.gcStats[s],p=this.gcStats.all,c=U8e.performance.timeOrigin+n.startTime;u.firstGCTime||(u.firstGCTime=c),p.firstGCTime||(p.firstGCTime=c),u.count++,p.count++,u.totalDuration+=a,p.totalDuration+=a,u.lastGCTime=c,p.lastGCTime=c,u.maxPause=Math.max(u.maxPause,a),p.maxPause=Math.max(p.maxPause,a)}}),this.performanceObserver.observe({entryTypes:["gc"]}),this.isActive=!0,this.trackingStartTime=Date.now(),Je("PERFORMANCE").debug(`${this.logTag} GC performance monitoring enabled`)}catch(t){Je("PERFORMANCE").error(`${this.logTag} Failed to initialize GC monitoring:`,t)}}stop(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=void 0,this.isActive=!1)}analyzePatterns(){let t=[],n=[];if(!this.performanceObserver||!this.trackingStartTime)return{statistics:n,warnings:t};let s=(U8e.performance.now()-this.trackingStartTime)/6e4,a=Object.entries(this.gcStats);for(let[p,c]of a)if(!(p!=="scavenge"&&p!=="mark_sweep_compact")&&(p==="scavenge"&&c.maxPause>100?t.push(`Long ${p} GC pause: ${c.maxPause.toFixed(1)}ms where typical is <10ms`):p==="mark_sweep_compact"&&c.maxPause>400&&t.push(`Long ${p} GC pause: ${c.maxPause.toFixed(1)}ms where typical is 10-100ms`),s>0)){let l=c.count/s;n.push(`${p} GC frequency: ${l.toFixed(1)} GCs/minute`)}let u=this.gcStats.mark_sweep_compact;if(u.count>0&&s>0){let p=u.count/s;n.push(`Full GCs (mark_sweep_compact): ${p.toFixed(1)}/minute`)}return{statistics:n,warnings:t}}};var t9t=yt(require("fs")),Xsp=yt(require("v8"));var nW=class extends zZe{logTag="[MemoryMonitor]: ";gcTracker;threshold=75;memoryLimit;constructor(){super(),this.memoryLimit=this.getMemoryLimit(),this.suppress||(this.gcTracker=new $Qr({logTag:this.logTag}))}cleanup(){this.gcTracker?.stop()}getLogContextWithMetrics(t,n,i){let o={metric_type:"memory_telemetry",operation:i,rss_bytes:n.memUsage.rss,heap_used_bytes:n.memUsage.heapUsed,heap_total_bytes:n.memUsage.heapTotal,external_bytes:n.memUsage.external,warnings_count:n.warnings.length};try{if(this.memoryLimit){let s=n.memUsage.rss/this.memoryLimit[0]*100;o.limit_bytes=this.memoryLimit[0],o.oom_risk=s>=90?1:0}try{o.v8_available_bytes=n.heapStats.total_available_size,o.v8_heap_size_limit_bytes=n.heapStats.heap_size_limit}catch{}n.deltaData&&(o.rss_delta_bytes=n.deltaData.rssDelta,o.heap_delta_bytes=n.deltaData.heapDelta,o.external_delta_bytes=n.deltaData.externalDelta)}catch(s){Je("PERFORMANCE").errorContext(t,`${this.logTag} Error getting metrics: ${s}`)}return{...t,memoryMetrics:o}}getMemoryUsage(t){if(typeof process<"u"&&process.memoryUsage!==void 0)return process.memoryUsage();Je("PERFORMANCE").infoContext(t,`${this.logTag} Cannot get memory usage in browser environment`)}getMemoryLimit(){try{let t=this.getContainerCgroupLimit();if(t)return[t,"container"];let n=this.getNodeMemoryInfo();if(n)return[n,"node"]}catch{}}getContainerCgroupLimit(){try{let t=["/sys/fs/cgroup/memory.max"],n=["/sys/fs/cgroup/memory/memory.limit_in_bytes"];for(let i of[...t,...n])if(t9t.default.existsSync(i)){let o=t9t.default.readFileSync(i,"utf8").trim();if(o!=="max"){let s=parseInt(o,10);if(s>=67108864&&s<=1099511627776)return s}}}catch{}}getNodeMemoryInfo(){try{if(t9t.default.existsSync("/proc/meminfo")){let n=t9t.default.readFileSync("/proc/meminfo","utf8").match(/^MemTotal:\s+(\d+)\s+kB$/m);if(n&&n[1]){let o=parseInt(n[1],10)*1024;if(o>=1073741824&&o<=1099511627776)return o}}}catch{}}formatBytes(t){if(t===0)return"0B";let n=1024,i=["B","KB","MB","GB","TB"],o=Math.floor(Math.log(t)/Math.log(n));return`${parseFloat((t/Math.pow(n,o)).toFixed(1))}${i[o]}`}getMemoryWarnings(t){let n=[];if(this.memoryLimit){let[a,u]=this.memoryLimit,p=t.rss/a*100,c=a-t.rss,l=u==="container"?"container limit":"node memory",d=u==="container"?"OOM kill":"node memory exhaustion";p>=90?n.push(`\u{1F6A8} K8S ${u==="container"?"OOM":"MEMORY"} RISK: RSS at ${p.toFixed(1)}% of ${l} - Only ${this.formatBytes(c)} remaining before ${d}`):p>=this.threshold&&n.push(`\u26A0\uFE0F K8S MEMORY PRESSURE: RSS at ${p.toFixed(1)}% of ${l} - ${this.formatBytes(c)} remaining`)}let i=Xsp.default.getHeapStatistics(),o=i.total_available_size/(1024*1024);o<50?n.push(`\u{1F6A8} V8 CRITICAL: Only ${this.formatBytes(i.total_available_size)} heap space available`):o<100&&n.push(`\u26A0\uFE0F V8 WARNING: Only ${this.formatBytes(i.total_available_size)} heap space available`);let s=(t.heapTotal-t.heapUsed)/t.heapTotal*100;return s>60&&n.push(`\u26A0\uFE0F High heap fragmentation: ${s.toFixed(1)}% - consider restart`),{warnings:n,heapStats:i}}formatMemoryUsage(t){let n=t.heapUsed/t.heapTotal*100,i=`RSS: ${this.formatBytes(t.rss)}`;if(this.memoryLimit){let[o,s]=this.memoryLimit,a=t.rss/o*100;i+=` (${a.toFixed(1)}% of ${s})`}return i+=` | Heap: ${this.formatBytes(t.heapUsed)}/${this.formatBytes(t.heapTotal)} (${n.toFixed(1)}% used)`,i+=` | External: ${this.formatBytes(t.external)}`,i}analyzeDeltaConcerns(t,n,i,o){let s=[];if(t>500*1024*1024)if(this.memoryLimit){let[a]=this.memoryLimit,u=o/a*100,p=t/a*100,c=u+p;c>95?s.push(`\u{1F6A8} CRITICAL: RSS +${p.toFixed(1)}% (${this.formatBytes(t)}) \u2192 ${c.toFixed(1)}% of ${this.memoryLimit[1]} limit - OOM risk if pattern continues`):c>85?s.push(`\u26A0\uFE0F HIGH RISK: RSS +${p.toFixed(1)}% (${this.formatBytes(t)}) \u2192 ${c.toFixed(1)}% of ${this.memoryLimit[1]} limit - Monitor closely`):u>70&&s.push(`\u26A0\uFE0F LARGE INCREASE while at ${u.toFixed(1)}%: +${this.formatBytes(t)} - Watch for continued growth`)}else s.push(`\u26A0\uFE0F LARGE RSS INCREASE: +${this.formatBytes(t)} - Cannot assess OOM risk (container limit unknown)`);return n>200*1024*1024&&s.push(`\u26A0\uFE0F LARGE HEAP GROWTH: +${this.formatBytes(n)} - Check for memory leaks`),i>200*1024*1024&&s.push(`\u26A0\uFE0F LARGE EXTERNAL MEMORY: +${this.formatBytes(i)} - Check buffers`),s}getMemoryReport(t,n){let{warnings:i,heapStats:o}=this.getMemoryWarnings(t),s=this.formatMemoryUsage(t);if(this.gcTracker){let{warnings:a,statistics:u}=this.gcTracker.analyzePatterns();a.length&&a.push(`~~ GC Warnings ~~: ${a.join(" | ")}`),u.length&&(s+=` | ~~ GC Stats ~~: ${u.join(" | ")}`)}for(let a of n??[])i.push(a);return{summary:s,warnings:i,heapStats:o,memUsage:t}}logMemorySnapshot(t,n,i,o=[],s=!1){if(this.suppress||s)return;let a=this.getMemoryUsage(t);if(a)try{let u=this.getMemoryReport(a,o),p=this.getLogContextWithMetrics(t,u,i);this.logMemory(p,n,u.summary,u.warnings);return}catch(u){Je("PERFORMANCE").errorContext(t,`${this.logTag} Error logging memory snapshot: ${u}`);return}}logDeltaMetrics(t,n,i,o,s=!1){if(this.suppress||!n||s)return;let a=process.memoryUsage(),u={rssDelta:a.rss-n.rss,heapDelta:a.heapUsed-n.heapUsed,externalDelta:a.external-n.external},p=this.analyzeDeltaConcerns(u.rssDelta,u.heapDelta,u.externalDelta,a.rss),c=this.getMemoryReport(a,p);c.deltaData=u;let l=this.getLogContextWithMetrics(t,c,i);this.logMemory(l,o,c.summary,c.warnings)}};var E_=Je("CONNECTION"),XQr=r=>t=>{E_.assert(`Got error in cannot-reject function "${r}":`,t)},vre=class{constructor(t,n,i,o){this.userContext=t;this.teamInfo=n;this.logContext=i;this.maximumConnections=o;this.slots=[],this.shutdown=!1,this.canceled=!1,hh("CONNECTION",o>0,this.logContext,"At least one connection is required!")}userContext;teamInfo;logContext;maximumConnections;slots;shutdown;canceled;queued=[];memoryMonitor=new nW;totalExecutions=0;incrementExecutions(t){E_.infoContext(this.logContext,`Incrementing executions for ${t}. Total executions: ${this.totalExecutions}`),this.totalExecutions++}get executions(){return this.totalExecutions}setup=async()=>{let t="[ConnectionManager.setup()]";E_.infoContext(this.logContext,"Setting up",this.maximumConnections,"connections - for large values this may take some time");let n="ConnectionManager.setup()";await this.memoryMonitor.measureOperationAsync(this.logContext,`${t}: Before setup initialization`,`${t}: Setup completed`,n,async()=>{for(let i=0;i<this.maximumConnections;i++){let o=this.NewSlotMember(i,mu());i===0&&(E_.infoContext(this.logContext,`${t}: first slot awaiting initialization`),await this.memoryMonitor.measureOperationAsync(this.logContext,`${t}: Before first connection initialization`,`${t}: First connection initialization completed`,n,async()=>{await o.isInitialized()}),E_.infoContext(this.logContext,`${t}: first slot done initializing`)),E_.infoContext(this.logContext,`${t}: initializing slot ${o.slotID}`),o.isInitialized().then(()=>{E_.infoContext(this.logContext,`${t}: slot ${o.slotID} initialized, marking unused`,o.connectionID),this.handleNextQueued(o.markUsed()).catch(XQr("handleNextQueued"))},s=>{E_.errorContext(this.logContext,`${t}: slot ${o.slotID} failed to initialize, error: `,o.connectionID,s),o.markErrored()}),this.slots.push(o)}})};teardown=async()=>{this.memoryMonitor.cleanup(),this.shutdown=!0,await UP(this.slots.map(t=>t.teardown()))};getFirstAvailableSlot=()=>this.slots.find(t=>t.state==="unused")?.markUsed()??null;handleNextQueued=async t=>{let n=this.queued.pop();if(n===void 0){E_.debug("connection pool queue empty, freeing slot"),t.markUnused();return}await this.handleItem(t,n).catch(XQr("handleItem"))};handleItem=async(t,n)=>{let{slotID:i}=t;E_.debugContext(this.logContext,"using connection: ",i);let{callback:o,promise:s,resolve:a,reject:u}=n;try{if(this.shutdown)throw new nt("Can't run on shutdown");if(this.canceled)return u(new BA(`Connection was canceled, aborting on slot ${i}`)),this.handleNextQueued(t).catch(XQr("handleNextQueued")),s;await t.acquire();let p=await t.unwrap(),c=await o(p);a(c)}catch(p){u(p)}finally{await t.release()}return this.handleNextQueued(t).catch(XQr("handleNextQueued")),s};withConnection=async t=>{let n="[ConnectionManager.withConnection()]";if(this.shutdown)throw E_.errorContext(this.logContext,`${n}: can't run on shutdown`),new nt("Can't run on shutdown");if(this.canceled)throw E_.errorContext(this.logContext,`${n}: connection canceled before item was handled or queued`),new BA("Connection canceled before item was handled or queued");let i={...TR(),callback:t};E_.infoContext(this.logContext,`${n}: attempting to acquire a connection slot`);let o=this.getFirstAvailableSlot();return o!==null?(E_.infoContext(this.logContext,`${n}: slot ${o.slotID} found ${o.state}`),await this.handleItem(o,i)):(E_.infoContext(this.logContext,`${n}:`,this.slots.length,"connections in use, couldn't find available slot, enqueueing item"),this.queued.push(i),this.queued.length>5&&this.memoryMonitor.logMemorySnapshot(this.logContext,`${n}: Queued connection pool size: ${this.queued.length}`,"withConnection")),i.promise};getConnection=()=>({execute:n=>this.withConnection(i=>i.execute(n)),teardown:()=>Promise.resolve(),logContext:this.logContext});async cancel(){try{if(E_.infoContext(this.logContext,"Begin canceling all connections in the ConnectionManager"),this.canceled)return E_.infoContext(this.logContext,"ConnectionManager already canceled"),Promise.resolve();this.canceled=!0;let t=this.slots.map(n=>n.cancel());await UP(t)}catch(t){throw E_.errorContext(this.logContext,"Error canceling all connections in the ConnectionManager",t),t}finally{E_.infoContext(this.logContext,"Completed canceling all connections in the ConnectionManager")}}showQueued=()=>this.queued};var jct=Je("CONNECTION"),Tre=class{constructor(t,n,i,o,s,a){this.slotID=t;this.connectionID=n;this.userContext=i;this.teamInfoAndFirebase=o;this.logContext=s;this.managerQueryStats=a;this.initPromise=this.initialize(),this.firstInitPromise=this.initPromise.then(()=>this.setup())}slotID;connectionID;userContext;teamInfoAndFirebase;logContext;managerQueryStats;handle=null;state="initializing";connection=null;firstInitPromise;initPromise;useCount=0;canceled=!1;async initialize(){this.handle=await this.createConnection()}async postReInitialization(){}reinitialize=async()=>{let t=this.createConnection();return this.initPromise=t.then(n=>{this.handle=n}),await this.postReInitialization(),t};async acquire(t){if(this.state!=="in use")throw new DA(`Expected slot to be in use, but it was ${this.state}`);if(!t&&this.connection)throw hh("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new DA(`Cannot acquire in-use connection ${this.connectionID}`);if(this.canceled)throw new BA("Attempting to acquire canceled connection slot entry",this.connectionID);if(this.connection=await this.newConnection(),this.useCount++,this.canceled)throw this.connection=null,new BA("Attempting to acquire canceled connection slot entry",this.connectionID)}async release(){this.connection=null}async unwrap(){if(this.state!=="in use")throw new DA(`Expected slot to be in use, but it was ${this.state}`);return await this.assertConnected(),this.connection}async isInitialized(){return this.firstInitPromise}async assertConnected(){if(!this.connection)throw hh("CONNECTION",!1,this.logContext,"Connection was not acquired before connection check!"),new DA("Connection was not acquired before connection check!");await this.initPromise}async execute(t){return(await Ah("Waiting for connection",this.logContext,"CONNECTION",()=>this.unwrap())).execute(t)}async cancel(){try{if(jct.infoContext(this.logContext,"Begin canceling connection slot entry",this.connectionID),this.canceled){jct.infoContext(this.logContext,"Connection slot entry already canceled",this.connectionID);return}if(this.canceled=!0,this.connection){let t=this.connection;this.connection=null,await t.cancel()}else jct.infoContext(this.logContext,"Canceling connection slot entry",this.connectionID,"no-op")}catch(t){throw jct.errorContext(this.logContext,"Error canceling connection slot entry",this.connectionID,t),t}finally{jct.infoContext(this.logContext,"Completed canceling managed connection",this.connectionID)}}async teardown(){jct.infoContext(this.logContext,`[ConnectionManagerSlotMember]: Tearing down ${this.userContext.kind} connection`,this.connectionID),await this.initPromise.catch(()=>{}),await this.firstInitPromise.catch(()=>{}),this.handle&&await(this.connection||this.newConnection()).teardown()}markUsed(){return this.state="in use",this}markUnused(){return this.state="unused",this}markErrored(){return this.state="error",this}};var r9t=Je("CONNECTION"),gvs=async(r,t,n)=>{let{rootRepository:i,teamInfo:o,teamInfo:{fbTeamID:s,fbUserID:a}}=t,{environmentID:u}=r;if(!u)throw new nt(`No environmentID provided for org ${s} by user ${a}`);if(r.authenticator!=="OAuthU2M")throw new eH(`Cannot reset oauth connection on a non-oauth connection type: ${r.authenticator}`,"OAuthU2M");let p=await Hct(i.org(s),o,u,jh.Values.databricks),c=await tjr(n);if(!c.refresh_token)throw new eH("Missing or invalid OAuth refresh token, please reauthenticate.","OAuthU2M");let l=c.refresh_token,d=await rjr(p,l,n);return await JQr(n,{access_token:d,refresh_token:l}),d},hvs=class extends Tre{name="databricks";async createConnection(){let t=this.userContext.authenticator==="OAuthU2M"?Zsp(this.userContext,this.teamInfoAndFirebase,this.logContext):void 0,n=await ejr(this.userContext,t);return Avs(n)}async updateFromResult(t){}async setup(){await this.connectAndValidate()}async assertConnected(){if(await super.assertConnected(),this.handle===null)throw hh("CONNECTION",!1,this.logContext,"Connection was null after initPromise!"),new DA("Connection was null after initPromise!")}async postReInitialization(){await this.connectAndValidate(),await this.acquire(!0)}async connect(){if(!this.handle){r9t.alertContext(this.logContext,"No handle found in DatabricksConnectionManagerSlotMember.connect");return}return this.handle.session||(this.handle.session=await this.handle.client.openSession(),this.handle.sessionOptions={}),this.handle.session}async resetOauth(){let t=await gvs(this.userContext,this.teamInfoAndFirebase,this.logContext);this.userContext.accessToken=t}async connectAndValidate(){await this.initPromise;try{await this.connect()}catch(t){if(this.userContext.authenticator==="OAuthU2M"&&Qct(t)){await this.resetOauth();try{this.initPromise=this.initialize(),await this.initPromise,await this.connect()}catch(n){if(r9t.errorContext(this.logContext,"Just refreshed oauth tokens, shouldn't have gotten here unless another process did it at the same time: ",n),Qct(n))this.initPromise=this.initialize(),await this.initPromise,await this.connect();else throw n}}else throw t}}async teardown(){r9t.infoContext(this.logContext,`Tearing down ${this.name} connection`,this.connectionID),await this.initPromise.catch(()=>{}),await this.firstInitPromise.catch(()=>{}),this.handle&&await mvs(this.handle,this.logContext)}async acquire(t){if(!t&&this.connection)throw hh("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new DA(`Cannot acquire in-use connection ${this.connectionID}`);if(this.canceled)throw new BA("Attempting to acquire canceled connection slot entry",this.connectionID);if(this.connection=new Gct(this.handle,this.logContext,this.connectionID,this.useCount,this),this.useCount++,this.canceled)throw this.connection=null,new BA("Attempting to acquire canceled connection slot entry",this.connectionID)}newConnection(){return new Gct(this.handle,this.logContext,this.connectionID,this.useCount,this)}},ZQr=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new hvs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}async test(){let t="DatabricksConnectionManager.test:",n=Nb(this.userContext,"authenticator","kind","role","user","warehouse");r9t.appContext(this.logContext,t,"testing connection",n),await this.withConnection(async i=>i.execute({statement:h5})),r9t.appContext(this.logContext,t,"connection successfully established",n)}};var LKp=yt(fYe()),bnn=yt(cWp());function lWp(r,t=null){return t??`https://${r}.snowflakecomputing.com`}var DKp=yt(NKp());var ymS=Je("JSON_PARSER");var M2m=Je("XML_PARSER");var BKp=r=>{let t=new DKp.Parser({attrkey:"@",charkey:"#",explicitArray:!1}),n;return t.parseString(r,(i,o)=>{if(i)throw i;n=o}),M2m.debug("$Parsed JSON",JSON.stringify(n,null,2)),n};var r1t=Je("CONNECTION"),x2m=()=>{let r=process.env.COALESCE_SNOWFLAKE_LOG_LEVEL?.toUpperCase(),t=r==="ERROR"||r==="WARN"||r==="INFO"||r==="DEBUG"||r==="TRACE"?r:"OFF",n=process.env.COALESCE_SNOWFLAKE_LOG_FILE;bnn.configure({xmlColumnVariantParser:BKp,keepAlive:!1,logLevel:t,logFilePath:n})};x2m();function P2m(r){return r.startsWith("https://")?r:`https://${r}`}var kKp={sfRetryMaxLoginRetries:4},Y7s=r=>!(!r.accountName||!r.user),J7s=r=>{let{accountName:t,accessUrl:n,user:i,warehouse:o}=r;return{account:t,username:i,application:"CoalesceIO_Coalesce",...n&&{accessUrl:P2m(n)},...o&&{warehouse:o}}},N2m=(r,t)=>{if(!Y7s(r))throw r1t.infoContext(t,"Error creating basic snowflake connection parameters (CreateSnowflakeConnectionBasic)",{user:Eme(r.user),accountName:Eme(r.accountName)}),new yX("Invalid Connection Information, please correct your account or username and proceed.","Basic");let{password:n,role:i}=r;return{...J7s(r),password:n,...i&&{role:i},...kKp}},D2m=(r,t)=>{if(!Y7s(r))throw r1t.infoContext(t,"Error creating basic snowflake connection (CreateSnowflakeConnectionKeyPair)",{user:Eme(r.user),accountName:Eme(r.accountName)}),new yX("Invalid Connection Information, please correct your account or username and proceed.","KeyPair");let{keyPairKey:n,keyPairPass:i,role:o}=r;return{...J7s(r),authenticator:"SNOWFLAKE_JWT",privateKey:n,privateKeyPass:i??void 0,...o&&{role:o},...kKp}},$7s=async(r,t)=>{let{workspaceID:n,orgID:i,userID:o}=r;try{let s=await hI(),a=await Wsp(s,{orgId:i,userId:o,workspaceId:n.toString()},t);if(r1t.infoContext(r,"get access token from secret (GetAccessTokenFromSecret)"),!a)throw new cWe("Invalid OAuth configuration.");return a.sensitiveValue}catch(s){throw r1t.errorContext(r,"Error getting access token from secret (GetAccessTokenFromSecret)",s),s}},B2m=async(r,t,n)=>{if(!Y7s(r))throw r1t.infoContext(t,"Error creating basic snowflake connection (CreateSnowflakeConnectionOAuth)",{user:Eme(r.user),accountName:Eme(r.accountName)}),new yX("Invalid Connection Information, please correct your account or username and proceed.","OAuth");let i=await $7s(t,n);return{...J7s(r),authenticator:"OAUTH",token:i.access_token??void 0}},L2m=r=>{try{return bnn.createConnection(r)}catch(t){throw new yle(t)}},Enn=async(r,t,n)=>{let i;switch(r.authenticator){case"Basic":case"Cloud":i=N2m(r,t);break;case"KeyPair":i=D2m(r,t);break;case"OAuth":i=await B2m(r,t,n);break;default:throw new DA(`authenticator type of ${r.authenticator} not supported`)}return L2m(i)},k2m=r=>`${r.response?.data?.error}: ${r.response?.data?.message}`,qKp=async(r,t,n)=>{let i=LKp.default.stringify({grant_type:"refresh_token",refresh_token:t}),s=`${lWp(r.connectionAccount,r.accessUrl)}/oauth/token-request`,a=Buffer.from(`${r.oauthClientID}:${r.oauthClientSecret}`).toString("base64"),u={method:"post",url:s,headers:{Authorization:`Basic ${a}`,"Content-Type":"application/x-www-form-urlencoded"},data:i};try{return(await dc(u)).data.access_token}catch(p){let c=p instanceof Sao?k2m(p):"unknown";throw r1t.errorContext(n,`RefreshAccessToken: ${c}`,p),new yX("An error occured refreshing your OAuth refresh_token. Please ensure your OAuth Security Integration is still valid or reauthenticate.","OAuth",p)}};var SRe=Je("CONNECTION"),Bne=class{constructor(t,n,i,o,s,a){this.handle=t;this.logContext=n;this.connectionID=i;this.useCounter=o;this.parent=s;a?this.resetConnectionHandle=()=>a():s?this.resetConnectionHandle=()=>s.reinitialize():this.resetConnectionHandle=()=>{throw new DA("Cannot reset the connection, no reset function provided")}}handle;logContext;connectionID;useCounter;parent;runningQueries=new Map;wasCanceled=!1;resetConnectionHandle;get memoryMonitor(){return this.parent?this.parent.managerQueryStats.memoryMonitor:(SRe.debugContext(this.logContext,"Could not get memory monitor from parent. This may be expected.",this.connectionID),{logDeltaMetrics:()=>{},getMemoryUsage:()=>{}})}async resetConnection(){if(this.wasCanceled)throw new BA("not resetting canceled connection");gI(`${this.name}.resetConnection`,this.logContext);let t=await this.resetConnectionHandle();return this.handle=t,t}async executeAndGetRunning(t){let n=this.parent?.managerQueryStats.executions,i=!n||n%50!==0,o=`(${this.name}) BaseConnection.executeAndGetRunning()`,s=this.memoryMonitor.getMemoryUsage(this.logContext),a=await this.makePendingQuery(t);return a.attachThen(u=>{this.parent&&this.parent.updateFromResult(u),this.memoryMonitor.logDeltaMetrics(this.logContext,s,o,`(connID: ${this.connectionID})[${this.name} executeAndGetRunning()]: completed pending query | total executions: ${n}`,i)}),this.parent&&this.parent.managerQueryStats.incrementExecutions(`[${this.name} executeAndGetRunning()]:${this.connectionID}`),a}execute=async t=>(await this.executeAndGetRunning(t)).promise;cancel=async()=>{try{if(SRe.infoContext(this.logContext,"Begin canceling connection",this.connectionID),this.wasCanceled)return SRe.infoContext(this.logContext,"Connection already canceled",this.connectionID),Promise.resolve();this.wasCanceled=!0;let t=Array.from(this.runningQueries.values()).map(async n=>{SRe.infoContext(this.logContext,"Begin canceling query",n.coalesceQueryID,"conn",this.connectionID);try{await n.Cancel()}catch(i){throw SRe.errorContext(this.logContext,"Error canceling query",n.coalesceQueryID,"conn",this.connectionID,i),i}finally{SRe.infoContext(this.logContext,"Completed canceling query",n.coalesceQueryID,"conn",this.connectionID)}});await UP(t)}catch(t){throw SRe.errorContext(this.logContext,"Error canceling connection",this.connectionID,t),t}finally{SRe.infoContext(this.logContext,"Completed canceling connection",this.connectionID)}}};var X7s=yt(require("v8"));var Lne=Je("CONNECTION"),Cnn=class extends Error{constructor(n,i,o,s){super("Heap size exceeded");this.heapStats=n;this.currentSize=i;this.stmt=o;this.rows=s}heapStats;currentSize;stmt;rows;makeResult=()=>{let n=this.stmt,i=n.getSessionState();return{rows:this.rows,stmt:this.stmt,status:dL,queryID:n.getStatementId(),warehouse:i?.getCurrentWarehouse?.()||null}};makeErrorMessage=n=>{let i=n$(this.heapStats.total_heap_size),o=n$(n.heap_size_limit),s=n$(this.currentSize),a=n$(s3e());return`Chunk limit reached,
|
|
10496
10496
|
current heap size: ${i} MB, total heap size: ${o} MB,
|
|
10497
|
-
response size: ${s} MB, max response size: ${a} MB`}},q2m=(r,t)=>new Promise((n,i)=>{let o=[],s=0,a=r.getStatementId(),u=r.streamRows(),p=r.getRequestId(),c=r.getSessionState()?.getCurrentWarehouse?.(),l=0;u.on("error",d=>{i(new cF(d,t,p,a,c))}).on("data",d=>{if(s+=lWe(d,!0),o.push(d),l++,s>s3e()){let f=X7s.default.getHeapStatistics(),h=new Cnn(f,s,r,o);i(h),u.destroy()}}).on("end",()=>{n({rows:o,stmt:r,status:"Success",queryID:a,warehouse:c||null})})}),F2m=async(r,t,n,i)=>{try{return await q2m(r,t)}catch(o){if(typeof o=="object"&&o instanceof Cnn){let s=o.makeErrorMessage(n);return Lne.errorContext(i,s),o.makeResult()}else{let s=o;throw typeof o=="object"&&o instanceof cF&&(s=o.toTRunError()),Lne.alertContext(i,"Error on streaming rows:",s),o}}},U2m="Unable to perform operation using terminated connection.",z2m=407002,Q2m="ECONNRESET",j2m="OAuth access token expired.",n1t=r=>!!r.message.includes(j2m),G2m=r=>r.code===z2m||r.message===U2m,H2m=r=>r&&r.code&&r.code===Q2m,V2m=(r,t)=>{let{promise:n,resolve:i,reject:o}=TR();return{statement:r.execute({...t,streamResult:!0,complete:function(a,u){if(a){let p=t.requestId||u&&u.getRequestId(),c=u&&u.getStatementId(),l=u&&u.getSessionState()?.getCurrentWarehouse?.();o(new cF(a,t,p,c,l))}else i(u)}}),resultStatementPromise:n}},O9e=async r=>{try{return await rAc(r)}catch(t){throw u9o(t)?new yle(t):t}},ejt=class extends a3e{constructor(n,i,o,s,a,u=5){let p={...s,snowflakeRequestID:o.requestId};super(i,o,p,a,u);this.completion=n}completion;initialStatement=null;firstSnowflakeExecutionError;get sqlText(){return this.queryParams.sqlText}makePendingQuery(n){let{statement:i,resultStatementPromise:o}=V2m(this.handle,n),s=Ah(`Back-end (retry=${n.requestId!==void 0}): ${n.sqlText}`,this.logContext,"PERFORMANCE",async()=>{let a=await o;return F2m(a,n,X7s.default.getHeapStatistics(),this.logContext)});return{statement:i,resultPromise:s}}shouldResetConnection=n=>{let i=n.coalesceCause;return n1t(i)||H2m(i)||G2m(i)};handleRetry=async(n,i)=>{if(this.shouldResetConnection(n))try{this.handle=await this.resetFunc()}catch(o){throw Lne.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",o),n.coalesceCause}return i};async queryWithRetries(){try{let n={...this.queryParams};Lne.debugContext(this.logContext,"Making request for CQID=",this.coalesceQueryID);let i=async()=>{gI("snowflake.runQuery.attempt",this.logContext);let l=this.makePendingQuery(n);this.initialStatement=l.statement;let d;try{d=await l.resultPromise;let f=d.status;gI("snowflake.runQuery.finished",{...this.logContext,status:f})}catch(f){throw gI("snowflake.runQuery.error",{...this.logContext,errorString:ua(f).error.errorString}),this.firstSnowflakeExecutionError||f}return Lne.debugContext(this.logContext,"Successfully got result for CQID=",this.coalesceQueryID),d},o=(l,d)=>{if(!(typeof l=="object"&&l instanceof cF))return Lne.errorContext(this.logContext,"Not retrying request CQID=",this.coalesceQueryID,"requestId=",n.requestId,"attempt=",d,"error=",l,"was unrecognized and not retryable"),l;if(l.getSnowflakeErrorCode()==="002043")return Lne.infoContext(this.logContext,"Not retrying request, insufficient privileges CQID=",this.coalesceQueryID,"requestId=",n.requestId,"attempt=",d,"error=",l.coalesceCause?l.coalesceCause:l),l;if(l.isCancel())return Lne.infoContext(this.logContext,"Not retrying request, it was canceled CQID=",this.coalesceQueryID,"error=",l.coalesceCause?l.coalesceCause:l),l},s=async l=>{typeof l=="object"&&l instanceof cF&&(this.firstSnowflakeExecutionError||(this.firstSnowflakeExecutionError=l),n=await this.handleRetry(l,n))},a=l=>["CQID=",this.coalesceQueryID,"requestId=",n.requestId,"retryOptions=",n,"error=",l.cause?l.cause:l],u={name:"backoff",base:5},p={name:"nowait"},c=(l,d)=>kGc(l)||JSON.stringify(ua(l,!0).error).match(/network ?error/i)?u:d||p;return await cf(i,this.maxAttempts,Lne,this.logContext,{alterRetryStrategy:c,beforeRetry:s,checkError:o,retryStrategy:p,retryLogLevel:"info",logOnRetry:"Retrying snowflake request",customErrorOnRetry:a,logOnFailure:"Out of retries for request",customErrorOnFailure:a})}finally{this.completion(this.coalesceQueryID)}}async tryCancel(){let n=this.initialStatement;n!==null&&await cf(()=>O9e(i=>n.cancel(i)),20,Lne,this.logContext,{retryStrategy:{name:"random",min:.05,max:.1},checkError:i=>{if(!(typeof i=="object"&&i instanceof Error&&i.message.includes("Identified SQL statement is not currently executing")))return i}})}};var FKp=Je("CONNECTION"),Z7s=async(r,t,n,i,o)=>{let s=u=>{},a=new ejt(s,r,t,n,i,o);return a.Start(),a.promise},i1t=class extends Bne{currentQueryTag=null;name="snowflake";settingQueryTag=!1;async resetConnection(){let t=await super.resetConnection();return this.currentQueryTag&&!this.settingQueryTag&&await this.setQueryTag(this.currentQueryTag),t}untrackedQuery=async t=>Z7s(this.handle,{sqlText:t},this.logContext,()=>this.resetConnection(),3);setQueryTag=async t=>{this.currentQueryTag=t;let n=this.currentQueryTag===null?"":this.currentQueryTag.replace("$","\\$");this.settingQueryTag=!0;try{gI("snowflake.queryTag",this.logContext),await this.untrackedQuery(`ALTER SESSION SET QUERY_TAG = $$${n}$$`)}finally{this.settingQueryTag=!1}};async makePendingQuery(t){if(this.wasCanceled)throw new BA;let n=o=>this.runningQueries.delete(o),i=new ejt(n,this.handle,t,this.logContext,()=>this.resetConnection());if(this.runningQueries.set(i.coalesceQueryID,i),FKp.debugContext(this.logContext,"Tracking snowflake query with CQID=",i.coalesceQueryID,"query=",i.sqlText),i.Start(),this.wasCanceled)throw FKp.infoContext(this.logContext,"Canceling just-started query due to connection cancellation",i.coalesceQueryID,"conn",this.connectionID),await i.Cancel(),new BA("canceling new query on canceled connection");return i}executeAndGetRunning(t){let n={...this.logContext};return t.requestId&&(n.requestID=t.requestId),gI("snowflake.execute",n),super.executeAndGetRunning(t)}async teardown(){await O9e(t=>this.handle?this.handle.destroy(t):t())}},UKp=async(r,t,n)=>{let i=()=>Enn(r,t,n),o=await i();return await O9e(s=>o.connect(s)),new i1t(o,t,mu(),0,null,i)};var tjt=Je("CONNECTION"),tqs=async(r,t,n)=>{let{rootRepository:i,teamInfo:o,teamInfo:{fbTeamID:s,fbUserID:a}}=t,{environmentID:u}=r;if(!u)throw new nt(`No environmentID provided for org ${s} by user ${a}`);if(r.authenticator!=="OAuth")throw new yX("Cannot reset oauth connection on a non-oauth error!","OAuth");let p=await Hct(i.org(s),o,u,jh.Values.snowflake),c=bc().featureFlags,l=await $7s(n,c);if(!l.refresh_token)throw new yX("Missing or invalid OAuth refresh token, please reauthenticate.","OAuth");let d=l.refresh_token,h={access_token:await qKp(p,d,n),refresh_token:d},A=await hI(),E={orgId:s,userId:a,workspaceId:u.toString()};await Jsp(A,E,new zd(h),c)},eqs=class extends Tre{defaultWarehouse=null;currentWarehouse=null;async createConnection(){return Enn(this.userContext,this.logContext,bc().featureFlags)}async updateFromResult(t){t.warehouse&&(this.currentWarehouse=t.warehouse)}async setup(){await this.connectAndValidate(),await this.setDefaultWarehouse()}async assertConnected(){if(await super.assertConnected(),this.handle===null)throw hh("CONNECTION",!1,this.logContext,"Connection was null after initPromise!"),new DA("Connection was null after initPromise!")}async postReInitialization(){await this.connectAndValidate(),await this.acquire(!0)}connect(){return O9e(t=>this.handle.connect(t))}async resetOauth(){await tqs(this.userContext,this.teamInfoAndFirebase,this.logContext)}async connectAndValidate(){await this.initPromise;try{await this.connect()}catch(t){if(this.userContext.authenticator==="OAuth"&&n1t(t)){await this.resetOauth();try{this.initPromise=this.initialize(),await this.initPromise,await this.connect()}catch(n){if(tjt.errorContext(this.logContext,"Just refreshed oauth tokens, shouldn't have gotten here unless another process did it at the same time: ",n),n1t(n))this.initPromise=this.initialize(),await this.initPromise,await this.connect();else throw n}}else throw t}this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.currentWarehouse)}async setDefaultWarehouse(){let n=(await Z7s(this.handle,{sqlText:"SELECT 1 as coalesce_init"},this.logContext,async()=>{throw new DA("Cannot reset connection")},2)).stmt;if(!n)throw hh("CONNECTION",!!n,this.logContext,"Snowflake did not return a statement!"),new DA("Snowflake did not return a statement!");if(this.defaultWarehouse=n.getSessionState()?.getCurrentWarehouse?.()||null,!this.defaultWarehouse)throw tjt.errorContext(this.logContext,"Could not identify the initial warehouse - possibly invalid credentials?"),new zEr(this.userContext.warehouse)}async teardown(){tjt.infoContext(this.logContext,"[SnowflakeConnectionManagerSlotMember]: Tearing down snowflake connection",this.connectionID),await this.initPromise.catch(()=>{}),await this.firstInitPromise.catch(()=>{}),await O9e(t=>this.handle?this.handle.destroy(t):t())}async acquire(t){if(!t&&this.connection)throw hh("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new DA(`Cannot acquire in-use connection ${this.connectionID}`);if(this.canceled)throw new BA("Attempting to acquire canceled connection slot entry",this.connectionID);if(this.connection=new i1t(this.handle,this.logContext,this.connectionID,this.useCount,this),this.useCount++,this.canceled)throw this.connection=null,new BA("Attempting to acquire canceled connection slot entry",this.connectionID)}newConnection(){return new i1t(this.handle,this.logContext,this.connectionID,this.useCount,this)}setWarehouse=async t=>{await this.assertConnected(),await this.execute({sqlText:`USE WAREHOUSE "${t}"`})};async release(){this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.defaultWarehouse),this.currentWarehouse=null,await super.release()}},Snn=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new eqs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}async test(){let t="SnowflakeConnectionManager.test:",n=Nb(this.userContext,"authenticator","kind","role","user","warehouse");tjt.appContext(this.logContext,t,"testing connection",n),await this.withConnection(async i=>i.execute({sqlText:h5})),tjt.appContext(this.logContext,t,"connection successfully established",n)}};var zKp=(r,t)=>$g({snowflake:()=>n1t(r),databricks:()=>Qct(r),fabric:()=>!1,bigquery:()=>!1},t,"CheckForDeadAccessTokenFromPlatform"),QKp=async(r,t,n)=>fL(r,{snowflake:async i=>await tqs(i,t,n),databricks:async i=>await gvs(i,t,n),fabric:async()=>Promise.reject(new nt(`Invalid platform kind: ${r.kind} for ResetOauthConnectionForPlatform`)),bigquery:async()=>Promise.reject(new nt(`Invalid platform kind: ${r.kind} for ResetOauthConnectionForPlatform`))}),Hct=async(r,t,n,i)=>{let o;try{o=await r.workspace(n).fetch()}catch(p){throw LE(p)&&p instanceof Du?new nt(`Environment ${n} doesn't exist in org ${t.fbTeamID}`):p}let s={orgId:t.fbTeamID,userId:t.fbUserID,workspaceId:n.toString()},a=await hI(),u=await $g({databricks:()=>jsp(a,s),snowflake:()=>Qsp(a,s,bc().featureFlags),fabric:()=>Promise.resolve(null),bigquery:()=>Promise.resolve(null)},i,"GetOAuthDetailsFromEnvironment");if(u===null)throw new nt(`Unable to get OAuth credentials for environment ${n} in org ${t.fbTeamID}!`);return{oauthClientID:u.sensitiveValue.clientId,oauthClientSecret:u.sensitiveValue.clientSecret,connectionAccount:o.connectionAccount,accessUrl:o.accessUrl||null}};var W2m=Je("CONNECTION"),K2m=120;function Y2m(r){try{let t=r.split(".");if(t.length<2||!t[1])return;let n=Buffer.from(t[1],"base64url").toString("utf8"),i=JSON.parse(n);return typeof i.exp=="number"?i.exp:void 0}catch{return}}function jKp(r,t=Math.floor(Date.now()/1e3)){let n=Y2m(r);return n===void 0?!1:t<n-K2m}var vnn=class{constructor(t,n){this.config=n;this.cachedAccessToken=t}config;cachedAccessToken;refreshInFlight=null;async authenticate(){return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}async getValidAccessToken(){return jKp(this.cachedAccessToken)?this.cachedAccessToken:(this.refreshInFlight||(this.refreshInFlight=this.performRefresh().finally(()=>{this.refreshInFlight=null})),this.refreshInFlight)}async performRefresh(){let t=await this.config.loadTokens();if(!t.refresh_token)throw new eH("Missing or invalid OAuth refresh token, please reauthenticate.","OAuthU2M");if(jKp(t.access_token))return this.cachedAccessToken=t.access_token,this.config.onAccessTokenUpdated(t.access_token),t.access_token;W2m.debugContext(this.config.logContext,"Databricks OAuth U2M: refreshing access token (SDK custom auth)");let n=await this.config.getOAuthDetails(),i=await this.config.refreshAccessToken(n,t.refresh_token,this.config.logContext),o={access_token:i,refresh_token:t.refresh_token};return await this.config.persistTokens(o),this.cachedAccessToken=i,this.config.onAccessTokenUpdated(i),i}},Zsp=(r,t,n)=>{let{rootRepository:i,teamInfo:o,teamInfo:{fbTeamID:s}}=t;return{u2mOAuthConfig:{logContext:n,getOAuthDetails:async()=>{let{environmentID:a}=r;if(!a)throw new nt(`No environmentID provided for org ${s}`);return Hct(i.org(s),o,a,jh.Values.databricks)},loadTokens:async()=>{let a=await tjr(n);if(!a.access_token||!a.refresh_token)throw new eH("Missing or invalid OAuth refresh token, please reauthenticate.","OAuthU2M",`Access token: ${a.access_token?"present":"missing"}
|
|
10497
|
+
response size: ${s} MB, max response size: ${a} MB`}},q2m=(r,t)=>new Promise((n,i)=>{let o=[],s=0,a=r.getStatementId(),u=r.streamRows(),p=r.getRequestId(),c=r.getSessionState()?.getCurrentWarehouse?.(),l=0;u.on("error",d=>{i(new cF(d,t,p,a,c))}).on("data",d=>{if(s+=lWe(d,!0),o.push(d),l++,s>s3e()){let f=X7s.default.getHeapStatistics(),h=new Cnn(f,s,r,o);i(h),u.destroy()}}).on("end",()=>{n({rows:o,stmt:r,status:"Success",queryID:a,warehouse:c||null})})}),F2m=async(r,t,n,i)=>{try{return await q2m(r,t)}catch(o){if(typeof o=="object"&&o instanceof Cnn){let s=o.makeErrorMessage(n);return Lne.errorContext(i,s),o.makeResult()}else{let s=o;throw typeof o=="object"&&o instanceof cF&&(s=o.toTRunError()),Lne.alertContext(i,"Error on streaming rows:",s),o}}},U2m="Unable to perform operation using terminated connection.",z2m=407002,Q2m="ECONNRESET",j2m="OAuth access token expired.",n1t=r=>!!r.message.includes(j2m),G2m=r=>r.code===z2m||r.message===U2m,H2m=r=>r&&r.code&&r.code===Q2m,V2m=(r,t)=>{let{promise:n,resolve:i,reject:o}=TR();return{statement:r.execute({...t,streamResult:!0,complete:function(a,u){if(a){let p=t.requestId||u&&u.getRequestId(),c=u&&u.getStatementId(),l=u&&u.getSessionState()?.getCurrentWarehouse?.();o(new cF(a,t,p,c,l))}else i(u)}}),resultStatementPromise:n}},O9e=async r=>{try{return await rAc(r)}catch(t){throw u9o(t)?new yle(t):t}},ejt=class extends a3e{constructor(n,i,o,s,a,u=5){let p={...s,snowflakeRequestID:o.requestId};super(i,o,p,a,u);this.completion=n}completion;initialStatement=null;firstSnowflakeExecutionError;get sqlText(){return this.queryParams.sqlText}makePendingQuery(n){let{statement:i,resultStatementPromise:o}=V2m(this.handle,n),s=Ah(`Back-end (retry=${n.requestId!==void 0}): ${n.sqlText}`,this.logContext,"PERFORMANCE",async()=>{let a=await o;return F2m(a,n,X7s.default.getHeapStatistics(),this.logContext)});return{statement:i,resultPromise:s}}shouldResetConnection=n=>{let i=n.coalesceCause;return n1t(i)||H2m(i)||G2m(i)};handleRetry=async(n,i)=>{if(this.shouldResetConnection(n))try{this.handle=await this.resetFunc()}catch(o){throw Lne.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",o),n.coalesceCause}return i};async queryWithRetries(){try{let n={...this.queryParams};Lne.debugContext(this.logContext,"Making request for CQID=",this.coalesceQueryID);let i=async()=>{gI("snowflake.runQuery.attempt",this.logContext);let l=this.makePendingQuery(n);this.initialStatement=l.statement;let d;try{d=await l.resultPromise;let f=d.status;gI("snowflake.runQuery.finished",{...this.logContext,status:f})}catch(f){throw gI("snowflake.runQuery.error",{...this.logContext,errorString:aa(f).error.errorString}),this.firstSnowflakeExecutionError||f}return Lne.debugContext(this.logContext,"Successfully got result for CQID=",this.coalesceQueryID),d},o=(l,d)=>{if(!(typeof l=="object"&&l instanceof cF))return Lne.errorContext(this.logContext,"Not retrying request CQID=",this.coalesceQueryID,"requestId=",n.requestId,"attempt=",d,"error=",l,"was unrecognized and not retryable"),l;if(l.getSnowflakeErrorCode()==="002043")return Lne.infoContext(this.logContext,"Not retrying request, insufficient privileges CQID=",this.coalesceQueryID,"requestId=",n.requestId,"attempt=",d,"error=",l.coalesceCause?l.coalesceCause:l),l;if(l.isCancel())return Lne.infoContext(this.logContext,"Not retrying request, it was canceled CQID=",this.coalesceQueryID,"error=",l.coalesceCause?l.coalesceCause:l),l},s=async l=>{typeof l=="object"&&l instanceof cF&&(this.firstSnowflakeExecutionError||(this.firstSnowflakeExecutionError=l),n=await this.handleRetry(l,n))},a=l=>["CQID=",this.coalesceQueryID,"requestId=",n.requestId,"retryOptions=",n,"error=",l.cause?l.cause:l],u={name:"backoff",base:5},p={name:"nowait"},c=(l,d)=>kGc(l)||JSON.stringify(aa(l,!0).error).match(/network ?error/i)?u:d||p;return await cf(i,this.maxAttempts,Lne,this.logContext,{alterRetryStrategy:c,beforeRetry:s,checkError:o,retryStrategy:p,retryLogLevel:"info",logOnRetry:"Retrying snowflake request",customErrorOnRetry:a,logOnFailure:"Out of retries for request",customErrorOnFailure:a})}finally{this.completion(this.coalesceQueryID)}}async tryCancel(){let n=this.initialStatement;n!==null&&await cf(()=>O9e(i=>n.cancel(i)),20,Lne,this.logContext,{retryStrategy:{name:"random",min:.05,max:.1},checkError:i=>{if(!(typeof i=="object"&&i instanceof Error&&i.message.includes("Identified SQL statement is not currently executing")))return i}})}};var FKp=Je("CONNECTION"),Z7s=async(r,t,n,i,o)=>{let s=u=>{},a=new ejt(s,r,t,n,i,o);return a.Start(),a.promise},i1t=class extends Bne{currentQueryTag=null;name="snowflake";settingQueryTag=!1;async resetConnection(){let t=await super.resetConnection();return this.currentQueryTag&&!this.settingQueryTag&&await this.setQueryTag(this.currentQueryTag),t}untrackedQuery=async t=>Z7s(this.handle,{sqlText:t},this.logContext,()=>this.resetConnection(),3);setQueryTag=async t=>{this.currentQueryTag=t;let n=this.currentQueryTag===null?"":this.currentQueryTag.replace("$","\\$");this.settingQueryTag=!0;try{gI("snowflake.queryTag",this.logContext),await this.untrackedQuery(`ALTER SESSION SET QUERY_TAG = $$${n}$$`)}finally{this.settingQueryTag=!1}};async makePendingQuery(t){if(this.wasCanceled)throw new BA;let n=o=>this.runningQueries.delete(o),i=new ejt(n,this.handle,t,this.logContext,()=>this.resetConnection());if(this.runningQueries.set(i.coalesceQueryID,i),FKp.debugContext(this.logContext,"Tracking snowflake query with CQID=",i.coalesceQueryID,"query=",i.sqlText),i.Start(),this.wasCanceled)throw FKp.infoContext(this.logContext,"Canceling just-started query due to connection cancellation",i.coalesceQueryID,"conn",this.connectionID),await i.Cancel(),new BA("canceling new query on canceled connection");return i}executeAndGetRunning(t){let n={...this.logContext};return t.requestId&&(n.requestID=t.requestId),gI("snowflake.execute",n),super.executeAndGetRunning(t)}async teardown(){await O9e(t=>this.handle?this.handle.destroy(t):t())}},UKp=async(r,t,n)=>{let i=()=>Enn(r,t,n),o=await i();return await O9e(s=>o.connect(s)),new i1t(o,t,mu(),0,null,i)};var tjt=Je("CONNECTION"),tqs=async(r,t,n)=>{let{rootRepository:i,teamInfo:o,teamInfo:{fbTeamID:s,fbUserID:a}}=t,{environmentID:u}=r;if(!u)throw new nt(`No environmentID provided for org ${s} by user ${a}`);if(r.authenticator!=="OAuth")throw new yX("Cannot reset oauth connection on a non-oauth error!","OAuth");let p=await Hct(i.org(s),o,u,jh.Values.snowflake),c=bc().featureFlags,l=await $7s(n,c);if(!l.refresh_token)throw new yX("Missing or invalid OAuth refresh token, please reauthenticate.","OAuth");let d=l.refresh_token,h={access_token:await qKp(p,d,n),refresh_token:d},A=await hI(),E={orgId:s,userId:a,workspaceId:u.toString()};await Jsp(A,E,new zd(h),c)},eqs=class extends Tre{defaultWarehouse=null;currentWarehouse=null;async createConnection(){return Enn(this.userContext,this.logContext,bc().featureFlags)}async updateFromResult(t){t.warehouse&&(this.currentWarehouse=t.warehouse)}async setup(){await this.connectAndValidate(),await this.setDefaultWarehouse()}async assertConnected(){if(await super.assertConnected(),this.handle===null)throw hh("CONNECTION",!1,this.logContext,"Connection was null after initPromise!"),new DA("Connection was null after initPromise!")}async postReInitialization(){await this.connectAndValidate(),await this.acquire(!0)}connect(){return O9e(t=>this.handle.connect(t))}async resetOauth(){await tqs(this.userContext,this.teamInfoAndFirebase,this.logContext)}async connectAndValidate(){await this.initPromise;try{await this.connect()}catch(t){if(this.userContext.authenticator==="OAuth"&&n1t(t)){await this.resetOauth();try{this.initPromise=this.initialize(),await this.initPromise,await this.connect()}catch(n){if(tjt.errorContext(this.logContext,"Just refreshed oauth tokens, shouldn't have gotten here unless another process did it at the same time: ",n),n1t(n))this.initPromise=this.initialize(),await this.initPromise,await this.connect();else throw n}}else throw t}this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.currentWarehouse)}async setDefaultWarehouse(){let n=(await Z7s(this.handle,{sqlText:"SELECT 1 as coalesce_init"},this.logContext,async()=>{throw new DA("Cannot reset connection")},2)).stmt;if(!n)throw hh("CONNECTION",!!n,this.logContext,"Snowflake did not return a statement!"),new DA("Snowflake did not return a statement!");if(this.defaultWarehouse=n.getSessionState()?.getCurrentWarehouse?.()||null,!this.defaultWarehouse)throw tjt.errorContext(this.logContext,"Could not identify the initial warehouse - possibly invalid credentials?"),new zEr(this.userContext.warehouse)}async teardown(){tjt.infoContext(this.logContext,"[SnowflakeConnectionManagerSlotMember]: Tearing down snowflake connection",this.connectionID),await this.initPromise.catch(()=>{}),await this.firstInitPromise.catch(()=>{}),await O9e(t=>this.handle?this.handle.destroy(t):t())}async acquire(t){if(!t&&this.connection)throw hh("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new DA(`Cannot acquire in-use connection ${this.connectionID}`);if(this.canceled)throw new BA("Attempting to acquire canceled connection slot entry",this.connectionID);if(this.connection=new i1t(this.handle,this.logContext,this.connectionID,this.useCount,this),this.useCount++,this.canceled)throw this.connection=null,new BA("Attempting to acquire canceled connection slot entry",this.connectionID)}newConnection(){return new i1t(this.handle,this.logContext,this.connectionID,this.useCount,this)}setWarehouse=async t=>{await this.assertConnected(),await this.execute({sqlText:`USE WAREHOUSE "${t}"`})};async release(){this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.defaultWarehouse),this.currentWarehouse=null,await super.release()}},Snn=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new eqs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}async test(){let t="SnowflakeConnectionManager.test:",n=Nb(this.userContext,"authenticator","kind","role","user","warehouse");tjt.appContext(this.logContext,t,"testing connection",n),await this.withConnection(async i=>i.execute({sqlText:h5})),tjt.appContext(this.logContext,t,"connection successfully established",n)}};var zKp=(r,t)=>$g({snowflake:()=>n1t(r),databricks:()=>Qct(r),fabric:()=>!1,bigquery:()=>!1},t,"CheckForDeadAccessTokenFromPlatform"),QKp=async(r,t,n)=>fL(r,{snowflake:async i=>await tqs(i,t,n),databricks:async i=>await gvs(i,t,n),fabric:async()=>Promise.reject(new nt(`Invalid platform kind: ${r.kind} for ResetOauthConnectionForPlatform`)),bigquery:async()=>Promise.reject(new nt(`Invalid platform kind: ${r.kind} for ResetOauthConnectionForPlatform`))}),Hct=async(r,t,n,i)=>{let o;try{o=await r.workspace(n).fetch()}catch(p){throw LE(p)&&p instanceof Du?new nt(`Environment ${n} doesn't exist in org ${t.fbTeamID}`):p}let s={orgId:t.fbTeamID,userId:t.fbUserID,workspaceId:n.toString()},a=await hI(),u=await $g({databricks:()=>jsp(a,s),snowflake:()=>Qsp(a,s,bc().featureFlags),fabric:()=>Promise.resolve(null),bigquery:()=>Promise.resolve(null)},i,"GetOAuthDetailsFromEnvironment");if(u===null)throw new nt(`Unable to get OAuth credentials for environment ${n} in org ${t.fbTeamID}!`);return{oauthClientID:u.sensitiveValue.clientId,oauthClientSecret:u.sensitiveValue.clientSecret,connectionAccount:o.connectionAccount,accessUrl:o.accessUrl||null}};var W2m=Je("CONNECTION"),K2m=120;function Y2m(r){try{let t=r.split(".");if(t.length<2||!t[1])return;let n=Buffer.from(t[1],"base64url").toString("utf8"),i=JSON.parse(n);return typeof i.exp=="number"?i.exp:void 0}catch{return}}function jKp(r,t=Math.floor(Date.now()/1e3)){let n=Y2m(r);return n===void 0?!1:t<n-K2m}var vnn=class{constructor(t,n){this.config=n;this.cachedAccessToken=t}config;cachedAccessToken;refreshInFlight=null;async authenticate(){return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}async getValidAccessToken(){return jKp(this.cachedAccessToken)?this.cachedAccessToken:(this.refreshInFlight||(this.refreshInFlight=this.performRefresh().finally(()=>{this.refreshInFlight=null})),this.refreshInFlight)}async performRefresh(){let t=await this.config.loadTokens();if(!t.refresh_token)throw new eH("Missing or invalid OAuth refresh token, please reauthenticate.","OAuthU2M");if(jKp(t.access_token))return this.cachedAccessToken=t.access_token,this.config.onAccessTokenUpdated(t.access_token),t.access_token;W2m.debugContext(this.config.logContext,"Databricks OAuth U2M: refreshing access token (SDK custom auth)");let n=await this.config.getOAuthDetails(),i=await this.config.refreshAccessToken(n,t.refresh_token,this.config.logContext),o={access_token:i,refresh_token:t.refresh_token};return await this.config.persistTokens(o),this.cachedAccessToken=i,this.config.onAccessTokenUpdated(i),i}},Zsp=(r,t,n)=>{let{rootRepository:i,teamInfo:o,teamInfo:{fbTeamID:s}}=t;return{u2mOAuthConfig:{logContext:n,getOAuthDetails:async()=>{let{environmentID:a}=r;if(!a)throw new nt(`No environmentID provided for org ${s}`);return Hct(i.org(s),o,a,jh.Values.databricks)},loadTokens:async()=>{let a=await tjr(n);if(!a.access_token||!a.refresh_token)throw new eH("Missing or invalid OAuth refresh token, please reauthenticate.","OAuthU2M",`Access token: ${a.access_token?"present":"missing"}
|
|
10498
10498
|
, Refresh token: ${a.refresh_token?"present":"missing"}`);return{access_token:a.access_token,refresh_token:a.refresh_token}},persistTokens:a=>JQr(n,a),onAccessTokenUpdated:a=>{r.accessToken=a},refreshAccessToken:rjr}}};var rqs=Je("CONNECTION"),GKp=r=>{if(!r.host)throw new Vi("Could not get a valid host for databricks user");if(!r.path)throw new Vi("Could not get a valid path for databricks user")},ejr=async(r,t)=>{let n,i=new HKp.DBSQLClient;if(!r.host)throw new Vi("Could not get a valid host for databricks user");if(!r.path)throw new Vi("Could not get a valid path for databricks user");if(r.authenticator==="Token"){if(GKp(r),!r.token)throw new Vi("Could not get a valid token for databricks user");n={host:r.host,path:r.path,token:r.token,clientId:"Coalesce.IO_Coalesce"}}else if(r.authenticator==="OAuthU2M"){if(!r.accessToken)throw new Vi("Could not get a valid access token for databricks OAuth U2M authentication");t?.u2mOAuthConfig?n={host:r.host,path:r.path,clientId:"Coalesce.IO_Coalesce",authType:"custom",provider:new vnn(r.accessToken,t.u2mOAuthConfig)}:n={host:r.host,path:r.path,token:r.accessToken,clientId:"Coalesce.IO_Coalesce",authType:"access-token"}}else if(r.authenticator==="OAuthM2M"){if(GKp(r),!r.clientID||!r.secret)throw new Vi("Missing Client ID or Secret for databricks user");n={authType:"databricks-oauth",oauthClientId:r.clientID,oauthClientSecret:r.secret,host:r.host,path:r.path}}else throw new Vi(`Could not authenticate using ${r.authenticator}`);return await i.connect(n)},tjr=async r=>{let{workspaceID:t,orgID:n,userID:i}=r;try{let o=await Ysp({orgId:n,userId:i,workspaceId:t.toString()});if(rqs.infoContext(r,"get access token from secret (GetAccessTokenFromSecret)"),!o)throw new cWe("Invalid OAuth configuration.");return o.sensitiveValue}catch(o){throw rqs.errorContext(r,"Error getting access token from secret (GetAccessTokenFromSecret)",o),o}},rjr=async(r,t,n)=>{if(!r.connectionAccount)throw new eH("Missing connection account for Databricks OAuth refresh","OAuthU2M");let o=`${`https://${r.connectionAccount}`}/oidc/v1/token`,s=VKp.default.stringify({grant_type:"refresh_token",client_id:r.oauthClientID,client_secret:r.oauthClientSecret,refresh_token:t}),a={method:"post",url:o,headers:{"Content-Type":"application/x-www-form-urlencoded"},data:s};try{return(await dc(a)).data.access_token}catch(u){throw rqs.errorContext(n,"RefreshAccessToken",u),new eH("An error occurred refreshing your OAuth refresh token. Please ensure your OAuth Security Integration is still valid or reauthenticate.","OAuthU2M",u)}};var nqs=Je("CONNECTION"),J2m=50,WKp=async(r,t,n,i,o)=>{let s=u=>{},a=new e9t(s,r,t,n,i,o);return a.Start(),a.promise},Avs=r=>({client:r,session:void 0,sessionOptions:{}}),Gct=class extends Bne{name="databricks";storageQueryCount=0;async waitForStorageQueries(){for(;this.storageQueryCount>0;)await kG(J2m)}async teardown(){await this.waitForStorageQueries(),await mvs(this.handle,this.logContext)}untrackedQuery=async(t,n)=>WKp(this.handle,{statement:t,...n},this.logContext,()=>this.resetConnection(),3);setQueryTag=async t=>{};async makePendingQuery(t){if(this.wasCanceled)throw new BA;let n=o=>this.runningQueries.delete(o),i=new e9t(n,this.handle,t,this.logContext,()=>this.resetConnection());if(this.runningQueries.set(i.coalesceQueryID,i),nqs.debugContext(this.logContext,`Tracking ${this.name} query with CQID=`,i.coalesceQueryID,"query=",i.sqlText),i.Start(),this.wasCanceled)throw nqs.infoContext(this.logContext,"Canceling just-started query due to connection cancellation",i.coalesceQueryID,"conn",this.connectionID),await i.Cancel(),new BA("canceling new query on canceled connection");return i}getConnectionLogContext(){return this.logContext}runQueryForStorage=async t=>{let n=()=>{throw new DA("Cannot reset: Storage connection reset is handled by DBConnectionStorageClass.")};this.storageQueryCount++;try{return await WKp(this.handle,t,this.logContext,n,1)}finally{this.storageQueryCount--}}},KKp=async(r,t)=>{let n=async()=>{let o=await ejr(r);return Avs(o)},i=await n();return new Gct(i,t,mu(),0,null,n)},mvs=async(r,t)=>{if(r.session)try{await r.session.close()}catch(n){nqs.errorContext(t,"Error closing session during teardown",n)}await r.client.close()};var Tnn=async(r,t,n,i,o)=>{let s={kind:"bigquery",authenticator:r,environmentID:i},a=await hI(),u={orgId:t,userId:n,workspaceId:i.toString()};if(r==="OAuth"){let p=await Hsp(a,u);if(!p?.sensitiveValue.clientID||!p?.sensitiveValue.clientSecret)throw new Du("BigQuery OAuth app credentials (clientID/clientSecret) not found");let c=await Ksp(u);if(!c?.sensitiveValue.refresh_token)throw new Du("BigQuery OAuth refresh token not found. Please re-authenticate.");s={...s,clientID:p.sensitiveValue.clientID,secret:p.sensitiveValue.clientSecret,refreshToken:c.sensitiveValue.refresh_token}}else if(r==="ServiceAccount"){let p=o;if(p||(p=(await Gsp(a,u))?.sensitiveValue?.serviceAccountKey),!p)throw new Du("No BigQuery credentials found!");s={...s,serviceAccountKey:p}}else throw new Vi(`connection type: ${r} is not valid for BigQuery`);return s};var iqs=require("crypto");function w9e(r,t){try{let i=(0,iqs.createPrivateKey)({key:r.sensitiveValue,passphrase:t?.sensitiveValue}).export({format:"pem",type:"pkcs8"});if(!i||typeof i!="string")throw new nt("Unknown error decrypting private key");if(t!==void 0)try{throw(0,iqs.createPrivateKey)({key:r.sensitiveValue}),new Vi("Private key is not encrypted but a passphrase was provided")}catch(o){if(LE(o))throw o;if(!o||typeof o!="object"||"code"in o&&o.code!=="ERR_OSSL_CRYPTO_INTERRUPTED_OR_CANCELLED")throw new nt("Unknown error decrypting private key",o?.message)}return new zd(i)}catch(n){if(LE(n))throw n;if(n&&typeof n=="object"&&"code"in n)switch(n.code){case"ERR_OSSL_UNSUPPORTED":throw new Vi("Unable to parse private key");case"ERR_OSSL_BAD_DECRYPT":throw new Vi("Unable to decrypt private key using the provided passphrase");case"ERR_OSSL_CRYPTO_INTERRUPTED_OR_CANCELLED":throw new Vi("Unable to decrypt private key without a passphrase")}throw new nt("Unknown error decrypting private key",n?.message)}}var YKp=r=>{let t=r.passphrase===void 0||r.passphrase===null?void 0:new zd(r.passphrase);try{w9e(new zd(r.key),t)}catch(n){if(!LE(n)||n.message!=="Unable to decrypt private key without a passphrase")throw new FP(n instanceof Error?n.message:"Unknown error validating private key")}};var $2m=async(r,t,n)=>{let i=n.isFeatureEnabled("enableSnowflakeSecretsV2"),o=await zct(r,t,Vet,i);return o&&YKp(o.sensitiveValue),o},X2m=async(r,t,n,i,o,s)=>{let a=n.toString();if(CWe(i)){if(!dTt(o))throw new Vi(`Got a snowflake user credentials with a ${o.connectionKind} userConnection`);if(i.snowflakeAuthType==="KeyPair"&&(i.snowflakeKeyPairKey===void 0||i.snowflakeKeyPairPass===void 0)){let u=await hI(),p=await $2m(u,{orgId:r,userId:t,workspaceId:a},s);if(!p){if(i.snowflakeKeyPairKey===void 0)throw new Vi("No Snowflake private key found!");return}i.snowflakeKeyPairKey===void 0&&(i.snowflakeKeyPairKey=p.sensitiveValue.key),!i.snowflakeUsername&&o.connectionDetails?.user&&(i.snowflakeUsername=o.connectionDetails.user),i.snowflakeKeyPairPass===void 0&&p.sensitiveValue.passphrase!==void 0&&(i.snowflakeKeyPairPass=p.sensitiveValue.passphrase)}}},Z2m=async(r,t,n,i,o,s)=>{let a={orgId:r,userId:t,workspaceId:n.toString()};await Lme(i,{databricks:async u=>{if(u.databricksAuthType==="Token")return;if(!P0r(o))throw new Vi(`Got a databricks auth credentials with a ${o.connectionKind??"snowflake"} userConnection`);let p=await hI();if(u.databricksAuthType==="OAuthM2M"){let c=await p.Get(e6e,a);if(!c)throw new Vi("No Databricks OAuth M2M credentials found!");u.clientSecret=c.sensitiveValue.clientSecret,u.clientID=c.sensitiveValue.clientID}else if(u.databricksAuthType==="Cloud"){let c=await p.Get(Get,a);if(!c)throw new Vi("No Databricks Cloud credentials found!");u.databricksAuthType="Token",u.token=c.sensitiveValue.token}else if(u.databricksAuthType==="OAuthU2M"){let c=await p.Get(T2e,a);if(!c)throw new Vi("No Databricks credentials found!");!u.path&&o.connectionDetails.path&&(u.path=o.connectionDetails.path),u.accessToken=c.sensitiveValue.access_token}!u.path&&o.connectionDetails.path&&(u.path=o.connectionDetails.path)},snowflake:async u=>{if(u.snowflakeAuthType!=="Cloud")return;if(!dTt(o))throw new Vi(`Got a snowflake user credentials with a ${o.connectionKind} userConnection`);let p=await hI(),c=await Vsp(p,a,s.isFeatureEnabled("enableSnowflakeSecretsV2"));if(!c)throw new Vi("No Snowflake credentials found!");!u.snowflakeUsername&&o.connectionDetails?.user&&(u.snowflakeUsername=o.connectionDetails.user),!u.snowflakeWarehouse&&o.connectionDetails?.warehouse&&(u.snowflakeWarehouse=o.connectionDetails.warehouse),!u.snowflakeRole&&o.connectionDetails?.role&&(u.snowflakeRole=o.connectionDetails.role),u.snowflakeAuthType="Basic",u.snowflakePassword=c.sensitiveValue.password},bigquery:async u=>{if(!N0r(o))throw new Vi(`Got a bigquery user credentials with a ${o.connectionKind} userConnection`);if(u.bigQueryAuthType!=="ServiceAccount")return;let{serviceAccountKey:p}=await Tnn(o.connectionType,r,t,n,u.serviceAccountKey);Object.assign(u,{serviceAccountKey:p})},fabric:async()=>{}},"CloudCredsToBasic")},M9e=async(r,t,n,i,o,s)=>{await Z2m(r,t,n,i,o,s),await X2m(r,t,n,i,o,s)};var JKp=require("crypto");var eCm=Je("PLAN"),_nn=class r{constructor(t,n,i,o){this.client=t;this.environmentID=n;this.cachedRefs=i;this.logContext=o}client;environmentID;cachedRefs;logContext;async getCachedRef(t,n){let i=this.hashRenderPlan(n);return this.cachedRefs.get(`${t}:${i}`)?.refData}updateCache(t,n,i){let o=`${t}:${i}`;this.cachedRefs.has(o)||this.cachedRefs.set(o,{nodeID:t,hash:i,requiresSync:!0,refData:n})}async syncCache(){let t=Array.from(this.cachedRefs.values()).filter(({requiresSync:n})=>n);return t.length===0?0:(await this.client.postRenderedRefs({renderedRefs:t.map(({nodeID:n,hash:i,refData:o})=>({nodeID:n,hash:i,ref:JSON.stringify(o),environmentID:this.environmentID}))}),t.length)}static stringifyNodeMetadata(t){let{operationName:n,deployStrategy:i,parameters:o}=t,s=[n,i];return o&&s.push(JSON.stringify(o)),s.join("|")}static async fetchCachedRefs(t,n,i){let o=await t.getRenderedRefs({queries:{environmentID:n}}),s=new Map;for(let a of o.renderedRefs){let u=r.parseRefUsage(a.ref,i);u&&s.set(`${a.nodeID}:${a.hash}`,{nodeID:a.nodeID,hash:a.hash,refData:u,requiresSync:!1})}return s}static parseRefUsage(t,n){try{return JSON.parse(t)}catch(i){eCm.errorContext(n,"parseRefUsage",`Failed to parse ref usage: ${t}`,{error:i});return}}};var rjt=class r extends _nn{hashRenderPlan(t){let{templateString:n,macrosString:i,nodeMetadata:o,runTimeParameters:s={},packages:a}=t,u=(0,JKp.createHash)("sha256");return u.update(n),u.update(i),u.update(r.stringifyNodeMetadata(o)),u.update(JSON.stringify(s)),u.update(JSON.stringify(a)),u.digest("hex")}};var tCm=Je("PLAN"),rCm=async(r,t,n)=>{let i=await rjt.fetchCachedRefs(t,r,n);return new rjt(t,r,i,n)};async function Inn(r,t){try{let n=vDe();return await rCm(r,n,t)}catch(n){tCm.warnContext(t,"getRenderCache","Failed to get render cache",{error:n});return}}var U$p=yt(kqs());var z$p=yt(uet());var kJp=["DATE","DATETIME","TIMESTAMP","TIME"],evm=B.object({table_catalog:B.string().optional(),table_schema:B.string().optional(),table_name:B.string(),column_name:B.string(),ordinal_position:B.union([B.number(),B.string()]).nullable().optional(),is_nullable:B.union([B.literal("YES"),B.literal("NO")]),data_type:B.string(),column_default:B.string().nullable().optional(),comment:B.string().nullable().optional()}),Jnn=class extends hZ{validator=Mr("BigQueryInformationSchemaColumnsType",evm);query(t){let n=zA([t.database,t.schema],"bigquery");return`SELECT
|
|
10499
10499
|
c.table_catalog,
|
|
10500
10500
|
c.table_schema,
|
|
@@ -10527,9 +10527,9 @@ ${c}`,l)});o.length&&yJo.infoContext(r.logContext,n,"Error(s) transforming resul
|
|
|
10527
10527
|
t.table_catalog,
|
|
10528
10528
|
t.table_schema,
|
|
10529
10529
|
t.table_name,
|
|
10530
|
-
t.table_type`}convert(t){let n=t.table_type==="BASE TABLE"?"TABLE":t.table_type.toUpperCase(),{table_name:i,table_type:o,comment:s,...a}=t,u=s&&s.length>=2&&s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1):s??"";return{kind:n,name:i,comment:u,extra:{...a,table_type:o}}}},rvm=B.object({name:B.string()}),Xnn=class extends gZ{validator=Mr("BigQueryShowSchemaRow",rvm);query(t){return`SELECT '${t.schema}' AS name`}convert(t){return{name:t.name,extra:{}}}};var qJp=(r,t)=>{let n=r;for(let i of t){let o=r[i.Name],s=kJp.includes(i.DataType);o&&s&&typeof o=="object"&&"value"in o&&(n[i.Name]=o.value)}return n};var fjt=class extends AZ{constructor(n){super("bigquery");this.userContext=n}userContext;getObjectsImplementation=new $nn;getColumnsImplementation=new Jnn;getSchemasImplementation=new Xnn;isVariantType(n){return n.toUpperCase()==="JSON"}validateUserContext(){let n="In your environment settings, verify that you have";if(!this.userContext)throw new Vi(`BigQuery user authentication unsuccessful: Missing ${this.name} connection information! ${n} selected and authenticated a connection type.`);if(this.userContext.kind!=="bigquery")throw new Vi(`BigQuery user authentication unsuccessful: ASSERTION FAILED: Expected ${this.name} user context but received kind ${this.userContext.kind}`)}async testConnection(){try{this.validateUserContext(),await this.runSQL({sql:h5})}catch(n){throw n instanceof Error?new nt(`Could not validate connection to ${this.name}: ${n.message}`):new nt(`Could not validate connection to ${this.name}`,ua(n).error.errorDetail)}}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n?.data?.status||"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data){let a=n.data.columns.map(c=>c.Name),u=n.data.rows.map(c=>{let l=qJp(c,n.data.columns);return{values:YYe(a,l)}}),p=n.data.columns.map(c=>({name:c.Name,type:c.DataType??""}));s.fields=p,s.rows=u}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}getBigQueryApiClient(){let n=this.userContext.environmentID;if(!n)throw new Vi("Missing environmentID in BigQuery user context");let i=Xc.isInitialized?Xc.resolveAuthToken:void 0;return{client:D3(void 0,i),workspaceID:n.toString()}}async getDatabaseNames(){let{client:n,workspaceID:i}=this.getBigQueryApiClient();return(await n.GetBigQueryProjects({params:{workspaceID:i}})).projects.map(s=>s.id)}async getSchemaNames(n){let{client:i,workspaceID:o}=this.getBigQueryApiClient();return await i.GetBigQueryDatasets({params:{workspaceID:o,projectID:n}})}async getObjectRows(n,i,o){let a=`SELECT * FROM ${IIt(n,i,"bigquery")} LIMIT 100`;return this.getSQLQueryResult({sql:a,options:{dryRun:o}})}async describeObject(n,i,o,s){let a=Xq(i.locationName,n,"[BigQueryBasePlatform.describeObject()]"),u=this.getColumnsImplementation.queryForObject(a,i.name);return(await this.runSQL({sql:u,overrideRequestID:mu()})).data.rows.map(c=>this.createColumnMetadata(c,s))}createColumnMetadata(n,i){return{name:n.column_name,dataType:n.data_type.toUpperCase(),transform:"",nullable:n.is_nullable==="YES",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},description:n.comment||"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async getVariantRows(n,i,o,s){let a=IIt(s,o,"bigquery"),u=`SELECT \`${n}\` FROM ${a} LIMIT ${i}`;return this.getSQLQueryResult({sql:u})}convertObjectRowsToMaterializationKinds(n){let i="convertObjectRowsToMaterializationKinds:",o=[],s=[];for(let a of n)a.kind==="TABLE"?o.push(a.name):a.kind==="VIEW"?s.push(a.name):Je("PLATFORM").errorContext({workspaceID:this.userContext.environmentID?+this.userContext.environmentID:void 0},i,`table ${a.name} is of unexpected table type ${a.kind} - skipping it`);return{tables:o,views:s}}createState(n,i,o,s){return new iMr(s,o,i,n)}wrapSQLWithExplain(n){return n}wrapSQLWithTest=n=>`SELECT 1 FROM UNNEST([1]) WHERE EXISTS (${n})`};var b$p=yt(lin());var Ein=r=>{let{authenticator:t,serviceAccountKey:n,clientID:i,secret:o,refreshToken:s,credentialsFile:a}=r,u={};switch(t){case"ServiceAccount":{if(!n)throw new Vi("BigQuery ServiceAccount credentials are required.");try{let p=typeof n=="string"?JSON.parse(n):n;u.credentials=p}catch(p){throw new nt("Invalid BigQuery serviceAccountKey provided (failed to parse JSON)",p instanceof Error?p.message:String(p))}u.credentials?.project_id&&(u.projectId=u.credentials.project_id);break}case"OAuth":{if(!i||!o)throw Je("CONNECTION").error("Missing clientID or secret. Cannot create BigQuery client"),new Du("Missing OAuth app credentials");if(!s)throw Je("CONNECTION").error("Missing refresh token. Cannot create BigQuery client"),new Du("Missing OAuth refresh token");u.credentials={type:"authorized_user",client_id:i,client_secret:o,refresh_token:s};break}case"ApplicationDefault":{a&&(u.keyFilename=a);break}default:throw new Vi(`Unsupported BigQuery authenticator: ${JSON.stringify(t)}`)}return Je("CONNECTION").info("Creating BigQuery client"),new b$p.BigQuery(u)};var Cin=async r=>Ein(r),E$p=r=>({client:r});var E1t=class extends nt{constructor(n,i){let{errorString:o,errorDetail:s}=ua(i).error;super(o,s);this.query=n;this.coalesceCause=i}query;coalesceCause;isCancel(){return!1}};var Wz=Je("CONNECTION"),C$p="number of rows inserted",S$p="number of rows updated",v$p="number of rows deleted",Ijt=class extends a3e{constructor(n,i,o,s,a,u=5){let p={...s,bigqueryRequestID:o.requestId};super(i,o,p,a,u);this.completion=n}completion;job;get sqlText(){return this.queryParams.statement}shouldResetConnection=n=>!!ua(n).error.errorString.match(/(network ?error|econnreset)/i);handleRetry=async(n,i)=>{if(this.shouldResetConnection(n))try{this.handle=await this.resetFunc()}catch(o){throw Wz.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",o),n.coalesceCause}return i};computeChunkAndNextQuery(n){let i=[],o;if(Array.isArray(n)){let s=n[0];Array.isArray(s)&&(i=s);let a=n.length>1?n[1]:void 0;if(a&&typeof a=="object"){let u=a.pageToken;u?o={pageToken:u,...this.queryParams.location?{location:this.queryParams.location}:{}}:o=void 0}else o=void 0}return{chunk:i,nextPageQuery:o}}async queryWithRetries(){let n=`[TrackedPendingBigQueryQuery.queryWithRetries() - '${this.queryParams.statement}']`;try{let i=async()=>{gI("bigquery.runQuery.attempt",this.logContext);let l={rows:[],status:"Success",columns:[]};try{let d={query:this.queryParams.statement,params:this.queryParams.params,location:this.queryParams.location,labels:this.queryParams.labels,dryRun:this.queryParams.dryRun};Wz.infoContext(this.logContext,"BigQuery createQueryJob starting",this.coalesceQueryID,this.queryParams.dryRun?"(dry run)":"");let[f]=await this.handle.client.createQueryJob(d);if(Wz.infoContext(this.logContext,"BigQuery createQueryJob finished",this.coalesceQueryID,this.queryParams.dryRun?"(dry run)":""),this.job=f,this.queryParams.dryRun)return this.getDryRunStats(f,l);let h=0,A;do{let{next:E,done:v,inMemorySize:T}=await this.processQueryPage(f,A,l,n,h);if(h=T,A=E,v)break}while(A);await this.getDMLStats(f,l),gI("bigquery.runQuery.finished",this.logContext)}catch(d){throw gI("bigquery.runQuery.error",{...this.logContext,errorString:ua(d).error.errorString}),d}return l},o=(l,d)=>{if(!(typeof l=="object"&&l instanceof E1t))return Wz.errorContext(this.logContext,"Not retrying BigQuery request",this.coalesceQueryID,"attempt=",d,"error=",l,"was unrecognized and not retryable"),l;if(l.isCancel())return Wz.infoContext(this.logContext,"Not retrying BigQuery request; it was canceled",this.coalesceQueryID),l},s=l=>{let d=l instanceof Error&&"cause"in l?l.cause:l;return["CQID=",this.coalesceQueryID,"error=",d]},a={name:"backoff",base:5},u={name:"nowait"},p=async l=>{typeof l=="object"&&l instanceof E1t&&await this.handleRetry(l,this.queryParams)},c=(l,d)=>JSON.stringify(ua(l,!0).error).match(/network ?error/i)?a:d||u;return await cf(i,this.maxAttempts,Wz,this.logContext,{beforeRetry:p,alterRetryStrategy:c,checkError:o,retryStrategy:u,retryLogLevel:"info",logOnRetry:"Retrying BigQuery request",customErrorOnRetry:s,logOnFailure:"Out of retries for BigQuery request",customErrorOnFailure:s})}catch(i){throw new E1t(this.queryParams,i)}finally{this.completion(this.coalesceQueryID)}}getDryRunStats(n,i){let s=n.metadata?.statistics;if(s?.query){let a="";Object.entries(s.query).forEach(([u,p])=>{p!=null&&typeof p!="object"&&(a+=`${u}: ${p} `)}),i.rows=[{content:a}],i.columns=[{name:"Dry Run Results",type:"STRING"}]}return Wz.infoContext(this.logContext,"BigQuery dry run validation successful",this.coalesceQueryID),gI("bigquery.runQuery.dryRun.finished",this.logContext),i}async getDMLStats(n,i){try{let a=(await n.getMetadata())[0]?.statistics?.query?.dmlStats;if(a&&i.rows.length===0){let u={},p=[],c=a.insertedRowCount?Number(a.insertedRowCount):0,l=a.updatedRowCount?Number(a.updatedRowCount):0,d=a.deletedRowCount?Number(a.deletedRowCount):0;c>0&&(u[C$p]=c,p.push({name:C$p,type:"INTEGER"})),l>0&&(u[S$p]=l,p.push({name:S$p,type:"INTEGER"})),d>0&&(u[v$p]=d,p.push({name:v$p,type:"INTEGER"})),p.length>0&&(i.rows=[u],i.columns=p)}}catch(o){Wz.warnContext(this.logContext,"Failed to synthesize BigQuery DML row counts from job statistics",this.coalesceQueryID,o)}}extractBigQueryAPIResponse(n){if(Array.isArray(n)&&n.length>=3)return n[2]?.schema?.fields;Wz.warnContext(this.logContext,"BigQuery response not in expected tuple format [rows, apiResponse, schema]")}async processQueryPage(n,i,o,s,a){Wz.infoContext(this.logContext,"BigQuery getQueryResults starting",this.coalesceQueryID);let u=await n.getQueryResults(i);Wz.infoContext(this.logContext,"BigQuery getQueryResults finished",this.coalesceQueryID);let p=this.extractBigQueryAPIResponse(u);p&&o.columns.length===0&&(o.columns=p);let{chunk:c,nextPageQuery:l}=this.computeChunkAndNextQuery(u);return a+=lWe(c,!0),a>s3e()?(o.status=dL,Wz.errorContext(this.logContext,s,`Chunk limit reached; returning partial rows (${o.rows.length})`),{next:void 0,done:!0,inMemorySize:a}):(o.rows.push(...c),{next:l??void 0,done:!1,inMemorySize:a})}async tryCancel(){if(this.job)try{await this.job.cancel();return}catch(n){throw new nt("Error canceling BigQuery job",JSON.stringify(ua(n).error))}throw new nt("No running BigQuery job to cancel")}};var dFs=Je("CONNECTION"),yTm=async(r,t,n,i,o)=>{let s=u=>{},a=new Ijt(s,{client:r},t,n,i,o);return a.Start(),a.promise},Rjt=class extends Bne{name="bigquery";async teardown(){return Promise.resolve()}untrackedQuery=async t=>yTm(this.handle.client,{statement:t},this.logContext,this.resetConnection,3);setQueryTag=async t=>Promise.resolve();async makePendingQuery(t){if(this.wasCanceled)throw new BA;let n=o=>this.runningQueries.delete(o);dFs.infoContext(this.logContext,"BigQuery makePendingQuery",t.statement);let i=new Ijt(n,this.handle,t,this.logContext,this.resetConnection);if(this.runningQueries.set(i.coalesceQueryID,i),dFs.debugContext(this.logContext,`Tracking ${this.name} query with CQID=`,i.coalesceQueryID,"query=",i.sqlText),i.Start(),this.wasCanceled)throw dFs.infoContext(this.logContext,"Canceling just-started query due to connection cancellation",i.coalesceQueryID,"conn",this.connectionID),await i.Cancel(),new BA("canceling new query on canceled connection");return i}getConnectionLogContext(){return this.logContext}getClient(){return this.handle.client}},T$p=async(r,t)=>{let n=async()=>({client:await Cin(r)}),i=await n();return new Rjt(i,t,mu(),0,null,n)};var _$p=Je("CONNECTION"),fFs=class extends Tre{name="bigquery";async createConnection(){let t=await Cin(this.userContext);return E$p(t)}async updateFromResult(t){return Promise.resolve()}async setup(){return Promise.resolve()}newConnection(){return new Rjt(this.handle,this.logContext,this.connectionID,this.useCount,this)}},Sin=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new fFs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}async test(){let t="BigQueryConnectionManager.test:",n=Nb(this.userContext,"authenticator","kind");_$p.appContext(this.logContext,t,"testing connection",n),await this.withConnection(async i=>i.execute({statement:h5})),_$p.appContext(this.logContext,t,"connection successfully established",n)}};var I$p="https://bigquery.googleapis.com/bigquery/v2",R$p=async r=>{let t=[],n;do{let i={maxResults:"1000"};n&&(i.pageToken=n);let{data:o}=await dc.get(`${I$p}/projects`,{headers:{Authorization:`Bearer ${r}`},params:i});o.projects&&t.push(...o.projects),n=o.nextPageToken}while(n);return{projects:t}},O$p=r=>{let t=[];for(let n of r.projects??[]){let i=n.projectReference.projectId;t.push({id:i,name:n.friendlyName})}return t},w$p=async(r,t)=>{let n=[],i;do{let o={maxResults:"1000"};i&&(o.pageToken=i);let{data:s}=await dc.get(`${I$p}/projects/${encodeURIComponent(t)}/datasets`,{headers:{Authorization:`Bearer ${r}`},params:o});s?.datasets&&n.push(...s.datasets.map(a=>a.datasetReference.datasetId)),i=s?.nextPageToken}while(i);return n};var hFs=Je("PLATFORM"),vin=class r extends fjt{constructor(n,i){super(i);this.connection=n}connection;usingConnection(n){return new r(n,this.userContext)}async teardown(){return this.connection.teardown()}async runSQL(n){let{sql:i,options:o={}}=n;this.warnAboutLargeQuery(i),hFs.info("BigQueryBackendPlatform.runSQL starting",o.dryRun?"(dry run)":"",i);try{let s=await this.connection.execute({statement:i,...o});return hFs.info("BigQueryBackendPlatform.runSQL finished",o.dryRun?"(dry run)":"","rows=",Array.isArray(s.rows)?s.rows.length:0),aKc(s,i)}catch(s){throw hFs.error("BigQueryBackendPlatform.runSQL error",s),s}}async getDatabaseNames(){let n=await this.getAccessToken();return O$p(await R$p(n)).map(o=>o.id)}async getSchemaNames(n){return w$p(await this.getAccessToken(),n)}async getAccessToken(){let i=await Ein(this.userContext).authClient.getAccessToken();if(!i)throw new Error("Failed to obtain BigQuery access token");return i}},M$p=async(r,t,n,i,o)=>{let s=await Sin.New(r,t,o,n);i&&await s.test();let a=new vin(s.getConnection(),r);return{connectionManager:s,platform:a}},x$p=async(r,t)=>{let n=await T$p(r,t);return new vin(n,r)};var bTm=B.object({table_catalog:B.string(),table_schema:B.string(),table_name:B.string(),table_type:B.string(),is_insertable_into:B.string(),commit_action:B.string(),table_owner:B.string(),comment:B.string().nullable(),created:B.union([B.string(),B.date()]),created_by:B.string(),last_altered:B.union([B.string(),B.date()]),last_altered_by:B.string(),data_source_format:B.string(),storage_sub_directory:B.string().nullable()}),Tin=class extends fZ{validator=Mr("DatabricksInformationSchemaTablesType",bTm);query(t){return`SELECT * FROM ${zA([t.database],"databricks")}.information_schema.tables where table_schema = '${t.schema.toLowerCase()}' `}convert(t){let n=t.table_type;(t.table_type==="MANAGED"||t.table_type==="MANAGED_SHALLOW_CLONE"||t.table_type==="BASE TABLE")&&(n="TABLE");let{table_name:i,comment:o,...s}=t;return{kind:n,name:i,extra:s,comment:o??""}}},ETm=B.object({table_catalog:B.string(),table_schema:B.string(),table_name:B.string(),column_name:B.string(),ordinal_position:B.number(),column_default:B.string().nullable(),is_nullable:B.union([B.literal("YES"),B.literal("NO")]),full_data_type:B.string(),data_type:B.string(),character_maximum_length:B.number().nullable(),comment:B.string().nullable()}),CTm=ETm.pick({column_name:!0,comment:!0,data_type:!0,is_nullable:!0,table_name:!0}),_in=class extends hZ{validator=Mr("DatabricksInformationSchemaColumnsType",CTm);get columnsString(){return"table_name, column_name, is_nullable, comment, data_type"}query(t){let n=zA([t.database],"databricks");return`select ${this.columnsString} from ${n}.information_schema.columns where table_schema = "${t.schema.toLowerCase()}"`}convert(t){let{table_name:n,column_name:i,comment:o,...s}=t;return{objectName:n,name:i,comment:o??"",extra:s}}queryForObject(t,n){return`${this.query(t)} and table_name = "${n.toLowerCase()}"`}async runQuery(t,n,i){let o=new lNt(t,["table_name","column_name"],n,{...i,platform:"databricks"});return await o.run(),o.checkForDuplicates(["table_name","column_name"]),o.aggregateRows.map(s=>this.validateAndConvert(s))}},STm=B.object({databaseName:B.string()}),Iin=class extends gZ{validator=Mr("DatabricksShowSchemaRow",STm);query(t){return`SHOW SCHEMAS IN ${zA([t.database],"databricks")}`}convert(t){return{name:t.databaseName,extra:{}}}},mCS=B.object({id:B.string(),name:B.string(),odbc_params:B.object({path:B.string()})});var vTm=Je("PLATFORM"),P$p=6e4,TTm=`Connection test timed out after ${P$p/1e3} seconds. Please verify that your SQL warehouse is running and accessible in Databricks.`,Ojt=class extends AZ{constructor(n){super("databricks");this.userContext=n}userContext;getObjectsImplementation=new Tin;getColumnsImplementation=new _in;getSchemasImplementation=new Iin;async getDatabaseNames(){return(await this.getRows("SHOW CATALOGS")).map(i=>i.catalog)}async getSchemaNames(n){let i=zA([n],"databricks");return(await this.getRows(`SHOW SCHEMAS IN ${i}`)).map(s=>s.databaseName)}async getVariantRows(n,i,o,s){let a=this.getName(s,o),u=`SELECT ${n} FROM ${a} TABLESAMPLE (${i} ROWS)`;return this.getSQLQueryResult({sql:u})}async getObjectRows(n,i,o){let s=`SELECT * FROM ${this.getName(n,i)} LIMIT 100`;return o&&(s=this.wrapSQLWithExplain(s)),this.getSQLQueryResult({sql:s})}createColumnMetadata(n,i){return{name:n.name,dataType:n.extra.data_type,transform:"",nullable:n.extra.is_nullable==="YES",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},description:n.comment||"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async describeObject(n,i,o,s){let a=Xq(i.locationName,n,"[DatabricksBasePlatform.describeObject()]"),u=this.getColumnsImplementation.queryForObject(a,i.name);return(await this.runSQL({sql:u,overrideRequestID:mu()})).data.rows.map(c=>this.createColumnMetadata(this.getColumnsImplementation.validateAndConvert(c),s))}validateUserContext(){let n="In your environment settings, verify that you have",i=[];if(!this.userContext)throw new Vi(`Databricks user authentication unsuccessful: Missing ${this.name} connection information! ${n} selected and authenticated a connection type.`);if(this.userContext.kind!=="databricks")throw new Vi(`Databricks user authentication unsuccessful: ASSERTION FAILED: Expected databricks user context but received kind ${this.userContext.kind}`);switch(this.userContext.authenticator){case"Token":this.userContext.host?.trim()||i.push(`Missing ${this.name} host information! ${n} added a host.`),this.userContext.path?.trim()||i.push(`Missing ${this.name} path information! ${n} added a path.`),this.userContext.token?.trim()||i.push(`Missing ${this.name} token! ${n} added a token.`);break;case"OAuthM2M":case"OAuthU2M":case"Cloud":this.userContext.host?.trim()||i.push(`Missing ${this.name} host information! ${n} added a host.`),this.userContext.path?.trim()||i.push(`Missing ${this.name} path information! ${n} added a path.`);break;default:throw new Vi(`Databricks user authentication unsuccessful: Unknown authenticator type: ${this.userContext.authenticator}`)}if(i.length>0)throw new Vi(`Databricks user authentication unsuccessful: ${i.join("; ")}`)}async testConnection(){let n=new AbortController,i,o=new Promise((s,a)=>{i=setTimeout(()=>{n.abort(),a(new nt(TTm))},P$p)});try{this.validateUserContext(),await Promise.race([this.runSQL({sql:h5,httpConfig:{signal:n.signal}}),o])}catch(s){if(s instanceof Vi)throw s;let a;throw s instanceof Error?a=new nt(`Could not validate connection to ${this.name}: ${s.message}`):a=new nt(`Could not validate connection to ${this.name}`,ua(s).error.errorDetail),a}finally{clearTimeout(i)}}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n?.data?.status||"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data){let a=n.data.columns.map(c=>c.Name),u=n.data.rows.map(c=>({values:YYe(a,c)})),p=n.data.columns.map(c=>({name:c.Name,type:c.DataType}));s.fields=p,s.rows=u}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}convertObjectRowsToMaterializationKinds(n){let i="convertObjectRowsToMaterializationKinds:",o=[],s=[];for(let a of n){let u=a.name.toLowerCase();a.kind==="TABLE"?o.push(u):a.kind==="VIEW"?s.push(u):vTm.errorContext({workspaceID:this.userContext.environmentID?+this.userContext.environmentID:void 0},i,`table ${u} is of unexpected table type ${a.kind} - skipping it`)}return{tables:o,views:s}}createState(n,i,o,s){return new oMr(s,o,i,n)}wrapSQLWithExplain(n){return`EXPLAIN COST ${n}`}};var Rin=class r extends Ojt{constructor(n,i){super(i);this.connection=n}connection;async runSQL(n){let{sql:i,options:o}=n;this.warnAboutLargeQuery(i);let s=await this.connection.execute({statement:i,...o});return sKc(s,i)}usingConnection=n=>new r(n,this.userContext);teardown(){return this.connection.teardown()}},N$p=async(r,t,n,i,o)=>{let s=await ZQr.New(r,t,o,n);i&&await s.test();let a=new Rin(s.getConnection(),r);return{connectionManager:s,platform:a}},D$p=async(r,t)=>{let n=await KKp(r,t);return new Rin(n,r)};var _Tm=B.object({database:B.string().optional()}),zCS=Mr("FabricSessionOptions",_Tm),ITm=B.object({TABLE_CATALOG:B.string(),TABLE_SCHEMA:B.string(),TABLE_NAME:B.string(),TABLE_TYPE:B.string()}),Oin=class extends fZ{validator=Mr("FabricInformationSchemaTablesType",ITm);query(t){return`SELECT * FROM ${zA([t.database],"fabric")}.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '${t.schema}'`}convert(t){let{TABLE_TYPE:n,TABLE_NAME:i}=t;return{kind:n,name:i,comment:"",extra:t}}},RTm=B.object({table_catalog:B.string(),table_schema:B.string(),table_name:B.string(),column_name:B.string(),ordinal_position:B.number(),column_default:B.string().nullable(),is_nullable:B.union([B.literal("YES"),B.literal("NO")]),data_type:B.string(),character_maximum_length:B.number().nullable()}),win=class extends hZ{validator=Mr("FabricInformationSchemaColumnsType",RTm);query(t){return`SELECT * FROM ${zA([t.database],"fabric")}.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${t.schema}'`}convert(t){throw new d1("Fabric is not implemented","FabricInformationSchemaColumnsImplementation - convert")}queryForObject(t,n){return`${this.query(t)} and table_name = "${n}"`}},OTm=B.object({name:B.string()}),Min=class extends gZ{validator=Mr("FabricShowSchemaRow",OTm);query(t){return`SELECT name FROM ${zA([t.database],"fabric")}.sys.schemas;`}convert(t){return{name:t.name,extra:{}}}};var wjt=class extends AZ{constructor(n){super("fabric");this.userContext=n}userContext;getObjectsImplementation=new Oin;getColumnsImplementation=new win;getSchemasImplementation=new Min;async getDatabaseNames(){return(await this.getRows(trl)).map(i=>i.name)}async getSchemaNames(n){let i=zA([n],"fabric");return(await this.getRows(`SELECT name FROM ${i}.sys.schemas;`)).map(s=>s.name)}async getVariantRows(n,i,o,s){throw new d1("Fabric is not implemented","getVariantRows")}async getObjectRows(n,i,o){let s=`SELECT TOP 100 * FROM ${this.getName(n,i)}`;return o&&(s=this.wrapSQLWithExplain(s)),this.getSQLQueryResult({sql:s})}mapDataTypePrecision(n){let i=n.DATA_TYPE,o="";switch(i){case"varchar":case"char":o=n.CHARACTER_MAXIMUM_LENGTH?.toString()||"8000";break;case"nvarchar":case"nchar":o=n.CHARACTER_MAXIMUM_LENGTH?.toString()||"4000";break;case"decimal":case"numeric":o=`${n.NUMERIC_PRECISION?.toString()||"38"},${n.NUMERIC_SCALE?.toString()||"0"}`;break;case"datetime2":case"datetimeoffset":case"time":o=n.DATETIME_PRECISION?.toString()||"7";break;default:return i.toUpperCase()}return`${i.toUpperCase()}(${o})`}createColumnMetadata(n,i){let o=this.mapDataTypePrecision(n);return{name:n.COLUMN_NAME,dataType:o,transform:"",nullable:n.IS_NULLABLE==="YES",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},description:"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async describeObject(n,i,o,s){let{database:a,schema:u}=Xq(i.locationName,n,"[FabricBasePlatform.describeObject()]"),c=`SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, DATETIME_PRECISION FROM ${zA([a],"fabric")}.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '${i.name}' AND TABLE_SCHEMA = '${u}'`;return(await this.runSQL({sql:c,overrideRequestID:mu()})).data.rows.map(d=>this.createColumnMetadata(d,s))}async testConnection(){try{await this.runSQL({sql:h5})}catch(n){throw LE(n)?new nt(`Could not validate connection to ${this.name}: ${n.message}`,n.detail):new nt(`Could not validate connection to ${this.name}`,yg(n).detail)}}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n.data.status??"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data.rows.length){let a=n.data.rows.map(p=>({values:Object.values(p)})),u=Object.keys(n.data.rows[0]??{}).map(p=>({name:p,type:""}));s.fields=u,s.rows=a}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}convertObjectRowsToMaterializationKinds(n){throw new d1("Fabric is not implemented","convertObjectRowsToMaterializationKinds")}createState(n,i,o,s){return new sMr(s,o,i,n)}wrapSQLWithExplain(n){return`SELECT TOP 0 * FROM (${n}) as CoalesceWrapped`}};var tSS=B.literal("oauth"),gFs=".datawarehouse.fabric.microsoft.com";var wTm=Je("RUNNER"),AFs=class extends nt{constructor(){super("No current user, cannot run SQL!")}},C1t=async(r,t,n)=>{if(t===null){if(!Xc.instance.currentUser)throw new AFs;t=Xc.resolveAuthToken}return MTm(r,typeof t=="function"?await t():t,n)},MTm=(r,t,n)=>{let i=r.userContext?.orgID,o=r.userContext.environmentID?+r.userContext.environmentID:void 0;return Ah(`Front-end/runSQL/API: ${r.templateString}`,{orgID:i,workspaceID:o},"RUNNER_BACKEND",async()=>{try{let s=await rJe("/scheduler/run",r,t,n,{retryTransientErrors:!1});if(s.data.error)throw new Error(s.data.error);return s.data}catch(s){throw wTm.error("got error on run sql with token",s),s}})};var mFs=Je("TESTING");async function B$p(r,t,n,i,o,s){let a=r.includes(gFs)?r:`${r}${gFs}`,u={clientID:i.clientID,clientSecret:i.clientSecret,connectionString:a,query:t,database:n??""};try{let p=process.env.JAVA_SERVICE_BASE_URL,c=process.env.JAVA_SERVICE_PORT;if(!p&&!Hg().isTest){let l=process.env.COALESCE_COA_CLOUD_TOKEN??null;return await C1t({userContext:{connectionString:u.connectionString,kind:"fabric",credentials:i,authenticator:"oauth",environmentID:s},templateString:t,requestId:mu(),options:{database:n}},l)}else{let l=`${p}:${c}/api/sql/v1/execute`;mFs.infoContext(o,"Fabric request sending query to JDBC");let d=await dc.post(l,u);return mFs.infoContext(o,"Fabric request response received from JDBC"),M2r(d.data,u.query)}}catch(p){let c=i3t(p);throw mFs.errorContext(o,"error querying the java service",c),c}}var Mjt=class extends Bne{name="fabric";userContext;constructor(t,n){super(void 0,n,mu(),0,null),this.userContext=t}async makePendingQuery(t){let{credentials:n,connectionString:i,environmentID:o}=this.userContext,s=async()=>{if(!o)throw new nt("Missing environmentID","makePendingQuery");if(!n)throw new nt("Failed to load secrets");if(!i)throw new nt("Connection string not found");return{rows:(await B$p(i,t.statement,t.database,n,this.logContext,o.toString())).data.rows}},a={Cancel:async()=>{},coalesceQueryID:mu(),sqlText:t.statement,promise:s(),attachThen:()=>{}};return this.runningQueries.set(a.coalesceQueryID,a),a}async teardown(){return Promise.resolve()}async resetConnection(){throw new d1("resetConnection() is not supported in FabricConnection.")}setQueryTag=async t=>{}},xin=async(r,t)=>new Mjt(r,t);var yFs=class extends Tre{async createConnection(){return await xin(this.userContext,this.logContext)}async updateFromResult(t){}async assertConnected(){}async setup(){this.newConnection()}newConnection(){return new Mjt(this.userContext,this.logContext)}},Pin=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new yFs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}test(){throw new d1("test() is not implemented in FabricConnectionManager.")}};var Nin=class r extends wjt{constructor(n,i){super(i);this.connection=n}connection;async runSQL(n){let{sql:i,options:o,overrideRequestID:s}=n;this.warnAboutLargeQuery(i);let a=await this.connection.execute({statement:i,database:o?.database??"",requestId:s});return M2r(a,i)}usingConnection=n=>new r(n,this.userContext);teardown(){return Promise.resolve()}},L$p=async(r,t,n,i)=>{let o=await Pin.New(r,t,i,n),s=new Nin(o.getConnection(),r);return{connectionManager:o,platform:s}},k$p=async(r,t)=>{let n=await xin(r,t);return new Nin(n,r)};var Din=class r extends pNt{constructor(n,i){super(i);this.connection=n}connection;async runSQL(n){let{sql:i,options:o,overrideRequestID:s}=n;this.warnAboutLargeQuery(i);let a=await this.connection.execute({sqlText:i,requestId:s||mu(),...o});return r.GetTemplateResultFromExecutionResult(i,a)}static GetTemplateResultFromExecutionResult(n,i){let o=i.stmt.getColumns().map(a=>({Name:a.getName(),DataType:a.getType()}));return{runDetails:{compiledSQL:n,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:i.queryID,warehouse:i.warehouse},data:{columns:o,rows:i.rows,status:i.status}}}usingConnection=n=>new r(n,this.userContext);teardown(){return this.connection.teardown()}},q$p=async(r,t,n,i,o)=>{let s=await Snn.New(r,t,o,n);i&&await s.test();let a=new Din(s.getConnection(),r);return{connectionManager:s,platform:a}},F$p=async(r,t,n)=>{let i=await UKp(r,t,n);return new Din(i,r)};var JW=(r,t,n)=>fL(r,{snowflake:i=>F$p(i,t,n),databricks:i=>D$p(i,t),fabric:i=>k$p(i,t),bigquery:i=>x$p(i,t)}),Mfe=(r,t,n,i,o)=>fL(r,{snowflake:s=>q$p(s,t,n,i,o),databricks:s=>N$p(s,t,n,i,o),fabric:s=>L$p(s,t,n,o),bigquery:s=>M$p(s,t,n,i,o)});var O9=async(r,t,n,i,o,s)=>{let a=r.org(t).workspace(i),[{accessUrl:u,connectionAccount:p},c]=await Promise.all([a.fetch(),mle(a.workspaceUser(n),s)]),l=p||"",d=u||null;return _We(c.connectionKind,c,{snowflake:async f=>{if(o.kind!=="snowflake")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for ${f.connectionKind??"snowflake"}`);let h={accountName:l,accessUrl:d,user:f.connectionDetails.user,role:f.connectionDetails.role,warehouse:f.connectionDetails.warehouse,environmentID:i,orgID:t,authenticator:f.connectionType,kind:"snowflake"};return bFs(h,o),h},databricks:async f=>{if(o.kind!=="databricks")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for ${f.connectionKind??"snowflake"}`);let h={...o,path:f.connectionDetails.path,host:l,environmentID:i};return bFs(h,o),h},fabric:async f=>{if(o.kind!=="fabric")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for fabric`);let A=await(await hI()).Get(WYo,{orgId:t,userId:n,workspaceId:i.toString()});if(!A)throw new nt("Fabric connection credentials not found","CreateUserContext");return{...o,connectionString:l,credentials:A.sensitiveValue,environmentID:i}},bigquery:async f=>{if(o.kind!=="bigquery")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for ${f.connectionKind??"bigquery"}`);let h=V5e(o.authenticator??f.connectionType),A=await Tnn(h,t,n,i,o.serviceAccountKey);return bFs(A,o),A}},"CreateUserContext")},bFs=(r,t)=>{for(let n in t)t[n]&&(r[n]=t[n])};var EFs=r=>({user:r.snowflakeUsername,role:r.snowflakeRole,warehouse:r.snowflakeWarehouse,authenticator:"Cloud",kind:"snowflake"}),z9e=r=>{let t=o=>({user:o.snowflakeUsername,password:o.snowflakePassword,role:o.snowflakeRole,warehouse:o.snowflakeWarehouse,authenticator:"Basic",kind:"snowflake"}),n=o=>{if(o.snowflakeKeyPairKey===void 0)throw new nt("No private key was provided, cannot perform key pair authentication with Snowflake");let s=o.snowflakeKeyPairPass?new zd(o.snowflakeKeyPairPass):void 0,a=w9e(new zd(o.snowflakeKeyPairKey),s);return{user:o.snowflakeUsername,keyPairKey:a.sensitiveValue,keyPairPass:o.snowflakeKeyPairPass,role:o.snowflakeRole,warehouse:o.snowflakeWarehouse,authenticator:"KeyPair",kind:"snowflake"}},i=o=>({warehouse:o.snowflakeWarehouse,authenticator:"OAuth",kind:"snowflake"});return Lme(r,{snowflake:o=>Dme(o,t,n,i,EFs),databricks:o=>o.databricksAuthType==="OAuthM2M"?{kind:"databricks",authenticator:o.databricksAuthType,clientID:o.clientID,secret:o.clientSecret}:o.databricksAuthType==="OAuthU2M"?{kind:"databricks",authenticator:o.databricksAuthType,accessToken:o.accessToken}:{kind:"databricks",authenticator:o.databricksAuthType,token:o.databricksAuthType==="Token"?o.token:void 0},fabric:o=>({kind:"fabric",authenticator:o.fabricAuthType,connectionString:o.connectionString}),bigquery:o=>{let s=o.bigQueryAuthType;return s==="ServiceAccount"?{kind:"bigquery",authenticator:s,serviceAccountKey:o.serviceAccountKey}:{kind:"bigquery",authenticator:s}}},"GetUserAuthContextInfoFromUserCredentials")};var Q9e=Je("PLAN"),Q$p=async(r,t,n,i,o,s,a)=>{let u="[getPlatformAndTest]",{measure:p,printSummary:c}=Bf(u,a),l,d=i.org(t).workspace(n).workspaceUser(r);try{let f=await p("GetUserConnectionInfo",()=>mle(d,a));await p("AdjustCreds",()=>M9e(t,r,n,o,f,s));let h=z9e(o),A=await p("CreateUserContext",()=>O9(i,t,r,n,h,a));try{l=await p("GetBackendPlatform",()=>JW(A,a,s)),await p("testConnection",()=>l.testConnection())}catch(E){if(A.kind==="none")throw new nt("User context is none","getPlatformAndTest");if(zKp(E,A.kind)){Q9e.errorContext(a,`Dead OAuth access token for platform ${A.kind} - Resetting oauth connection in getPlatformAndTest. Error: `,E);let v=await QKp(A,{rootRepository:i,teamInfo:{fbTeamID:t,fbUserID:r,fbEmail:"",fbFullName:"",fbFirstName:"",fbLastName:""}},a);A.kind==="databricks"&&v&&(A.accessToken=v),Q9e.infoContext(a,`Retrying ${A.kind} platform connection after oauth connection reset`),l=await JW(A,a,s),await l.testConnection()}else throw E}return l}catch(f){let{message:h,detail:A}=await xTm(f,d,a);throw new nt(h,A)}finally{c()}},xTm=async(r,t,n)=>{let i="[createPlan (endpoint)]";Q9e.errorContext(n,i,"Error authenticating user",r);let o;try{({connectionKind:o}=await t.fetch())}catch(u){Q9e.errorContext(n,i,"Couldn't fetch workspace user",u)}let{error:{errorString:s,errorDetail:a}}=ua(r);return{message:`${o?TD(o)+" u":"U"}ser authentication unsuccessful: ${s}`,detail:a}},j$p=async(r,t,n,i,o,s,a,u,p,c)=>{let l="[performPlanCreation]",{measure:d,printSummary:f}=Bf(l,c);try{let h,{useRenderCache:A}=r;A&&(h=await d("acquiring renderer cache",()=>Inn(i.toString(),c)));let E=await d("plan calculation (total)",()=>mJo({...r,skipAwaitPlanContext:!0},t,h,n,i,o,s,a,u,p,c)),v=await d("stringify & compress plan",async()=>{let T=await(0,U$p.stringify)({body:E});return(0,z$p.deflate)(T,{to:"string"})});Q9e.appContext(c,l,`Processing for plan ${n} completed. Size was ${n$(v.length)}mb. Storing compressed data`),await d("store completed plan",()=>Pal(p,o,i,n,v,c)),Q9e.appContext(c,l,`Storage for plan ${n} completed`)}catch(h){Q9e.errorContext(c,l,"Plan creation failed",h),await Nal(p,o,i,n,{status:"failed",error:h instanceof nt?h.toTRunError():ua(h)},c)}finally{f()}};var nXp=require("node:os");var Une=class extends nt{constructor(n,i){super(n,i?`Request ID: ${i}`:void 0);this.requestId=i}requestId};var xC=Je("RENDERER"),G$p=r=>{let t=r;return t.state="in use",t},PTm=r=>{let t=r;return t.state="unused",t},H$p=r=>{let t=r;return t.state="terminated",t},NTm=r=>{let t=r;return t.state="error",t},CFs=class extends nt{constructor(n=null){let i="Cannot render on shutdown pool!"+(n===null?"":`, requestID=${n}`);super(i);this.requestID=n}requestID},Lin=class extends nt{constructor(n=null){let i="Exiting terminated pool"+(n===null?"":`, requestID=${n}`);super(i);this.requestID=n}requestID},kin=class{constructor(t,n){this.size=t;this.renderFactory=n;if(this.initializeNewRenderer(),!this.renderers[0])throw new Une("A render pool must have a size greater than 0")}size;renderFactory;renderers=[];queued=[];terminated=!1;stopped=!1;initFailureTracker=new Map;renderFailureTracker=new Map;allSlotsTerminal=()=>this.renderers.every(t=>t.state==="error"||t.state==="terminated");getInitFailureCount=t=>this.initFailureTracker.get(t.id)||0;getRenderFailureCount=t=>this.renderFailureTracker.get(t.id)||0;IsAcceptingRequests=()=>!(this.terminated||this.stopped);IsInitialized=()=>Promise.any(this.renderers.map(t=>t.renderer.IsInitialized())).catch(()=>this.renderers[0].renderer.IsInitialized());handleNextQueued=async t=>{let n=this.queued.pop();if(n===void 0){xC.debug("render pool queue empty, freeing slot"),PTm(t);return}xC.debug("Rendering request",n.request.id),await this.renderWithRetries(t,n)};handleError=(t,n)=>{if(this.terminated){H$p(t);return}xC.error("Got a critical renderer error, terminating and creating a new renderer:",n),t.renderer.terminate(.1).catch(()=>{}),t.renderer=this.renderFactory()};awaitInitializationWithRetries=async t=>{if(t.id>0){let i=this.renderers[t.id-1];if(i)try{await i.renderer.IsInitialized()}catch{}}let n=3;do try{await t.renderer.IsInitialized();break}catch(i){if(this.terminated)return;this.initFailureTracker.set(t.id,this.getInitFailureCount(t)+1),this.handleError(t,i)}while(this.getInitFailureCount(t)<n-1);try{await t.renderer.IsInitialized()}catch(i){if(this.terminated)return;if(NTm(t),xC.error("Fatal error: Renderer never initialized:",i),this.allSlotsTerminal()&&!this.terminated)try{await this.terminate()}catch(o){xC.alert("During termination due to fatal renderer error, got an error!",o)}return}xC.debug("Initialized a renderer at slot",t.id),this.handleNextQueued(G$p(t)).catch(i=>{xC.debug("Got an error in queue after awaiting initialization with retries",i)})};initializeNewRenderer=()=>{if(this.renderers.length<this.size){let t=this.renderFactory(),n=this.renderers.length,i={id:n,state:"initializing",renderer:t};this.renderers.push(i),xC.debug("Initializing a renderer at slot",n),this.awaitInitializationWithRetries(i).catch(o=>{xC.alert("Got an unexpected uncaught error in initializing new renderer",o)})}else xC.debug("All renderer slots populated, size:",this.size,"and renderers:",this.renderers.length)};availableRenderer=()=>{for(let t of this.renderers)if(t.state==="unused"){let n=G$p(t);return this.initializeNewRenderer(),n}return this.initializeNewRenderer(),null};renderOnSlot=(t,n)=>t.renderer.render(n).then(o=>(xC.debug("Render promise for request",n.id,"completed on slot",t.id),this.renderFailureTracker.set(t.id,0),this.handleNextQueued(t).catch(s=>{xC.debug("Got an error in queue in renderOnSlot",s)}),o),o=>{throw this.renderFailureTracker.set(t.id,this.getRenderFailureCount(t)+1),this.handleError(t,o),o});stop=async()=>{if(this.stopped=!0,xC.info("Shutting down renderer pool, queue has",this.queued.length,"items in it"),await UP(this.queued.map(t=>t.promise)),xC.info("Terminating renderer threads"),await UP(this.renderers.map(t=>t.renderer.terminate())).catch(t=>xC.error("Renderer terminate() failed",t)),this.queued.length>0){let n="Request IDs:",i=this.queued.map(o=>o.request.id);this.queued.length>10&&(n="First 10 "+n,i=i.slice(0,10)),xC.alert("Unexpectedly, after stop() completed there were still queue entries in the renderer pool!",n,i)}else xC.info("Renderer pool shut down")};async terminate(t=5){this.terminated=!0;let n=this.renderers.filter(a=>a.state!=="terminated").map(a=>(H$p(a),a.renderer.terminate(t))),i=this.queued;this.queued=[],i.forEach(a=>{xC.info("Rejecting queued request",a.request.id),a.reject(new Lin(a.request.id))});let s=(await JR(t*1e3,"Terminate timed out",Promise.allSettled(n))).map(a=>a.status==="rejected"?a.reason:null).filter(a=>a!==null);s.length>0&&xC.alert("Got",s.length,"errors when terminating",n.length,"renderers. First failure:",s[0])}renderWithRetries=async(t,n)=>{let{resolve:i,promise:o,reject:s,request:a}=n,u=3,p=null,c=null,l=async()=>{try{do try{c=await this.renderOnSlot(t,a),this.renderFailureTracker.set(t.id,0),i(c);return}catch(d){p=d}while(p&&this.getRenderFailureCount(t)<u);typeof p=="object"&&p instanceof Error&&(p.stack=`${n.stack}
|
|
10530
|
+
t.table_type`}convert(t){let n=t.table_type==="BASE TABLE"?"TABLE":t.table_type.toUpperCase(),{table_name:i,table_type:o,comment:s,...a}=t,u=s&&s.length>=2&&s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1):s??"";return{kind:n,name:i,comment:u,extra:{...a,table_type:o}}}},rvm=B.object({name:B.string()}),Xnn=class extends gZ{validator=Mr("BigQueryShowSchemaRow",rvm);query(t){return`SELECT '${t.schema}' AS name`}convert(t){return{name:t.name,extra:{}}}};var qJp=(r,t)=>{let n=r;for(let i of t){let o=r[i.Name],s=kJp.includes(i.DataType);o&&s&&typeof o=="object"&&"value"in o&&(n[i.Name]=o.value)}return n};var fjt=class extends AZ{constructor(n){super("bigquery");this.userContext=n}userContext;getObjectsImplementation=new $nn;getColumnsImplementation=new Jnn;getSchemasImplementation=new Xnn;isVariantType(n){return n.toUpperCase()==="JSON"}validateUserContext(){let n="In your environment settings, verify that you have";if(!this.userContext)throw new Vi(`BigQuery user authentication unsuccessful: Missing ${this.name} connection information! ${n} selected and authenticated a connection type.`);if(this.userContext.kind!=="bigquery")throw new Vi(`BigQuery user authentication unsuccessful: ASSERTION FAILED: Expected ${this.name} user context but received kind ${this.userContext.kind}`)}async testConnection(){try{this.validateUserContext(),await this.runSQL({sql:h5})}catch(n){throw n instanceof Error?new nt(`Could not validate connection to ${this.name}: ${n.message}`):new nt(`Could not validate connection to ${this.name}`,aa(n).error.errorDetail)}}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n?.data?.status||"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data){let a=n.data.columns.map(c=>c.Name),u=n.data.rows.map(c=>{let l=qJp(c,n.data.columns);return{values:YYe(a,l)}}),p=n.data.columns.map(c=>({name:c.Name,type:c.DataType??""}));s.fields=p,s.rows=u}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}getBigQueryApiClient(){let n=this.userContext.environmentID;if(!n)throw new Vi("Missing environmentID in BigQuery user context");let i=Xc.isInitialized?Xc.resolveAuthToken:void 0;return{client:D3(void 0,i),workspaceID:n.toString()}}async getDatabaseNames(){let{client:n,workspaceID:i}=this.getBigQueryApiClient();return(await n.GetBigQueryProjects({params:{workspaceID:i}})).projects.map(s=>s.id)}async getSchemaNames(n){let{client:i,workspaceID:o}=this.getBigQueryApiClient();return await i.GetBigQueryDatasets({params:{workspaceID:o,projectID:n}})}async getObjectRows(n,i,o){let a=`SELECT * FROM ${IIt(n,i,"bigquery")} LIMIT 100`;return this.getSQLQueryResult({sql:a,options:{dryRun:o}})}async describeObject(n,i,o,s){let a=Xq(i.locationName,n,"[BigQueryBasePlatform.describeObject()]"),u=this.getColumnsImplementation.queryForObject(a,i.name);return(await this.runSQL({sql:u,overrideRequestID:mu()})).data.rows.map(c=>this.createColumnMetadata(c,s))}createColumnMetadata(n,i){return{name:n.column_name,dataType:n.data_type.toUpperCase(),transform:"",nullable:n.is_nullable==="YES",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},description:n.comment||"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async getVariantRows(n,i,o,s){let a=IIt(s,o,"bigquery"),u=`SELECT \`${n}\` FROM ${a} LIMIT ${i}`;return this.getSQLQueryResult({sql:u})}convertObjectRowsToMaterializationKinds(n){let i="convertObjectRowsToMaterializationKinds:",o=[],s=[];for(let a of n)a.kind==="TABLE"?o.push(a.name):a.kind==="VIEW"?s.push(a.name):Je("PLATFORM").errorContext({workspaceID:this.userContext.environmentID?+this.userContext.environmentID:void 0},i,`table ${a.name} is of unexpected table type ${a.kind} - skipping it`);return{tables:o,views:s}}createState(n,i,o,s){return new iMr(s,o,i,n)}wrapSQLWithExplain(n){return n}wrapSQLWithTest=n=>`SELECT 1 FROM UNNEST([1]) WHERE EXISTS (${n})`};var b$p=yt(lin());var Ein=r=>{let{authenticator:t,serviceAccountKey:n,clientID:i,secret:o,refreshToken:s,credentialsFile:a}=r,u={};switch(t){case"ServiceAccount":{if(!n)throw new Vi("BigQuery ServiceAccount credentials are required.");try{let p=typeof n=="string"?JSON.parse(n):n;u.credentials=p}catch(p){throw new nt("Invalid BigQuery serviceAccountKey provided (failed to parse JSON)",p instanceof Error?p.message:String(p))}u.credentials?.project_id&&(u.projectId=u.credentials.project_id);break}case"OAuth":{if(!i||!o)throw Je("CONNECTION").error("Missing clientID or secret. Cannot create BigQuery client"),new Du("Missing OAuth app credentials");if(!s)throw Je("CONNECTION").error("Missing refresh token. Cannot create BigQuery client"),new Du("Missing OAuth refresh token");u.credentials={type:"authorized_user",client_id:i,client_secret:o,refresh_token:s};break}case"ApplicationDefault":{a&&(u.keyFilename=a);break}default:throw new Vi(`Unsupported BigQuery authenticator: ${JSON.stringify(t)}`)}return Je("CONNECTION").info("Creating BigQuery client"),new b$p.BigQuery(u)};var Cin=async r=>Ein(r),E$p=r=>({client:r});var E1t=class extends nt{constructor(n,i){let{errorString:o,errorDetail:s}=aa(i).error;super(o,s);this.query=n;this.coalesceCause=i}query;coalesceCause;isCancel(){return!1}};var Wz=Je("CONNECTION"),C$p="number of rows inserted",S$p="number of rows updated",v$p="number of rows deleted",Ijt=class extends a3e{constructor(n,i,o,s,a,u=5){let p={...s,bigqueryRequestID:o.requestId};super(i,o,p,a,u);this.completion=n}completion;job;get sqlText(){return this.queryParams.statement}shouldResetConnection=n=>!!aa(n).error.errorString.match(/(network ?error|econnreset)/i);handleRetry=async(n,i)=>{if(this.shouldResetConnection(n))try{this.handle=await this.resetFunc()}catch(o){throw Wz.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",o),n.coalesceCause}return i};computeChunkAndNextQuery(n){let i=[],o;if(Array.isArray(n)){let s=n[0];Array.isArray(s)&&(i=s);let a=n.length>1?n[1]:void 0;if(a&&typeof a=="object"){let u=a.pageToken;u?o={pageToken:u,...this.queryParams.location?{location:this.queryParams.location}:{}}:o=void 0}else o=void 0}return{chunk:i,nextPageQuery:o}}async queryWithRetries(){let n=`[TrackedPendingBigQueryQuery.queryWithRetries() - '${this.queryParams.statement}']`;try{let i=async()=>{gI("bigquery.runQuery.attempt",this.logContext);let l={rows:[],status:"Success",columns:[]};try{let d={query:this.queryParams.statement,params:this.queryParams.params,location:this.queryParams.location,labels:this.queryParams.labels,dryRun:this.queryParams.dryRun};Wz.infoContext(this.logContext,"BigQuery createQueryJob starting",this.coalesceQueryID,this.queryParams.dryRun?"(dry run)":"");let[f]=await this.handle.client.createQueryJob(d);if(Wz.infoContext(this.logContext,"BigQuery createQueryJob finished",this.coalesceQueryID,this.queryParams.dryRun?"(dry run)":""),this.job=f,this.queryParams.dryRun)return this.getDryRunStats(f,l);let h=0,A;do{let{next:E,done:v,inMemorySize:T}=await this.processQueryPage(f,A,l,n,h);if(h=T,A=E,v)break}while(A);await this.getDMLStats(f,l),gI("bigquery.runQuery.finished",this.logContext)}catch(d){throw gI("bigquery.runQuery.error",{...this.logContext,errorString:aa(d).error.errorString}),d}return l},o=(l,d)=>{if(!(typeof l=="object"&&l instanceof E1t))return Wz.errorContext(this.logContext,"Not retrying BigQuery request",this.coalesceQueryID,"attempt=",d,"error=",l,"was unrecognized and not retryable"),l;if(l.isCancel())return Wz.infoContext(this.logContext,"Not retrying BigQuery request; it was canceled",this.coalesceQueryID),l},s=l=>{let d=l instanceof Error&&"cause"in l?l.cause:l;return["CQID=",this.coalesceQueryID,"error=",d]},a={name:"backoff",base:5},u={name:"nowait"},p=async l=>{typeof l=="object"&&l instanceof E1t&&await this.handleRetry(l,this.queryParams)},c=(l,d)=>JSON.stringify(aa(l,!0).error).match(/network ?error/i)?a:d||u;return await cf(i,this.maxAttempts,Wz,this.logContext,{beforeRetry:p,alterRetryStrategy:c,checkError:o,retryStrategy:u,retryLogLevel:"info",logOnRetry:"Retrying BigQuery request",customErrorOnRetry:s,logOnFailure:"Out of retries for BigQuery request",customErrorOnFailure:s})}catch(i){throw new E1t(this.queryParams,i)}finally{this.completion(this.coalesceQueryID)}}getDryRunStats(n,i){let s=n.metadata?.statistics;if(s?.query){let a="";Object.entries(s.query).forEach(([u,p])=>{p!=null&&typeof p!="object"&&(a+=`${u}: ${p} `)}),i.rows=[{content:a}],i.columns=[{name:"Dry Run Results",type:"STRING"}]}return Wz.infoContext(this.logContext,"BigQuery dry run validation successful",this.coalesceQueryID),gI("bigquery.runQuery.dryRun.finished",this.logContext),i}async getDMLStats(n,i){try{let a=(await n.getMetadata())[0]?.statistics?.query?.dmlStats;if(a&&i.rows.length===0){let u={},p=[],c=a.insertedRowCount?Number(a.insertedRowCount):0,l=a.updatedRowCount?Number(a.updatedRowCount):0,d=a.deletedRowCount?Number(a.deletedRowCount):0;c>0&&(u[C$p]=c,p.push({name:C$p,type:"INTEGER"})),l>0&&(u[S$p]=l,p.push({name:S$p,type:"INTEGER"})),d>0&&(u[v$p]=d,p.push({name:v$p,type:"INTEGER"})),p.length>0&&(i.rows=[u],i.columns=p)}}catch(o){Wz.warnContext(this.logContext,"Failed to synthesize BigQuery DML row counts from job statistics",this.coalesceQueryID,o)}}extractBigQueryAPIResponse(n){if(Array.isArray(n)&&n.length>=3)return n[2]?.schema?.fields;Wz.warnContext(this.logContext,"BigQuery response not in expected tuple format [rows, apiResponse, schema]")}async processQueryPage(n,i,o,s,a){Wz.infoContext(this.logContext,"BigQuery getQueryResults starting",this.coalesceQueryID);let u=await n.getQueryResults(i);Wz.infoContext(this.logContext,"BigQuery getQueryResults finished",this.coalesceQueryID);let p=this.extractBigQueryAPIResponse(u);p&&o.columns.length===0&&(o.columns=p);let{chunk:c,nextPageQuery:l}=this.computeChunkAndNextQuery(u);return a+=lWe(c,!0),a>s3e()?(o.status=dL,Wz.errorContext(this.logContext,s,`Chunk limit reached; returning partial rows (${o.rows.length})`),{next:void 0,done:!0,inMemorySize:a}):(o.rows.push(...c),{next:l??void 0,done:!1,inMemorySize:a})}async tryCancel(){if(this.job)try{await this.job.cancel();return}catch(n){throw new nt("Error canceling BigQuery job",JSON.stringify(aa(n).error))}throw new nt("No running BigQuery job to cancel")}};var dFs=Je("CONNECTION"),yTm=async(r,t,n,i,o)=>{let s=u=>{},a=new Ijt(s,{client:r},t,n,i,o);return a.Start(),a.promise},Rjt=class extends Bne{name="bigquery";async teardown(){return Promise.resolve()}untrackedQuery=async t=>yTm(this.handle.client,{statement:t},this.logContext,this.resetConnection,3);setQueryTag=async t=>Promise.resolve();async makePendingQuery(t){if(this.wasCanceled)throw new BA;let n=o=>this.runningQueries.delete(o);dFs.infoContext(this.logContext,"BigQuery makePendingQuery",t.statement);let i=new Ijt(n,this.handle,t,this.logContext,this.resetConnection);if(this.runningQueries.set(i.coalesceQueryID,i),dFs.debugContext(this.logContext,`Tracking ${this.name} query with CQID=`,i.coalesceQueryID,"query=",i.sqlText),i.Start(),this.wasCanceled)throw dFs.infoContext(this.logContext,"Canceling just-started query due to connection cancellation",i.coalesceQueryID,"conn",this.connectionID),await i.Cancel(),new BA("canceling new query on canceled connection");return i}getConnectionLogContext(){return this.logContext}getClient(){return this.handle.client}},T$p=async(r,t)=>{let n=async()=>({client:await Cin(r)}),i=await n();return new Rjt(i,t,mu(),0,null,n)};var _$p=Je("CONNECTION"),fFs=class extends Tre{name="bigquery";async createConnection(){let t=await Cin(this.userContext);return E$p(t)}async updateFromResult(t){return Promise.resolve()}async setup(){return Promise.resolve()}newConnection(){return new Rjt(this.handle,this.logContext,this.connectionID,this.useCount,this)}},Sin=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new fFs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}async test(){let t="BigQueryConnectionManager.test:",n=Nb(this.userContext,"authenticator","kind");_$p.appContext(this.logContext,t,"testing connection",n),await this.withConnection(async i=>i.execute({statement:h5})),_$p.appContext(this.logContext,t,"connection successfully established",n)}};var I$p="https://bigquery.googleapis.com/bigquery/v2",R$p=async r=>{let t=[],n;do{let i={maxResults:"1000"};n&&(i.pageToken=n);let{data:o}=await dc.get(`${I$p}/projects`,{headers:{Authorization:`Bearer ${r}`},params:i});o.projects&&t.push(...o.projects),n=o.nextPageToken}while(n);return{projects:t}},O$p=r=>{let t=[];for(let n of r.projects??[]){let i=n.projectReference.projectId;t.push({id:i,name:n.friendlyName})}return t},w$p=async(r,t)=>{let n=[],i;do{let o={maxResults:"1000"};i&&(o.pageToken=i);let{data:s}=await dc.get(`${I$p}/projects/${encodeURIComponent(t)}/datasets`,{headers:{Authorization:`Bearer ${r}`},params:o});s?.datasets&&n.push(...s.datasets.map(a=>a.datasetReference.datasetId)),i=s?.nextPageToken}while(i);return n};var hFs=Je("PLATFORM"),vin=class r extends fjt{constructor(n,i){super(i);this.connection=n}connection;usingConnection(n){return new r(n,this.userContext)}async teardown(){return this.connection.teardown()}async runSQL(n){let{sql:i,options:o={}}=n;this.warnAboutLargeQuery(i),hFs.info("BigQueryBackendPlatform.runSQL starting",o.dryRun?"(dry run)":"",i);try{let s=await this.connection.execute({statement:i,...o});return hFs.info("BigQueryBackendPlatform.runSQL finished",o.dryRun?"(dry run)":"","rows=",Array.isArray(s.rows)?s.rows.length:0),aKc(s,i)}catch(s){throw hFs.error("BigQueryBackendPlatform.runSQL error",s),s}}async getDatabaseNames(){let n=await this.getAccessToken();return O$p(await R$p(n)).map(o=>o.id)}async getSchemaNames(n){return w$p(await this.getAccessToken(),n)}async getAccessToken(){let i=await Ein(this.userContext).authClient.getAccessToken();if(!i)throw new Error("Failed to obtain BigQuery access token");return i}},M$p=async(r,t,n,i,o)=>{let s=await Sin.New(r,t,o,n);i&&await s.test();let a=new vin(s.getConnection(),r);return{connectionManager:s,platform:a}},x$p=async(r,t)=>{let n=await T$p(r,t);return new vin(n,r)};var bTm=B.object({table_catalog:B.string(),table_schema:B.string(),table_name:B.string(),table_type:B.string(),is_insertable_into:B.string(),commit_action:B.string(),table_owner:B.string(),comment:B.string().nullable(),created:B.union([B.string(),B.date()]),created_by:B.string(),last_altered:B.union([B.string(),B.date()]),last_altered_by:B.string(),data_source_format:B.string(),storage_sub_directory:B.string().nullable()}),Tin=class extends fZ{validator=Mr("DatabricksInformationSchemaTablesType",bTm);query(t){return`SELECT * FROM ${zA([t.database],"databricks")}.information_schema.tables where table_schema = '${t.schema.toLowerCase()}' `}convert(t){let n=t.table_type;(t.table_type==="MANAGED"||t.table_type==="MANAGED_SHALLOW_CLONE"||t.table_type==="BASE TABLE")&&(n="TABLE");let{table_name:i,comment:o,...s}=t;return{kind:n,name:i,extra:s,comment:o??""}}},ETm=B.object({table_catalog:B.string(),table_schema:B.string(),table_name:B.string(),column_name:B.string(),ordinal_position:B.number(),column_default:B.string().nullable(),is_nullable:B.union([B.literal("YES"),B.literal("NO")]),full_data_type:B.string(),data_type:B.string(),character_maximum_length:B.number().nullable(),comment:B.string().nullable()}),CTm=ETm.pick({column_name:!0,comment:!0,data_type:!0,is_nullable:!0,table_name:!0}),_in=class extends hZ{validator=Mr("DatabricksInformationSchemaColumnsType",CTm);get columnsString(){return"table_name, column_name, is_nullable, comment, data_type"}query(t){let n=zA([t.database],"databricks");return`select ${this.columnsString} from ${n}.information_schema.columns where table_schema = "${t.schema.toLowerCase()}"`}convert(t){let{table_name:n,column_name:i,comment:o,...s}=t;return{objectName:n,name:i,comment:o??"",extra:s}}queryForObject(t,n){return`${this.query(t)} and table_name = "${n.toLowerCase()}"`}async runQuery(t,n,i){let o=new lNt(t,["table_name","column_name"],n,{...i,platform:"databricks"});return await o.run(),o.checkForDuplicates(["table_name","column_name"]),o.aggregateRows.map(s=>this.validateAndConvert(s))}},STm=B.object({databaseName:B.string()}),Iin=class extends gZ{validator=Mr("DatabricksShowSchemaRow",STm);query(t){return`SHOW SCHEMAS IN ${zA([t.database],"databricks")}`}convert(t){return{name:t.databaseName,extra:{}}}},mCS=B.object({id:B.string(),name:B.string(),odbc_params:B.object({path:B.string()})});var vTm=Je("PLATFORM"),P$p=6e4,TTm=`Connection test timed out after ${P$p/1e3} seconds. Please verify that your SQL warehouse is running and accessible in Databricks.`,Ojt=class extends AZ{constructor(n){super("databricks");this.userContext=n}userContext;getObjectsImplementation=new Tin;getColumnsImplementation=new _in;getSchemasImplementation=new Iin;async getDatabaseNames(){return(await this.getRows("SHOW CATALOGS")).map(i=>i.catalog)}async getSchemaNames(n){let i=zA([n],"databricks");return(await this.getRows(`SHOW SCHEMAS IN ${i}`)).map(s=>s.databaseName)}async getVariantRows(n,i,o,s){let a=this.getName(s,o),u=`SELECT ${n} FROM ${a} TABLESAMPLE (${i} ROWS)`;return this.getSQLQueryResult({sql:u})}async getObjectRows(n,i,o){let s=`SELECT * FROM ${this.getName(n,i)} LIMIT 100`;return o&&(s=this.wrapSQLWithExplain(s)),this.getSQLQueryResult({sql:s})}createColumnMetadata(n,i){return{name:n.name,dataType:n.extra.data_type,transform:"",nullable:n.extra.is_nullable==="YES",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},description:n.comment||"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async describeObject(n,i,o,s){let a=Xq(i.locationName,n,"[DatabricksBasePlatform.describeObject()]"),u=this.getColumnsImplementation.queryForObject(a,i.name);return(await this.runSQL({sql:u,overrideRequestID:mu()})).data.rows.map(c=>this.createColumnMetadata(this.getColumnsImplementation.validateAndConvert(c),s))}validateUserContext(){let n="In your environment settings, verify that you have",i=[];if(!this.userContext)throw new Vi(`Databricks user authentication unsuccessful: Missing ${this.name} connection information! ${n} selected and authenticated a connection type.`);if(this.userContext.kind!=="databricks")throw new Vi(`Databricks user authentication unsuccessful: ASSERTION FAILED: Expected databricks user context but received kind ${this.userContext.kind}`);switch(this.userContext.authenticator){case"Token":this.userContext.host?.trim()||i.push(`Missing ${this.name} host information! ${n} added a host.`),this.userContext.path?.trim()||i.push(`Missing ${this.name} path information! ${n} added a path.`),this.userContext.token?.trim()||i.push(`Missing ${this.name} token! ${n} added a token.`);break;case"OAuthM2M":case"OAuthU2M":case"Cloud":this.userContext.host?.trim()||i.push(`Missing ${this.name} host information! ${n} added a host.`),this.userContext.path?.trim()||i.push(`Missing ${this.name} path information! ${n} added a path.`);break;default:throw new Vi(`Databricks user authentication unsuccessful: Unknown authenticator type: ${this.userContext.authenticator}`)}if(i.length>0)throw new Vi(`Databricks user authentication unsuccessful: ${i.join("; ")}`)}async testConnection(){let n=new AbortController,i,o=new Promise((s,a)=>{i=setTimeout(()=>{n.abort(),a(new nt(TTm))},P$p)});try{this.validateUserContext(),await Promise.race([this.runSQL({sql:h5,httpConfig:{signal:n.signal}}),o])}catch(s){if(s instanceof Vi)throw s;let a;throw s instanceof Error?a=new nt(`Could not validate connection to ${this.name}: ${s.message}`):a=new nt(`Could not validate connection to ${this.name}`,aa(s).error.errorDetail),a}finally{clearTimeout(i)}}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n?.data?.status||"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data){let a=n.data.columns.map(c=>c.Name),u=n.data.rows.map(c=>({values:YYe(a,c)})),p=n.data.columns.map(c=>({name:c.Name,type:c.DataType}));s.fields=p,s.rows=u}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}convertObjectRowsToMaterializationKinds(n){let i="convertObjectRowsToMaterializationKinds:",o=[],s=[];for(let a of n){let u=a.name.toLowerCase();a.kind==="TABLE"?o.push(u):a.kind==="VIEW"?s.push(u):vTm.errorContext({workspaceID:this.userContext.environmentID?+this.userContext.environmentID:void 0},i,`table ${u} is of unexpected table type ${a.kind} - skipping it`)}return{tables:o,views:s}}createState(n,i,o,s){return new oMr(s,o,i,n)}wrapSQLWithExplain(n){return`EXPLAIN COST ${n}`}};var Rin=class r extends Ojt{constructor(n,i){super(i);this.connection=n}connection;async runSQL(n){let{sql:i,options:o}=n;this.warnAboutLargeQuery(i);let s=await this.connection.execute({statement:i,...o});return sKc(s,i)}usingConnection=n=>new r(n,this.userContext);teardown(){return this.connection.teardown()}},N$p=async(r,t,n,i,o)=>{let s=await ZQr.New(r,t,o,n);i&&await s.test();let a=new Rin(s.getConnection(),r);return{connectionManager:s,platform:a}},D$p=async(r,t)=>{let n=await KKp(r,t);return new Rin(n,r)};var _Tm=B.object({database:B.string().optional()}),zCS=Mr("FabricSessionOptions",_Tm),ITm=B.object({TABLE_CATALOG:B.string(),TABLE_SCHEMA:B.string(),TABLE_NAME:B.string(),TABLE_TYPE:B.string()}),Oin=class extends fZ{validator=Mr("FabricInformationSchemaTablesType",ITm);query(t){return`SELECT * FROM ${zA([t.database],"fabric")}.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '${t.schema}'`}convert(t){let{TABLE_TYPE:n,TABLE_NAME:i}=t;return{kind:n,name:i,comment:"",extra:t}}},RTm=B.object({table_catalog:B.string(),table_schema:B.string(),table_name:B.string(),column_name:B.string(),ordinal_position:B.number(),column_default:B.string().nullable(),is_nullable:B.union([B.literal("YES"),B.literal("NO")]),data_type:B.string(),character_maximum_length:B.number().nullable()}),win=class extends hZ{validator=Mr("FabricInformationSchemaColumnsType",RTm);query(t){return`SELECT * FROM ${zA([t.database],"fabric")}.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${t.schema}'`}convert(t){throw new d1("Fabric is not implemented","FabricInformationSchemaColumnsImplementation - convert")}queryForObject(t,n){return`${this.query(t)} and table_name = "${n}"`}},OTm=B.object({name:B.string()}),Min=class extends gZ{validator=Mr("FabricShowSchemaRow",OTm);query(t){return`SELECT name FROM ${zA([t.database],"fabric")}.sys.schemas;`}convert(t){return{name:t.name,extra:{}}}};var wjt=class extends AZ{constructor(n){super("fabric");this.userContext=n}userContext;getObjectsImplementation=new Oin;getColumnsImplementation=new win;getSchemasImplementation=new Min;async getDatabaseNames(){return(await this.getRows(trl)).map(i=>i.name)}async getSchemaNames(n){let i=zA([n],"fabric");return(await this.getRows(`SELECT name FROM ${i}.sys.schemas;`)).map(s=>s.name)}async getVariantRows(n,i,o,s){throw new d1("Fabric is not implemented","getVariantRows")}async getObjectRows(n,i,o){let s=`SELECT TOP 100 * FROM ${this.getName(n,i)}`;return o&&(s=this.wrapSQLWithExplain(s)),this.getSQLQueryResult({sql:s})}mapDataTypePrecision(n){let i=n.DATA_TYPE,o="";switch(i){case"varchar":case"char":o=n.CHARACTER_MAXIMUM_LENGTH?.toString()||"8000";break;case"nvarchar":case"nchar":o=n.CHARACTER_MAXIMUM_LENGTH?.toString()||"4000";break;case"decimal":case"numeric":o=`${n.NUMERIC_PRECISION?.toString()||"38"},${n.NUMERIC_SCALE?.toString()||"0"}`;break;case"datetime2":case"datetimeoffset":case"time":o=n.DATETIME_PRECISION?.toString()||"7";break;default:return i.toUpperCase()}return`${i.toUpperCase()}(${o})`}createColumnMetadata(n,i){let o=this.mapDataTypePrecision(n);return{name:n.COLUMN_NAME,dataType:o,transform:"",nullable:n.IS_NULLABLE==="YES",defaultValue:"",columnReference:{columnCounter:mu(),stepCounter:i},description:"",appliedColumnTests:{},acceptedValues:{strictMatch:!0,values:[]},config:{},sourceColumnReferences:[{transform:"",columnReferences:[]}]}}async describeObject(n,i,o,s){let{database:a,schema:u}=Xq(i.locationName,n,"[FabricBasePlatform.describeObject()]"),c=`SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, DATETIME_PRECISION FROM ${zA([a],"fabric")}.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '${i.name}' AND TABLE_SCHEMA = '${u}'`;return(await this.runSQL({sql:c,overrideRequestID:mu()})).data.rows.map(d=>this.createColumnMetadata(d,s))}async testConnection(){try{await this.runSQL({sql:h5})}catch(n){throw LE(n)?new nt(`Could not validate connection to ${this.name}: ${n.message}`,n.detail):new nt(`Could not validate connection to ${this.name}`,yg(n).detail)}}getQueryResultFromTemplateRunResult(n,i){let o=n.runDetails.compiledSQL,s={error:null,fields:[],rows:[],success:!0,sql:o,exportedRefs:[],invalidExportedRefs:[],startTime:i,endTime:new Date,isRunning:!1,name:"",status:n.data.status??"Success",type:"sql",queryID:n.runDetails.queryID,warehouse:n.runDetails.warehouse};if(n.data.rows.length){let a=n.data.rows.map(p=>({values:Object.values(p)})),u=Object.keys(n.data.rows[0]??{}).map(p=>({name:p,type:""}));s.fields=u,s.rows=a}if(n?.runDetails?.exported_refs.length){let a=n.runDetails.exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.exportedRefs=BM(a)}if(n?.runDetails?.invalid_exported_refs.length){let a=n.runDetails.invalid_exported_refs.map(u=>({locationName:u.location_name,nodeName:u.node_name}));s.invalidExportedRefs=BM(a)}return s}convertObjectRowsToMaterializationKinds(n){throw new d1("Fabric is not implemented","convertObjectRowsToMaterializationKinds")}createState(n,i,o,s){return new sMr(s,o,i,n)}wrapSQLWithExplain(n){return`SELECT TOP 0 * FROM (${n}) as CoalesceWrapped`}};var tSS=B.literal("oauth"),gFs=".datawarehouse.fabric.microsoft.com";var wTm=Je("RUNNER"),AFs=class extends nt{constructor(){super("No current user, cannot run SQL!")}},C1t=async(r,t,n)=>{if(t===null){if(!Xc.instance.currentUser)throw new AFs;t=Xc.resolveAuthToken}return MTm(r,typeof t=="function"?await t():t,n)},MTm=(r,t,n)=>{let i=r.userContext?.orgID,o=r.userContext.environmentID?+r.userContext.environmentID:void 0;return Ah(`Front-end/runSQL/API: ${r.templateString}`,{orgID:i,workspaceID:o},"RUNNER_BACKEND",async()=>{try{let s=await rJe("/scheduler/run",r,t,n,{retryTransientErrors:!1});if(s.data.error)throw new Error(s.data.error);return s.data}catch(s){throw wTm.error("got error on run sql with token",s),s}})};var mFs=Je("TESTING");async function B$p(r,t,n,i,o,s){let a=r.includes(gFs)?r:`${r}${gFs}`,u={clientID:i.clientID,clientSecret:i.clientSecret,connectionString:a,query:t,database:n??""};try{let p=process.env.JAVA_SERVICE_BASE_URL,c=process.env.JAVA_SERVICE_PORT;if(!p&&!Hg().isTest){let l=process.env.COALESCE_COA_CLOUD_TOKEN??null;return await C1t({userContext:{connectionString:u.connectionString,kind:"fabric",credentials:i,authenticator:"oauth",environmentID:s},templateString:t,requestId:mu(),options:{database:n}},l)}else{let l=`${p}:${c}/api/sql/v1/execute`;mFs.infoContext(o,"Fabric request sending query to JDBC");let d=await dc.post(l,u);return mFs.infoContext(o,"Fabric request response received from JDBC"),M2r(d.data,u.query)}}catch(p){let c=i3t(p);throw mFs.errorContext(o,"error querying the java service",c),c}}var Mjt=class extends Bne{name="fabric";userContext;constructor(t,n){super(void 0,n,mu(),0,null),this.userContext=t}async makePendingQuery(t){let{credentials:n,connectionString:i,environmentID:o}=this.userContext,s=async()=>{if(!o)throw new nt("Missing environmentID","makePendingQuery");if(!n)throw new nt("Failed to load secrets");if(!i)throw new nt("Connection string not found");return{rows:(await B$p(i,t.statement,t.database,n,this.logContext,o.toString())).data.rows}},a={Cancel:async()=>{},coalesceQueryID:mu(),sqlText:t.statement,promise:s(),attachThen:()=>{}};return this.runningQueries.set(a.coalesceQueryID,a),a}async teardown(){return Promise.resolve()}async resetConnection(){throw new d1("resetConnection() is not supported in FabricConnection.")}setQueryTag=async t=>{}},xin=async(r,t)=>new Mjt(r,t);var yFs=class extends Tre{async createConnection(){return await xin(this.userContext,this.logContext)}async updateFromResult(t){}async assertConnected(){}async setup(){this.newConnection()}newConnection(){return new Mjt(this.userContext,this.logContext)}},Pin=class r extends vre{static async New(t,n,i,o){let s=new r(t,n,i,o);return await s.setup(),s}NewSlotMember(t,n){return new yFs(t,n,{...this.userContext},this.teamInfo,this.logContext,this)}test(){throw new d1("test() is not implemented in FabricConnectionManager.")}};var Nin=class r extends wjt{constructor(n,i){super(i);this.connection=n}connection;async runSQL(n){let{sql:i,options:o,overrideRequestID:s}=n;this.warnAboutLargeQuery(i);let a=await this.connection.execute({statement:i,database:o?.database??"",requestId:s});return M2r(a,i)}usingConnection=n=>new r(n,this.userContext);teardown(){return Promise.resolve()}},L$p=async(r,t,n,i)=>{let o=await Pin.New(r,t,i,n),s=new Nin(o.getConnection(),r);return{connectionManager:o,platform:s}},k$p=async(r,t)=>{let n=await xin(r,t);return new Nin(n,r)};var Din=class r extends pNt{constructor(n,i){super(i);this.connection=n}connection;async runSQL(n){let{sql:i,options:o,overrideRequestID:s}=n;this.warnAboutLargeQuery(i);let a=await this.connection.execute({sqlText:i,requestId:s||mu(),...o});return r.GetTemplateResultFromExecutionResult(i,a)}static GetTemplateResultFromExecutionResult(n,i){let o=i.stmt.getColumns().map(a=>({Name:a.getName(),DataType:a.getType()}));return{runDetails:{compiledSQL:n,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:i.queryID,warehouse:i.warehouse},data:{columns:o,rows:i.rows,status:i.status}}}usingConnection=n=>new r(n,this.userContext);teardown(){return this.connection.teardown()}},q$p=async(r,t,n,i,o)=>{let s=await Snn.New(r,t,o,n);i&&await s.test();let a=new Din(s.getConnection(),r);return{connectionManager:s,platform:a}},F$p=async(r,t,n)=>{let i=await UKp(r,t,n);return new Din(i,r)};var JW=(r,t,n)=>fL(r,{snowflake:i=>F$p(i,t,n),databricks:i=>D$p(i,t),fabric:i=>k$p(i,t),bigquery:i=>x$p(i,t)}),Mfe=(r,t,n,i,o)=>fL(r,{snowflake:s=>q$p(s,t,n,i,o),databricks:s=>N$p(s,t,n,i,o),fabric:s=>L$p(s,t,n,o),bigquery:s=>M$p(s,t,n,i,o)});var O9=async(r,t,n,i,o,s)=>{let a=r.org(t).workspace(i),[{accessUrl:u,connectionAccount:p},c]=await Promise.all([a.fetch(),mle(a.workspaceUser(n),s)]),l=p||"",d=u||null;return _We(c.connectionKind,c,{snowflake:async f=>{if(o.kind!=="snowflake")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for ${f.connectionKind??"snowflake"}`);let h={accountName:l,accessUrl:d,user:f.connectionDetails.user,role:f.connectionDetails.role,warehouse:f.connectionDetails.warehouse,environmentID:i,orgID:t,authenticator:f.connectionType,kind:"snowflake"};return bFs(h,o),h},databricks:async f=>{if(o.kind!=="databricks")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for ${f.connectionKind??"snowflake"}`);let h={...o,path:f.connectionDetails.path,host:l,environmentID:i};return bFs(h,o),h},fabric:async f=>{if(o.kind!=="fabric")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for fabric`);let A=await(await hI()).Get(WYo,{orgId:t,userId:n,workspaceId:i.toString()});if(!A)throw new nt("Fabric connection credentials not found","CreateUserContext");return{...o,connectionString:l,credentials:A.sensitiveValue,environmentID:i}},bigquery:async f=>{if(o.kind!=="bigquery")throw new Vi(`Got a userContext for a ${o.kind}, but the connection info on the workspace was for ${f.connectionKind??"bigquery"}`);let h=V5e(o.authenticator??f.connectionType),A=await Tnn(h,t,n,i,o.serviceAccountKey);return bFs(A,o),A}},"CreateUserContext")},bFs=(r,t)=>{for(let n in t)t[n]&&(r[n]=t[n])};var EFs=r=>({user:r.snowflakeUsername,role:r.snowflakeRole,warehouse:r.snowflakeWarehouse,authenticator:"Cloud",kind:"snowflake"}),z9e=r=>{let t=o=>({user:o.snowflakeUsername,password:o.snowflakePassword,role:o.snowflakeRole,warehouse:o.snowflakeWarehouse,authenticator:"Basic",kind:"snowflake"}),n=o=>{if(o.snowflakeKeyPairKey===void 0)throw new nt("No private key was provided, cannot perform key pair authentication with Snowflake");let s=o.snowflakeKeyPairPass?new zd(o.snowflakeKeyPairPass):void 0,a=w9e(new zd(o.snowflakeKeyPairKey),s);return{user:o.snowflakeUsername,keyPairKey:a.sensitiveValue,keyPairPass:o.snowflakeKeyPairPass,role:o.snowflakeRole,warehouse:o.snowflakeWarehouse,authenticator:"KeyPair",kind:"snowflake"}},i=o=>({warehouse:o.snowflakeWarehouse,authenticator:"OAuth",kind:"snowflake"});return Lme(r,{snowflake:o=>Dme(o,t,n,i,EFs),databricks:o=>o.databricksAuthType==="OAuthM2M"?{kind:"databricks",authenticator:o.databricksAuthType,clientID:o.clientID,secret:o.clientSecret}:o.databricksAuthType==="OAuthU2M"?{kind:"databricks",authenticator:o.databricksAuthType,accessToken:o.accessToken}:{kind:"databricks",authenticator:o.databricksAuthType,token:o.databricksAuthType==="Token"?o.token:void 0},fabric:o=>({kind:"fabric",authenticator:o.fabricAuthType,connectionString:o.connectionString}),bigquery:o=>{let s=o.bigQueryAuthType;return s==="ServiceAccount"?{kind:"bigquery",authenticator:s,serviceAccountKey:o.serviceAccountKey}:{kind:"bigquery",authenticator:s}}},"GetUserAuthContextInfoFromUserCredentials")};var Q9e=Je("PLAN"),Q$p=async(r,t,n,i,o,s,a)=>{let u="[getPlatformAndTest]",{measure:p,printSummary:c}=Bf(u,a),l,d=i.org(t).workspace(n).workspaceUser(r);try{let f=await p("GetUserConnectionInfo",()=>mle(d,a));await p("AdjustCreds",()=>M9e(t,r,n,o,f,s));let h=z9e(o),A=await p("CreateUserContext",()=>O9(i,t,r,n,h,a));try{l=await p("GetBackendPlatform",()=>JW(A,a,s)),await p("testConnection",()=>l.testConnection())}catch(E){if(A.kind==="none")throw new nt("User context is none","getPlatformAndTest");if(zKp(E,A.kind)){Q9e.errorContext(a,`Dead OAuth access token for platform ${A.kind} - Resetting oauth connection in getPlatformAndTest. Error: `,E);let v=await QKp(A,{rootRepository:i,teamInfo:{fbTeamID:t,fbUserID:r,fbEmail:"",fbFullName:"",fbFirstName:"",fbLastName:""}},a);A.kind==="databricks"&&v&&(A.accessToken=v),Q9e.infoContext(a,`Retrying ${A.kind} platform connection after oauth connection reset`),l=await JW(A,a,s),await l.testConnection()}else throw E}return l}catch(f){let{message:h,detail:A}=await xTm(f,d,a);throw new nt(h,A)}finally{c()}},xTm=async(r,t,n)=>{let i="[createPlan (endpoint)]";Q9e.errorContext(n,i,"Error authenticating user",r);let o;try{({connectionKind:o}=await t.fetch())}catch(u){Q9e.errorContext(n,i,"Couldn't fetch workspace user",u)}let{error:{errorString:s,errorDetail:a}}=aa(r);return{message:`${o?TD(o)+" u":"U"}ser authentication unsuccessful: ${s}`,detail:a}},j$p=async(r,t,n,i,o,s,a,u,p,c)=>{let l="[performPlanCreation]",{measure:d,printSummary:f}=Bf(l,c);try{let h,{useRenderCache:A}=r;A&&(h=await d("acquiring renderer cache",()=>Inn(i.toString(),c)));let E=await d("plan calculation (total)",()=>mJo({...r,skipAwaitPlanContext:!0},t,h,n,i,o,s,a,u,p,c)),v=await d("stringify & compress plan",async()=>{let T=await(0,U$p.stringify)({body:E});return(0,z$p.deflate)(T,{to:"string"})});Q9e.appContext(c,l,`Processing for plan ${n} completed. Size was ${n$(v.length)}mb. Storing compressed data`),await d("store completed plan",()=>Pal(p,o,i,n,v,c)),Q9e.appContext(c,l,`Storage for plan ${n} completed`)}catch(h){Q9e.errorContext(c,l,"Plan creation failed",h),await Nal(p,o,i,n,{status:"failed",error:h instanceof nt?h.toTRunError():aa(h)},c)}finally{f()}};var nXp=require("node:os");var Une=class extends nt{constructor(n,i){super(n,i?`Request ID: ${i}`:void 0);this.requestId=i}requestId};var xC=Je("RENDERER"),G$p=r=>{let t=r;return t.state="in use",t},PTm=r=>{let t=r;return t.state="unused",t},H$p=r=>{let t=r;return t.state="terminated",t},NTm=r=>{let t=r;return t.state="error",t},CFs=class extends nt{constructor(n=null){let i="Cannot render on shutdown pool!"+(n===null?"":`, requestID=${n}`);super(i);this.requestID=n}requestID},Lin=class extends nt{constructor(n=null){let i="Exiting terminated pool"+(n===null?"":`, requestID=${n}`);super(i);this.requestID=n}requestID},kin=class{constructor(t,n){this.size=t;this.renderFactory=n;if(this.initializeNewRenderer(),!this.renderers[0])throw new Une("A render pool must have a size greater than 0")}size;renderFactory;renderers=[];queued=[];terminated=!1;stopped=!1;initFailureTracker=new Map;renderFailureTracker=new Map;allSlotsTerminal=()=>this.renderers.every(t=>t.state==="error"||t.state==="terminated");getInitFailureCount=t=>this.initFailureTracker.get(t.id)||0;getRenderFailureCount=t=>this.renderFailureTracker.get(t.id)||0;IsAcceptingRequests=()=>!(this.terminated||this.stopped);IsInitialized=()=>Promise.any(this.renderers.map(t=>t.renderer.IsInitialized())).catch(()=>this.renderers[0].renderer.IsInitialized());handleNextQueued=async t=>{let n=this.queued.pop();if(n===void 0){xC.debug("render pool queue empty, freeing slot"),PTm(t);return}xC.debug("Rendering request",n.request.id),await this.renderWithRetries(t,n)};handleError=(t,n)=>{if(this.terminated){H$p(t);return}xC.error("Got a critical renderer error, terminating and creating a new renderer:",n),t.renderer.terminate(.1).catch(()=>{}),t.renderer=this.renderFactory()};awaitInitializationWithRetries=async t=>{if(t.id>0){let i=this.renderers[t.id-1];if(i)try{await i.renderer.IsInitialized()}catch{}}let n=3;do try{await t.renderer.IsInitialized();break}catch(i){if(this.terminated)return;this.initFailureTracker.set(t.id,this.getInitFailureCount(t)+1),this.handleError(t,i)}while(this.getInitFailureCount(t)<n-1);try{await t.renderer.IsInitialized()}catch(i){if(this.terminated)return;if(NTm(t),xC.error("Fatal error: Renderer never initialized:",i),this.allSlotsTerminal()&&!this.terminated)try{await this.terminate()}catch(o){xC.alert("During termination due to fatal renderer error, got an error!",o)}return}xC.debug("Initialized a renderer at slot",t.id),this.handleNextQueued(G$p(t)).catch(i=>{xC.debug("Got an error in queue after awaiting initialization with retries",i)})};initializeNewRenderer=()=>{if(this.renderers.length<this.size){let t=this.renderFactory(),n=this.renderers.length,i={id:n,state:"initializing",renderer:t};this.renderers.push(i),xC.debug("Initializing a renderer at slot",n),this.awaitInitializationWithRetries(i).catch(o=>{xC.alert("Got an unexpected uncaught error in initializing new renderer",o)})}else xC.debug("All renderer slots populated, size:",this.size,"and renderers:",this.renderers.length)};availableRenderer=()=>{for(let t of this.renderers)if(t.state==="unused"){let n=G$p(t);return this.initializeNewRenderer(),n}return this.initializeNewRenderer(),null};renderOnSlot=(t,n)=>t.renderer.render(n).then(o=>(xC.debug("Render promise for request",n.id,"completed on slot",t.id),this.renderFailureTracker.set(t.id,0),this.handleNextQueued(t).catch(s=>{xC.debug("Got an error in queue in renderOnSlot",s)}),o),o=>{throw this.renderFailureTracker.set(t.id,this.getRenderFailureCount(t)+1),this.handleError(t,o),o});stop=async()=>{if(this.stopped=!0,xC.info("Shutting down renderer pool, queue has",this.queued.length,"items in it"),await UP(this.queued.map(t=>t.promise)),xC.info("Terminating renderer threads"),await UP(this.renderers.map(t=>t.renderer.terminate())).catch(t=>xC.error("Renderer terminate() failed",t)),this.queued.length>0){let n="Request IDs:",i=this.queued.map(o=>o.request.id);this.queued.length>10&&(n="First 10 "+n,i=i.slice(0,10)),xC.alert("Unexpectedly, after stop() completed there were still queue entries in the renderer pool!",n,i)}else xC.info("Renderer pool shut down")};async terminate(t=5){this.terminated=!0;let n=this.renderers.filter(a=>a.state!=="terminated").map(a=>(H$p(a),a.renderer.terminate(t))),i=this.queued;this.queued=[],i.forEach(a=>{xC.info("Rejecting queued request",a.request.id),a.reject(new Lin(a.request.id))});let s=(await JR(t*1e3,"Terminate timed out",Promise.allSettled(n))).map(a=>a.status==="rejected"?a.reason:null).filter(a=>a!==null);s.length>0&&xC.alert("Got",s.length,"errors when terminating",n.length,"renderers. First failure:",s[0])}renderWithRetries=async(t,n)=>{let{resolve:i,promise:o,reject:s,request:a}=n,u=3,p=null,c=null,l=async()=>{try{do try{c=await this.renderOnSlot(t,a),this.renderFailureTracker.set(t.id,0),i(c);return}catch(d){p=d}while(p&&this.getRenderFailureCount(t)<u);typeof p=="object"&&p instanceof Error&&(p.stack=`${n.stack}
|
|
10531
10531
|
<=== PROMISE BOUNDARY ===>
|
|
10532
|
-
${p.stack||""}`),xC.alert(`Out of retries on render request ${a.id}, failing:`,p)}catch{}s(p)};return setImmediate(()=>l().catch(()=>{})),o};render=async t=>{if(this.terminated)throw new Lin(t.id);if(this.stopped)throw new CFs(t.id);let n={...TR(),request:t,stack:new Error().stack},i=this.availableRenderer();return i!==null?this.renderWithRetries(i,n):(this.queued.push(n),n.promise)}},Bin={pyodide:void 0,unix:void 0,dual:void 0},V$p=(r,t)=>{let n=Bin[r];if(!n||!n.IsAcceptingRequests()){n=t();let i=Bin[r];i&&i.IsAcceptingRequests()?(xC.alert("Pool initialization had a race!"),n.terminate().catch(o=>Je("RENDERER").error("termination of raced renderer failed",o)),n=i):Bin[r]=n}else xC.debug("Pool was already set up, no need to initialize!");return n},SFs=(r="pyodide")=>Bin[r],W$p=r=>{if(r){let t=+r;if(!isNaN(t))return t}};var Y$p=require("node:fs"),Fin=require("node:path"),Uin=require("node:worker_threads");var zne=Je("RENDERER"),qin=class{worker;state;inFlight={};error=null;initialized;constructor(t=60,n){let{resolve:i,reject:o,promise:s}=TR();this.initialized=JR(t*1e3,`Startup timed out in ${t}s`,s),n&&JR(n*1e3,"TimeoutSentinel",s).catch(u=>{typeof u=="object"&&u instanceof zNe&&u.message==="TimeoutSentinel"&&zne.alert(`Startup took longer than warnAfter time period of ${n}s`)}),this.worker=this.GetWorker(),this.state="initializing";let a=u=>{if(this.error!==null){zne.error("Renderer got a message while in the error state: ",u);return}if(zne.debug("Got a",u.type,"message in the",this.state,"state"),this.state==="initializing")u.type==="initialized"?(this.state="ready",i()):u.type==="error"?(this.setError(u),o(this.error)):zne.alert("Renderer ignoring message during initialization:",u);else if(this.state==="ready")this.inReady(u);else if(this.state==="error")zne.error("Got a message while in the error state:",u);else{let p=u.type==="rendered"||u.type==="error"?u.id:void 0;this.setError(new Une(`In state=${this.state}, got message type=${u.type}`,p))}};this.worker.handleMessage(a),this.worker.handleError(u=>this.setError(u)),this.worker.handleMessageError(u=>this.setError(u))}size=1;IsInitialized=()=>this.initialized;setError=t=>{this.state==="initializing"?(t?.value&&(t=t.value),zne.alert("Renderer initialization hit an error!",t)):zne.error("Got an error message from the worker in",this.state,t),this.state!=="error"&&(this.state="error",this.error=t)};inReady=t=>{if(t.type==="rendered"){let n=this.inFlight[t.id];n?(delete this.inFlight[t.id],zne.debug("Got response for render request",t.id),n.resolve(t.value)):this.setError(new Une("Could not find an inflight request!",t.id))}else if(t.type==="error")if(t.id){let n=this.inFlight[t.id];n?(delete this.inFlight[t.id],n.reject(t.value)):this.setError(new Une("Could not find an inflight request for ID!",t.id))}else this.setError(t.value);else zne.alert("Unexpected response message with type",t.type,"will be ignored")};checkState=t=>{if(this.state==="error"||this.error)throw this.error||new Une("Cannot render in the error state!",t.id);if(this.state==="terminated")throw new Une("Cannot render with terminated renderer!",t.id)};render=async t=>{this.checkState(t),await this.initialized,this.checkState(t);let n={type:"render",value:t},i=t.templateVars?.nodeMetadata?.operationName||"<unknown>";zne.debug("Sending request to render node",i,"request ID=",t.id),this.worker.postMessage(n);let o=TR();return this.inFlight[n.value.id]=o,o.promise};terminate=async(t=5)=>{if(this.state==="terminated")return;let n=async()=>{this.state="terminated";let i={type:"terminate"};this.worker.postMessage(i),this.worker.unhandleAll(),await this.worker.terminate()};await JR(t*1e3,"worker terminate timed out!",n())}};if(!Uin.isMainThread)throw new Error("Cannot import this file outside the main thread!");var K$p=Je("RENDERER"),vFs=class extends Uin.Worker{messageHandlers=[];messageErrorHandlers=[];errorHandlers=[];handleMessage=t=>{this.messageHandlers.push(t),this.on("message",t)};handleMessageError=t=>{this.messageErrorHandlers.push(t),this.on("messageerror",t)};handleError=t=>{this.errorHandlers.push(t),this.on("error",t)};unhandleAll=()=>{for(let t of this.messageHandlers)this.off("message",t);this.messageHandlers=[];for(let t of this.messageErrorHandlers)this.off("messageerror",t);this.messageErrorHandlers=[];for(let t of this.errorHandlers)this.off("error",t);this.errorHandlers=[]}},DTm=()=>{let r="worker.node.js",t=a=>(0,Fin.join)(a,"..","build-coa",r),n=a=>(0,Fin.join)(a,r),i=a=>(0,Y$p.existsSync)(a)?a:void 0,o=i(n(__dirname));if(o)return o;let s=module.paths?.length>0?module.paths:[(0,Fin.join)(process.cwd(),"node_modules")];for(let a of s){let u=i(t(a));if(u)return u;let p=i(n(a));if(p)return p}throw new Error("Could not find a worker path")},S1t=class extends qin{logTag="[PyodideRenderer]";constructor(t,n){super(t,n),Je("RENDERER").info(this.logTag,"Starting")}GetWorker(){let t=DTm(),n=new vFs(t,{stdout:!0});return n.stdout.on("data",i=>{let o=i.toString().trimEnd();o&&K$p.info(o)}),n.on("message",i=>{i.type||K$p.info("Worker Message: ",i)}),n}};var rXp=require("os");var eXp=require("net");var TFs=require("node:buffer");var J$p=r=>{let t;return JR(600*1e3,"renderer socket read timed out after 600s",new Promise((n,i)=>{let o=a=>{r.off("readable",s),r.off("error",o),i(a)},s=()=>{try{let a=r.read(t??4);if(a){if(t===void 0){if(a.byteLength!=4)throw new nt(`impossible state, got ${a.byteLength} bytes reading a unix socket for 4 bytes`);if(t=a.readUInt32BE(),a=r.read(t),!a)return;if(a.byteLength!=t)throw new nt(`Got an unexpected number of bytes. expected ${t}, got ${a.byteLength}`)}}else return;r.off("readable",s),r.off("error",o),n(JSON.parse(a.toString("utf-8")))}catch(a){o(a)}};r.on("error",o),r.on("readable",s)}))},$$p=(r,t)=>JR(600*1e3,"renderer socket write timed out after 600s",new Promise((n,i)=>{try{let o=TFs.Buffer.from(JSON.stringify(t),"utf-8"),s=o.byteLength,a=TFs.Buffer.allocUnsafe(4+s);a.writeUInt32BE(s,0),o.copy(a,4,0),r.write(a,u=>{u?i(u):n()})}catch(o){i(o)}})),X$p=(r,t)=>JR(600*1e3,"renderer socket write timed out after 600s",new Promise((n,i)=>{let o=()=>{n(),r.off("error",s),r.off("connect",o)},s=a=>{i(a),r.off("error",s),r.off("connect",o)};r.on("error",s),r.on("connect",o),r.connect(t)})),Z$p=async r=>JR(600*1e3,"renderer socket write timed out after 600s",new Promise((t,n)=>{if(r.closed||r.destroyed){t();return}let i=()=>{r.off("close",i),r.off("error",o),t()},o=s=>{r.off("close",i),r.off("error",o),n(s)};r.on("close",i),r.on("error",o);try{r.destroy()}catch(s){n(s);return}}));var tXp=async(r,t)=>{let n,i=new eXp.Socket;try{return await X$p(i,r),await $$p(i,t),n=await J$p(i),n}catch(o){if(o instanceof nt)throw o;{let{error:{errorDetail:s,errorString:a}}=ua(o);throw new nt(`Error trying to render over the socket: ${a}`,s)}}finally{try{await Z$p(i)}catch(o){Je("RENDERER").error("Got an error destroying the unix socket, but rendering was still successful",o)}}};var v1t=class{constructor(t){this.path=t;Je("RENDERER").info(this.logTag,"Starting, using path",t)}path;buffer=void 0;nextLength=void 0;logTag="[UnixSocketRenderer]";retryStrategy={name:"random",min:.5,max:4};setRetryStrategy(t){this.retryStrategy=t}async render(t){try{return await cf(()=>tXp(this.path,t),5,Je("RENDERER"),{},{retryStrategy:this.retryStrategy,retryLogLevel:"info"})}catch(n){throw Je("RENDERER").error("Got an error during rendering",n),n}}async terminate(){}async IsInitialized(){return Promise.resolve()}get size(){let t=process.env.COALESCE_MAX_RENDERER_CONCURRENCY?parseInt(process.env.COALESCE_MAX_RENDERER_CONCURRENCY):(0,rXp.cpus)().length;if(isNaN(t))throw new nt("Got a non-numeric value for COALESCE_MAX_RENDERER_CONCURRENCY");return t}};var zin=class{pyodide;unix;logTag="[DualValidatingRenderer]";constructor(t){Je("RENDERER").info(this.logTag,"Starting"),this.unix=new v1t(t),this.pyodide=new S1t}alert(...t){Je("RENDERER").alert(this.logTag,...t)}compare(t,n,i){if("error"in n&&"error"in i){if(!$1e(n.error,i.error))return this.alert("Error mismatch for render request ID",t.id,"unix says",n.error,"but pyodide says",i.error),!1}else{if("error"in n)return this.alert("Got an error in the unix result, but pyodide was fine",n.error),!1;if("error"in i)return this.alert("Got an error in the unix result, but pyodide was fine",i.error),!1;if(n.runDetails.compiledSQL!==i.runDetails.compiledSQL)return this.alert("Compiled SQL mismatch for render request ID",t.id),!1;if(!$1e(n.runDetails.ref_usage,i.runDetails.ref_usage))return this.alert("Compiled SQL matched but refs did not for render request ID",t.id),!1}return!0}async render(t){let[n,i]=await Promise.allSettled([this.unix.render(t),this.pyodide.render(t)]);if(n.status==="fulfilled"&&i.status==="fulfilled")return this.compare(t,n.value,i.value),i.value;if(n.status==="rejected"&&i.status==="rejected")throw i.reason;if(n.status==="rejected"&&i.status==="fulfilled")return this.alert("Pyodide succeeded with",i.value,"but unix renderer failed with alert",n.reason),i.value;if(n.status==="fulfilled"&&i.status==="rejected")throw this.alert("Pyodide failed with",i.reason,"but unix renderer succeeded with",n.value),i.reason;if(Je("RENDERER").emerg(this.logTag,"Reached an unexpected state! unixResult.status:",n.status,"pyodideResult.status:",i.status,"but wasn't that case already handled?"),i.status==="rejected")throw i.reason;return i.value}async IsInitialized(){await Promise.all([this.unix.IsInitialized(),this.pyodide.IsInitialized()])}async terminate(t){await Promise.all([this.unix.terminate(),this.pyodide.terminate(t)])}get size(){return this.unix.size!==this.pyodide.size&&this.alert("Size mismatch! Unix:",this.unix.size,"Pyodide:",this.pyodide.size),this.pyodide.size}};var _Fs=W$p(process.env.COALESCE_MAX_RENDERER_CONCURRENCY),BTm=()=>{if(Hg().isTest)return 1;let r=((0,nXp.cpus)()?.length||1)-2,t=r<2?2:r;return _Fs&&t>_Fs?_Fs:t},IFs=process.env.COALESCE_RENDERER_UNIX_SOCKET_PATH,LTm=r=>{if(IFs){if(r==="unix")return new v1t(IFs);if(r==="dual")return new zin(IFs)}return new S1t},iXp=(r="pyodide")=>V$p(r,()=>new kin(BTm(),()=>LTm(r)));var Ux=r=>{let t;return process.env.COALESCE_RENDERER_UNIX_SOCKET_PATH?r.isFeatureEnabled("enablePyodideAsValidator")?t="dual":t="unix":t="pyodide",Je("RENDERER").info(`Getting a pool of kind ${t}`),iXp(t)};vr();var ced=require("node:worker_threads");var dA=yt($Ss(),1),t_S=dA.default.AggregateField,r_S=dA.default.AggregateQuery,n_S=dA.default.AggregateQuerySnapshot,i_S=dA.default.BulkWriter,o_S=dA.default.BundleBuilder,s_S=dA.default.CollectionGroup,a_S=dA.default.CollectionReference,u_S=dA.default.DocumentReference,c_S=dA.default.DocumentSnapshot,l_S=dA.default.FieldPath,p_S=dA.default.FieldValue,d_S=dA.default.Filter,f_S=dA.default.Firestore,h_S=dA.default.GeoPoint,g_S=dA.default.GrpcStatus,A_S=dA.default.Query,m_S=dA.default.QueryDocumentSnapshot,y_S=dA.default.QueryPartition,b_S=dA.default.QuerySnapshot,E_S=dA.default.Timestamp,C_S=dA.default.Transaction,S_S=dA.default.WriteBatch,v_S=dA.default.WriteResult,kTm=dA.default.getFirestore,T_S=dA.default.initializeFirestore,__S=dA.default.setLogFunction,I_S=dA.default.v1;var ezs=require("node:fs"),tzs=require("node:path"),sed=require("util");var qTm=/^([a-zA-Z0-9_=]+)\.([a-zA-Z0-9_=]+)\.([a-zA-Z0-9_\-\+\/=]*)/,Qin=r=>qTm.test(r);var P_S=Mr("Cookie Session",B.object({accessToken:B.string(),refreshTokenId:B.string()}));var RFs=(r,t,n)=>{let i=mu();return n.warning(r,{correlationID:i,...t}),new KY(`Unauthorized. For more information, contact Coalesce support. correlationID = ${i}`)};var RRe=new TextEncoder,Kz=new TextDecoder,z_S=2**32;var sXp=yt(require("node:crypto"),1);var jTm=sXp.webcrypto,aXp=jTm;var Yz=["KeyObject"];(globalThis.CryptoKey||aXp?.CryptoKey)&&Yz.push("CryptoKey");var jin=require("node:crypto"),cXp=require("node:util");var tIS=(0,cXp.promisify)(jin.generateKeyPair);var pXp=require("node:util"),wFs=require("node:crypto");var AIS=(0,pXp.promisify)(wFs.pbkdf2);var Pjt=require("node:crypto"),dXp=require("node:util");var _IS=(0,dXp.deprecate)(()=>Pjt.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var DFs=yt(require("node:crypto"),1),mXp=require("node:util");var PFs=require("node:crypto");var KOS={padding:PFs.constants.RSA_PKCS1_PSS_PADDING,saltLength:PFs.constants.RSA_PSS_SALTLEN_DIGEST};var NFs=yt(require("node:crypto"),1),AXp=require("node:util");var cwS=(0,AXp.promisify)(NFs.sign);var gwS=(0,mXp.promisify)(DFs.verify);var C_m;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(C_m="jose/v5.2.3");var BFs=require("node:crypto"),SXp=require("node:util");var mxS=(0,SXp.promisify)(BFs.generateKeyPair);var IXp=yt(_Xp());var zPS=new IXp.default({max:1e3});var j9e=class extends Error{};j9e.prototype.name="InvalidTokenError";function I_m(r){return decodeURIComponent(atob(r).replace(/(.)/g,(t,n)=>{let i=n.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}function R_m(r){let t=r.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return I_m(t)}catch{return atob(t)}}function RXp(r,t){if(typeof r!="string")throw new j9e("Invalid token specified: must be a string");t||(t={});let n=t.header===!0?0:1,i=r.split(".")[n];if(typeof i!="string")throw new j9e(`Invalid token specified: missing part #${n+1}`);let o;try{o=R_m(i)}catch(s){throw new j9e(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(o)}catch(s){throw new j9e(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var Kin=class r{constructor(t=Db(),n,i,o){this.baseUrl=t;this.resolveAuthToken=n;this.resolveFirebaseRefreshToken=i;this.requestConfig=o}baseUrl;resolveAuthToken;resolveFirebaseRefreshToken;requestConfig;static createInstance(t=Db(),n,i,o){return new r(t,n,i,o)}async startDeploy(t){return await XP(this.getRequestUrl("/scheduler/startDeploy"),{deployRequestPath:t},this.resolveFirebaseRefreshToken,this.requestConfig)}async startRun(t){return XP(this.getRequestUrl("/scheduler/startRun"),t,this.resolveFirebaseRefreshToken,this.requestConfig)}async reRun(t){return XP(this.getRequestUrl("/scheduler/reRun"),t,this.resolveFirebaseRefreshToken,this.requestConfig)}async unlockUser(t){return XP(this.getRequestUrl(`/scheduler/unlockUser?uid=${t}`),{},this.resolveAuthToken,this.requestConfig)}async getAuthDisabledStatuses(t){return XP(this.getRequestUrl("/scheduler/getAuthDisabledStatuses"),{override:t},this.resolveAuthToken,this.requestConfig)}async getPlatformOAuthUrl(t,n,i){return XP(this.getRequestUrl(`/scheduler/oAuth/${t}`),{role:i,path:n},this.resolveAuthToken,this.requestConfig)}async deleteUserConnection(t,n){return XP(this.getRequestUrl("/scheduler/deleteUserConnection"),{workspaceID:t,userContext:n},this.resolveAuthToken,this.requestConfig)}async registerTrialOrg(t){return XP(this.getRequestUrl("/scheduler/registerTrialOrg"),t,void 0,this.requestConfig)}async generateLoginToken(t){return XP(this.getRequestUrl("/scheduler/generateLoginToken"),{},t??this.resolveAuthToken,this.requestConfig)}getRequestUrl(t){return new URL(t,this.baseUrl).href}};var O_m=1800,Bjt=class extends Xc{constructor(n,i,o,s,a=Db(),u){super(n);this.googleApiKey=i;this.usingFirebaseEmulator=o;this.firebaseApp=s;this.requestTimeoutMs=u;this.resolveAuthToken=this.resolveAuthToken.bind(this),this.getFirebaseRefreshToken=this.getFirebaseRefreshToken.bind(this),this.getFirebaseIDToken=this.getFirebaseIDToken.bind(this),this.getToken=this.getToken.bind(this),this.legacyApiClient=Kin.createInstance(a,this.resolveAuthToken,this.getFirebaseRefreshToken,this.requestConfig)}googleApiKey;usingFirebaseEmulator;firebaseApp;requestTimeoutMs;legacyApiClient;name="Firebase";get requestConfig(){return typeof this.requestTimeoutMs=="number"?{timeout:this.requestTimeoutMs}:void 0}async initialize(){this.logger.info("Initializing Firebase client auth service")}async loginWithEmailAndPassword(n,i){this.logger.info(`Logging user '${n}' into firebase with a password`);let o=await this.firebaseApp.auth().signInWithEmailAndPassword(n,i);return kE(!!o.user,"Failed to login with email and password",this.logger),this.mapToAuthUser(o.user)}async loginWithRefreshToken(n){let i;if(this.usingFirebaseEmulator)this.logger.info("Using the emulator, skipping token refresh"),i=n;else{this.logger.info("Calling the google token API to refresh a firebase token");try{i=(await XP(`https://securetoken.googleapis.com/v1/token?key=${this.googleApiKey}`,{refresh_token:n,grant_type:"refresh_token"},void 0,this.requestConfig)).data.id_token}catch(o){throw await new Promise(s=>setTimeout(s,5e3)),o}}return this.loginWithIdToken(i)}async loginWithIdToken(n){this.logger.info("Generating a custom token from a firebase ID token");let i=await this.legacyApiClient.generateLoginToken(n),{customToken:o}=i.data;return this.loginWithCustomToken(o)}async loginWithCustomToken(n){this.logger.info("Logging into firebase with a custom token");let i=await this.firebaseApp.auth().signInWithCustomToken(n);return kE(!!i.user,"Failed to login with custom token",this.logger),this.mapToAuthUser(i.user)}async logout(){this.logger.info(`Logging out user '${this.currentUser?.email}' from firebase`),await this.firebaseApp.auth().signOut()}get currentUser(){let n=this.firebaseApp.auth().currentUser;return n?this.mapToAuthUser(n):void 0}get isUsingBearerToken(){return!0}async resolveAuthToken(){let n,i=this.firebaseApp.auth().currentUser;if(i){n=await i.getIdToken();let o=RXp(n);o.exp&&o.exp<Date.now()/1e3+O_m&&(n=await i.getIdToken(!0))}return n}async getFirebaseIDToken(){return await this.getAuthToken()}async getFirebaseRefreshToken(){let n=this.firebaseApp.auth().currentUser;if(!n)throw new nt("Unable to obtain refresh token, no user is currently signed in");return this.usingFirebaseEmulator?this.getFirebaseIDToken():n.refreshToken}setupApiClient(n){return n.use(z4e({getToken:this.getToken})),n}onAuthStateChanged(n){return this.firebaseApp.auth().onAuthStateChanged(i=>{n(i?this.mapToAuthUser(i):void 0)})}async getToken(){return this.isLoggedIn?this.resolveAuthToken():void 0}mapToAuthUser(n){return{email:n.email??"",id:n.uid}}};var OXp=r=>"recursiveDelete"in r,Yin=r=>r?r?.message??"":"",w_m=r=>/(PERMISSION_DENIED)|(false for 'get')|(false for 'list')|(false for 'update')|(false for 'delete')|(Missing or insufficient permissions.)/.test(Yin(r)),M_m=r=>/(NOT_FOUND)|(No document to update)/.test(Yin(r)),Ljt=r=>w_m(r)?new Ww("Permission denied",Yin(r)):M_m(r)?new Du("Not found",Yin(r)):r,nB=async r=>{try{return await r}catch(t){throw Ljt(t)}};var UXp=yt(Y5(),1);A6();var H9e=yt(DXe(),1),LXp=yt(MEs(),1),FFs=yt(Y5(),1),UFs=yt(IXe(),1),kXp=require("stream"),zFs=yt(PUr(),1);A6();var MXp=yt(require("querystring"),1),xXp=require("stream");var PXp=yt(T1t(),1);var P_m=!0;function $z(r,t){return{options:typeof r=="object"?r:{},callback:typeof r=="function"?r:t}}function qFs(r){return Object.keys(r).map(t=>[t,r[t]])}function N_m(r){return encodeURIComponent(r).replace(/[!'()*]/g,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function qjt(r,t){return r.split("/").map(N_m).join(t?"%2F":"/")}function NXp(r){return MXp.stringify(r,"&","=",{encodeURIComponent:t=>qjt(t,!0)})}function DXp(r){let t={};for(let n of Object.keys(r)){let i=r[n];n=n.toLowerCase(),t[n]=i}return t}function BXp(r){return JSON.stringify(r).replace(/[\u0080-\uFFFF]/g,t=>"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4))}function Jin(r){return r instanceof Date||r instanceof RegExp?r:Array.isArray(r)?r.map(Jin):r instanceof Object?Object.keys(r).reduce((t,n)=>{let i=n[0].toLocaleLowerCase()+n.slice(1).replace(/([A-Z]+)/g,(o,s)=>`_${s.toLowerCase()}`);return t[i]=Jin(r[n]),t},Object()):r}function G9e(r,t=!1,n="",i=""){let o=r.getUTCFullYear(),s=r.getUTCMonth()+1,a=r.getUTCDate(),u=r.getUTCHours(),p=r.getUTCMinutes(),c=r.getUTCSeconds(),l=`${o.toString().padStart(4,"0")}${n}${s.toString().padStart(2,"0")}${n}${a.toString().padStart(2,"0")}`;return t&&(l=`${l}T${u.toString().padStart(2,"0")}${i}${p.toString().padStart(2,"0")}${i}${c.toString().padStart(2,"0")}Z`),l}function Gne(){return globalThis.Deno&&globalThis.Deno.version&&globalThis.Deno.version.deno?`gl-deno/${globalThis.Deno.version.deno}`:`gl-node/${process.versions.node}`}function Hne(){let r=(0,PXp.getPackageJSON)();return r.name.replace("@google-cloud","gcloud-node").replace("/","-")+"/"+r.version}function ORe(){return P_m?"ESM":"CJS"}var kjt=class extends xXp.PassThrough{constructor(){super(...arguments),this.shouldEmitReading=!0,this.shouldEmitWriting=!0}_read(t){this.shouldEmitReading&&(this.emit("reading"),this.shouldEmitReading=!1),super._read(t)}_write(t,n,i){this.shouldEmitWriting&&(this.emit("writing"),this.shouldEmitWriting=!1),process.nextTick(()=>{super._write(t,n,i)})}_final(t){this.shouldEmitReading&&(this.emit("reading"),this.shouldEmitReading=!1),this.shouldEmitWriting&&(this.emit("writing"),this.shouldEmitWriting=!1),t(null)}};var qXp=yt(Ple(),1),FXp=yt(T1t(),1);var D_m=(0,FXp.getPackageJSON)(),jI=Symbol.for("GCCL_GCS_CMD"),$in={timeout:6e4,gzip:!0,forever:!0,pool:{maxSockets:1/0}},B_m=!0,L_m=3,Bfe=class r extends Error{constructor(t){if(super(),typeof t!="object"){this.message=t||"";return}let n=t;this.code=n.code,this.errors=n.errors,this.response=n.response;try{this.errors=JSON.parse(this.response.body).error.errors}catch{this.errors=n.errors}this.message=r.createMultiErrorMessage(n,this.errors),Error.captureStackTrace(this)}static createMultiErrorMessage(t,n){let i=new Set;t.message&&i.add(t.message),n&&n.length?n.forEach(({message:s})=>i.add(s)):t.response&&t.response.body?i.add(LXp.decode(t.response.body.toString())):t.message||i.add("A failure occurred during this request.");let o=Array.from(i);return o.length>1&&(o=o.map((s,a)=>` ${a+1}. ${s}`),o.unshift("Multiple errors occurred during the request. Please see the `errors` array for complete details.\n"),o.push(`
|
|
10532
|
+
${p.stack||""}`),xC.alert(`Out of retries on render request ${a.id}, failing:`,p)}catch{}s(p)};return setImmediate(()=>l().catch(()=>{})),o};render=async t=>{if(this.terminated)throw new Lin(t.id);if(this.stopped)throw new CFs(t.id);let n={...TR(),request:t,stack:new Error().stack},i=this.availableRenderer();return i!==null?this.renderWithRetries(i,n):(this.queued.push(n),n.promise)}},Bin={pyodide:void 0,unix:void 0,dual:void 0},V$p=(r,t)=>{let n=Bin[r];if(!n||!n.IsAcceptingRequests()){n=t();let i=Bin[r];i&&i.IsAcceptingRequests()?(xC.alert("Pool initialization had a race!"),n.terminate().catch(o=>Je("RENDERER").error("termination of raced renderer failed",o)),n=i):Bin[r]=n}else xC.debug("Pool was already set up, no need to initialize!");return n},SFs=(r="pyodide")=>Bin[r],W$p=r=>{if(r){let t=+r;if(!isNaN(t))return t}};var Y$p=require("node:fs"),Fin=require("node:path"),Uin=require("node:worker_threads");var zne=Je("RENDERER"),qin=class{worker;state;inFlight={};error=null;initialized;constructor(t=60,n){let{resolve:i,reject:o,promise:s}=TR();this.initialized=JR(t*1e3,`Startup timed out in ${t}s`,s),n&&JR(n*1e3,"TimeoutSentinel",s).catch(u=>{typeof u=="object"&&u instanceof zNe&&u.message==="TimeoutSentinel"&&zne.alert(`Startup took longer than warnAfter time period of ${n}s`)}),this.worker=this.GetWorker(),this.state="initializing";let a=u=>{if(this.error!==null){zne.error("Renderer got a message while in the error state: ",u);return}if(zne.debug("Got a",u.type,"message in the",this.state,"state"),this.state==="initializing")u.type==="initialized"?(this.state="ready",i()):u.type==="error"?(this.setError(u),o(this.error)):zne.alert("Renderer ignoring message during initialization:",u);else if(this.state==="ready")this.inReady(u);else if(this.state==="error")zne.error("Got a message while in the error state:",u);else{let p=u.type==="rendered"||u.type==="error"?u.id:void 0;this.setError(new Une(`In state=${this.state}, got message type=${u.type}`,p))}};this.worker.handleMessage(a),this.worker.handleError(u=>this.setError(u)),this.worker.handleMessageError(u=>this.setError(u))}size=1;IsInitialized=()=>this.initialized;setError=t=>{this.state==="initializing"?(t?.value&&(t=t.value),zne.alert("Renderer initialization hit an error!",t)):zne.error("Got an error message from the worker in",this.state,t),this.state!=="error"&&(this.state="error",this.error=t)};inReady=t=>{if(t.type==="rendered"){let n=this.inFlight[t.id];n?(delete this.inFlight[t.id],zne.debug("Got response for render request",t.id),n.resolve(t.value)):this.setError(new Une("Could not find an inflight request!",t.id))}else if(t.type==="error")if(t.id){let n=this.inFlight[t.id];n?(delete this.inFlight[t.id],n.reject(t.value)):this.setError(new Une("Could not find an inflight request for ID!",t.id))}else this.setError(t.value);else zne.alert("Unexpected response message with type",t.type,"will be ignored")};checkState=t=>{if(this.state==="error"||this.error)throw this.error||new Une("Cannot render in the error state!",t.id);if(this.state==="terminated")throw new Une("Cannot render with terminated renderer!",t.id)};render=async t=>{this.checkState(t),await this.initialized,this.checkState(t);let n={type:"render",value:t},i=t.templateVars?.nodeMetadata?.operationName||"<unknown>";zne.debug("Sending request to render node",i,"request ID=",t.id),this.worker.postMessage(n);let o=TR();return this.inFlight[n.value.id]=o,o.promise};terminate=async(t=5)=>{if(this.state==="terminated")return;let n=async()=>{this.state="terminated";let i={type:"terminate"};this.worker.postMessage(i),this.worker.unhandleAll(),await this.worker.terminate()};await JR(t*1e3,"worker terminate timed out!",n())}};if(!Uin.isMainThread)throw new Error("Cannot import this file outside the main thread!");var K$p=Je("RENDERER"),vFs=class extends Uin.Worker{messageHandlers=[];messageErrorHandlers=[];errorHandlers=[];handleMessage=t=>{this.messageHandlers.push(t),this.on("message",t)};handleMessageError=t=>{this.messageErrorHandlers.push(t),this.on("messageerror",t)};handleError=t=>{this.errorHandlers.push(t),this.on("error",t)};unhandleAll=()=>{for(let t of this.messageHandlers)this.off("message",t);this.messageHandlers=[];for(let t of this.messageErrorHandlers)this.off("messageerror",t);this.messageErrorHandlers=[];for(let t of this.errorHandlers)this.off("error",t);this.errorHandlers=[]}},DTm=()=>{let r="worker.node.js",t=a=>(0,Fin.join)(a,"..","build-coa",r),n=a=>(0,Fin.join)(a,r),i=a=>(0,Y$p.existsSync)(a)?a:void 0,o=i(n(__dirname));if(o)return o;let s=module.paths?.length>0?module.paths:[(0,Fin.join)(process.cwd(),"node_modules")];for(let a of s){let u=i(t(a));if(u)return u;let p=i(n(a));if(p)return p}throw new Error("Could not find a worker path")},S1t=class extends qin{logTag="[PyodideRenderer]";constructor(t,n){super(t,n),Je("RENDERER").info(this.logTag,"Starting")}GetWorker(){let t=DTm(),n=new vFs(t,{stdout:!0});return n.stdout.on("data",i=>{let o=i.toString().trimEnd();o&&K$p.info(o)}),n.on("message",i=>{i.type||K$p.info("Worker Message: ",i)}),n}};var rXp=require("os");var eXp=require("net");var TFs=require("node:buffer");var J$p=r=>{let t;return JR(600*1e3,"renderer socket read timed out after 600s",new Promise((n,i)=>{let o=a=>{r.off("readable",s),r.off("error",o),i(a)},s=()=>{try{let a=r.read(t??4);if(a){if(t===void 0){if(a.byteLength!=4)throw new nt(`impossible state, got ${a.byteLength} bytes reading a unix socket for 4 bytes`);if(t=a.readUInt32BE(),a=r.read(t),!a)return;if(a.byteLength!=t)throw new nt(`Got an unexpected number of bytes. expected ${t}, got ${a.byteLength}`)}}else return;r.off("readable",s),r.off("error",o),n(JSON.parse(a.toString("utf-8")))}catch(a){o(a)}};r.on("error",o),r.on("readable",s)}))},$$p=(r,t)=>JR(600*1e3,"renderer socket write timed out after 600s",new Promise((n,i)=>{try{let o=TFs.Buffer.from(JSON.stringify(t),"utf-8"),s=o.byteLength,a=TFs.Buffer.allocUnsafe(4+s);a.writeUInt32BE(s,0),o.copy(a,4,0),r.write(a,u=>{u?i(u):n()})}catch(o){i(o)}})),X$p=(r,t)=>JR(600*1e3,"renderer socket write timed out after 600s",new Promise((n,i)=>{let o=()=>{n(),r.off("error",s),r.off("connect",o)},s=a=>{i(a),r.off("error",s),r.off("connect",o)};r.on("error",s),r.on("connect",o),r.connect(t)})),Z$p=async r=>JR(600*1e3,"renderer socket write timed out after 600s",new Promise((t,n)=>{if(r.closed||r.destroyed){t();return}let i=()=>{r.off("close",i),r.off("error",o),t()},o=s=>{r.off("close",i),r.off("error",o),n(s)};r.on("close",i),r.on("error",o);try{r.destroy()}catch(s){n(s);return}}));var tXp=async(r,t)=>{let n,i=new eXp.Socket;try{return await X$p(i,r),await $$p(i,t),n=await J$p(i),n}catch(o){if(o instanceof nt)throw o;{let{error:{errorDetail:s,errorString:a}}=aa(o);throw new nt(`Error trying to render over the socket: ${a}`,s)}}finally{try{await Z$p(i)}catch(o){Je("RENDERER").error("Got an error destroying the unix socket, but rendering was still successful",o)}}};var v1t=class{constructor(t){this.path=t;Je("RENDERER").info(this.logTag,"Starting, using path",t)}path;buffer=void 0;nextLength=void 0;logTag="[UnixSocketRenderer]";retryStrategy={name:"random",min:.5,max:4};setRetryStrategy(t){this.retryStrategy=t}async render(t){try{return await cf(()=>tXp(this.path,t),5,Je("RENDERER"),{},{retryStrategy:this.retryStrategy,retryLogLevel:"info"})}catch(n){throw Je("RENDERER").error("Got an error during rendering",n),n}}async terminate(){}async IsInitialized(){return Promise.resolve()}get size(){let t=process.env.COALESCE_MAX_RENDERER_CONCURRENCY?parseInt(process.env.COALESCE_MAX_RENDERER_CONCURRENCY):(0,rXp.cpus)().length;if(isNaN(t))throw new nt("Got a non-numeric value for COALESCE_MAX_RENDERER_CONCURRENCY");return t}};var zin=class{pyodide;unix;logTag="[DualValidatingRenderer]";constructor(t){Je("RENDERER").info(this.logTag,"Starting"),this.unix=new v1t(t),this.pyodide=new S1t}alert(...t){Je("RENDERER").alert(this.logTag,...t)}compare(t,n,i){if("error"in n&&"error"in i){if(!$1e(n.error,i.error))return this.alert("Error mismatch for render request ID",t.id,"unix says",n.error,"but pyodide says",i.error),!1}else{if("error"in n)return this.alert("Got an error in the unix result, but pyodide was fine",n.error),!1;if("error"in i)return this.alert("Got an error in the unix result, but pyodide was fine",i.error),!1;if(n.runDetails.compiledSQL!==i.runDetails.compiledSQL)return this.alert("Compiled SQL mismatch for render request ID",t.id),!1;if(!$1e(n.runDetails.ref_usage,i.runDetails.ref_usage))return this.alert("Compiled SQL matched but refs did not for render request ID",t.id),!1}return!0}async render(t){let[n,i]=await Promise.allSettled([this.unix.render(t),this.pyodide.render(t)]);if(n.status==="fulfilled"&&i.status==="fulfilled")return this.compare(t,n.value,i.value),i.value;if(n.status==="rejected"&&i.status==="rejected")throw i.reason;if(n.status==="rejected"&&i.status==="fulfilled")return this.alert("Pyodide succeeded with",i.value,"but unix renderer failed with alert",n.reason),i.value;if(n.status==="fulfilled"&&i.status==="rejected")throw this.alert("Pyodide failed with",i.reason,"but unix renderer succeeded with",n.value),i.reason;if(Je("RENDERER").emerg(this.logTag,"Reached an unexpected state! unixResult.status:",n.status,"pyodideResult.status:",i.status,"but wasn't that case already handled?"),i.status==="rejected")throw i.reason;return i.value}async IsInitialized(){await Promise.all([this.unix.IsInitialized(),this.pyodide.IsInitialized()])}async terminate(t){await Promise.all([this.unix.terminate(),this.pyodide.terminate(t)])}get size(){return this.unix.size!==this.pyodide.size&&this.alert("Size mismatch! Unix:",this.unix.size,"Pyodide:",this.pyodide.size),this.pyodide.size}};var _Fs=W$p(process.env.COALESCE_MAX_RENDERER_CONCURRENCY),BTm=()=>{if(Hg().isTest)return 1;let r=((0,nXp.cpus)()?.length||1)-2,t=r<2?2:r;return _Fs&&t>_Fs?_Fs:t},IFs=process.env.COALESCE_RENDERER_UNIX_SOCKET_PATH,LTm=r=>{if(IFs){if(r==="unix")return new v1t(IFs);if(r==="dual")return new zin(IFs)}return new S1t},iXp=(r="pyodide")=>V$p(r,()=>new kin(BTm(),()=>LTm(r)));var Ux=r=>{let t;return process.env.COALESCE_RENDERER_UNIX_SOCKET_PATH?r.isFeatureEnabled("enablePyodideAsValidator")?t="dual":t="unix":t="pyodide",Je("RENDERER").info(`Getting a pool of kind ${t}`),iXp(t)};vr();var ced=require("node:worker_threads");var dA=yt($Ss(),1),t_S=dA.default.AggregateField,r_S=dA.default.AggregateQuery,n_S=dA.default.AggregateQuerySnapshot,i_S=dA.default.BulkWriter,o_S=dA.default.BundleBuilder,s_S=dA.default.CollectionGroup,a_S=dA.default.CollectionReference,u_S=dA.default.DocumentReference,c_S=dA.default.DocumentSnapshot,l_S=dA.default.FieldPath,p_S=dA.default.FieldValue,d_S=dA.default.Filter,f_S=dA.default.Firestore,h_S=dA.default.GeoPoint,g_S=dA.default.GrpcStatus,A_S=dA.default.Query,m_S=dA.default.QueryDocumentSnapshot,y_S=dA.default.QueryPartition,b_S=dA.default.QuerySnapshot,E_S=dA.default.Timestamp,C_S=dA.default.Transaction,S_S=dA.default.WriteBatch,v_S=dA.default.WriteResult,kTm=dA.default.getFirestore,T_S=dA.default.initializeFirestore,__S=dA.default.setLogFunction,I_S=dA.default.v1;var ezs=require("node:fs"),tzs=require("node:path"),sed=require("util");var qTm=/^([a-zA-Z0-9_=]+)\.([a-zA-Z0-9_=]+)\.([a-zA-Z0-9_\-\+\/=]*)/,Qin=r=>qTm.test(r);var P_S=Mr("Cookie Session",B.object({accessToken:B.string(),refreshTokenId:B.string()}));var RFs=(r,t,n)=>{let i=mu();return n.warning(r,{correlationID:i,...t}),new KY(`Unauthorized. For more information, contact Coalesce support. correlationID = ${i}`)};var RRe=new TextEncoder,Kz=new TextDecoder,z_S=2**32;var sXp=yt(require("node:crypto"),1);var jTm=sXp.webcrypto,aXp=jTm;var Yz=["KeyObject"];(globalThis.CryptoKey||aXp?.CryptoKey)&&Yz.push("CryptoKey");var jin=require("node:crypto"),cXp=require("node:util");var tIS=(0,cXp.promisify)(jin.generateKeyPair);var pXp=require("node:util"),wFs=require("node:crypto");var AIS=(0,pXp.promisify)(wFs.pbkdf2);var Pjt=require("node:crypto"),dXp=require("node:util");var _IS=(0,dXp.deprecate)(()=>Pjt.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');var DFs=yt(require("node:crypto"),1),mXp=require("node:util");var PFs=require("node:crypto");var KOS={padding:PFs.constants.RSA_PKCS1_PSS_PADDING,saltLength:PFs.constants.RSA_PSS_SALTLEN_DIGEST};var NFs=yt(require("node:crypto"),1),AXp=require("node:util");var cwS=(0,AXp.promisify)(NFs.sign);var gwS=(0,mXp.promisify)(DFs.verify);var C_m;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(C_m="jose/v5.2.3");var BFs=require("node:crypto"),SXp=require("node:util");var mxS=(0,SXp.promisify)(BFs.generateKeyPair);var IXp=yt(_Xp());var zPS=new IXp.default({max:1e3});var j9e=class extends Error{};j9e.prototype.name="InvalidTokenError";function I_m(r){return decodeURIComponent(atob(r).replace(/(.)/g,(t,n)=>{let i=n.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}function R_m(r){let t=r.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return I_m(t)}catch{return atob(t)}}function RXp(r,t){if(typeof r!="string")throw new j9e("Invalid token specified: must be a string");t||(t={});let n=t.header===!0?0:1,i=r.split(".")[n];if(typeof i!="string")throw new j9e(`Invalid token specified: missing part #${n+1}`);let o;try{o=R_m(i)}catch(s){throw new j9e(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(o)}catch(s){throw new j9e(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var Kin=class r{constructor(t=Db(),n,i,o){this.baseUrl=t;this.resolveAuthToken=n;this.resolveFirebaseRefreshToken=i;this.requestConfig=o}baseUrl;resolveAuthToken;resolveFirebaseRefreshToken;requestConfig;static createInstance(t=Db(),n,i,o){return new r(t,n,i,o)}async startDeploy(t){return await XP(this.getRequestUrl("/scheduler/startDeploy"),{deployRequestPath:t},this.resolveFirebaseRefreshToken,this.requestConfig)}async startRun(t){return XP(this.getRequestUrl("/scheduler/startRun"),t,this.resolveFirebaseRefreshToken,this.requestConfig)}async reRun(t){return XP(this.getRequestUrl("/scheduler/reRun"),t,this.resolveFirebaseRefreshToken,this.requestConfig)}async unlockUser(t){return XP(this.getRequestUrl(`/scheduler/unlockUser?uid=${t}`),{},this.resolveAuthToken,this.requestConfig)}async getAuthDisabledStatuses(t){return XP(this.getRequestUrl("/scheduler/getAuthDisabledStatuses"),{override:t},this.resolveAuthToken,this.requestConfig)}async getPlatformOAuthUrl(t,n,i){return XP(this.getRequestUrl(`/scheduler/oAuth/${t}`),{role:i,path:n},this.resolveAuthToken,this.requestConfig)}async deleteUserConnection(t,n){return XP(this.getRequestUrl("/scheduler/deleteUserConnection"),{workspaceID:t,userContext:n},this.resolveAuthToken,this.requestConfig)}async registerTrialOrg(t){return XP(this.getRequestUrl("/scheduler/registerTrialOrg"),t,void 0,this.requestConfig)}async generateLoginToken(t){return XP(this.getRequestUrl("/scheduler/generateLoginToken"),{},t??this.resolveAuthToken,this.requestConfig)}getRequestUrl(t){return new URL(t,this.baseUrl).href}};var O_m=1800,Bjt=class extends Xc{constructor(n,i,o,s,a=Db(),u){super(n);this.googleApiKey=i;this.usingFirebaseEmulator=o;this.firebaseApp=s;this.requestTimeoutMs=u;this.resolveAuthToken=this.resolveAuthToken.bind(this),this.getFirebaseRefreshToken=this.getFirebaseRefreshToken.bind(this),this.getFirebaseIDToken=this.getFirebaseIDToken.bind(this),this.getToken=this.getToken.bind(this),this.legacyApiClient=Kin.createInstance(a,this.resolveAuthToken,this.getFirebaseRefreshToken,this.requestConfig)}googleApiKey;usingFirebaseEmulator;firebaseApp;requestTimeoutMs;legacyApiClient;name="Firebase";get requestConfig(){return typeof this.requestTimeoutMs=="number"?{timeout:this.requestTimeoutMs}:void 0}async initialize(){this.logger.info("Initializing Firebase client auth service")}async loginWithEmailAndPassword(n,i){this.logger.info(`Logging user '${n}' into firebase with a password`);let o=await this.firebaseApp.auth().signInWithEmailAndPassword(n,i);return kE(!!o.user,"Failed to login with email and password",this.logger),this.mapToAuthUser(o.user)}async loginWithRefreshToken(n){let i;if(this.usingFirebaseEmulator)this.logger.info("Using the emulator, skipping token refresh"),i=n;else{this.logger.info("Calling the google token API to refresh a firebase token");try{i=(await XP(`https://securetoken.googleapis.com/v1/token?key=${this.googleApiKey}`,{refresh_token:n,grant_type:"refresh_token"},void 0,this.requestConfig)).data.id_token}catch(o){throw await new Promise(s=>setTimeout(s,5e3)),o}}return this.loginWithIdToken(i)}async loginWithIdToken(n){this.logger.info("Generating a custom token from a firebase ID token");let i=await this.legacyApiClient.generateLoginToken(n),{customToken:o}=i.data;return this.loginWithCustomToken(o)}async loginWithCustomToken(n){this.logger.info("Logging into firebase with a custom token");let i=await this.firebaseApp.auth().signInWithCustomToken(n);return kE(!!i.user,"Failed to login with custom token",this.logger),this.mapToAuthUser(i.user)}async logout(){this.logger.info(`Logging out user '${this.currentUser?.email}' from firebase`),await this.firebaseApp.auth().signOut()}get currentUser(){let n=this.firebaseApp.auth().currentUser;return n?this.mapToAuthUser(n):void 0}get isUsingBearerToken(){return!0}async resolveAuthToken(){let n,i=this.firebaseApp.auth().currentUser;if(i){n=await i.getIdToken();let o=RXp(n);o.exp&&o.exp<Date.now()/1e3+O_m&&(n=await i.getIdToken(!0))}return n}async getFirebaseIDToken(){return await this.getAuthToken()}async getFirebaseRefreshToken(){let n=this.firebaseApp.auth().currentUser;if(!n)throw new nt("Unable to obtain refresh token, no user is currently signed in");return this.usingFirebaseEmulator?this.getFirebaseIDToken():n.refreshToken}setupApiClient(n){return n.use(z4e({getToken:this.getToken})),n}onAuthStateChanged(n){return this.firebaseApp.auth().onAuthStateChanged(i=>{n(i?this.mapToAuthUser(i):void 0)})}async getToken(){return this.isLoggedIn?this.resolveAuthToken():void 0}mapToAuthUser(n){return{email:n.email??"",id:n.uid}}};var OXp=r=>"recursiveDelete"in r,Yin=r=>r?r?.message??"":"",w_m=r=>/(PERMISSION_DENIED)|(false for 'get')|(false for 'list')|(false for 'update')|(false for 'delete')|(Missing or insufficient permissions.)/.test(Yin(r)),M_m=r=>/(NOT_FOUND)|(No document to update)/.test(Yin(r)),Ljt=r=>w_m(r)?new Ww("Permission denied",Yin(r)):M_m(r)?new Du("Not found",Yin(r)):r,nB=async r=>{try{return await r}catch(t){throw Ljt(t)}};var UXp=yt(Y5(),1);A6();var H9e=yt(DXe(),1),LXp=yt(MEs(),1),FFs=yt(Y5(),1),UFs=yt(IXe(),1),kXp=require("stream"),zFs=yt(PUr(),1);A6();var MXp=yt(require("querystring"),1),xXp=require("stream");var PXp=yt(T1t(),1);var P_m=!0;function $z(r,t){return{options:typeof r=="object"?r:{},callback:typeof r=="function"?r:t}}function qFs(r){return Object.keys(r).map(t=>[t,r[t]])}function N_m(r){return encodeURIComponent(r).replace(/[!'()*]/g,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function qjt(r,t){return r.split("/").map(N_m).join(t?"%2F":"/")}function NXp(r){return MXp.stringify(r,"&","=",{encodeURIComponent:t=>qjt(t,!0)})}function DXp(r){let t={};for(let n of Object.keys(r)){let i=r[n];n=n.toLowerCase(),t[n]=i}return t}function BXp(r){return JSON.stringify(r).replace(/[\u0080-\uFFFF]/g,t=>"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4))}function Jin(r){return r instanceof Date||r instanceof RegExp?r:Array.isArray(r)?r.map(Jin):r instanceof Object?Object.keys(r).reduce((t,n)=>{let i=n[0].toLocaleLowerCase()+n.slice(1).replace(/([A-Z]+)/g,(o,s)=>`_${s.toLowerCase()}`);return t[i]=Jin(r[n]),t},Object()):r}function G9e(r,t=!1,n="",i=""){let o=r.getUTCFullYear(),s=r.getUTCMonth()+1,a=r.getUTCDate(),u=r.getUTCHours(),p=r.getUTCMinutes(),c=r.getUTCSeconds(),l=`${o.toString().padStart(4,"0")}${n}${s.toString().padStart(2,"0")}${n}${a.toString().padStart(2,"0")}`;return t&&(l=`${l}T${u.toString().padStart(2,"0")}${i}${p.toString().padStart(2,"0")}${i}${c.toString().padStart(2,"0")}Z`),l}function Gne(){return globalThis.Deno&&globalThis.Deno.version&&globalThis.Deno.version.deno?`gl-deno/${globalThis.Deno.version.deno}`:`gl-node/${process.versions.node}`}function Hne(){let r=(0,PXp.getPackageJSON)();return r.name.replace("@google-cloud","gcloud-node").replace("/","-")+"/"+r.version}function ORe(){return P_m?"ESM":"CJS"}var kjt=class extends xXp.PassThrough{constructor(){super(...arguments),this.shouldEmitReading=!0,this.shouldEmitWriting=!0}_read(t){this.shouldEmitReading&&(this.emit("reading"),this.shouldEmitReading=!1),super._read(t)}_write(t,n,i){this.shouldEmitWriting&&(this.emit("writing"),this.shouldEmitWriting=!1),process.nextTick(()=>{super._write(t,n,i)})}_final(t){this.shouldEmitReading&&(this.emit("reading"),this.shouldEmitReading=!1),this.shouldEmitWriting&&(this.emit("writing"),this.shouldEmitWriting=!1),t(null)}};var qXp=yt(Ple(),1),FXp=yt(T1t(),1);var D_m=(0,FXp.getPackageJSON)(),jI=Symbol.for("GCCL_GCS_CMD"),$in={timeout:6e4,gzip:!0,forever:!0,pool:{maxSockets:1/0}},B_m=!0,L_m=3,Bfe=class r extends Error{constructor(t){if(super(),typeof t!="object"){this.message=t||"";return}let n=t;this.code=n.code,this.errors=n.errors,this.response=n.response;try{this.errors=JSON.parse(this.response.body).error.errors}catch{this.errors=n.errors}this.message=r.createMultiErrorMessage(n,this.errors),Error.captureStackTrace(this)}static createMultiErrorMessage(t,n){let i=new Set;t.message&&i.add(t.message),n&&n.length?n.forEach(({message:s})=>i.add(s)):t.response&&t.response.body?i.add(LXp.decode(t.response.body.toString())):t.message||i.add("A failure occurred during this request.");let o=Array.from(i);return o.length>1&&(o=o.map((s,a)=>` ${a+1}. ${s}`),o.unshift("Multiple errors occurred during the request. Please see the `errors` array for complete details.\n"),o.push(`
|
|
10533
10533
|
`)),o.join(`
|
|
10534
10534
|
`)}},QFs=class extends Error{constructor(t){super();let n=t;this.errors=n.errors,this.name="PartialFailureError",this.response=n.response,this.message=Bfe.createMultiErrorMessage(n,this.errors)}},jFs=class{constructor(){this.ApiError=Bfe,this.PartialFailureError=QFs}noop(){}handleResp(t,n,i,o){o=o||bf.noop;let s={err:t||null,...n&&bf.parseHttpRespMessage(n),...i&&bf.parseHttpRespBody(i)};!s.err&&n&&typeof s.body=="object"&&(s.resp.body=s.body),s.err&&n&&(s.err.response=n),o(s.err,s.body,s.resp)}parseHttpRespMessage(t){let n={resp:t};return(t.statusCode<200||t.statusCode>299)&&(n.err=new Bfe({errors:new Array,code:t.statusCode,message:t.statusMessage,response:t})),n}parseHttpRespBody(t){let n={body:t};if(typeof t=="string")try{n.body=JSON.parse(t)}catch{n.body=t}return n.body&&n.body.error&&(n.err=new Bfe(n.body.error)),n}makeWritableStream(t,n,i){var o;i=i||bf.noop;let s=new GFs;s.on("progress",c=>t.emit("progress",c)),t.setWritable(s);let a={method:"POST",qs:{uploadType:"multipart"},timeout:0,maxRetries:0},u=n.metadata||{},p={...a,...n.request,qs:{...a.qs,...(o=n.request)===null||o===void 0?void 0:o.qs},multipart:[{"Content-Type":"application/json",body:JSON.stringify(u)},{"Content-Type":u.contentType||"application/octet-stream",body:s}]};n.makeAuthenticatedRequest(p,{onAuthenticated(c,l){if(c){t.destroy(c);return}$in.headers=bf._getDefaultHeaders(p[jI]),zFs.teenyRequest.defaults($in)(l,(f,h,A)=>{bf.handleResp(f,h,A,(E,v)=>{if(E){t.destroy(E);return}t.emit("response",h),i(v)})})}})}shouldRetryRequest(t){if(t){if([408,429,500,502,503,504].indexOf(t.code)!==-1)return!0;if(t.errors)for(let n of t.errors){let i=n.reason;if(i==="rateLimitExceeded"||i==="userRateLimitExceeded"||i&&i.includes("EAI_AGAIN"))return!0}}return!1}makeAuthenticatedRequestFactory(t){let n={...t};n.projectId===_1t&&delete n.projectId;let i;n.authClient instanceof FFs.GoogleAuth?i=n.authClient:i=new FFs.GoogleAuth({...n,authClient:n.authClient,clientOptions:n.clientOptions});function o(a,u){let p,c,l={...t},d;u||(p=(0,qXp.default)(),l.stream=p);let f=typeof u=="object"?u:void 0,h=typeof u=="function"?u:void 0;async function A(){c=await i.getProjectId()}let E=async(T,w)=>{let N=T,k=T&&typeof T.message=="string"&&T.message.indexOf("Could not load the default credentials")>-1;if(k&&(w=a),!T||k)try{w=bf.decorateRequest(w,c),T=null}catch(L){if(L instanceof H9e.MissingProjectIdError)try{await A(),w=bf.decorateRequest(w,c),T=null}catch(q){T=T||q}else T=T||L}if(T){p?p.destroy(T):(f&&f.onAuthenticated?f.onAuthenticated:h)(T);return}f&&f.onAuthenticated?f.onAuthenticated(null,w):d=bf.makeRequest(w,l,(L,...q)=>{L&&L.code===401&&N&&(L=N),h(L,...q)})};return(async()=>{try{let T=async()=>t.projectId&&t.projectId!==_1t?t.projectId:t.projectIdRequired===!1?_1t:A(),w=async()=>l.customEndpoint&&!l.useAuthWithCustomEndpoint?a:i.authorizeRequest(a),[N,k]=await Promise.all([T(),w()]);return N&&(c=N),E(null,k)}catch(T){return E(T)}})(),p||{abort(){setImmediate(()=>{d&&(d.abort(),d=null)})}}}let s=o;return s.getCredentials=i.getCredentials.bind(i),s.authClient=i,s}makeRequest(t,n,i){var o,s,a,u,p;let c=B_m;n.autoRetry!==void 0?c=n.autoRetry:((o=n.retryOptions)===null||o===void 0?void 0:o.autoRetry)!==void 0&&(c=n.retryOptions.autoRetry);let l=L_m;n.maxRetries!==void 0?l=n.maxRetries:((s=n.retryOptions)===null||s===void 0?void 0:s.maxRetries)!==void 0&&(l=n.retryOptions.maxRetries),$in.headers=this._getDefaultHeaders(t[jI]);let d={request:zFs.teenyRequest.defaults($in),retries:c!==!1?l:0,noResponseRetries:c!==!1?l:0,shouldRetryFn(E){var v,T;let w=bf.parseHttpRespMessage(E).err;return!((v=n.retryOptions)===null||v===void 0)&&v.retryableErrorFn?w&&((T=n.retryOptions)===null||T===void 0?void 0:T.retryableErrorFn(w)):w&&bf.shouldRetryRequest(w)},maxRetryDelay:(a=n.retryOptions)===null||a===void 0?void 0:a.maxRetryDelay,retryDelayMultiplier:(u=n.retryOptions)===null||u===void 0?void 0:u.retryDelayMultiplier,totalTimeout:(p=n.retryOptions)===null||p===void 0?void 0:p.totalTimeout};if(typeof t.maxRetries=="number"&&(d.retries=t.maxRetries,d.noResponseRetries=t.maxRetries),!n.stream)return(0,UFs.default)(t,d,(E,v,T)=>{bf.handleResp(E,v,T,i)});let f=n.stream,h;return(t.method||"GET").toUpperCase()==="GET"?(h=(0,UFs.default)(t,d),f.setReadable(h)):(h=d.request(t),f.setWritable(h)),h.on("error",f.destroy.bind(f)).on("response",f.emit.bind(f,"response")).on("complete",f.emit.bind(f,"complete")),f.abort=h.abort,f}decorateRequest(t,n){return delete t.autoPaginate,delete t.autoPaginateVal,delete t.objectMode,t.qs!==null&&typeof t.qs=="object"&&(delete t.qs.autoPaginate,delete t.qs.autoPaginateVal,t.qs=(0,H9e.replaceProjectIdToken)(t.qs,n)),Array.isArray(t.multipart)&&(t.multipart=t.multipart.map(i=>(0,H9e.replaceProjectIdToken)(i,n))),t.json!==null&&typeof t.json=="object"&&(delete t.json.autoPaginate,delete t.json.autoPaginateVal,t.json=(0,H9e.replaceProjectIdToken)(t.json,n)),t.uri=(0,H9e.replaceProjectIdToken)(t.uri,n),t}isCustomType(t,n){function i(p){return p.constructor&&p.constructor.name.toLowerCase()}let o=n.split("/"),s=o[0]&&o[0].toLowerCase(),a=o[1]&&o[1].toLowerCase();if(a&&i(t)!==a)return!1;let u=t;for(;;){if(i(u)===s)return!0;if(u=u.parent,!u)return!1}}maybeOptionsOrCallback(t,n){return typeof t=="function"?[{},t]:[t,n]}_getDefaultHeaders(t){let n={"User-Agent":Hne(),"x-goog-api-client":`${Gne()} gccl/${D_m.version}-${ORe()} gccl-invocation-id/${kk()}`};return t&&(n["x-goog-api-client"]+=` gccl-gcs-cmd/${t}`),n}},GFs=class extends kXp.Transform{constructor(){super(...arguments),this.bytesRead=0}_transform(t,n,i){this.bytesRead+=t.length,this.emit("progress",{bytesWritten:this.bytesRead,contentLength:"*"}),this.push(t),i()}},bf=new jFs;var _1t="{{projectId}}",Fjt=class r{constructor(t,n={}){this.baseUrl=t.baseUrl,this.apiEndpoint=t.apiEndpoint,this.timeout=n.timeout,this.globalInterceptors=Array.isArray(n.interceptors_)?n.interceptors_:[],this.interceptors=[],this.packageJson=t.packageJson,this.projectId=n.projectId||_1t,this.projectIdRequired=t.projectIdRequired!==!1,this.providedUserAgent=n.userAgent,this.universeDomain=n.universeDomain||UXp.DEFAULT_UNIVERSE,this.customEndpoint=t.customEndpoint||!1,this.makeAuthenticatedRequest=bf.makeAuthenticatedRequestFactory({...t,projectIdRequired:this.projectIdRequired,projectId:this.projectId,authClient:n.authClient||t.authClient,credentials:n.credentials,keyFile:n.keyFilename,email:n.email,clientOptions:{universeDomain:n.universeDomain,...n.clientOptions}}),this.authClient=this.makeAuthenticatedRequest.authClient,process.env.FUNCTION_NAME&&this.interceptors.push({request(o){return o.forever=!1,o}})}getRequestInterceptors(){return[].slice.call(this.globalInterceptors).concat(this.interceptors).filter(t=>typeof t.request=="function").map(t=>t.request)}getProjectId(t){if(!t)return this.getProjectIdAsync();this.getProjectIdAsync().then(n=>t(null,n),t)}async getProjectIdAsync(){let t=await this.authClient.getProjectId();return this.projectId===_1t&&t&&(this.projectId=t),this.projectId}request_(t,n){t={...t,timeout:this.timeout};let i=t.uri.indexOf("http")===0,o=[this.baseUrl];this.projectIdRequired&&(t.projectId?(o.push("projects"),o.push(t.projectId)):(o.push("projects"),o.push(this.projectId))),o.push(t.uri),i&&o.splice(0,o.indexOf(t.uri)),t.uri=o.map(c=>{let l=/^\/*|\/*$/g;return c.replace(l,"")}).join("/").replace(/\/:/g,":");let s=this.getRequestInterceptors();(Array.isArray(t.interceptors_)?t.interceptors_:[]).forEach(c=>{typeof c.request=="function"&&s.push(c.request)}),s.forEach(c=>{t=c(t)}),delete t.interceptors_;let u=this.packageJson,p=Hne();if(this.providedUserAgent&&(p=`${this.providedUserAgent} ${p}`),t.headers={...t.headers,"User-Agent":p,"x-goog-api-client":`${Gne()} gccl/${u.version}-${ORe()} gccl-invocation-id/${kk()}`},t[jI]&&(t.headers["x-goog-api-client"]+=` gccl-gcs-cmd/${t[jI]}`),t.shouldReturnStream)return this.makeAuthenticatedRequest(t);this.makeAuthenticatedRequest(t,n)}request(t,n){r.prototype.request_.call(this,t,n)}requestStream(t){let n={...t,shouldReturnStream:!0};return r.prototype.request_.call(this,n)}};var zXp=yt(Sg(),1),QXp=require("events");var iB=class r extends QXp.EventEmitter{constructor(t){super(),this.metadata={},this.baseUrl=t.baseUrl,this.parent=t.parent,this.id=t.id,this.createMethod=t.createMethod,this.methods=t.methods||{},this.interceptors=[],this.projectId=t.projectId,t.methods&&Object.getOwnPropertyNames(r.prototype).filter(n=>!/^request/.test(n)&&!/^getRequestInterceptors/.test(n)&&this[n]===r.prototype[n]&&!t.methods[n]).forEach(n=>{this[n]=void 0})}create(t,n){let i=this,o=[this.id];typeof t=="function"&&(n=t),typeof t=="object"&&o.push(t);function s(...a){let[u,p]=a;u||(i.metadata=p.metadata,i.id&&p.metadata&&(i.id=p.metadata.id),a[1]=i),n(...a)}o.push(s),this.createMethod.apply(null,o)}delete(t,n){var i;let[o,s]=bf.maybeOptionsOrCallback(t,n),a=o.ignoreNotFound;delete o.ignoreNotFound;let u=typeof this.methods.delete=="object"&&this.methods.delete||{},p={method:"DELETE",uri:"",...u.reqOpts,qs:{...(i=u.reqOpts)===null||i===void 0?void 0:i.qs,...o}};r.prototype.request.call(this,p,(c,l,d)=>{c&&c.code===404&&a&&(c=null),s(c,d)})}exists(t,n){let[i,o]=bf.maybeOptionsOrCallback(t,n);this.get(i,s=>{if(s){s.code===404?o(null,!1):o(s);return}o(null,!0)})}get(t,n){let i=this,[o,s]=bf.maybeOptionsOrCallback(t,n),a=Object.assign({},o),u=a.autoCreate&&typeof this.create=="function";delete a.autoCreate;function p(c,l,d){if(c){if(c.code===409){i.get(a,s);return}s(c,null,d);return}s(null,l,d)}this.getMetadata(a,(c,l)=>{if(c){if(c.code===404&&u){let d=[];Object.keys(a).length>0&&d.push(a),d.push(p),i.create(...d);return}s(c,null,l);return}s(null,i,l)})}getMetadata(t,n){var i;let[o,s]=bf.maybeOptionsOrCallback(t,n),a=typeof this.methods.getMetadata=="object"&&this.methods.getMetadata||{},u={uri:"",...a.reqOpts,qs:{...(i=a.reqOpts)===null||i===void 0?void 0:i.qs,...o}};r.prototype.request.call(this,u,(p,c,l)=>{this.metadata=c,s(p,this.metadata,l)})}getRequestInterceptors(){let t=this.interceptors.filter(n=>typeof n.request=="function").map(n=>n.request);return this.parent.getRequestInterceptors().concat(t)}setMetadata(t,n,i){var o,s;let[a,u]=bf.maybeOptionsOrCallback(n,i),p=typeof this.methods.setMetadata=="object"&&this.methods.setMetadata||{},c={method:"PATCH",uri:"",...p.reqOpts,json:{...(o=p.reqOpts)===null||o===void 0?void 0:o.json,...t},qs:{...(s=p.reqOpts)===null||s===void 0?void 0:s.qs,...a}};r.prototype.request.call(this,c,(l,d,f)=>{this.metadata=d,u(l,this.metadata,f)})}request_(t,n){t={...t},this.projectId&&(t.projectId=this.projectId);let i=t.uri.indexOf("http")===0,o=[this.baseUrl,this.id||"",t.uri];i&&o.splice(0,o.indexOf(t.uri)),t.uri=o.filter(u=>u.trim()).map(u=>{let p=/^\/*|\/*$/g;return u.replace(p,"")}).join("/");let s=Array.isArray(t.interceptors_)?t.interceptors_:[],a=[].slice.call(this.interceptors);if(t.interceptors_=s.concat(a),t.shouldReturnStream)return this.parent.requestStream(t);this.parent.request(t,n)}request(t,n){this.request_(t,n)}requestStream(t){let n={...t,shouldReturnStream:!0};return this.request_(n)}};(0,zXp.promisifyAll)(iB,{exclude:["getRequestInterceptors"]});var con=yt(skt(),1),SZp=yt(Sg(),1),eUs=require("stream");var ZFs=yt(skt(),1),fZp=yt(Sg(),1),hZp=yt(require("fs"),1),gZp=yt(aMe(),1),AZp=yt(require("path"),1),JFs=yt(akt(),1),$Fs=require("util"),mZp=yt(Bde(),1);var jXp=yt(Sg(),1),I1t=class r{constructor(){this.owners={},this.readers={},this.writers={},this.owners={},this.readers={},this.writers={},r.roles.forEach(this._assignAccessMethods.bind(this))}_assignAccessMethods(t){let n=r.accessMethods,i=r.entities,o=t.toLowerCase()+"s";this[o]=i.reduce((s,a)=>{let u=a.charAt(a.length-1)==="-";return n.forEach(p=>{let c=p+a[0].toUpperCase()+a.substring(1);u&&(c=c.replace("-","")),s[c]=(l,d,f)=>{let h;typeof d=="function"&&(f=d,d={}),u?h=a+l:(h=a,f=l),d=Object.assign({entity:h,role:t},d);let A=[d];return typeof f=="function"&&A.push(f),this[p].apply(this,A)}}),s},{})}};I1t.accessMethods=["add","delete"];I1t.entities=["allAuthenticatedUsers","allUsers","domain-","group-","project-","user-"];I1t.roles=["OWNER","READER","WRITER"];var wRe=class extends I1t{constructor(t){super(),this.pathPrefix=t.pathPrefix,this.request_=t.request}add(t,n){let i={};t.generation&&(i.generation=t.generation),t.userProject&&(i.userProject=t.userProject),this.request({method:"POST",uri:"",qs:i,maxRetries:0,json:{entity:t.entity,role:t.role.toUpperCase()}},(o,s)=>{if(o){n(o,null,s);return}n(null,this.makeAclObject_(s),s)})}delete(t,n){let i={};t.generation&&(i.generation=t.generation),t.userProject&&(i.userProject=t.userProject),this.request({method:"DELETE",uri:"/"+encodeURIComponent(t.entity),qs:i},(o,s)=>{n(o,s)})}get(t,n){let i=typeof t=="object"?t:null,o=typeof t=="function"?t:n,s="",a={};i&&(s="/"+encodeURIComponent(i.entity),i.generation&&(a.generation=i.generation),i.userProject&&(a.userProject=i.userProject)),this.request({uri:s,qs:a},(u,p)=>{if(u){o(u,null,p);return}let c;p.items?c=p.items.map(this.makeAclObject_):c=this.makeAclObject_(p),o(null,c,p)})}update(t,n){let i={};t.generation&&(i.generation=t.generation),t.userProject&&(i.userProject=t.userProject),this.request({method:"PUT",uri:"/"+encodeURIComponent(t.entity),qs:i,json:{role:t.role.toUpperCase()}},(o,s)=>{if(o){n(o,null,s);return}n(null,this.makeAclObject_(s),s)})}makeAclObject_(t){let n={entity:t.entity,role:t.role};return t.projectTeam&&(n.projectTeam=t.projectTeam),n}request(t,n){t.uri=this.pathPrefix+t.uri,this.request_(t,n)}};(0,jXp.promisifyAll)(wRe,{exclude:["request"]});var oZp=yt(Sg(),1),sZp=yt(p2s(),1),aZp=yt(require("crypto"),1),son=yt(require("fs"),1),uZp=yt(d2s(),1);var GXp=yt(pDe(),1),HXp=require("crypto"),q_m=yt(m2s(),1),V9e=yt(Y5(),1),ton=require("stream"),VXp=yt(Bde(),1);A6();var WXp=yt(T1t(),1),k_m=function(r,t,n,i,o){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?r!==t||!o:!t.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?o.call(r,n):o?o.value=n:t.set(r,n),n},w9=function(r,t,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?r!==t||!i:!t.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(r):i?i.value:t.get(r)},Lfe,kfe,Ujt,Zin,F_m=404,Xin=308,HFs=(0,WXp.getPackageJSON)(),U_m=/^(\w*):\/\//,eon=class extends ton.Writable{constructor(t){var n;if(super(t),Lfe.add(this),this.numBytesWritten=0,this.numRetries=0,this.currentInvocationId={checkUploadStatus:kk(),chunk:kk(),uri:kk()},this.writeBuffers=[],this.numChunksReadInRequest=0,this.localWriteCache=[],this.localWriteCacheByteLength=0,this.upstreamEnded=!1,kfe.set(this,void 0),t=t||{},!t.bucket||!t.file)throw new Error("A bucket and file name are required");if(t.offset&&!t.uri)throw new RangeError("Cannot provide an `offset` without providing a `uri`");if(t.isPartialUpload&&!t.chunkSize)throw new RangeError("Cannot set `isPartialUpload` without providing a `chunkSize`");t.authConfig=t.authConfig||{},t.authConfig.scopes=["https://www.googleapis.com/auth/devstorage.full_control"],this.authClient=t.authClient||new V9e.GoogleAuth(t.authConfig);let i=t.universeDomain||V9e.DEFAULT_UNIVERSE;if(this.apiEndpoint=`https://storage.${i}`,t.apiEndpoint&&t.apiEndpoint!==this.apiEndpoint){this.apiEndpoint=this.sanitizeEndpoint(t.apiEndpoint);let u=new URL(this.apiEndpoint).hostname,p=u===i,c=u===V9e.DEFAULT_UNIVERSE,l=u.slice(-(i.length+1))===`.${i}`,d=u.slice(-(V9e.DEFAULT_UNIVERSE.length+1))===`.${V9e.DEFAULT_UNIVERSE}`;!p&&!c&&!l&&!d&&(this.authClient=q_m)}this.baseURI=`${this.apiEndpoint}/upload/storage/v1/b`,this.bucket=t.bucket;let o=[t.bucket,t.file];if(typeof t.generation=="number"&&o.push(`${t.generation}`),this.cacheKey=o.join("/"),this.customRequestOptions=t.customRequestOptions||{},this.file=t.file,this.generation=t.generation,this.kmsKeyName=t.kmsKeyName,this.metadata=t.metadata||{},this.offset=t.offset,this.origin=t.origin,this.params=t.params||{},this.userProject=t.userProject,this.chunkSize=t.chunkSize,this.retryOptions=t.retryOptions,this.isPartialUpload=(n=t.isPartialUpload)!==null&&n!==void 0?n:!1,t.key){let u=Buffer.from(t.key).toString("base64");this.encryption={key:u,hash:(0,HXp.createHash)("sha256").update(t.key).digest("base64")}}this.predefinedAcl=t.predefinedAcl,t.private&&(this.predefinedAcl="private"),t.public&&(this.predefinedAcl="publicRead");let s=t.retryOptions.autoRetry;this.uriProvidedManually=!!t.uri,this.uri=t.uri,this.offset&&(this.numBytesWritten=this.offset),this.numRetries=0,s||(t.retryOptions.maxRetries=0),this.timeOfFirstRequest=Date.now();let a=t.metadata?Number(t.metadata.contentLength):NaN;this.contentLength=isNaN(a)?"*":a,k_m(this,kfe,t[jI],"f"),this.once("writing",()=>{this.uri?this.continueUploading():this.createURI(u=>{if(u)return this.destroy(u);this.startUploading()})})}_final(t=()=>{}){this.upstreamEnded=!0,this.once("uploadFinished",t),process.nextTick(()=>{this.emit("upstreamFinished"),this.emit("writing")})}_write(t,n,i=()=>{}){this.emit("writing"),this.writeBuffers.push(typeof t=="string"?Buffer.from(t,n):t),this.once("readFromChunkBuffer",i),process.nextTick(()=>this.emit("wroteToChunkBuffer"))}prependLocalBufferToUpstream(t){let n=[];if(t){let o=0;for(;t>o;){let s=this.localWriteCache.pop();if(!s)break;if(o+=s.byteLength,o>t){let a=o-t;s=s.subarray(a),o-=a}n.unshift(s)}}else n=this.localWriteCache;let i=this.writeBuffers;this.writeBuffers=n;for(let o of i)this.writeBuffers.push(o);w9(this,Lfe,"m",Ujt).call(this)}*pullFromChunkBuffer(t){for(;t;){let n=this.writeBuffers.shift();if(!n)break;let i=n;n.byteLength>t?(i=n.subarray(0,t),this.writeBuffers.unshift(n.subarray(t)),t=0):t-=n.byteLength,yield i,this.emit("readFromChunkBuffer")}}async waitForNextChunk(){return await new Promise(n=>{if(this.writeBuffers.length)return n(!0);if(this.upstreamEnded)return n(!1);let i=()=>(s(),n(!0)),o=()=>(s(),this.writeBuffers.length?n(!0):n(!1)),s=()=>{this.removeListener("wroteToChunkBuffer",i),this.removeListener("upstreamFinished",o)};this.once("wroteToChunkBuffer",i),this.once("upstreamFinished",o)})}async*upstreamIterator(t=1/0){for(;t&&await this.waitForNextChunk();)for(let n of this.pullFromChunkBuffer(t))t-=n.byteLength,yield n}createURI(t){if(!t)return this.createURIAsync();this.createURIAsync().then(n=>t(null,n),t)}async createURIAsync(){let t={...this.metadata},n={};t.contentLength&&(n["X-Upload-Content-Length"]=t.contentLength.toString(),delete t.contentLength),t.contentType&&(n["X-Upload-Content-Type"]=t.contentType,delete t.contentType);let i=`${Gne()} gccl/${HFs.version}-${ORe()} gccl-invocation-id/${this.currentInvocationId.uri}`;w9(this,kfe,"f")&&(i+=` gccl-gcs-cmd/${w9(this,kfe,"f")}`);let o={method:"POST",url:[this.baseURI,this.bucket,"o"].join("/"),params:Object.assign({name:this.file,uploadType:"resumable"},this.params),data:t,headers:{"User-Agent":Hne(),"x-goog-api-client":i,...n}};t.contentLength&&(o.headers["X-Upload-Content-Length"]=t.contentLength.toString()),t.contentType&&(o.headers["X-Upload-Content-Type"]=t.contentType),typeof this.generation<"u"&&(o.params.ifGenerationMatch=this.generation),this.kmsKeyName&&(o.params.kmsKeyName=this.kmsKeyName),this.predefinedAcl&&(o.params.predefinedAcl=this.predefinedAcl),this.origin&&(o.headers.Origin=this.origin);let s=await(0,VXp.default)(async a=>{var u,p,c;try{let l=await this.makeRequest(o);return this.currentInvocationId.uri=kk(),l.headers.location}catch(l){let d=l,f={code:(u=d.response)===null||u===void 0?void 0:u.status,name:(p=d.response)===null||p===void 0?void 0:p.statusText,message:(c=d.response)===null||c===void 0?void 0:c.statusText,errors:[{reason:d.code}]};if(this.retryOptions.maxRetries>0&&this.retryOptions.retryableErrorFn(f))throw d;return a(d)}},{retries:this.retryOptions.maxRetries,factor:this.retryOptions.retryDelayMultiplier,maxTimeout:this.retryOptions.maxRetryDelay*1e3,maxRetryTime:this.retryOptions.totalTimeout*1e3});return this.uri=s,this.offset=0,this.emit("uri",s),s}async continueUploading(){var t;return(t=this.offset)!==null&&t!==void 0||await this.getAndSetOffset(),this.startUploading()}async startUploading(){let t=!!this.chunkSize,n=!1;if(this.numChunksReadInRequest=0,this.offset||(this.offset=0),this.offset<this.numBytesWritten){let c=this.numBytesWritten-this.offset,l=`The offset is lower than the number of bytes written. The server has ${this.offset} bytes and while ${this.numBytesWritten} bytes has been uploaded - thus ${c} bytes are missing. Stopping as this could result in data loss. Initiate a new upload to continue.`;this.emit("error",new RangeError(l));return}if(this.numBytesWritten<this.offset){let c=this.offset-this.numBytesWritten;for await(let l of this.upstreamIterator(c));this.numBytesWritten=this.offset}let i;typeof this.contentLength=="number"&&(i=this.contentLength-this.numBytesWritten),this.chunkSize&&(i=i?Math.min(this.chunkSize,i):this.chunkSize);let o=this.upstreamIterator(i),s=new ton.Readable({read:async()=>{n&&s.push(null);let c=await o.next();c.value&&(this.numChunksReadInRequest++,t?w9(this,Lfe,"m",Zin).call(this,c.value):(w9(this,Lfe,"m",Ujt).call(this),w9(this,Lfe,"m",Zin).call(this,c.value)),this.numBytesWritten+=c.value.byteLength,this.emit("progress",{bytesWritten:this.numBytesWritten,contentLength:this.contentLength}),s.push(c.value)),c.done&&s.push(null)}}),a=`${Gne()} gccl/${HFs.version}-${ORe()} gccl-invocation-id/${this.currentInvocationId.chunk}`;w9(this,kfe,"f")&&(a+=` gccl-gcs-cmd/${w9(this,kfe,"f")}`);let u={"User-Agent":Hne(),"x-goog-api-client":a};if(t){for await(let h of this.upstreamIterator(i))w9(this,Lfe,"m",Zin).call(this,h);let c=this.localWriteCacheByteLength,l=!await this.waitForNextChunk();this.prependLocalBufferToUpstream();let d=this.contentLength;typeof this.contentLength!="number"&&l&&!this.isPartialUpload&&(d=c+this.numBytesWritten);let f=c+this.numBytesWritten-1;u["Content-Length"]=c,u["Content-Range"]=`bytes ${this.offset}-${f}/${d}`}else u["Content-Range"]=`bytes ${this.offset}-*/${this.contentLength}`;let p={method:"PUT",url:this.uri,headers:u,body:s};try{let c=await this.makeRequestStream(p);c&&(n=!0,await this.responseHandler(c))}catch(c){let l=c;if(this.retryOptions.retryableErrorFn(l)){this.attemptDelayedRetry({status:NaN,data:l});return}this.destroy(l)}}async responseHandler(t){if(t.data.error){this.destroy(t.data.error);return}this.currentInvocationId.chunk=kk();let n=await this.waitForNextChunk(),i=this.chunkSize&&t.status===Xin&&t.headers.range&&n,o=this.isPartialUpload&&t.status===Xin&&!n;if(i){let s=t.headers.range;this.offset=Number(s.split("-")[1])+1;let a=this.numBytesWritten-this.offset;a?(this.prependLocalBufferToUpstream(a),this.numBytesWritten-=a):w9(this,Lfe,"m",Ujt).call(this),this.continueUploading()}else if(!this.isSuccessfulResponse(t.status)&&!o){let s=new Error("Upload failed");s.code=t.status,s.name="Upload failed",t?.data&&(s.errors=[t?.data]),this.destroy(s)}else w9(this,Lfe,"m",Ujt).call(this),t&&t.data&&(t.data.size=Number(t.data.size)),this.emit("metadata",t.data),this.emit("uploadFinished")}async checkUploadStatus(t={}){let n=`${Gne()} gccl/${HFs.version}-${ORe()} gccl-invocation-id/${this.currentInvocationId.checkUploadStatus}`;w9(this,kfe,"f")&&(n+=` gccl-gcs-cmd/${w9(this,kfe,"f")}`);let i={method:"PUT",url:this.uri,headers:{"Content-Length":0,"Content-Range":"bytes */*","User-Agent":Hne(),"x-goog-api-client":n}};try{let o=await this.makeRequest(i);return this.currentInvocationId.checkUploadStatus=kk(),o}catch(o){if(t.retry===!1||!(o instanceof Error)||!this.retryOptions.retryableErrorFn(o))throw o;let s=this.getRetryDelay();if(s<=0)throw o;return await new Promise(a=>setTimeout(a,s)),this.checkUploadStatus(t)}}async getAndSetOffset(){try{let t=await this.checkUploadStatus({retry:!1});if(t.status===Xin&&typeof t.headers.range=="string"){this.offset=Number(t.headers.range.split("-")[1])+1;return}this.offset=0}catch(t){let n=t;if(this.retryOptions.retryableErrorFn(n)){this.attemptDelayedRetry({status:NaN,data:n});return}this.destroy(n)}}async makeRequest(t){this.encryption&&(t.headers=t.headers||{},t.headers["x-goog-encryption-algorithm"]="AES256",t.headers["x-goog-encryption-key"]=this.encryption.key.toString(),t.headers["x-goog-encryption-key-sha256"]=this.encryption.hash.toString()),this.userProject&&(t.params=t.params||{},t.params.userProject=this.userProject),t.validateStatus=o=>this.isSuccessfulResponse(o)||o===Xin;let n={...this.customRequestOptions,...t,headers:{...this.customRequestOptions.headers,...t.headers}},i=await this.authClient.request(n);if(i.data&&i.data.error)throw i.data.error;return i}async makeRequestStream(t){let n=new GXp.default,i=()=>n.abort();this.once("error",i),this.userProject&&(t.params=t.params||{},t.params.userProject=this.userProject),t.signal=n.signal,t.validateStatus=()=>!0;let o={...this.customRequestOptions,...t,headers:{...this.customRequestOptions.headers,...t.headers}},s=await this.authClient.request(o),a=this.onResponse(s);return this.removeListener("error",i),a?s:null}onResponse(t){return t.status!==200&&this.retryOptions.retryableErrorFn({code:t.status,message:t.statusText,name:t.statusText})?(this.attemptDelayedRetry(t),!1):(this.emit("response",t),!0)}attemptDelayedRetry(t){if(this.numRetries<this.retryOptions.maxRetries){if(t.status===F_m&&this.numChunksReadInRequest===0)this.startUploading();else{let n=this.getRetryDelay();if(n<=0){this.destroy(new Error(`Retry total time limit exceeded - ${t.data}`));return}this.numBytesWritten-=this.localWriteCacheByteLength,this.prependLocalBufferToUpstream(),this.offset=void 0,setTimeout(this.continueUploading.bind(this),n)}this.numRetries++}else this.destroy(new Error("Retry limit exceeded - "+t.data))}getRetryDelay(){let t=Math.round(Math.random()*1e3),n=Math.pow(this.retryOptions.retryDelayMultiplier,this.numRetries)*1e3+t,i=this.retryOptions.totalTimeout*1e3-(Date.now()-this.timeOfFirstRequest),o=this.retryOptions.maxRetryDelay*1e3;return Math.min(n,o,i)}sanitizeEndpoint(t){return U_m.test(t)||(t=`https://${t}`),t.replace(/\/+$/,"")}isSuccessfulResponse(t){return t>=200&&t<300}};kfe=new WeakMap,Lfe=new WeakSet,Ujt=function(){this.localWriteCache=[],this.localWriteCacheByteLength=0},Zin=function(t){this.localWriteCache.push(t),this.localWriteCacheByteLength+=t.byteLength};function KXp(r){return new eon(r)}function YXp(r,t){let n=new eon(r);if(!t)return n.createURI();n.createURI().then(i=>t(null,i),t)}var O1t=require("stream"),aon=yt(require("zlib"),1);var $Xp=yt(require("crypto"),1),VFs=yt(require("url"),1);var zjt;(function(r){r.ACCESSIBLE_DATE_INVALID="The accessible at date provided was invalid.",r.EXPIRATION_BEFORE_ACCESSIBLE_DATE="An expiration date cannot be before accessible date.",r.X_GOOG_CONTENT_SHA256="The header X-Goog-Content-SHA256 must be a hexadecimal string."})(zjt||(zjt={}));var Q_m="v2",JXp=10080*60;var R1t=class{constructor(t,n,i,o=new Xz){this.auth=t,this.bucket=n,this.file=i,this.storage=o}getSignedUrl(t){let n=this.parseExpires(t.expires),i=t.method,o=this.parseAccessibleAt(t.accessibleAt);if(n<o)throw new Error(zjt.EXPIRATION_BEFORE_ACCESSIBLE_DATE);let s,a=t.virtualHostedStyle||!1;t.cname?s=t.cname:a&&(s=`https://${this.bucket.name}.storage.${this.storage.universeDomain}`);let u=1e3,p=Object.assign({},t,{method:i,expiration:n,accessibleAt:new Date(u*o),bucket:this.bucket.name,file:this.file?qjt(this.file.name,!1):void 0});s&&(p.cname=s);let c=t.version||Q_m,l;if(c==="v2")l=this.getSignedUrlV2(p);else if(c==="v4")l=this.getSignedUrlV4(p);else throw new Error(`Invalid signed URL version: ${c}. Supported versions are 'v2' and 'v4'.`);return l.then(d=>{var f;d=Object.assign(d,t.queryParams);let h=new VFs.URL(((f=t.host)===null||f===void 0?void 0:f.toString())||p.cname||this.storage.apiEndpoint);return h.pathname=this.getResourcePath(!!p.cname,this.bucket.name,p.file),h.search=NXp(d),h.href})}getSignedUrlV2(t){let n=this.getCanonicalHeaders(t.extensionHeaders||{}),i=this.getResourcePath(!1,t.bucket,t.file),o=[t.method,t.contentMd5||"",t.contentType||"",t.expiration,n+i].join(`
|
|
10535
10535
|
`);return(async()=>{var a;let u=this.auth;try{let p=await u.sign(o,(a=t.signingEndpoint)===null||a===void 0?void 0:a.toString());return{GoogleAccessId:(await u.getCredentials()).client_email,Expires:t.expiration,Signature:p}}catch(p){let c=p,l=new W9e(c.message);throw l.stack=c.stack,l}})()}getSignedUrlV4(t){var n;t.accessibleAt=t.accessibleAt?t.accessibleAt:new Date;let i=1/1e3,o=t.expiration-t.accessibleAt.valueOf()*i;if(o>JXp)throw new Error(`Max allowed expiration is seven days (${JXp} seconds).`);let s=Object.assign({},t.extensionHeaders),a=new VFs.URL(((n=t.host)===null||n===void 0?void 0:n.toString())||t.cname||this.storage.apiEndpoint);s.host=a.hostname,t.contentMd5&&(s["content-md5"]=t.contentMd5),t.contentType&&(s["content-type"]=t.contentType);let u,p=s["x-goog-content-sha256"];if(p){if(typeof p!="string"||!/[A-Fa-f0-9]{40}/.test(p))throw new Error(zjt.X_GOOG_CONTENT_SHA256);u=p}let c=Object.keys(s).map(A=>A.toLowerCase()).sort().join(";"),l=this.getCanonicalHeaders(s),f=`${G9e(t.accessibleAt)}/auto/storage/goog4_request`;return(async()=>{var A;let v=`${(await this.auth.getCredentials()).client_email}/${f}`,T=G9e(t.accessibleAt?t.accessibleAt:new Date,!0),w={"X-Goog-Algorithm":"GOOG4-RSA-SHA256","X-Goog-Credential":v,"X-Goog-Date":T,"X-Goog-Expires":o.toString(10),"X-Goog-SignedHeaders":c,...t.queryParams||{}},N=this.getCanonicalQueryParams(w),k=this.getCanonicalRequest(t.method,this.getResourcePath(!!t.cname,t.bucket,t.file),N,l,c,u),L=$Xp.createHash("sha256").update(k).digest("hex"),q=["GOOG4-RSA-SHA256",T,f,L].join(`
|
|
@@ -10633,12 +10633,12 @@ ${d.indent}`:""}${bbd(l)}:${u.indent?" ":""}`;return a=!1,c=!0,u.objectItem=void
|
|
|
10633
10633
|
`).map(b$b).filter(Boolean);t||n.sort(function(o,s){let a=o.split("."),u=s.split(".");if(a.length===1||u.length===1)return y$b(zto(a[0]),zto(u[0]));for(let p=0,c=Math.max(a.length,u.length);p<c;p++){let l=SCd(zto(a[p]),zto(u[p]));if(l)return l}return 0});let i=t?n[0]:[...n].reverse().find(o=>o.indexOf(".")>=0);return new yEd(n,i)}}}),TCd={};iv(TCd,{addAnnotatedTagTask:()=>v$b,addTagTask:()=>S$b,tagListTask:()=>C$b});function C$b(r=[]){let t=r.some(n=>/^--sort=/.test(n));return{format:"utf-8",commands:["tag","-l",...r],parser(n){return vCd(n,t)}}}function S$b(r){return{format:"utf-8",commands:["tag",r],parser(){return{name:r}}}}function v$b(r,t){return{format:"utf-8",commands:["tag","-a","-m",t,r],parser(){return{name:r}}}}var T$b=No({"src/lib/tasks/tag.ts"(){"use strict";E$b()}}),_$b=QKb({"src/git.js"(r,t){"use strict";var{GitExecutor:n}=(RYb(),UC(m2d)),{SimpleGitApi:i}=(_Jb(),UC($2d)),{Scheduler:o}=(IJb(),UC(X2d)),{configurationErrorTask:s}=(rv(),UC(hKa)),{asArray:a,filterArray:u,filterPrimitives:p,filterString:c,filterStringOrStringArray:l,filterType:d,getTrailingOptions:f,trailingFunctionArgument:h,trailingOptionsArgument:A}=(Kc(),UC(zEd)),{applyPatchTask:E}=(OJb(),UC(tCd)),{branchTask:v,branchLocalTask:T,deleteBranchesTask:w,deleteBranchTask:N}=(FJb(),UC(aCd)),{checkIgnoreTask:k}=(QJb(),UC(lCd)),{checkIsRepoTask:L}=(HEd(),UC(QEd)),{cloneTask:q,cloneMirrorTask:G}=(HJb(),UC(pCd)),{cleanWithOptionsTask:H,isCleanOptionsArray:V}=(r2d(),UC(e2d)),{diffSummaryTask:W}=(QKa(),UC(M2d)),{fetchTask:F}=(JJb(),UC(hCd)),{moveTask:J}=(e$b(),UC(ACd)),{pullTask:Y}=(r$b(),UC(mCd)),{pushTagsTask:z}=(H2d(),UC(G2d)),{addRemoteTask:X,getRemotesTask:Z,listRemotesTask:re,remoteTask:oe,removeRemoteTask:ee}=(p$b(),UC(bCd)),{getResetMode:ce,resetTask:de}=(h2d(),UC(p2d)),{stashListTask:pe}=(f$b(),UC(ECd)),{addSubModuleTask:le,initSubModuleTask:Ne,subModuleTask:Qe,updateSubModuleTask:Ee}=(m$b(),UC(CCd)),{addAnnotatedTagTask:_e,addTagTask:tt,tagListTask:b}=(T$b(),UC(TCd)),{straightThroughBufferTask:R,straightThroughStringTask:O}=(rv(),UC(hKa));function j(Te,De){this._plugins=De,this._executor=new n(Te.baseDir,new o(Te.maxConcurrentProcesses),De),this._trimmed=Te.trimmed}(j.prototype=Object.create(i.prototype)).constructor=j,j.prototype.customBinary=function(Te){return this._plugins.reconfigure("binary",Te),this},j.prototype.env=function(Te,De){return arguments.length===1&&typeof Te=="object"?this._executor.env=Te:(this._executor.env=this._executor.env||{})[Te]=De,this},j.prototype.stashList=function(Te){return this._runTask(pe(A(arguments)||{},u(Te)&&Te||[]),h(arguments))};function Ae(Te,De,y,I){return typeof y!="string"?s(`git.${Te}() requires a string 'repoPath'`):De(y,d(I,c),f(arguments))}j.prototype.clone=function(){return this._runTask(Ae("clone",q,...arguments),h(arguments))},j.prototype.mirror=function(){return this._runTask(Ae("mirror",G,...arguments),h(arguments))},j.prototype.mv=function(Te,De){return this._runTask(J(Te,De),h(arguments))},j.prototype.checkoutLatestTag=function(Te){var De=this;return this.pull(function(){De.tags(function(y,I){De.checkout(I.latest,Te)})})},j.prototype.pull=function(Te,De,y,I){return this._runTask(Y(d(Te,c),d(De,c),f(arguments)),h(arguments))},j.prototype.fetch=function(Te,De){return this._runTask(F(d(Te,c),d(De,c),f(arguments)),h(arguments))},j.prototype.silent=function(Te){return console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"),this},j.prototype.tags=function(Te,De){return this._runTask(b(f(arguments)),h(arguments))},j.prototype.rebase=function(){return this._runTask(O(["rebase",...f(arguments)]),h(arguments))},j.prototype.reset=function(Te){return this._runTask(de(ce(Te),f(arguments)),h(arguments))},j.prototype.revert=function(Te){let De=h(arguments);return typeof Te!="string"?this._runTask(s("Commit must be a string"),De):this._runTask(O(["revert",...f(arguments,0,!0),Te]),De)},j.prototype.addTag=function(Te){let De=typeof Te=="string"?tt(Te):s("Git.addTag requires a tag name");return this._runTask(De,h(arguments))},j.prototype.addAnnotatedTag=function(Te,De){return this._runTask(_e(Te,De),h(arguments))},j.prototype.deleteLocalBranch=function(Te,De,y){return this._runTask(N(Te,typeof De=="boolean"?De:!1),h(arguments))},j.prototype.deleteLocalBranches=function(Te,De,y){return this._runTask(w(Te,typeof De=="boolean"?De:!1),h(arguments))},j.prototype.branch=function(Te,De){return this._runTask(v(f(arguments)),h(arguments))},j.prototype.branchLocal=function(Te){return this._runTask(T(),h(arguments))},j.prototype.raw=function(Te){let De=!Array.isArray(Te),y=[].slice.call(De?arguments:Te,0);for(let P=0;P<y.length&&De;P++)if(!p(y[P])){y.splice(P,y.length-P);break}y.push(...f(arguments,0,!0));var I=h(arguments);return y.length?this._runTask(O(y,this._trimmed),I):this._runTask(s("Raw: must supply one or more command to execute"),I)},j.prototype.submoduleAdd=function(Te,De,y){return this._runTask(le(Te,De),h(arguments))},j.prototype.submoduleUpdate=function(Te,De){return this._runTask(Ee(f(arguments,!0)),h(arguments))},j.prototype.submoduleInit=function(Te,De){return this._runTask(Ne(f(arguments,!0)),h(arguments))},j.prototype.subModule=function(Te,De){return this._runTask(Qe(f(arguments)),h(arguments))},j.prototype.listRemote=function(){return this._runTask(re(f(arguments)),h(arguments))},j.prototype.addRemote=function(Te,De,y){return this._runTask(X(Te,De,f(arguments)),h(arguments))},j.prototype.removeRemote=function(Te,De){return this._runTask(ee(Te),h(arguments))},j.prototype.getRemotes=function(Te,De){return this._runTask(Z(Te===!0),h(arguments))},j.prototype.remote=function(Te,De){return this._runTask(oe(f(arguments)),h(arguments))},j.prototype.tag=function(Te,De){let y=f(arguments);return y[0]!=="tag"&&y.unshift("tag"),this._runTask(O(y),h(arguments))},j.prototype.updateServerInfo=function(Te){return this._runTask(O(["update-server-info"]),h(arguments))},j.prototype.pushTags=function(Te,De){let y=z({remote:d(Te,c)},f(arguments));return this._runTask(y,h(arguments))},j.prototype.rm=function(Te){return this._runTask(O(["rm","-f",...a(Te)]),h(arguments))},j.prototype.rmKeepLocal=function(Te){return this._runTask(O(["rm","--cached",...a(Te)]),h(arguments))},j.prototype.catFile=function(Te,De){return this._catFile("utf-8",arguments)},j.prototype.binaryCatFile=function(){return this._catFile("buffer",arguments)},j.prototype._catFile=function(Te,De){var y=h(De),I=["cat-file"],P=De[0];if(typeof P=="string")return this._runTask(s("Git.catFile: options must be supplied as an array of strings"),y);Array.isArray(P)&&I.push.apply(I,P);let g=Te==="buffer"?R(I):O(I);return this._runTask(g,y)},j.prototype.diff=function(Te,De){let y=c(Te)?s("git.diff: supplying options as a single string is no longer supported, switch to an array of strings"):O(["diff",...f(arguments)]);return this._runTask(y,h(arguments))},j.prototype.diffSummary=function(){return this._runTask(W(f(arguments,1)),h(arguments))},j.prototype.applyPatch=function(Te){let De=l(Te)?E(a(Te),f([].slice.call(arguments,1))):s("git.applyPatch requires one or more string patches as the first argument");return this._runTask(De,h(arguments))},j.prototype.revparse=function(){let Te=["rev-parse",...f(arguments,!0)];return this._runTask(O(Te,!0),h(arguments))},j.prototype.clean=function(Te,De,y){let I=V(Te),P=I&&Te.join("")||d(Te,c)||"",g=f([].slice.call(arguments,I?1:0));return this._runTask(H(P,g),h(arguments))},j.prototype.exec=function(Te){let De={commands:[],format:"utf-8",parser(){typeof Te=="function"&&Te()}};return this._runTask(De)},j.prototype.clearQueue=function(){return this},j.prototype.checkIgnore=function(Te,De){return this._runTask(k(a(d(Te,l,[]))),h(arguments))},j.prototype.checkIsRepo=function(Te,De){return this._runTask(L(d(Te,c)),h(arguments))},t.exports=j}});bWt();vwe();var I$b=class extends khe{constructor(r,t){super(void 0,t),this.config=r}};vwe();vwe();var Lhe=class extends khe{constructor(r,t,n){super(r,n),this.task=r,this.plugin=t,Object.setPrototypeOf(this,new.target.prototype)}};Umt();_Ed();HEd();r2d();o2d();a2d();l2d();h2d();function R$b(r){return r?[{type:"spawn.before",action(i,o){r.aborted&&o.kill(new Lhe(void 0,"abort","Abort already signaled"))}},{type:"spawn.after",action(i,o){function s(){o.kill(new Lhe(void 0,"abort","Abort signal received"))}r.addEventListener("abort",s),o.spawned.on("close",()=>r.removeEventListener("abort",s))}}]:void 0}function O$b(r){return typeof r=="string"&&r.trim().toLowerCase()==="-c"}function w$b(r,t){if(O$b(r)&&/^\s*protocol(.[a-z]+)?.allow/.test(t))throw new Lhe(void 0,"unsafe","Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol")}function M$b(r,t){if(/^\s*--(upload|receive)-pack/.test(r))throw new Lhe(void 0,"unsafe","Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack");if(t==="clone"&&/^\s*-u\b/.test(r))throw new Lhe(void 0,"unsafe","Use of clone with option -u is not permitted without enabling allowUnsafePack");if(t==="push"&&/^\s*--exec\b/.test(r))throw new Lhe(void 0,"unsafe","Use of push with option --exec is not permitted without enabling allowUnsafePack")}function x$b({allowUnsafeProtocolOverride:r=!1,allowUnsafePack:t=!1}={}){return{type:"spawn.args",action(n,i){return n.forEach((o,s)=>{let a=s<n.length?n[s+1]:"";r||w$b(o,a),t||M$b(o,i.method)}),n}}}Kc();function P$b(r){let t=AWt(r,"-c");return{type:"spawn.args",action(n){return[...t,...n]}}}Kc();var bEd=(0,qmt.deferred)().promise;function N$b({onClose:r=!0,onExit:t=50}={}){function n(){let o=-1,s={close:(0,qmt.deferred)(),closeTimeout:(0,qmt.deferred)(),exit:(0,qmt.deferred)(),exitTimeout:(0,qmt.deferred)()},a=Promise.race([r===!1?bEd:s.closeTimeout.promise,t===!1?bEd:s.exitTimeout.promise]);return i(r,s.close,s.closeTimeout),i(t,s.exit,s.exitTimeout),{close(u){o=u,s.close.done()},exit(u){o=u,s.exit.done()},get exitCode(){return o},result:a}}function i(o,s,a){o!==!1&&(o===!0?s.promise:s.promise.then(()=>lKa(o))).then(a.done)}return{type:"spawn.after",action(o,s){return hWt(this,arguments,function*(a,{spawned:u,close:p}){var c,l;let d=n(),f=!0,h=()=>{f=!1};(c=u.stdout)==null||c.on("data",h),(l=u.stderr)==null||l.on("data",h),u.on("error",h),u.on("close",A=>d.close(A)),u.on("exit",A=>d.exit(A));try{yield d.result,f&&(yield lKa(50)),p(d.exitCode)}catch(A){p(d.exitCode,A)}})}}}Kc();var D$b="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",EEd="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function B$b(r){return!r||!/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(r)}function CEd(r,t){if(r.length<1||r.length>2)throw new Lhe(void 0,"binary",D$b);if(r.some(B$b))if(t)console.warn(EEd);else throw new Lhe(void 0,"binary",EEd);let[i,o]=r;return{binary:i,prefix:o}}function L$b(r,t=["git"],n=!1){let i=CEd(iae(t),n);r.on("binary",o=>{i=CEd(iae(o),n)}),r.append("spawn.binary",()=>i.binary),r.append("spawn.args",o=>i.prefix?[i.prefix,...o]:o)}vwe();function k$b(r){return!!(r.exitCode&&r.stdErr.length)}function q$b(r){return Buffer.concat([...r.stdOut,...r.stdErr])}function F$b(r=!1,t=k$b,n=q$b){return(i,o)=>!r&&i||!t(o)?i:n(o)}function SEd(r){return{type:"task.error",action(t,n){let i=r(t.error,{stdErr:n.stdErr,stdOut:n.stdOut,exitCode:n.exitCode});return Buffer.isBuffer(i)?{error:new khe(void 0,i.toString("utf-8"))}:{error:i}}}}Kc();var U$b=class{constructor(){this.plugins=new Set,this.events=new _Cd.EventEmitter}on(r,t){this.events.on(r,t)}reconfigure(r,t){this.events.emit(r,t)}append(r,t){let n=i1(this.plugins,{type:r,action:t});return()=>this.plugins.delete(n)}add(r){let t=[];return iae(r).forEach(n=>n&&this.plugins.add(i1(t,n))),()=>{t.forEach(n=>this.plugins.delete(n))}}exec(r,t,n){let i=t,o=Object.freeze(Object.create(n));for(let s of this.plugins)s.type===r&&(i=s.action(i,o));return i}};Kc();function z$b(r){let t="--progress",n=["checkout","clone","fetch","pull","push"];return[{type:"spawn.args",action(s,a){return n.includes(a.method)?xEd(s,t):s}},{type:"spawn.after",action(s,a){var u;a.commands.includes(t)&&((u=a.spawned.stderr)==null||u.on("data",p=>{let c=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(p.toString("utf8"));c&&r({method:a.method,stage:Q$b(c[1]),progress:Sb(c[2]),processed:Sb(c[3]),total:Sb(c[4])})}))}}]}function Q$b(r){return String(r.toLowerCase().split(" ",1))||"unknown"}Kc();function j$b(r){let t=DEd(r,["uid","gid"]);return{type:"spawn.options",action(n){return ZQ(ZQ({},t),n)}}}function G$b({block:r,stdErr:t=!0,stdOut:n=!0}){if(r>0)return{type:"spawn.after",action(i,o){var s,a;let u;function p(){u&&clearTimeout(u),u=setTimeout(l,r)}function c(){var d,f;(d=o.spawned.stdout)==null||d.off("data",p),(f=o.spawned.stderr)==null||f.off("data",p),o.spawned.off("exit",c),o.spawned.off("close",c),u&&clearTimeout(u)}function l(){c(),o.kill(new Lhe(void 0,"timeout","block timeout reached"))}n&&((s=o.spawned.stdout)==null||s.on("data",p)),t&&((a=o.spawned.stderr)==null||a.on("data",p)),o.spawned.on("exit",c),o.spawned.on("close",c),p()}}}bWt();function H$b(){return{type:"spawn.args",action(r){let t=[],n;function i(o){(n=n||[]).push(...o)}for(let o=0;o<r.length;o++){let s=r[o];if(Vto(s)){i(Vbd(s));continue}if(s==="--"){i(r.slice(o+1).flatMap(a=>Vto(a)&&Vbd(a)||a));break}t.push(s)}return n?[...t,"--",...n.map(String)]:t}}}Kc();var V$b=_$b();function ICd(r,t){var n;let i=new U$b,o=FEd(r&&(typeof r=="string"?{baseDir:r}:r)||{},t);if(!TKa(o.baseDir))throw new I$b(o,"Cannot use simple-git on a directory that does not exist");return Array.isArray(o.config)&&i.add(P$b(o.config)),i.add(x$b(o.unsafe)),i.add(H$b()),i.add(N$b(o.completion)),o.abort&&i.add(R$b(o.abort)),o.progress&&i.add(z$b(o.progress)),o.timeout&&i.add(G$b(o.timeout)),o.spawnOptions&&i.add(j$b(o.spawnOptions)),i.add(SEd(F$b(!0))),o.errors&&i.add(SEd(o.errors)),L$b(i,o.binary,(n=o.unsafe)==null?void 0:n.allowUnsafeCustomBinary),new V$b(o,i)}Umt();var VK=ICd,RCd=ICd;var OCd=async r=>{let n=await RCd(r.dir).status(),{files:i}=n;return Je("CLI_INTERNAL").info("Found files with statuses: ",n),i.filter(s=>Ket(s.path)).map(s=>({name:s.path,status:W$b(s.working_dir),shouldCommit:!1})).filter(s=>s.status!=="unmodified")},W$b=r=>{switch(r){case"M":return"modified";case"?":return"untracked";case"A":return"added";case" ":case"":return"unmodified";case"D":return"deleted";case"R":return"renamed";default:return r}};var wCd=async(r,t,n)=>{let i={commit:{message:""},oid:""},o=!0;try{let s=await pJo(r);if(!s)throw new nt("No current git branch was found.");i.branch=s;let a=await lJo(r,s);if(!a)throw new nt("Could not retrieve head commit of current branch");let{commit:u,oid:p}=a;i.commit=u,i.oid=p;let c=await OCd(r);c.length&&(o=await pyd(c))}catch(s){i.oid||Je("CLI_INTERNAL").errorContext(n,"No head commit for current branch was found during CLI plan creation.",i,r,wOt(t)),Je("CLI_INTERNAL").errorContext(n,s)}if(!o)throw new qRe;return i};var K$b=5,xCd=r=>{let{branch:t,commit:{author:n,message:i},oid:o}=r,s=t?.trim()||"<unknown branch>",a=o.substring(0,8)||"<unknown commit>",u=i.trim()||"<no message>",p=n?.name.trim()||"<unknown author>",c=n?.timestamp?`${u_c(new Date(n.timestamp*1e3))} days ago`:"<unknown date>";eK("Git context"),gc(`Branch: ${s}`,4),gc(`Commit: ${u} (${a})`,4),gc(`Author: ${p}, ${c}`,4)},VKa=r=>{r.stop.length&&MCd(r.stop,"error"),r.warn.length&&MCd(r.warn,"warning")},MCd=(r,t)=>{eK(`${t==="error"?"Errors":"Warnings"} (${r.length})`),r.forEach((i,o)=>{Y$b(i,t),o<r.length-1&&cu()})},Y$b=(r,t)=>{(t==="error"?fT:Kd)(r.title),r.subtitle&&gc(r.subtitle,6);let{messages:i}=r,o=Yi.isVerbose?i.length:K$b,s=i.slice(0,o),a=i.length-s.length;for(let u of s)gc(`\u2022 ${u}`,6);a>0&&gc(`\u2026 ${a} more (use --verbose to see all)`,6)};var KKa={name:"plan",description:"Diff workspace state against deployed state",category:"cloud",options:{...dK,...Jfe,include:{flag:"--include <selector>",description:"Coalesce Node Selector",hidden:!0},exclude:{flag:"--exclude <selector>",description:"Coalesce Node Selector",hidden:!0},jobID:{flag:"--jobID <value>",description:"Coalesce JobID",hidden:!0},parallelism:{flag:"--parallelism <value>",description:"Parallelism level to use",hidden:!0},parameters:{flag:"--parameters <value>",description:"Parameters"},dir:{flag:"-d, --dir <dir>",description:"Coalesce pipeline Yaml file path",default:"."},out:{flag:"--out <plan-location>",description:"Coalesce plan location",default:"./coa-plan.json"},gitsha:{flag:"--gitsha <sha>",description:"Sets the git commit SHA shown in the plan manifest and UI. This does not affect which files are used\u2014those come from the current directory or are set with the --dir parameter."},enableCache:{flag:"--enableCache",description:"Enable caching to improve deploy plan generation times. Coalesce recommends keeping caching disabled unless you\u2019re experiencing very long plan generation times.",default:!1},disablePresync:{flag:"--disablePresync",description:"Disable presync",hidden:!0},clearTargetEnvironment:{flag:"--clearTargetEnvironment",description:"Clear target environment",hidden:!0}}},sro=async r=>{Jf(r,KKa).action((t,n)=>Fg(n,"Plan",i=>B9(i,NCd)))},NCd=async(r,t,n,i)=>{let o="[PlanRunner]",{runDetails:{environmentID:s},runtimeParameters:a,token:u,userCredentials:p}=t,c=parseInt(s),{teamInfo:{fbTeamID:l,fbUserID:d},rootRepository:f,userPermissions:h,featureFlags:A}=r,{measure:E,printSummary:v}=Bf(o,i),T=f.org(l),w=T.workspace(c),{devEnv:N,project:k}=await w.fetch();if(h.throwIfEnvironmentPermissionDenied("env-deploy",k,c),N)throw new nt(nol);await Tbe(w.workspaceUser(d),t.userCredentials);let L=n.dir;if(L&&WKa.existsSync(PCd.join(L,R1))){let pe=await JQ({dir:L,tolerateLoadFailures:!0},i);QK(pe,{command:"plan",logContext:i,logTag:o})}let q=n.disablePresync,G=!!n.clearTargetEnvironment,H=n.gitsha,V=n.jobID,W=n.out,F=n.parallelism,J=n.parameters,Y=n.profile,z=n.snowflakeAuthType,X=!!n.enableCache,Z={environmentID:c,gitsha:H,jobID:V,parallelism:F,parameters:J,profile:Y,snowflakeAuthType:z};if(Je("CLI_INTERNAL").infoContext(i,o,"Planning with options:",Z),G)if(A.isFeatureEnabled("clearTargetEnvironment"))Je("CLI_INTERNAL").infoContext(i,o,"Planning with cleared target environment");else throw Je("CLI_INTERNAL").errorContext(i,o,"Got flag to plan with cleared target environment, but feature flag was disabled"),new nt("Got an unsupported parameter: --clearTargetEnvironment");let re=await BRe(f,l,c,a),oe=await Kfe(p),ee=await O9(f,l,d,+c,oe,i),ce={fs:WKa,dir:L},de;if(H)de={commit:{message:`Deploy to environment ${c}`},oid:H};else try{de=await wCd(ce,ee,i),de.commit.message||(de.commit.message=`Deploy to environment ${c}`),xCd(de),Je("CLI").infoContext(i,o,"Git context",{branch:de.branch||null,oid:de.oid,message:de.commit.message})}catch(pe){throw pe instanceof qRe&&Kd("Plan cancelled by user"),pe}try{let pe=await JW(ee,i,r.featureFlags),le=await E("gather workspace data",()=>O0l("CLI",l,c,T,new nW,pe.name,ce,null,u,i,G)),Ne={branchName:de.branch,disablePresync:q,platform:pe,skipPlanContextUpload:A.isFeatureEnabled("skipPlanContextUpload"),usePlanAPI:!1,useRenderCache:X,loadWarehouseComments:(await T.fetch())?.preferences?.descriptionsManagedExternally??!1},Qe=X?await E("acquire render cache",()=>Inn(c.toString(),i)):void 0,{plan:Ee,issues:_e}=await E("create plan",()=>P0l(Ne,Ux(A),Qe,l,c,d,re,le,f,null,i));_e.warn.length&&(VKa(_e),Je("CLI").warnContext(i,o,"Plan issues",_e));let{gitWorkspaceData:tt}=gol(Ee,le.currentWorkspaceData,le.desiredWorkspaceData,i),b={...Ee,environmentState:tt,gitInfo:de,runtimeParameters:JSON.stringify(re)};await vbd(W,b)}catch(pe){throw pe instanceof u2e&&(VKa(pe.issues),Je("CLI").errorContext(i,o,"Plan issues",pe.issues)),pe}finally{v()}};var YKa={name:"refresh",description:"Run DML for selected nodes in a deployed environment",category:"cloud",options:{...dK,...UWs,...Jfe,out:{flag:"-o, --out <output json>",description:"Run Results Output in Json "},forceIgnoreEnvironmentStatus:{flag:"--forceIgnoreEnvironmentStatus",description:"Ignore the environment status and refresh even if there is a failed deploy. This may cause refresh failures!"},forceIgnoreWorkspaceStatus:{flag:"--forceIgnoreWorkspaceStatus",description:"Deprecated: use forceIgnoreEnvironmentStatus",hidden:!0}}},JKa=r=>{Jf(r,YKa).action((t,n)=>Fg(n,"Refresh",i=>B9(i,wmt(J$b,"Refresh"))))},J$b=async(r,t,n,i)=>{let o="[RefreshRunner]",{featureFlags:s,teamInfo:{fbTeamID:a,fbUserID:u},userPermissions:p,rootRepository:c}=r,{runDetails:l,runDetails:{environmentID:d},runtimeParameters:f,userCredentials:h}=t,A=parseInt(d),E=await BRe(c,a,A,f),v=c.org(a).workspace(A),T=await v.fetch();p.throwIfEnvironmentPermissionDenied("env-refresh",T.project,T.id),await Tbe(v.workspaceUser(u),h),Je("CLI").appContext(i,o,"Making request");let w=new B0r({origin:"CLI",parameters:E,runDetails:{...l,forceIgnoreWorkspaceStatus:n.forceIgnoreWorkspaceStatus||n.forceIgnoreEnvironmentStatus},userCredentials:h});_M(w);let N=await Kfe(h),{runCounter:k,runCompletion:L}=await ded(w,r,N,Ux(s),i);return CG({...i,runID:k}),{runCompletion:L,runCounter:k}};var $Ka={name:"rerun",description:"Re-run a failed pipeline from the point of failure",category:"cloud",options:{...dK,...Jfe,include:{flag:"--include <selector>",description:"Coalesce Node Selector",hidden:!0},exclude:{flag:"--exclude <selector>",description:"Coalesce Node Selector",hidden:!0},jobID:{flag:"--jobID <value>",description:"Coalesce JobID",hidden:!0},parallelism:{flag:"--parallelism <value>",description:"Parallelism level to use",hidden:!0},parameters:{flag:"--parameters <value>",description:"Parameters"},out:{flag:"-o, --out <output json>",description:"Run Results Output in Json "},forceIgnoreEnvironmentStatus:{flag:"--forceIgnoreEnvironmentStatus",description:"Ignore the environment status and refresh even if there is a failed deploy. This may cause refresh failures!"},forceIgnoreWorkspaceStatus:{flag:"--forceIgnoreWorkspaceStatus",description:"Deprecated: use forceIgnoreEnvironmentStatus",hidden:!0}},args:[{name:"runID",description:"The ID of the failed refresh to re-run",required:!0}]},XKa=r=>{Jf(r,$Ka).action((t,n,i)=>Fg(i,"Re-run",o=>B9(o,wmt($$b(t),"Rerun"))))},$$b=r=>async(t,n,i,o)=>{let s="[ReRunRunner]",{featureFlags:a,rootRepository:u,userPermissions:p,teamInfo:{fbTeamID:c,fbUserID:l}}=t,{runDetails:{environmentID:d},runtimeParameters:f,userCredentials:h}=n,A=parseInt(d),E=u.org(c).workspace(A),v=await E.fetch();p.throwIfEnvironmentPermissionDenied("env-refresh",v.project,v.id),await Tbe(E.workspaceUser(l),h),Je("CLI").appContext(o,s,"Making request");let T=new TWe({origin:"CLI",parameters:f,runDetails:{forceIgnoreWorkspaceStatus:i.forceIgnoreWorkspaceStatus||i.forceIgnoreEnvironmentStatus,runID:r},userCredentials:h});if(!r.match(/^[0-9]+$/))throw new nt(`Could not convert old run ID ${r} to a number`);let w=parseInt(r),N;try{N=await u.org(c).run(w).fetch()}catch(G){throw G instanceof Du?new Vi(`Could not find runInfo for orgID=${c}, oldRunID=${w}`):G}let k=await Kfe(h),{runCounter:L,runCompletion:q}=await fed(T,N,t,k,Ux(a),o);return CG({...o,runID:L}),{runCounter:L,runCompletion:q}};var ZKa={name:"run",description:"Execute DML (insert/merge) for selected nodes",detailedDescription:"Execute RUN/DML operations on nodes. Populates tables by running the node's SQL template (INSERT, MERGE, etc.).",category:"local",options:{dir:{flag:"-d, --dir <dir>",description:"Coalesce pipeline Yaml file path",default:"."},include:{flag:"--include <selector>",description:`Node selector syntax (e.g., '{ ORDERS }+', '{ name: "CUSTOMER" }', '{ location: "SRC" }+')`},exclude:{flag:"--exclude <selector>",description:`Node selector syntax for excluding nodes (e.g., '{ TEST }', '{ location: "TEMP" }')`},...aB,listNodes:{flag:"--list-nodes",description:"List all available nodes (names and IDs) and exit"},dryRun:{flag:"--dry-run",description:"Preview which nodes would be affected without executing. Use --verbose to see generated SQL"}},examples:['coa run -d ./my-project --include "{ STG_ORDERS }"','coa run -d ./my-project --include "{ location: \\"STG\\" }" --dry-run --verbose',"coa run -d ./my-project --dry-run --json # batch validate all nodes"]},eYa=async r=>{Jf(r,ZKa).action((t,n)=>Fg(n,"Run",i=>IWa(i.optsWithGlobals,i.logContext),!0))};var fDd=require("node:child_process");var pDd=require("fs"),dDd=yt(require("path"));var nNd=require("child_process"),etu=yt(Dro()),iNd=yt(KPd()),ttu=yt(require("fs"));var oNd=yt(require("os")),S8=yt(require("path")),sNd=require("util");var YPd=require("child_process"),Dio=require("fs/promises"),Feu=yt(require("http")),XKt=yt(require("path"));var PFe=Je("COA_WATCH"),dEE=8400,fEE=8500,hEE=500,gEE=30,Nio=class{constructor(t){this.workspaceDir=t}workspaceDir;runningApps=new Map;usedPorts=new Set;getAppsDir(){return XKt.default.join(this.workspaceDir,"apps")}async allocatePort(){for(let t=dEE;t<=fEE;t++)if(!this.usedPorts.has(t)&&!await this.isPortInUse(t))return this.usedPorts.add(t),t;throw new Error("No available ports in range")}isPortInUse(t){return new Promise(n=>{let i=Feu.default.get(`http://localhost:${t}`,()=>n(!0));i.on("error",()=>n(!1)),i.setTimeout(200,()=>{i.destroy(),n(!1)})})}releasePort(t){this.usedPorts.delete(t)}async waitForPort(t){for(let n=0;n<gEE;n++)try{return await new Promise((i,o)=>{let s=Feu.default.get(`http://localhost:${t}`,()=>{i()});s.on("error",o),s.setTimeout(400,()=>{s.destroy(),o(new Error("timeout"))})}),!0}catch{await new Promise(i=>setTimeout(i,hEE))}return!1}async discoverAppDirs(){let t=this.getAppsDir(),n;try{n=await(0,Dio.readdir)(t)}catch{return[]}let i=[];for(let o of n){let s=XKt.default.join(t,o),a=XKt.default.join(s,"package.json");try{let u=await(0,Dio.readFile)(a,"utf-8"),p=JSON.parse(u);i.push({appId:o,name:p.name||o,description:p.description||"",dir:s})}catch{}}return i}async discoverApps(){return(await this.discoverAppDirs()).map(n=>({appId:n.appId,name:n.name,description:n.description}))}async startApp(t){let n=this.runningApps.get(t);if(n)return n;let o=(await this.discoverAppDirs()).find(c=>c.appId===t);if(!o)throw new Error(`App not found: ${t}`);let s=await this.allocatePort();PFe.info("[AppManager] Starting app",{appId:t,port:s,dir:o.dir});let a=(0,YPd.spawn)("npm",["start"],{cwd:o.dir,env:{...process.env,PORT:String(s),WORKSPACE_DIR:XKt.default.resolve(this.workspaceDir)},stdio:["ignore","pipe","pipe"],shell:!0}),u={appId:t,port:s,process:a};if(this.runningApps.set(t,u),a.stdout?.on("data",c=>{PFe.info(`[App:${t}] ${c.toString().trimEnd()}`)}),a.stderr?.on("data",c=>{PFe.warn(`[App:${t}] ${c.toString().trimEnd()}`)}),a.on("exit",c=>{PFe.info("[AppManager] App process exited",{appId:t,code:c}),this.runningApps.delete(t),this.releasePort(s)}),!await this.waitForPort(s))throw PFe.error("[AppManager] App failed to start within timeout",{appId:t,port:s}),new Error(`App ${t} failed to start within timeout`);return PFe.info("[AppManager] App is running",{appId:t,port:s}),u}async ensureRunning(t){return`http://localhost:${(await this.startApp(t)).port}`}shutdownAll(){for(let[t,n]of this.runningApps)PFe.info("[AppManager] Shutting down app",{appId:t,pid:n.process.pid}),n.process.kill("SIGTERM"),this.releasePort(n.port);this.runningApps.clear()}};function AEE(r){let t=r.type,n=JSON.stringify(r);return`event: ${t}
|
|
10634
10634
|
data: ${n}
|
|
10635
10635
|
|
|
10636
|
-
`}function Vwe(r,t){try{return r.write(AEE(t)),!0}catch{return!1}}var Ueu=r=>{let{id:t,fileVersion:n,type:i,...o}=r;return{...o,jobCounter:Number(t),id:Number(t),version:c$}},JPd=r=>{let{id:t,operation:n}=r;return{operation:{...n,id:t}}},$Pd=r=>{let{id:t,fileVersion:n,type:i,name:o,...s}=r;return{...s,id:t,version:gh}},XPd=r=>{let{type:t,id:n,fileVersion:i,...o}=r;return sTt.assert({id:n,...o,version:oTt})},zeu=r=>{let{nodeType:t,create:n,run:i}=r,{id:o,type:s,fileVersion:a,...u}=t,{defaultStorageLocation:p,nodeMetadataSpec:c}=u.metadata,l=p??null,d=a??gWe,f=c??"",h=AWe.parse({defaultStorageLocation:l,nodeMetadataSpec:f,error:null,templates:{create:{templateString:n||""},run:{templateString:i||""}}});return{...u,version:d,metadata:h,id:o}};var yEE=1,bEE=1,EEE=1,Qeu=r=>WH.parse({name:r.name??`Job ${r.id}`,includeSelector:r.includeSelector??"",excludeSelector:r.excludeSelector??"",id:r.id.toString(),type:"Job",fileVersion:bEE}),jeu=r=>{let t=r.operation,{id:n,name:i,...o}=t,s={id:n,name:i,operation:{...o,name:i},type:"Node",fileVersion:yEE};return _Z.parse(s)},ZPd=r=>TZ.parse({macroString:r.macroString??"",id:r.id,name:"macro",type:"Macro",fileVersion:EEE}),Geu=r=>{let t=new Set(r.steps?.map(n=>n.toString()));return IZ.parse({name:r.name??`Subgraph ${r.id}`,steps:Array.from(t).sort(),id:r.id,type:lxr,fileVersion:cxr})},e4d=r=>tbe.parse({fileVersion:xmr,type:Pmr,id:r.contents.packageID,name:r.alias,releaseID:r.contents.release.releaseID,packageID:r.contents.packageID,config:r.config}),Heu=r=>{let{isDisabled:t,name:n,version:i,id:o}=r,{templates:s,...a}=r.metadata;a.defaultStorageLocation===void 0&&(a.defaultStorageLocation=null),"error"in a||(a.error=null);let u=$Yo.assert(a),{templateString:p}=s.create,{templateString:c}=s.run;return{nodeType:{isDisabled:t,name:n,fileVersion:i??1,metadata:u,id:o,type:"NodeType"},create:p,run:c}};var Z4d=yt(Dro()),Zeu=yt($4d()),Uio=yt(require("fs")),eNd=yt(require("https")),tNd=yt(require("net")),tYt=yt(require("path"));var ZKt=Je("COA_WATCH"),eYt=null;function $eu(){eYt=null}async function Xeu(){if(eYt)return eYt;let r=Ufe("default"),t=0,n={orgID:zqe,userID:"cli",workspaceID:t},i=Dmt(r,zqe,t,n),o=new hv(rOe());return eYt=await JW(i,n,o),ZKt.info("[LocalSQL] Backend platform created",{platform:i.kind}),eYt}function X4d(r,t){r.post("/scheduler/run",async(n,i)=>{try{let{templateString:o,requestId:s}=n.body;if(!o){i.status(400).json({error:"templateString is required"});return}ZKt.info("[LocalSQL] Executing query",{requestId:s,sql:o.substring(0,200)});let u=await(await Xeu()).runSQL({sql:o,...s&&{overrideRequestID:s}});i.json(u)}catch(o){$eu();let s=
|
|
10636
|
+
`}function Vwe(r,t){try{return r.write(AEE(t)),!0}catch{return!1}}var Ueu=r=>{let{id:t,fileVersion:n,type:i,...o}=r;return{...o,jobCounter:Number(t),id:Number(t),version:c$}},JPd=r=>{let{id:t,operation:n}=r;return{operation:{...n,id:t}}},$Pd=r=>{let{id:t,fileVersion:n,type:i,name:o,...s}=r;return{...s,id:t,version:gh}},XPd=r=>{let{type:t,id:n,fileVersion:i,...o}=r;return sTt.assert({id:n,...o,version:oTt})},zeu=r=>{let{nodeType:t,create:n,run:i}=r,{id:o,type:s,fileVersion:a,...u}=t,{defaultStorageLocation:p,nodeMetadataSpec:c}=u.metadata,l=p??null,d=a??gWe,f=c??"",h=AWe.parse({defaultStorageLocation:l,nodeMetadataSpec:f,error:null,templates:{create:{templateString:n||""},run:{templateString:i||""}}});return{...u,version:d,metadata:h,id:o}};var yEE=1,bEE=1,EEE=1,Qeu=r=>WH.parse({name:r.name??`Job ${r.id}`,includeSelector:r.includeSelector??"",excludeSelector:r.excludeSelector??"",id:r.id.toString(),type:"Job",fileVersion:bEE}),jeu=r=>{let t=r.operation,{id:n,name:i,...o}=t,s={id:n,name:i,operation:{...o,name:i},type:"Node",fileVersion:yEE};return _Z.parse(s)},ZPd=r=>TZ.parse({macroString:r.macroString??"",id:r.id,name:"macro",type:"Macro",fileVersion:EEE}),Geu=r=>{let t=new Set(r.steps?.map(n=>n.toString()));return IZ.parse({name:r.name??`Subgraph ${r.id}`,steps:Array.from(t).sort(),id:r.id,type:lxr,fileVersion:cxr})},e4d=r=>tbe.parse({fileVersion:xmr,type:Pmr,id:r.contents.packageID,name:r.alias,releaseID:r.contents.release.releaseID,packageID:r.contents.packageID,config:r.config}),Heu=r=>{let{isDisabled:t,name:n,version:i,id:o}=r,{templates:s,...a}=r.metadata;a.defaultStorageLocation===void 0&&(a.defaultStorageLocation=null),"error"in a||(a.error=null);let u=$Yo.assert(a),{templateString:p}=s.create,{templateString:c}=s.run;return{nodeType:{isDisabled:t,name:n,fileVersion:i??1,metadata:u,id:o,type:"NodeType"},create:p,run:c}};var Z4d=yt(Dro()),Zeu=yt($4d()),Uio=yt(require("fs")),eNd=yt(require("https")),tNd=yt(require("net")),tYt=yt(require("path"));var ZKt=Je("COA_WATCH"),eYt=null;function $eu(){eYt=null}async function Xeu(){if(eYt)return eYt;let r=Ufe("default"),t=0,n={orgID:zqe,userID:"cli",workspaceID:t},i=Dmt(r,zqe,t,n),o=new hv(rOe());return eYt=await JW(i,n,o),ZKt.info("[LocalSQL] Backend platform created",{platform:i.kind}),eYt}function X4d(r,t){r.post("/scheduler/run",async(n,i)=>{try{let{templateString:o,requestId:s}=n.body;if(!o){i.status(400).json({error:"templateString is required"});return}ZKt.info("[LocalSQL] Executing query",{requestId:s,sql:o.substring(0,200)});let u=await(await Xeu()).runSQL({sql:o,...s&&{overrideRequestID:s}});i.json(u)}catch(o){$eu();let s=aa(o);ZKt.error("[LocalSQL] Query failed",{error:s.error.errorString}),i.status(500).json(s)}}),r.post("/scheduler/getDatabaseNames",async(n,i)=>{try{let s=await(await Xeu()).getDatabaseNames();i.json({databases:s})}catch(o){$eu();let s=o instanceof Error?o.message:String(o);ZKt.error("[LocalSQL] getDatabaseNames failed",{error:s}),i.status(500).json({error:s})}}),r.post("/scheduler/getSchemaNames",async(n,i)=>{try{let{database:o}=n.body;if(!o){i.status(400).json({error:"database is required"});return}let a=await(await Xeu()).getSchemaNames(o);i.json({schemas:a})}catch(o){$eu();let s=o instanceof Error?o.message:String(o);ZKt.error("[LocalSQL] getSchemaNames failed",{error:s}),i.status(500).json({error:s})}})}var Xhe=Je("COA_WATCH");function eCE(){return"<script>self.__COALESCE_LOCAL_MODE__=true</script>"}async function rNd(r,t){let{cloudDomain:n,refreshToken:i}=t;Xhe.debug("[ServeUI] Bootstrapping local auth...");let s=(await dc.get(`${n}/api/v1/database`)).data.apiKey,a=await dc.post(`https://securetoken.googleapis.com/v1/token?key=${s}`,{refresh_token:i,grant_type:"refresh_token"}),{id_token:u}=et.object({id_token:et.string()}).parse(a.data),c=(await XP(`${n}/scheduler/generateLoginToken`,{},u)).data.customToken;Xhe.debug("[ServeUI] Local auth bootstrapped successfully");let l=crypto.randomUUID(),d=!1;r.get("/api/v1/local/auth",(w,N)=>{let k=w.headers.authorization,L=k?.startsWith("Bearer ")?k.slice(7):void 0;if(Xhe.debug("[ServeUI] Auth request received",{hasAuthHeader:!!k,hasBearer:!!L,bearerMatches:L===l,nonceConsumed:d}),!L){Xhe.debug("[ServeUI] Auth rejected: missing or malformed Authorization bearer token"),N.status(401).json({error:"Unauthorized"});return}if(L!==l){Xhe.debug("[ServeUI] Auth rejected: nonce mismatch (stale login URL?)"),N.status(401).json({error:"Unauthorized"});return}if(d){Xhe.debug("[ServeUI] Auth rejected: nonce already consumed (page reloaded or re-requested)"),N.status(401).json({error:"Unauthorized"});return}d=!0,Xhe.debug("[ServeUI] Auth accepted: nonce valid, returning custom token"),N.json({customToken:c})}),X4d(r,n),r.use(["/api","/scheduler"],(0,Zeu.default)(n,{proxyReqPathResolver:w=>w.originalUrl}));let f=new URL(n);r.use("/git",(w,N)=>{let k=eNd.default.request({hostname:f.hostname,port:443,path:w.originalUrl,method:w.method,headers:{...w.headers,host:f.host}},L=>{N.writeHead(L.statusCode??502,L.headers),L.pipe(N)});k.on("error",L=>{Xhe.error("[ServeUI] Git proxy error",L),N.headersSent||N.status(502).json({error:"Git proxy failed"})}),w.pipe(k)});let h=tYt.default.join(__dirname,"web-ui"),A=Uio.default.existsSync(tYt.default.join(h,"index.html")),E=`<head>${eCE()}`;if(A)return r.get("/",(w,N)=>{let k=Uio.default.readFileSync(tYt.default.join(h,"index.html"),"utf-8");N.type("html").send(k.replace("<head>",E))}),r.use(Z4d.default.static(h)),r.get("*",(w,N)=>{let k=Uio.default.readFileSync(tYt.default.join(h,"index.html"),"utf-8");N.type("html").send(k.replace("<head>",E))}),{nonce:l};let v=3e3;return Xhe.debug("[ServeUI] No built UI found, proxying to Vite dev server",{vitePort:v}),r.use((0,Zeu.default)(`http://localhost:${v}`,{proxyReqPathResolver:w=>w.originalUrl,userResDecorator:(w,N,k)=>{if(k.headers.accept?.includes("text/html")){let L=N.toString("utf-8");if(L.includes("<head>"))return L.replace("<head>",E)}return k.url?.includes("@vite/client")?N.toString("utf-8").replace(/const socketProtocol = "[^"]*"/,'const socketProtocol = "ws"').replace(/const socketHost = [^;]+;/,`const socketHost = "localhost:${k.socket.localPort}/";`).replace(/const directSocketHost = "[^"]*";/,`const directSocketHost = "localhost:${k.socket.localPort}/";`):N}})),{nonce:l,onUpgrade:(w,N,k)=>{let L=tNd.default.createConnection(v,"localhost",()=>{let q=`${w.method} ${w.url} HTTP/${w.httpVersion}\r
|
|
10637
10637
|
`,G=w.rawHeaders.reduce((H,V,W)=>W%2===0?H+V+": ":H+V+`\r
|
|
10638
10638
|
`,"");L.write(q+G+`\r
|
|
10639
|
-
`),k.length>0&&L.write(new Uint8Array(k)),N.pipe(L).pipe(N)});L.on("error",()=>N.destroy()),N.on("error",()=>L.destroy())}}}var
|
|
10639
|
+
`),k.length>0&&L.write(new Uint8Array(k)),N.pipe(L).pipe(N)});L.on("error",()=>N.destroy()),N.on("error",()=>L.destroy())}}}var ca=Je("COA_WATCH"),tCE=(0,sNd.promisify)(nNd.execFile),zio=class{options;clients=new Map;keepaliveIntervals=new Map;httpServer=null;sequenceNumber=0;serverId="coa-watch";pathIndex=new Map;queue=[];processing=!1;chokidarChanges=new Set;chokidarDeletes=new Set;chokidarTimer=null;CHOKIDAR_DEBOUNCE_MS=300;MAX_CLIENT_BUFFER_SIZE=1e4;SNAPSHOT_THRESHOLD=200;appManager;constructor(t){this.options=t,this.appManager=new Nio(this.options.coordinator.getWorkspaceDir()),this.options.coordinator.onUpdate(n=>this.handleFileEvent(n))}async start(){let t=(0,etu.default)();t.use(etu.default.json({limit:"50mb"})),t.use(iNd.middleware({apiSpec:S8.default.join(__dirname,"openapi.yaml"),validateRequests:{allowUnknownQueryParameters:!0,removeAdditional:!0},validateResponses:!0,ignorePaths:this.options.serveUI?/^(?!\/api\/v1\/watch|\/api\/rescan)|^\/api\/v1\/watch\/apps/:/^(?!\/api)|^\/api\/v1\/watch\/apps/})),t.get("/health",(o,s)=>{s.json({status:"ok"})}),t.get("/api/v1/watch/stream",(o,s)=>this.handleSSEConnection(o,s)),t.post("/api/v1/watch/node/bulk",(o,s)=>this.handleBulkNodesWrite(o,s)),t.post("/api/v1/watch/node/:id",(o,s)=>this.handleNodeWrite(o,s)),t.post("/api/v1/watch/job",(o,s)=>this.handleJobCreate(o,s)),t.post("/api/v1/watch/job/:id",(o,s)=>this.handleJobUpdate(o,s)),t.post("/api/v1/watch/macro/:id",(o,s)=>this.handleMacroWrite(o,s)),t.post("/api/v1/watch/subgraph",(o,s)=>this.handleSubgraphCreate(o,s)),t.post("/api/v1/watch/subgraph/:id",(o,s)=>this.handleSubgraphUpdate(o,s)),t.post("/api/v1/watch/nodeType",(o,s)=>this.handleNodeTypeCreate(o,s)),t.post("/api/v1/watch/nodeType/:id",(o,s)=>this.handleNodeTypeUpdate(o,s)),t.post("/api/v1/watch/environment/:id",(o,s)=>this.handleEnvironmentWrite(o,s)),t.post("/api/v1/watch/package/:id",(o,s)=>this.handlePackageWrite(o,s)),t.post("/api/v2/node/:id",(o,s)=>this.handleNodeWriteV2(o,s)),t.post("/api/v1/watch/node/bulk/delete",(o,s)=>this.handleBulkNodesDelete(o,s)),t.delete("/api/v1/watch/node/:id",(o,s)=>this.handleDelete("Node",o,s)),t.delete("/api/v1/watch/job/:id",(o,s)=>this.handleDelete("Job",o,s)),t.delete("/api/v1/watch/macro/:id",(o,s)=>this.handleDelete("Macro",o,s)),t.delete("/api/v1/watch/subgraph/:id",(o,s)=>this.handleDelete("Subgraph",o,s)),t.delete("/api/v1/watch/nodeType/:id",(o,s)=>this.handleDelete("NodeType",o,s)),t.delete("/api/v1/watch/package/:id",(o,s)=>this.handleDelete("Package",o,s)),t.post("/api/v1/watch/storage-locations",(o,s)=>this.handleCreateStorageLocation(o,s)),t.delete("/api/v1/watch/storage-locations/:name",(o,s)=>this.handleDeleteStorageLocation(o,s)),t.patch("/api/v1/watch/storage-locations/default",(o,s)=>this.handleSetDefaultStorageLocation(o,s)),t.patch("/api/v1/watch/environment",(o,s)=>this.handleUpdateEnvironmentMappings(o,s)),t.get("/api/v1/watch/git/status",(o,s)=>this.handleGitStatus(o,s)),t.get("/api/v1/watch/git/branches",(o,s)=>this.handleGitBranches(o,s)),t.get("/api/v1/watch/git/log",(o,s)=>this.handleGitLog(o,s)),t.get("/api/v1/watch/git/diff",(o,s)=>this.handleGitDiff(o,s)),t.post("/api/v1/watch/git/checkout",(o,s)=>this.handleGitCheckout(o,s)),t.post("/api/v1/watch/git/commit",(o,s)=>this.handleGitCommit(o,s)),t.post("/api/v1/watch/git/push",(o,s)=>this.handleGitPush(o,s)),t.post("/api/v1/watch/git/branch",(o,s)=>this.handleGitCreateBranch(o,s)),t.post("/api/v1/watch/git/add",(o,s)=>this.handleGitAddAll(o,s)),t.post("/api/v1/watch/config",(o,s)=>this.handleUpdateConfig(o,s)),t.post("/api/v1/watch/install",(o,s)=>this.handleInstall(o,s)),t.post("/api/rescan",(o,s)=>this.handleRescan(o,s)),t.get("/api/v1/watch/apps",(o,s)=>this.handleListApps(o,s)),t.all("/api/v1/watch/apps/:appId/proxy/*",(o,s)=>this.handleAppProxy(o,s));let n,i;if(this.options.serveUI){let{cloudDomain:o,refreshToken:s}=this.options;if(!o||!s)throw new Error("Cloud domain and refresh token are required for --serve-ui. Run `coa login` first.");let a=await rNd(t,{cloudDomain:o,refreshToken:s});n=a.nonce,i=a.onUpgrade}return this.httpServer=t.listen(this.options.port,()=>{ca.info("[RepositoryServer] Started",{port:this.options.port})}),i&&this.httpServer.on("upgrade",i),n}async shutdown(){ca.info("[RepositoryServer] Shutting down"),this.appManager.shutdownAll(),this.chokidarTimer&&(clearTimeout(this.chokidarTimer),this.chokidarTimer=null);for(let[i,o]of this.clients.entries()){try{o.res.end()}catch{}this.cleanupClient(i)}let t=5e3,n=Date.now();for(;this.queue.length>0&&Date.now()-n<t;)await new Promise(i=>setTimeout(i,100));this.queue.length>0&&ca.warn("[RepositoryServer] Queue not empty at shutdown",{remaining:this.queue.length}),this.httpServer&&await new Promise(i=>this.httpServer.close(()=>i())),ca.info("[RepositoryServer] Shutdown complete")}handleFileEvent(t){switch(ca.info("[RepositoryServer] handleFileEvent received",{type:t.type,path:"path"in t?t.path:"batch"}),t.type){case"file-add":case"file-changed":this.chokidarChanges.add(t.path),this.scheduleChokidarBatch();break;case"file-deleted":this.chokidarDeletes.add(t.path),this.scheduleChokidarBatch();break;case"file-batch-changed":this.enqueueNoReply({type:"ProcessChokidarBatch",changes:t.paths,deletes:[],forceSnapshot:!0});break}}scheduleChokidarBatch(){this.chokidarTimer&&clearTimeout(this.chokidarTimer),this.chokidarTimer=setTimeout(()=>{let t=[...this.chokidarChanges],n=[...this.chokidarDeletes];this.chokidarChanges.clear(),this.chokidarDeletes.clear(),this.chokidarTimer=null,(t.length>0||n.length>0)&&this.enqueueNoReply({type:"ProcessChokidarBatch",changes:t,deletes:n})},this.CHOKIDAR_DEBOUNCE_MS)}async handleSSEConnection(t,n){let i=`client-${Date.now()}-${Math.random().toString(36).substring(7)}`;ca.info("[RepositoryServer] SSE client connected",{clientId:i}),n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{await this.enqueue({type:"SSEClientConnected",clientId:i,res:n,reply:()=>{}})}catch(s){ca.error("[RepositoryServer] Failed to send snapshot",{clientId:i,error:s instanceof Error?s.message:String(s)}),n.end();return}let o=setInterval(()=>{this.clients.has(i)?n.write(`: keepalive
|
|
10640
10640
|
|
|
10641
|
-
`):(clearInterval(o),this.keepaliveIntervals.delete(i))},3e4);this.keepaliveIntervals.set(i,o),t.on("close",()=>{aa.info("[RepositoryServer] SSE client disconnected",{clientId:i});let s=this.keepaliveIntervals.get(i);s&&(clearInterval(s),this.keepaliveIntervals.delete(i)),this.enqueueNoReply({type:"SSEClientDisconnected",clientId:i})})}async sendSnapshotToClient(t,n,i){aa.info("[RepositoryServer] sendSnapshotToClient called",{clientId:t,entityCount:i.length});let o=this.clients.get(t);if(!o){aa.warn("[RepositoryServer] Client not found during snapshot",{clientId:t});return}let s={type:"snapshot-start",serverId:this.serverId,sequenceNumber:this.sequenceNumber++};Vwe(n,s),aa.info("[RepositoryServer] Snapshot-start sent",{clientId:t});let a=new Map;for(let{entityType:p,id:c,path:l}of i)try{let d=await this.parseFileToRepository(l);if(!d){aa.debug("[RepositoryServer] Entity deleted during snapshot",{entityType:p,id:c,path:l});continue}let f=a.get(p)||[];f.push(d),a.set(p,f)}catch(d){aa.debug("[RepositoryServer] Entity changed during snapshot",{entityType:p,id:c,path:l,error:d instanceof Error?d.message:String(d)})}for(let[p,c]of a.entries()){if(p==="Package")continue;let l=c;if(p==="NodeType"&&!c.some(h=>h.id==="Source")){let h=await this.getPlatformKind(),A=this.getDefaultSourceNodeType(h);l=[...c,A]}let d={type:"snapshot-chunk",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:p,data:l};Vwe(n,d)}this.sendPackagesToClient(n),aa.info("[RepositoryServer] Sending envs-and-mappings",{clientId:t}),await this.sendEnvsAndMappingsToClient(n),aa.info("[RepositoryServer] Envs-and-mappings sent",{clientId:t});let u={type:"snapshot-complete",serverId:this.serverId,sequenceNumber:this.sequenceNumber++};Vwe(n,u),aa.info("[RepositoryServer] Snapshot complete sent",{clientId:t}),o.mode="draining",this.drainClientBuffer(t,n)}drainClientBuffer(t,n){let i=this.clients.get(t);if(i){for(let o of i.buffer)Vwe(n,o);i.buffer=[],i.mode="live"}}async parseFileToRepository(t){let n=await this.options.coordinator.parseFile(t);if(!n)return null;if(n.entityType==="NodeType"){let i=this.getEntityId(n,t),o={entityType:"NodeType",gitData:{...n.gitData,nodeType:{...n.gitData.nodeType,id:i}}};return this.convertGitToRepository(o)}return this.convertGitToRepository(n)}broadcastEntityUpdate(t,n){let i={type:"entity-update",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:t,data:n};this.broadcastToClients(i)}broadcastEntityDelete(t,n){let i={type:"entity-delete",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:t,id:n};this.broadcastToClients(i)}async buildEnvAndMappingsMessage(){let{locations:t,workspaceMappings:n,environments:i}=await this.options.coordinator.getMappingsSnapshot(),o=await this.getPlatformKind(),s={},a=t?.locations||[];for(let u of a)s[u]={};for(let u of a){let p=n?.[u];s[u]||(s[u]={}),s[u].__workspace__={database:p?.database??"",schema:p?.schema??""}}for(let u of i)for(let p of Object.keys(u.mappingDefinitions||{})){s[p]||(s[p]={});let c=u.mappingDefinitions[p];c&&(s[p][u.id]={database:c.database??"",schema:c.schema??""})}return{type:"env-and-mappings-updated",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,data:{mappings:s,environments:i.map(u=>({id:u.id,name:u.name,type:u.type,fileVersion:u.fileVersion})),defaultStorageMapping:t?.defaultStorageMapping||null,platformKind:o}}}async broadcastMappingsUpdate(){try{let t=await this.buildEnvAndMappingsMessage();this.broadcastToClients(t),aa.info("[RepositoryServer] Broadcasted env-and-mappings-updated")}catch(t){aa.error("[RepositoryServer] Failed to broadcast mappings update",{error:t instanceof Error?t.message:String(t)})}}broadcastToClients(t){let n=[];for(let[i,o]of this.clients.entries())if(o.mode==="live"){if(!Vwe(o.res,t)){aa.debug("[RepositoryServer] Client disconnected during broadcast",{clientId:i}),n.push(i);continue}}else{if(o.buffer.length>=this.MAX_CLIENT_BUFFER_SIZE){aa.error("[RepositoryServer] Client buffer exceeded limit, disconnecting",{clientId:i,bufferSize:o.buffer.length,limit:this.MAX_CLIENT_BUFFER_SIZE});try{o.res.end()}catch{}n.push(i);continue}o.buffer.push(t)}for(let i of n)this.cleanupClient(i)}getPackagesData(){let t=this.options.coordinator.readPackageCache();return t?Object.values(t):[]}sendPackagesToClient(t){let n={type:"snapshot-chunk",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:"Package",data:this.getPackagesData()};Vwe(t,n)}broadcastPackagesUpdate(){let t={type:"entity-bulk-update",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:"Package",data:this.getPackagesData()};this.broadcastToClients(t)}async sendEnvsAndMappingsToClient(t){try{let n=await this.buildEnvAndMappingsMessage();Vwe(t,n),aa.info("[RepositoryServer] Sent envs-and-mappings to snapshot client")}catch(n){aa.error("[RepositoryServer] Failed to send envs-and-mappings to snapshot client",{error:n instanceof Error?n.message:String(n)})}}convertGitToRepository(t){try{switch(t.entityType){case"Node":return JPd(t.gitData);case"Job":return Ueu(t.gitData);case"Macro":return $Pd(t.gitData);case"Subgraph":return XPd(t.gitData);case"NodeType":return zeu(t.gitData);case"Environment":case"Package":return t.gitData}}catch(n){return aa.error("[RepositoryServer] Failed to convert Git \u2192 Repository",{entityType:t.entityType,error:n instanceof Error?n.message:String(n)}),null}}async handleNodeWrite(t,n){try{let i=t.params.id,o=t.body;aa.info("[RepositoryServer] handleNodeWrite received",{nodeId:i,hasOperation:!!o.operation,operationKeys:o.operation?Object.keys(o.operation):[],operationName:o.operation?.name});let s={operation:{...o.operation,id:i}};aa.info("[RepositoryServer] handleNodeWrite after merge",{nodeId:i,operationKeys:Object.keys(s.operation),operationId:s.operation.id,operationName:s.operation.name});let a=jeu(s);await this.enqueue({type:"WriteNode",node:a,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Node write failed",{nodeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write node",details:o,nodeId:t.params.id})}}async handleNodeWriteV2(t,n){try{let i=t.params.id,{sql:o,name:s,location:a}=t.body;aa.info("[RepositoryServer] handleNodeWriteV2",{nodeId:i,name:s,location:a}),await this.enqueue({type:"WriteSQLNode",nodeId:i,sql:o,name:s,location:a,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] V2 node write failed",{nodeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write node",details:o})}}async handleJobCreate(t,n){try{let i=t.body,o=i.id,s=Qeu({name:i.name??"",includeSelector:i.includeSelector??"",excludeSelector:i.excludeSelector??"",version:2,id:o,jobCounter:o});await this.enqueue({type:"WriteJob",job:s,reply:()=>{}}),n.json({id:o})}catch(i){aa.error("[RepositoryServer] Job create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create job",details:o})}}async handleJobUpdate(t,n){try{let i=t.params.id,o=t.body;await this.enqueue({type:"UpdateJob",jobId:i,partialUpdate:o,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Job update failed",{jobId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update job",details:o,jobId:t.params.id})}}async handleMacroWrite(t,n){try{let i=t.params.id,o=t.body,s=ZPd({...o,id:i});await this.enqueue({type:"WriteMacro",macro:s,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Macro write failed",{macroId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write macro",details:o,macroId:t.params.id})}}async handleSubgraphCreate(t,n){try{aa.info("[RepositoryServer] Subgraph create request received",{body:t.body});let i=t.body,o=i.id;aa.info("[RepositoryServer] Converting subgraph",{subgraphId:o,repositorySubgraph:i});let s=Geu({...i,id:o});await this.enqueue({type:"WriteSubgraph",subgraph:s,reply:()=>{}}),n.json({id:o})}catch(i){aa.error("[RepositoryServer] Subgraph create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create subgraph",details:o})}}async handleSubgraphUpdate(t,n){try{let i=t.params.id,o=t.body,s=Geu({...o,id:i});await this.enqueue({type:"WriteSubgraph",subgraph:s,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Subgraph update failed",{subgraphId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update subgraph",details:o,subgraphId:t.params.id})}}async handleNodeTypeCreate(t,n){try{let i=t.body,o=crypto.randomUUID(),s={...i,id:o},a=Heu(s);await this.enqueue({type:"WriteNodeType",nodeType:a,reply:()=>{}}),n.json({id:o})}catch(i){aa.error("[RepositoryServer] NodeType create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create nodeType",details:o})}}async handleNodeTypeUpdate(t,n){try{let i=t.params.id,o=t.body;await this.enqueue({type:"UpdateNodeType",nodeTypeId:i,partialUpdate:o,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] NodeType update failed",{nodeTypeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update nodeType",details:o,nodeTypeId:t.params.id})}}async handleEnvironmentWrite(t,n){try{let i=t.body;await this.enqueue({type:"WriteEnvironment",env:i,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handlePackageWrite(t,n){try{let i=t.params.id,s={...t.body,id:i},a=e4d(s);await this.enqueue({type:"WritePackage",pkg:a,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleBulkNodesWrite(t,n){try{let o=t.body.nodes.map((s,a)=>{try{return jeu(s)}catch(u){throw new Error(`Failed to convert node at index ${a}: ${u instanceof Error?u.message:String(u)}`)}});await this.enqueue({type:"WriteBulkNodes",nodes:o,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Bulk nodes write failed",{count:t.body.nodes.length,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write bulk nodes",details:o})}}async handleBulkNodesDelete(t,n){try{let{nodeIds:i}=t.body;if(!Array.isArray(i)||i.length===0){n.status(400).json({error:"nodeIds must be a non-empty array"});return}for(let o of i)await this.enqueue({type:"DeleteEntity",entityType:"Node",id:o,reply:()=>{}});n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Bulk nodes delete failed",{count:Array.isArray(t.body)?t.body.length:0,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to delete bulk nodes",details:o})}}async handleDelete(t,n,i){try{let o=n.params.id;await this.enqueue({type:"DeleteEntity",entityType:t,id:o,reply:()=>{}}),i.json({success:!0})}catch(o){let s=o instanceof Error?o.message:String(o);i.status(500).json({error:s})}}async handleCreateStorageLocation(t,n){try{let{name:i}=t.body,{locations:o,workspaceMappings:s,environments:a}=await this.options.coordinator.getMappingsSnapshot(),u=o?.locations||[];if(u.includes(i)){n.status(400).json({error:`Storage location '${i}' already exists`});return}await this.options.coordinator.writeLocations({locations:[...u,i],defaultStorageMapping:o?.defaultStorageMapping||null,fileVersion:1});let p={...s,[i]:{database:"",schema:""}};await this.options.coordinator.writeWorkspaceYml(p);for(let c of a){let l={...c,mappingDefinitions:{...c.mappingDefinitions,[i]:{database:"",schema:""}}};await this.options.coordinator.writeEnvironment(l)}n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Create storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleDeleteStorageLocation(t,n){try{let{name:i}=t.params,{locations:o,workspaceMappings:s,environments:a}=await this.options.coordinator.getMappingsSnapshot(),p=(o?.locations||[]).filter(l=>l!==i);await this.options.coordinator.writeLocations({locations:p,defaultStorageMapping:o?.defaultStorageMapping===i?null:o?.defaultStorageMapping||null,fileVersion:1});let c={...s};delete c[i],await this.options.coordinator.writeWorkspaceYml(c);for(let l of a){let d={...l.mappingDefinitions};delete d[i];let f={...l,mappingDefinitions:d};await this.options.coordinator.writeEnvironment(f)}n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Delete storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleSetDefaultStorageLocation(t,n){try{let{name:i}=t.body,{locations:o}=await this.options.coordinator.getMappingsSnapshot();await this.options.coordinator.writeLocations({locations:o?.locations||[],defaultStorageMapping:i,fileVersion:1}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Set default storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleUpdateEnvironmentMappings(t,n){try{let{environmentId:i,workspaceId:o}=t.query,{mappings:s,name:a}=t.body;if(aa.info("[RepositoryServer] Update environment mappings",{environmentId:i,workspaceId:o,mappings:s,name:a}),i===o)await this.options.coordinator.writeWorkspaceYml(s);else{let{environments:u}=await this.options.coordinator.getMappingsSnapshot(),p=u.find(l=>l.id===i),c={type:"Environment",fileVersion:1,id:i,name:a||p?.name||`Environment ${i}`,mappingDefinitions:s};await this.options.coordinator.writeEnvironment(c)}n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Update environment mappings failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCheckout(t,n){try{let{branch:i,force:o}=t.body;await this.enqueue({type:"GitCheckout",branch:i,force:o??!1,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCommit(t,n){try{let{message:i,author:o}=t.body,s=await this.options.coordinator.gitCommit(i,o);n.json({commitSha:s})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitPush(t,n){try{let{branch:i,gitToken:o,gitUsername:s}=t.body;await this.options.coordinator.gitPush(i,o,s),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitStatus(t,n){try{let i=await this.options.coordinator.gitStatus();n.json({files:i.files})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitBranches(t,n){try{let i=await this.options.coordinator.gitBranches();n.json(i)}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitLog(t,n){try{let i=t.query.branch||"HEAD",o=t.query.limit?parseInt(t.query.limit,10):50,s=await this.options.coordinator.gitLog(i,o);n.json({commits:s})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitDiff(t,n){try{let i=t.query.file;if(!i||typeof i!="string"){n.status(400).json({error:"file query parameter required"});return}let o=await this.options.coordinator.gitDiff(i);n.json({diff:o})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCreateBranch(t,n){try{let{name:i}=t.body;if(!i||typeof i!="string"){n.status(400).json({error:"Branch name required"});return}await this.options.coordinator.gitCreateBranch(i),n.json({branch:i})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitAddAll(t,n){try{await this.options.coordinator.gitAddAll(),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleRescan(t,n){try{await this.options.coordinator.rescan(),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}handleUpdateConfig(t,n){try{let{content:i}=t.body;if(!i){n.status(400).json({error:"content is required"});return}this.writeCoaConfig(i),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Failed to update COA config",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleInstall(t,n){try{await this.enqueue({type:"CoaInstall",reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async processInstall(t){try{await this.runInstall(),t.reply()}catch(n){aa.error("[RepositoryServer] coa install failed",{error:n instanceof Error?n.message:String(n)}),t.reply(n instanceof Error?n:new Error(String(n)))}}processBroadcastPackagesUpdated(){this.broadcastPackagesUpdate()}getPathIndexKey(t,n){return`${t}:${n}`}findEntryByPath(t){for(let[n,i]of this.pathIndex.entries())if(i.path===t){let[o,s]=n.split(":");return{entityType:o,id:s}}}getEntityId(t,n){let i=S8.default.basename(n,S8.default.extname(n));switch(t.entityType){case"Node":if("id"in t.gitData&&typeof t.gitData.id=="string")return t.gitData.id;throw new Error(`Node file missing 'id' field: ${n}`);case"Job":case"Macro":case"Subgraph":case"Environment":{let o=i.lastIndexOf("-");if(o===-1)throw new Error(`${t.entityType} filename missing dash separator: ${n}`);return i.substring(o+1)}case"NodeType":{let o=S8.default.basename(S8.default.dirname(n)),s=o.indexOf("-");if(s===-1)throw new Error(`NodeType directory missing dash separator: ${n}`);return o.substring(s+1)}case"Package":return i;default:throw new Error(`Unknown entity type: ${t.entityType}`)}}async processChokidarBatch(t){let{changes:n,deletes:i,forceSnapshot:o}=t;aa.info("[RepositoryServer] Processing chokidar batch",{changes:n.length,deletes:i.length,forceSnapshot:o});let s=n.length+i.length,a=o||s>this.SNAPSHOT_THRESHOLD;a&&aa.info("[RepositoryServer] Will send snapshot instead of individual updates",{totalEvents:s,threshold:this.SNAPSHOT_THRESHOLD,forced:o});for(let u of n)try{let p=S8.default.basename(u);if(p==="locations.yml"||p==="workspace.yml"){await this.broadcastMappingsUpdate();continue}let c=await this.options.coordinator.parseFile(u);if(!c)continue;let l=this.getEntityId(c,u),d=this.getPathIndexKey(c.entityType,l);if(this.pathIndex.set(d,{path:u}),c.entityType==="Environment"){await this.broadcastMappingsUpdate();continue}if(c.entityType==="Package")continue;if(!a){let f=await this.parseFileToRepository(u);f&&this.broadcastEntityUpdate(c.entityType,f)}}catch(p){aa.error("[RepositoryServer] Failed to process file change",{path:u,error:p instanceof Error?p.message:String(p)})}for(let u of i)try{let p=this.findEntryByPath(u);if(!p){aa.debug("[RepositoryServer] Dropping programmatic delete event",{path:u});continue}let c=this.getPathIndexKey(p.entityType,p.id);this.pathIndex.delete(c),a||this.broadcastEntityDelete(p.entityType,p.id)}catch(p){aa.error("[RepositoryServer] Failed to process file delete",{path:u,error:p instanceof Error?p.message:String(p)})}if(a){let u=[];for(let[p,c]of this.pathIndex.entries()){let[l,d]=p.split(":");u.push({entityType:l,id:d,path:c.path})}aa.info("[RepositoryServer] Large batch - transitioning clients to snapshot mode",{entityCount:u.length,clientCount:this.clients.size});for(let p of this.clients.values())(p.mode==="live"||p.mode==="draining")&&(p.mode="snapshotting");this.sendSnapshotsAsync(u)}}async sendSnapshotsAsync(t){aa.info("[RepositoryServer] Broadcasting snapshots to all clients",{entityCount:t.length});for(let[n,i]of this.clients.entries())try{await this.sendSnapshotToClient(n,i.res,t)}catch(o){aa.error("[RepositoryServer] Failed to send snapshot to client",{clientId:n,error:o instanceof Error?o.message:String(o)}),this.clients.delete(n)}aa.info("[RepositoryServer] Snapshot broadcast complete")}async processSSEClientConnected(t){let{clientId:n,res:i}=t,o=[];for(let[s,a]of this.pathIndex.entries()){let[u,p]=s.split(":");o.push({entityType:u,id:p,path:a.path})}this.clients.set(n,{mode:"snapshotting",buffer:[],res:i}),t.reply();try{await this.sendSnapshotToClient(n,i,o)}catch(s){aa.error("[RepositoryServer] Snapshot failed",{clientId:n,error:s instanceof Error?s.message:String(s)}),this.clients.delete(n);try{i.end()}catch{}}}async processSSEClientDisconnected(t){this.cleanupClient(t.clientId)}cleanupClient(t){this.clients.delete(t);let n=this.keepaliveIntervals.get(t);n&&(clearInterval(n),this.keepaliveIntervals.delete(t))}async processWriteNode(t){let{node:n}=t,i=n.id,o=this.getPathIndexKey("Node",i),a=this.pathIndex.get(o)?.path;if(a?.endsWith(".sql")&&n.operation.type==="sql"){let{name:p,locationName:c}=n.operation,l=n.operation.metadata.sourceMapping?.[0]?.customSQL?.customSQL??"";aa.info("[RepositoryServer] v1 write to a .sql (v2) node \u2014 keeping .sql format",{nodeId:i,name:p,location:c}),await this.writeNodeAsSQL(i,l,p,c,t.reply);return}let u=this.options.coordinator.getPathForNode(n);this.pathIndex.set(o,{path:u});try{await this.options.coordinator.writeNode(n),a&&a!==u&&await this.options.coordinator.deleteFile(a),t.reply()}catch(p){a?this.pathIndex.set(o,{path:a}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteSQLNode(t){let{nodeId:n,sql:i,name:o,location:s}=t;await this.writeNodeAsSQL(n,i,o,s,t.reply)}async writeNodeAsSQL(t,n,i,o,s){let a=this.getPathIndexKey("Node",t),u=this.options.coordinator.getPathForSQLNode(i,o),c=this.pathIndex.get(a)?.path;this.pathIndex.set(a,{path:u});try{await this.options.coordinator.writeSQLNode(n,i,o),c&&c!==u&&await this.options.coordinator.deleteFile(c),s()}catch(l){c?this.pathIndex.set(a,{path:c}):this.pathIndex.delete(a),s(l instanceof Error?l:new Error(String(l)))}}async processWriteJob(t){let{job:n}=t,i=String(n.id),o=this.getPathIndexKey("Job",i),s=this.options.coordinator.getPathForJob(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeJob(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processUpdateJob(t){let{jobId:n,partialUpdate:i}=t,o=this.getPathIndexKey("Job",n),s=this.pathIndex.get(o);try{let a={...i,id:Number(n)};if(s){let l=await this.options.coordinator.parseFile(s.path);if(l&&l.entityType==="Job"){let d=Ueu(l.gitData);a=iQe({},d,i,{id:Number(n)})}}let u=Qeu(a),p=this.options.coordinator.getPathForJob(u),c=s?.path;this.pathIndex.set(o,{path:p}),await this.options.coordinator.writeJob(u),c&&c!==p&&await this.options.coordinator.deleteFile(c),t.reply()}catch(a){s?this.pathIndex.set(o,s):this.pathIndex.delete(o),t.reply(a instanceof Error?a:new Error(String(a)))}}async processWriteMacro(t){let{macro:n}=t,i=n.id,o=this.getPathIndexKey("Macro",i),s=this.options.coordinator.getPathForMacro(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeMacro(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteSubgraph(t){let{subgraph:n}=t,i=String(n.id),o=this.getPathIndexKey("Subgraph",i),s=this.options.coordinator.getPathForSubgraph(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeSubgraph(n),aa.info("[RepositoryServer] processWriteSubgraph completed",{id:i,newPath:s,oldPath:u}),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteNodeType(t){let{nodeType:n}=t,i=String(n.nodeType.id);if(i==="Source"){t.reply();return}let o=this.getPathIndexKey("NodeType",i),s=this.options.coordinator.getPathForNodeType(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeNodeType(n),u&&u!==s&&await this.options.coordinator.deleteDirectory(S8.default.dirname(u)),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processUpdateNodeType(t){let{nodeTypeId:n,partialUpdate:i}=t;if(n==="Source"){t.reply();return}let o=this.getPathIndexKey("NodeType",n),s=this.pathIndex.get(o);try{let a={...i,id:n};if(s){let l=S8.default.dirname(s.path),d=S8.default.join(l,"definition.yml"),f=await this.options.coordinator.parseFile(d);if(f&&f.entityType==="NodeType"){let h={...f.gitData,nodeType:{...f.gitData.nodeType,id:n}};a=iQe({},zeu(h),i,{id:n})}}let u=Heu(a),p=this.options.coordinator.getPathForNodeType(u),c=s?.path;this.pathIndex.set(o,{path:p}),await this.options.coordinator.writeNodeType(u),c&&c!==p&&await this.options.coordinator.deleteDirectory(S8.default.dirname(c)),t.reply()}catch(a){s?this.pathIndex.set(o,s):this.pathIndex.delete(o),t.reply(a instanceof Error?a:new Error(String(a)))}}async processWriteEnvironment(t){let{env:n}=t,i=String(n.id),o=this.getPathIndexKey("Environment",i),s=this.options.coordinator.getPathForEnvironment(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeEnvironment(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWritePackage(t){let{pkg:n}=t,i=n.packageID,o=this.getPathIndexKey("Package",i),s=this.options.coordinator.getPathForPackage(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s}),await this.options.coordinator.writePackage(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),await this.runInstall(),t.reply()}async processWriteBulkNodes(t){let{nodes:n}=t,i=[];for(let o of n){let s=o.id,a=this.getPathIndexKey("Node",s),u=this.options.coordinator.getPathForNode(o),p=this.pathIndex.get(a)?.path;this.pathIndex.set(a,{path:u}),p&&p!==u&&i.push({oldPath:p,newPath:u})}await this.options.coordinator.writeBulkNodes(n);for(let{oldPath:o}of i)await this.options.coordinator.deleteFile(o);t.reply()}async processDeleteEntity(t){let{entityType:n,id:i}=t,o=this.getPathIndexKey(n,i),s=this.pathIndex.get(o);if(!s){t.reply(new Error(`Entity not found: ${n}:${i}`));return}this.pathIndex.delete(o);try{n==="NodeType"?await this.options.coordinator.deleteDirectory(S8.default.dirname(s.path)):await this.options.coordinator.deleteFile(s.path)}catch(a){this.pathIndex.set(o,s),t.reply(a instanceof Error?a:new Error(String(a)));return}if(this.broadcastEntityDelete(n,i),t.reply(),n==="Package")try{await this.runInstall()}catch(a){aa.error("[RepositoryServer] coa install failed after package delete",{id:i,error:a instanceof Error?a.message:String(a)})}}async processWriteDataYml(t){try{await this.options.coordinator.writeDataYml(t.data),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)))}}async processWriteLocations(t){try{await this.options.coordinator.writeLocations(t.locations),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)))}}async processGitCheckout(t){try{let{branch:n,force:i}=t;await this.options.coordinator.gitCheckout(n,i),this.pathIndex.clear(),await this.options.coordinator.rescan(),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)));return}await this.runInstall()}writeCoaConfig(t){let n=S8.default.join(oNd.default.homedir(),".coa","config"),i=S8.default.dirname(n);ttu.default.mkdirSync(i,{recursive:!0,mode:448}),ttu.default.writeFileSync(n,t,{encoding:"utf-8",mode:384}),aa.info("[RepositoryServer] Updated COA config")}async runInstall(){let t=this.options.coordinator.getWorkspaceDir(),{stderr:n}=await tCE("coa",["install","-d",t]);n&&aa.warn("[RepositoryServer] coa install stderr",{stderr:n}),aa.info("[RepositoryServer] coa install completed"),this.processBroadcastPackagesUpdated()}enqueue(t){return new Promise((n,i)=>{let o={...t,reply:s=>{s instanceof Error?i(s):n(s)}};this.queue.push(o),this.processQueue()})}enqueueNoReply(t){this.queue.push(t),this.processQueue()}async processQueue(){if(!(this.processing||this.queue.length===0)){for(this.processing=!0;this.queue.length>0;){let t=this.queue.shift();try{await this.handleMessage(t)}catch(n){aa.error("[RepositoryServer] Message processing failed",{messageType:t.type,error:n instanceof Error?n.message:String(n)}),"reply"in t&&t.reply(n instanceof Error?n:new Error(String(n)))}}this.processing=!1}}async handleMessage(t){switch(t.type){case"WriteNode":await this.processWriteNode(t);break;case"WriteSQLNode":await this.processWriteSQLNode(t);break;case"WriteJob":await this.processWriteJob(t);break;case"UpdateJob":await this.processUpdateJob(t);break;case"WriteMacro":await this.processWriteMacro(t);break;case"WriteSubgraph":await this.processWriteSubgraph(t);break;case"WriteNodeType":await this.processWriteNodeType(t);break;case"UpdateNodeType":await this.processUpdateNodeType(t);break;case"WriteEnvironment":await this.processWriteEnvironment(t);break;case"WritePackage":await this.processWritePackage(t);break;case"WriteBulkNodes":await this.processWriteBulkNodes(t);break;case"DeleteEntity":await this.processDeleteEntity(t);break;case"WriteDataYml":await this.processWriteDataYml(t);break;case"WriteLocations":await this.processWriteLocations(t);break;case"GitCheckout":await this.processGitCheckout(t);break;case"ProcessChokidarBatch":await this.processChokidarBatch(t);break;case"BroadcastPackagesUpdated":this.processBroadcastPackagesUpdated();break;case"CoaInstall":await this.processInstall(t);break;case"SSEClientConnected":await this.processSSEClientConnected(t);break;case"SSEClientDisconnected":await this.processSSEClientDisconnected(t);break;default:{let n=t;throw new Error(`Unknown message type: ${n.type}`)}}}async readPlatformKindFromDataYml(){try{let t=await this.options.coordinator.loadDataYml(),n=jh.safeParse(t?.platformKind);return n.success?n.data:void 0}catch{return}}async getPlatformKind(){return await this.readPlatformKindFromDataYml()??"snowflake"}getDefaultSourceNodeType(t){let i=lNe(t).Source;if(!i)throw new Error(`Source node type not found in defaults for platform ${t}`);return i}async handleListApps(t,n){try{let i=await this.appManager.discoverApps();n.json({apps:i})}catch(i){aa.error("[RepositoryServer] Failed to list apps",{error:i}),n.status(500).json({error:{errorString:String(i)}})}}async handleAppProxy(t,n){let{appId:i}=t.params;if(!i){n.status(400).json({error:{errorString:"appId required"}});return}let o;try{o=await this.appManager.ensureRunning(i)}catch(p){aa.error("[RepositoryServer] Failed to start app for proxy",{appId:i,error:p}),n.status(502).json({error:{errorString:String(p)}});return}let s=`/api/v1/watch/apps/${i}/proxy`,a=t.originalUrl.slice(t.originalUrl.indexOf(s)+s.length)||"/",u=`${o}${a}`;try{let p={};t.headers["content-type"]&&(p["content-type"]=t.headers["content-type"]),t.headers.accept&&(p.accept=t.headers.accept);let c=await fetch(u,{method:t.method,headers:p,body:t.method!=="GET"&&t.method!=="HEAD"?JSON.stringify(t.body):void 0});if(n.status(c.status),c.headers.forEach((l,d)=>{d!=="transfer-encoding"&&n.setHeader(d,l)}),c.body){let l=c.body.getReader();try{for(;;){let{done:d,value:f}=await l.read();if(d)break;n.write(f)}}finally{l.releaseLock()}}n.end()}catch(p){aa.error("[RepositoryServer] App proxy error",{appId:i,error:p}),n.headersSent||n.status(502).json({error:{errorString:String(p)}})}}};var fY=require("fs"),t1e=yt(require("path"));var Eae=yt(require("crypto")),aNd=yt(require("fs")),O1=require("fs"),Up=yt(require("path"));var bae=Je("COA_WATCH"),rCE=mce.strip().extend({contents:mce.shape.contents.strip()});async function uNd(r,t,n,i="snowflake"){try{let o=await O1.promises.readFile(r,"utf-8"),s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16),u=Up.default.relative(t,r).split(Up.default.sep);if(u[0]==="nodes"&&r.endsWith(".sql"))return{entityType:"Node",data:await hxr({fileData:o,filePath:r,type:"File"},n,i),hash:s};if(u[0]==="nodes"&&r.endsWith(".yml"))return{entityType:"Node",data:Sp(r,o),hash:s};if(u[0]==="jobs"&&r.endsWith(".yml"))return{entityType:"Job",data:Sp(r,o),hash:s};if(u[0]==="macros"&&r.endsWith(".yml"))return{entityType:"Macro",data:Sp(r,o),hash:s};if(u[0]==="subgraphs"&&r.endsWith(".yml"))return{entityType:"Subgraph",data:Sp(r,o),hash:s};if(u[0]==="nodeTypes"&&u[u.length-1]==="definition.yml"){let p=await nCE(Up.default.dirname(r),n);if(p)return{entityType:"NodeType",data:p,hash:s}}else{if(u[0]==="environments"&&r.endsWith(".yml"))return{entityType:"Environment",data:Sp(r,o),hash:s};if(u[0]==="packages"&&r.endsWith(".yml"))return{entityType:"Package",data:Sp(r,o),hash:s}}return null}catch(o){return bae.error("[FileIO] Error parsing file",{filePath:r,error:o instanceof Error?o.message:String(o)}),null}}async function nCE(r,t){try{let n=Up.default.join(r,"definition.yml"),i=await O1.promises.readFile(n,"utf-8"),o=Sp(n,i),s=Up.default.join(r,"create.sql"),a=Up.default.join(r,"create.sql.j2"),u=Up.default.join(r,"run.sql"),p=Up.default.join(r,"run.sql.j2"),c=await O1.promises.readFile(s,"utf-8").catch(()=>null)||await O1.promises.readFile(a,"utf-8").catch(()=>null),l=await O1.promises.readFile(u,"utf-8").catch(()=>null)||await O1.promises.readFile(p,"utf-8").catch(()=>null);return{nodeType:o,create:c||"",run:l||""}}catch(n){return bae.error("[FileIO] Failed to parse NodeType",{nodeTypeDir:r,error:n instanceof Error?n.message:String(n)}),null}}async function rtu(r,t){_Z.parse(r);let n=r.operation.name,i=r.operation.locationName,o=BR(`${i}-${n}`),s=Up.default.join(t,"nodes",`${o}.yml`);await O1.promises.mkdir(Up.default.dirname(s),{recursive:!0});let a=UA(r,{sortKeys:!0});await O1.promises.writeFile(s,a,"utf-8");let u=Eae.createHash("sha256").update(a).digest("hex").substring(0,16);return{path:s,hash:u}}async function cNd(r,t){if(WH.parse(r),!r.name)throw new Error(`Job ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"jobs",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function lNd(r,t){if(TZ.parse(r),!r.name)throw new Error(`Macro ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"macros",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function pNd(r,t){if(IZ.parse(r),!r.name)throw new Error(`Subgraph ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"subgraphs",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function dNd(r,t){if(_2e.parse(r),!r.name)throw new Error(`Environment ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"environments",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function fNd(r,t){tbe.parse(r);let n=BR(r.name),i=Up.default.join(t,"packages",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function hNd(r,t){let{nodeType:n,create:i,run:o}=r;if(!n.name)throw new Error(`NodeType ${n.id} missing required name field`);let s=BR(`${n.name}-${n.id}`),a=Up.default.join(t,"nodeTypes",s);await O1.promises.mkdir(a,{recursive:!0});let u=Up.default.join(a,"definition.yml"),p=UA(n,{sortKeys:!0});if(await O1.promises.writeFile(u,p,"utf-8"),i){let l=Up.default.join(a,"create.sql.j2");await O1.promises.writeFile(l,i,"utf-8")}if(o){let l=Up.default.join(a,"run.sql.j2");await O1.promises.writeFile(l,o,"utf-8")}let c=Eae.createHash("sha256").update(p).digest("hex").substring(0,16);return{definitionPath:u,hash:c}}async function gNd(r){try{let t=Up.default.join(r,"data.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n)}catch(t){return bae.error("[FileIO] Failed to load data.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function ANd(r){try{let t=Up.default.join(r,"locations.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n)}catch(t){return bae.error("[FileIO] Failed to load locations.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function mNd(r){try{let t=Up.default.join(r,"environments"),n=await O1.promises.readdir(t),i=[];for(let o of n)if(o.endsWith(".yml"))try{let s=Up.default.join(t,o),a=await O1.promises.readFile(s,"utf-8"),u=Sp(s,a);u&&i.push(u)}catch(s){bae.warn("[FileIO] Failed to load environment file",{file:o,error:s instanceof Error?s.message:String(s)})}return i}catch(t){return bae.error("[FileIO] Failed to load environments directory",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),[]}}async function yNd(r){try{let t=Up.default.join(r,"workspace.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n).locations||null}catch(t){return t instanceof Error&&t.message.includes("ENOENT")||bae.error("[FileIO] Failed to load workspace.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function bNd(r,t){let n=Up.default.join(r,"workspace.yml"),i=UA({locations:t},{sortKeys:!0});await O1.promises.writeFile(n,i,"utf-8")}function ENd(r,t){let n=t.operation.locationName,i=t.operation.name,o=BR(`${n}-${i}`);return Up.default.join(r,"nodes",`${o}.yml`)}function ntu(r,t,n){let i=BR(`${n}-${t}`);return Up.default.join(r,"nodes",`${i}.sql`)}async function CNd(r,t,n,i){let o=ntu(i,t,n);await O1.promises.mkdir(Up.default.dirname(o),{recursive:!0}),await O1.promises.writeFile(o,r,"utf-8");let s=Eae.createHash("sha256").update(r).digest("hex").substring(0,16);return{path:o,hash:s}}function SNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"jobs",`${n}.yml`)}function vNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"macros",`${n}.yml`)}function TNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"subgraphs",`${n}.yml`)}function _Nd(r,t){let n=BR(`${t.nodeType.name}-${t.nodeType.id}`);return Up.default.join(r,"nodeTypes",n,"definition.yml")}function INd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"environments",`${n}.yml`)}function RNd(r,t){let n=BR(t.name);return Up.default.join(r,"packages",`${n}.yml`)}var iCE=".coa/cache",oCE="packages.json";function ONd(r){let t=Up.default.join(r,iCE,oCE);try{let n=JSON.parse(aNd.readFileSync(t,"utf-8"));if(typeof n!="object"||n===null)return bae.warn("[FileIO] Package cache is not a valid object",{cachePath:t}),null;let i={};for(let[o,s]of Object.entries(n)){let a=rCE.safeParse(s);a.success?i[o]=a.data:bae.warn("[FileIO] Skipping invalid package in cache",{alias:o})}return Object.keys(i).length>0?i:null}catch(n){return bae.error("[FileIO] Failed to read package cache",{cachePath:t,error:n instanceof Error?n.message:String(n)}),null}}var GNd=require("node:events"),HNd=require("node:fs"),Jio=require("node:fs/promises"),R0=yt(require("node:path"),1);var Zhe=require("node:fs/promises"),e1e=require("node:path"),PNd=require("node:stream"),r7={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},itu={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:r7.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(itu);var NNd="READDIRP_RECURSIVE_ERROR",aCE=new Set(["ENOENT","EPERM","EACCES","ELOOP",NNd]),wNd=[r7.DIR_TYPE,r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE,r7.FILE_TYPE],uCE=new Set([r7.DIR_TYPE,r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE]),cCE=new Set([r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE,r7.FILE_TYPE]),lCE=r=>aCE.has(r.code),pCE=process.platform==="win32",MNd=r=>!0,xNd=r=>{if(r===void 0)return MNd;if(typeof r=="function")return r;if(typeof r=="string"){let t=r.trim();return n=>n.basename===t}if(Array.isArray(r)){let t=r.map(n=>n.trim());return n=>t.some(i=>n.basename===i)}return MNd},otu=class extends PNd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let n={...itu,...t},{root:i,type:o}=n;this._fileFilter=xNd(n.fileFilter),this._directoryFilter=xNd(n.directoryFilter);let s=n.lstat?Zhe.lstat:Zhe.stat;pCE?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:itu.depth,this._wantsDir=o?uCE.has(o):!1,this._wantsFile=o?cCE.has(o):!1,this._wantsEverything=o===r7.EVERYTHING_TYPE,this._root=(0,e1e.resolve)(i),this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let n=this.parent,i=n&&n.files;if(i&&i.length>0){let{path:o,depth:s}=n,a=i.splice(0,t).map(p=>this._formatEntry(p,o)),u=await Promise.all(a);for(let p of u){if(!p)continue;if(this.destroyed)return;let c=await this._getEntryType(p);c==="directory"&&this._directoryFilter(p)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(p.fullPath,s+1)),this._wantsDir&&(this.push(p),t--)):(c==="file"||this._includeAsFile(p))&&this._fileFilter(p)&&this._wantsFile&&(this.push(p),t--)}}else{let o=this.parents.pop();if(!o){this.push(null);break}if(this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(t,n){let i;try{i=await(0,Zhe.readdir)(t,this._rdOptions)}catch(o){this._onError(o)}return{files:i,depth:n,path:t}}async _formatEntry(t,n){let i,o=this._isDirent?t.name:t;try{let s=(0,e1e.resolve)((0,e1e.join)(n,o));i={path:(0,e1e.relative)(this._root,s),fullPath:s,basename:o},i[this._statsProp]=this._isDirent?t:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(t){lCE(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let n=t[this._statsProp];if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let i=t.fullPath;try{let o=await(0,Zhe.realpath)(i),s=await(0,Zhe.lstat)(o);if(s.isFile())return"file";if(s.isDirectory()){let a=o.length;if(i.startsWith(o)&&i.substr(a,1)===e1e.sep){let u=new Error(`Circular symlink detected: "${i}" points to "${o}"`);return u.code=NNd,this._onError(u)}return"directory"}}catch(o){return this._onError(o),""}}}_includeAsFile(t){let n=t&&t[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function DNd(r,t={}){let n=t.entryType||t.type;if(n==="both"&&(n=r7.FILE_DIR_TYPE),n&&(t.type=n),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!wNd.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${wNd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=r,new otu(t)}var DFe=require("node:fs"),dY=require("node:fs/promises"),LNd=require("node:os"),OE=yt(require("node:path"),1),dCE="data",utu="end",kNd="close",Vio=()=>{};var Wio=process.platform,ctu=Wio==="win32",fCE=Wio==="darwin",hCE=Wio==="linux",gCE=Wio==="freebsd",qNd=(0,LNd.type)()==="OS400",P2={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},pY=P2,ACE="watch",mCE={lstat:dY.lstat,stat:dY.stat},NFe="listeners",Qio="errHandlers",Qyt="rawEmitters",yCE=[NFe,Qio,Qyt],bCE=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),ECE=r=>bCE.has(OE.extname(r).slice(1).toLowerCase()),atu=(r,t)=>{r instanceof Set?r.forEach(t):t(r)},rYt=(r,t,n)=>{let i=r[t];i instanceof Set||(r[t]=i=new Set([i])),i.add(n)},CCE=r=>t=>{let n=r[t];n instanceof Set?n.clear():delete r[t]},nYt=(r,t,n)=>{let i=r[t];i instanceof Set?i.delete(n):i===n&&delete r[t]},FNd=r=>r instanceof Set?r.size===0:!r,jio=new Map;function BNd(r,t,n,i,o){let s=(a,u)=>{n(r),o(a,u,{watchedPath:r}),u&&r!==u&&Gio(OE.resolve(r,u),NFe,OE.join(r,u))};try{return(0,DFe.watch)(r,{persistent:t.persistent},s)}catch(a){i(a);return}}var Gio=(r,t,n,i,o)=>{let s=jio.get(r);s&&atu(s[t],a=>{a(n,i,o)})},SCE=(r,t,n,i)=>{let{listener:o,errHandler:s,rawEmitter:a}=i,u=jio.get(t),p;if(!n.persistent)return p=BNd(r,n,o,s,a),p?p.close.bind(p):void 0;if(u)rYt(u,NFe,o),rYt(u,Qio,s),rYt(u,Qyt,a);else{if(p=BNd(r,n,Gio.bind(null,t,NFe),s,Gio.bind(null,t,Qyt)),!p)return;p.on(pY.ERROR,async c=>{let l=Gio.bind(null,t,Qio);if(u&&(u.watcherUnusable=!0),ctu&&c.code==="EPERM")try{await(await(0,dY.open)(r,"r")).close(),l(c)}catch{}else l(c)}),u={listeners:o,errHandlers:s,rawEmitters:a,watcher:p},jio.set(t,u)}return()=>{nYt(u,NFe,o),nYt(u,Qio,s),nYt(u,Qyt,a),FNd(u.listeners)&&(u.watcher.close(),jio.delete(t),yCE.forEach(CCE(u)),u.watcher=void 0,Object.freeze(u))}},stu=new Map,vCE=(r,t,n,i)=>{let{listener:o,rawEmitter:s}=i,a=stu.get(t),u=a&&a.options;return u&&(u.persistent<n.persistent||u.interval>n.interval)&&((0,DFe.unwatchFile)(t),a=void 0),a?(rYt(a,NFe,o),rYt(a,Qyt,s)):(a={listeners:o,rawEmitters:s,options:n,watcher:(0,DFe.watchFile)(t,n,(p,c)=>{atu(a.rawEmitters,d=>{d(pY.CHANGE,t,{curr:p,prev:c})});let l=p.mtimeMs;(p.size!==c.size||l>c.mtimeMs||l===0)&&atu(a.listeners,d=>d(r,p))})},stu.set(t,a)),()=>{nYt(a,NFe,o),nYt(a,Qyt,s),FNd(a.listeners)&&(stu.delete(t),(0,DFe.unwatchFile)(t),a.options=a.watcher=void 0,Object.freeze(a))}},Hio=class{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=n=>t._handleError(n)}_watchWithNodeFs(t,n){let i=this.fsw.options,o=OE.dirname(t),s=OE.basename(t);this.fsw._getWatchedDir(o).add(s);let u=OE.resolve(t),p={persistent:i.persistent};n||(n=Vio);let c;if(i.usePolling){let l=i.interval!==i.binaryInterval;p.interval=l&&ECE(s)?i.binaryInterval:i.interval,c=vCE(t,u,p,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=SCE(t,u,p,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(t,n,i){if(this.fsw.closed)return;let o=OE.dirname(t),s=OE.basename(t),a=this.fsw._getWatchedDir(o),u=n;if(a.has(s))return;let p=async(l,d)=>{if(this.fsw._throttle(ACE,t,5)){if(!d||d.mtimeMs===0)try{let f=await(0,dY.stat)(t);if(this.fsw.closed)return;let h=f.atimeMs,A=f.mtimeMs;if((!h||h<=A||A!==u.mtimeMs)&&this.fsw._emit(pY.CHANGE,t,f),(fCE||hCE||gCE)&&u.ino!==f.ino){this.fsw._closeFile(l),u=f;let E=this._watchWithNodeFs(t,p);E&&this.fsw._addPathCloser(l,E)}else u=f}catch{this.fsw._remove(o,s)}else if(a.has(s)){let f=d.atimeMs,h=d.mtimeMs;(!f||f<=h||h!==u.mtimeMs)&&this.fsw._emit(pY.CHANGE,t,d),u=d}}},c=this._watchWithNodeFs(t,p);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(pY.ADD,t,0))return;this.fsw._emit(pY.ADD,t,n)}return c}async _handleSymlink(t,n,i,o){if(this.fsw.closed)return;let s=t.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let u;try{u=await(0,dY.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(o)?this.fsw._symlinkPaths.get(s)!==u&&(this.fsw._symlinkPaths.set(s,u),this.fsw._emit(pY.CHANGE,i,t.stats)):(a.add(o),this.fsw._symlinkPaths.set(s,u),this.fsw._emit(pY.ADD,i,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(t,n,i,o,s,a,u){t=OE.join(t,"");let p=o?`${t}:${o}`:t;if(u=this.fsw._throttle("readdir",p,1e3),!u)return;let c=this.fsw._getWatchedDir(i.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>i.filterPath(f),directoryFilter:f=>i.filterDir(f)});if(d)return d.on(dCE,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,A=OE.join(t,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,A,h))){if(this.fsw.closed){d=void 0;return}(h===o||!o&&!c.has(h))&&(this.fsw._incrReadyCount(),A=OE.join(s,OE.relative(s,A)),this._addToNodeFs(A,n,i,a+1))}}).on(pY.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!d)return h();d.once(utu,()=>{if(this.fsw.closed){d=void 0;return}let A=u?u.clear():!1;f(void 0),c.getChildren().filter(E=>E!==t&&!l.has(E)).forEach(E=>{this.fsw._remove(t,E)}),d=void 0,A&&this._handleRead(t,!1,i,o,s,a,u)})})}async _handleDir(t,n,i,o,s,a,u){let p=this.fsw._getWatchedDir(OE.dirname(t)),c=p.has(OE.basename(t));!(i&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(pY.ADD_DIR,t,n),p.add(OE.basename(t)),this.fsw._getWatchedDir(t);let l,d,f=this.fsw.options.depth;if((f==null||o<=f)&&!this.fsw._symlinkPaths.has(u)){if(!s&&(await this._handleRead(t,i,a,s,t,o,l),this.fsw.closed))return;d=this._watchWithNodeFs(t,(h,A)=>{A&&A.mtimeMs===0||this._handleRead(h,!1,a,s,t,o,l)})}return d}async _addToNodeFs(t,n,i,o,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let u=this.fsw._getWatchHelpers(t);i&&(u.filterPath=p=>i.filterPath(p),u.filterDir=p=>i.filterDir(p));try{let p=await mCE[u.statMethod](u.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(u.watchPath,p))return a(),!1;let c=this.fsw.options.followSymlinks,l;if(p.isDirectory()){let d=OE.resolve(t),f=c?await(0,dY.realpath)(t):t;if(this.fsw.closed||(l=await this._handleDir(u.watchPath,p,n,o,s,u,f),this.fsw.closed))return;d!==f&&f!==void 0&&this.fsw._symlinkPaths.set(d,f)}else if(p.isSymbolicLink()){let d=c?await(0,dY.realpath)(t):t;if(this.fsw.closed)return;let f=OE.dirname(u.watchPath);if(this.fsw._getWatchedDir(f).add(u.watchPath),this.fsw._emit(pY.ADD,u.watchPath,p),l=await this._handleDir(f,p,n,o,t,u,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(OE.resolve(t),d)}else l=this._handleFile(u.watchPath,p,n);return a(),l&&this.fsw._addPathCloser(t,l),!1}catch(p){if(this.fsw._handleError(p))return a(),t}}};var ltu="/",TCE="//",VNd=".",_CE="..",ICE="string",RCE=/\\/g,WNd=/\/\//g,OCE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,wCE=/^\.[/\\]/;function Kio(r){return Array.isArray(r)?r:[r]}var ptu=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function MCE(r){return typeof r=="function"?r:typeof r=="string"?t=>r===t:r instanceof RegExp?t=>r.test(t):typeof r=="object"&&r!==null?t=>{if(r.path===t)return!0;if(r.recursive){let n=R0.relative(r.path,t);return n?!n.startsWith("..")&&!R0.isAbsolute(n):!1}return!1}:()=>!1}function xCE(r){if(typeof r!="string")throw new Error("string expected");r=R0.normalize(r),r=r.replace(/\\/g,"/");let t=!1;return r.startsWith("//")&&(t=!0),r=r.replace(WNd,"/"),t&&(r="/"+r),r}function UNd(r,t,n){let i=xCE(t);for(let o=0;o<r.length;o++){let s=r[o];if(s(i,n))return!0}return!1}function PCE(r,t){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Kio(r).map(o=>MCE(o));return t==null?(o,s)=>UNd(i,o,s):UNd(i,t)}var zNd=r=>{let t=Kio(r).flat();if(!t.every(n=>typeof n===ICE))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(KNd)},QNd=r=>{let t=r.replace(RCE,ltu),n=!1;return t.startsWith(TCE)&&(n=!0),t=t.replace(WNd,ltu),n&&(t=ltu+t),t},KNd=r=>QNd(R0.normalize(QNd(r))),jNd=(r="")=>t=>typeof t=="string"?KNd(R0.isAbsolute(t)?t:R0.join(r,t)):t,NCE=(r,t)=>R0.isAbsolute(r)?r:R0.join(t,r),DCE=Object.freeze(new Set),dtu=class{path;_removeWatcher;items;constructor(t,n){this.path=t,this._removeWatcher=n,this.items=new Set}add(t){let{items:n}=this;n&&t!==VNd&&t!==_CE&&n.add(t)}async remove(t){let{items:n}=this;if(!n||(n.delete(t),n.size>0))return;let i=this.path;try{await(0,Jio.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(R0.dirname(i),R0.basename(i))}}has(t){let{items:n}=this;if(n)return n.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Vio,this.items=DCE,Object.freeze(this)}},BCE="stat",LCE="lstat",ftu=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,n,i){this.fsw=i;let o=t;this.path=t=t.replace(wCE,""),this.watchPath=o,this.fullWatchPath=R0.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?BCE:LCE}entryPath(t){return R0.join(this.watchPath,R0.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:n}=t;if(n&&n.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,n)&&this.fsw._hasReadPermissions(n)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},Yio=class extends GNd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},o={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?Kio(t.ignored):Kio([]),awaitWriteFinish:n===!0?i:typeof n=="object"?{...i,...n}:!1};qNd&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let p=s.toLowerCase();p==="false"||p==="0"?o.usePolling=!1:p==="true"||p==="1"?o.usePolling=!0:o.usePolling=!!p}let a=process.env.CHOKIDAR_INTERVAL;a&&(o.interval=Number.parseInt(a,10));let u=0;this._emitReady=()=>{u++,u>=this._readyCount&&(this._emitReady=Vio,this._readyEmitted=!0,process.nextTick(()=>this.emit(P2.READY)))},this._emitRaw=(...p)=>this.emit(P2.RAW,...p),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Hio(this),Object.freeze(o)}_addIgnoredPath(t){if(ptu(t)){for(let n of this._ignoredPaths)if(ptu(n)&&n.path===t.path&&n.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let n of this._ignoredPaths)ptu(n)&&n.path===t&&this._ignoredPaths.delete(n)}add(t,n,i){let{cwd:o}=this.options;this.closed=!1,this._closePromise=void 0;let s=zNd(t);return o&&(s=s.map(a=>NCE(a,o))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let u=await this._nodeFsHandler._addToNodeFs(a,!i,void 0,0,n);return u&&this._emitReady(),u})).then(a=>{this.closed||a.forEach(u=>{u&&this.add(R0.dirname(u),R0.basename(n||u))})}),this}unwatch(t){if(this.closed)return this;let n=zNd(t),{cwd:i}=this.options;return n.forEach(o=>{!R0.isAbsolute(o)&&!this._closers.has(o)&&(i&&(o=R0.join(i,o)),o=R0.resolve(o)),this._closePath(o),this._addIgnoredPath(o),this._watched.has(o)&&this._addIgnoredPath({path:o,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(n=>n.forEach(i=>{let o=i();o instanceof Promise&&t.push(o)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((n,i)=>{let s=(this.options.cwd?R0.relative(this.options.cwd,i):i)||VNd;t[s]=n.getChildren().sort()}),t}emitWithAll(t,n){this.emit(t,...n),t!==P2.ERROR&&this.emit(P2.ALL,t,...n)}async _emit(t,n,i){if(this.closed)return;let o=this.options;ctu&&(n=R0.normalize(n)),o.cwd&&(n=R0.relative(o.cwd,n));let s=[n];i!=null&&s.push(i);let a=o.awaitWriteFinish,u;if(a&&(u=this._pendingWrites.get(n)))return u.lastChange=new Date,this;if(o.atomic){if(t===P2.UNLINK)return this._pendingUnlinks.set(n,[t,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((p,c)=>{this.emit(...p),this.emit(P2.ALL,...p),this._pendingUnlinks.delete(c)})},typeof o.atomic=="number"?o.atomic:100),this;t===P2.ADD&&this._pendingUnlinks.has(n)&&(t=P2.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(t===P2.ADD||t===P2.CHANGE)&&this._readyEmitted){let p=(c,l)=>{c?(t=P2.ERROR,s[0]=c,this.emitWithAll(t,s)):l&&(s.length>1?s[1]=l:s.push(l),this.emitWithAll(t,s))};return this._awaitWriteFinish(n,a.stabilityThreshold,t,p),this}if(t===P2.CHANGE&&!this._throttle(P2.CHANGE,n,50))return this;if(o.alwaysStat&&i===void 0&&(t===P2.ADD||t===P2.ADD_DIR||t===P2.CHANGE)){let p=o.cwd?R0.join(o.cwd,n):n,c;try{c=await(0,Jio.stat)(p)}catch{}if(!c||this.closed)return;s.push(c)}return this.emitWithAll(t,s),this}_handleError(t){let n=t&&t.code;return t&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(P2.ERROR,t),t||this.closed}_throttle(t,n,i){this._throttled.has(t)||this._throttled.set(t,new Map);let o=this._throttled.get(t);if(!o)throw new Error("invalid throttle");let s=o.get(n);if(s)return s.count++,!1;let a,u=()=>{let c=o.get(n),l=c?c.count:0;return o.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),l};a=setTimeout(u,i);let p={timeoutObject:a,clear:u,count:0};return o.set(n,p),p}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,n,i,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,u,p=t;this.options.cwd&&!R0.isAbsolute(t)&&(p=R0.join(this.options.cwd,t));let c=new Date,l=this._pendingWrites;function d(f){(0,HNd.stat)(p,(h,A)=>{if(h||!l.has(t)){h&&h.code!=="ENOENT"&&o(h);return}let E=Number(new Date);f&&A.size!==f.size&&(l.get(t).lastChange=E);let v=l.get(t);E-v.lastChange>=n?(l.delete(t),o(void 0,A)):u=setTimeout(d,a,A)})}l.has(t)||(l.set(t,{lastChange:c,cancelWait:()=>(l.delete(t),clearTimeout(u),i)}),u=setTimeout(d,a))}_isIgnored(t,n){if(this.options.atomic&&OCE.test(t))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(jNd(i)),u=[...[...this._ignoredPaths].map(jNd(i)),...s];this._userIgnored=PCE(u,void 0)}return this._userIgnored(t,n)}_isntIgnored(t,n){return!this._isIgnored(t,n)}_getWatchHelpers(t){return new ftu(t,this.options.followSymlinks,this)}_getWatchedDir(t){let n=R0.resolve(t);return this._watched.has(n)||this._watched.set(n,new dtu(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,n,i){let o=R0.join(t,n),s=R0.resolve(o);if(i=i??(this._watched.has(o)||this._watched.has(s)),!this._throttle("remove",o,100))return;!i&&this._watched.size===1&&this.add(t,n,!0),this._getWatchedDir(o).getChildren().forEach(f=>this._remove(o,f));let p=this._getWatchedDir(t),c=p.has(n);p.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let l=o;if(this.options.cwd&&(l=R0.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===P2.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=i?P2.UNLINK_DIR:P2.UNLINK;c&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(t){this._closeFile(t);let n=R0.dirname(t);this._getWatchedDir(n).remove(R0.basename(t))}_closeFile(t){let n=this._closers.get(t);n&&(n.forEach(i=>i()),this._closers.delete(t))}_addPathCloser(t,n){if(!n)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(n)}_readdirp(t,n){if(this.closed)return;let i={type:P2.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=DNd(t,i);return this._streams.add(o),o.once(kNd,()=>{o=void 0}),o.once(utu,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function kCE(r,t={}){let n=new Yio(t);return n.add(r),n}var YNd={watch:kCE,FSWatcher:Yio};var JNd=yt(require("path"));function jyt(r){if(JNd.default.basename(r).startsWith(".tmp-"))return!1;let n=r.substring(r.lastIndexOf("."));return n===".yml"||n===".yaml"||n===".sql"}function $Nd(r,t,n){let i=r==="."?".":r;return YNd.watch(i,{ignoreInitial:!0,persistent:!0,usePolling:!1,depth:99,ignored:[/(^|[\/\\])\../,/node_modules/]}).on("change",s=>{console.log(`[CHOKIDAR] change: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onChange(s)}).on("add",s=>{console.log(`[CHOKIDAR] add: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onAdd(s)}).on("unlink",s=>{console.log(`[CHOKIDAR] unlink: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onUnlink(s)}).on("error",t.onError).on("ready",t.onReady)}var XNd=require("node:fs/promises"),ZNd=require("node:path");async function eDd(r,t,n){let i=VK({baseDir:r}),o=n?["--force",t]:[t];await i.checkout(o)}async function tDd(r,t,n){let i=VK({baseDir:r});return n.name&&n.email&&(i=i.env("GIT_AUTHOR_NAME",n.name).env("GIT_AUTHOR_EMAIL",n.email).env("GIT_COMMITTER_NAME",n.name).env("GIT_COMMITTER_EMAIL",n.email)),await i.add("."),{commitSha:(await i.commit(t)).commit}}async function rDd(r,t,n){let i=VK({baseDir:r});try{let o=n||(await i.branch()).current;await i.push(["-u",t,o])}catch(o){let s=o instanceof Error?o.message:String(o),a=UCE(s);throw new Error(a)}}async function nDd(r){return{files:(await VK({baseDir:r}).status()).files.map(o=>({path:o.path,status:FCE(o.index+o.working_dir)}))}}async function iDd(r,t){let n=VK({baseDir:r}),o=(await n.status()).files.find(a=>a.path===t);if(o&&o.index==="?"&&o.working_dir==="?"){let a=(0,ZNd.join)(r,t),p=(await(0,XNd.readFile)(a,"utf-8")).split(`
|
|
10641
|
+
`):(clearInterval(o),this.keepaliveIntervals.delete(i))},3e4);this.keepaliveIntervals.set(i,o),t.on("close",()=>{ca.info("[RepositoryServer] SSE client disconnected",{clientId:i});let s=this.keepaliveIntervals.get(i);s&&(clearInterval(s),this.keepaliveIntervals.delete(i)),this.enqueueNoReply({type:"SSEClientDisconnected",clientId:i})})}async sendSnapshotToClient(t,n,i){ca.info("[RepositoryServer] sendSnapshotToClient called",{clientId:t,entityCount:i.length});let o=this.clients.get(t);if(!o){ca.warn("[RepositoryServer] Client not found during snapshot",{clientId:t});return}let s={type:"snapshot-start",serverId:this.serverId,sequenceNumber:this.sequenceNumber++};Vwe(n,s),ca.info("[RepositoryServer] Snapshot-start sent",{clientId:t});let a=new Map;for(let{entityType:p,id:c,path:l}of i)try{let d=await this.parseFileToRepository(l);if(!d){ca.debug("[RepositoryServer] Entity deleted during snapshot",{entityType:p,id:c,path:l});continue}let f=a.get(p)||[];f.push(d),a.set(p,f)}catch(d){ca.debug("[RepositoryServer] Entity changed during snapshot",{entityType:p,id:c,path:l,error:d instanceof Error?d.message:String(d)})}for(let[p,c]of a.entries()){if(p==="Package")continue;let l=c;if(p==="NodeType"&&!c.some(h=>h.id==="Source")){let h=await this.getPlatformKind(),A=this.getDefaultSourceNodeType(h);l=[...c,A]}let d={type:"snapshot-chunk",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:p,data:l};Vwe(n,d)}this.sendPackagesToClient(n),ca.info("[RepositoryServer] Sending envs-and-mappings",{clientId:t}),await this.sendEnvsAndMappingsToClient(n),ca.info("[RepositoryServer] Envs-and-mappings sent",{clientId:t});let u={type:"snapshot-complete",serverId:this.serverId,sequenceNumber:this.sequenceNumber++};Vwe(n,u),ca.info("[RepositoryServer] Snapshot complete sent",{clientId:t}),o.mode="draining",this.drainClientBuffer(t,n)}drainClientBuffer(t,n){let i=this.clients.get(t);if(i){for(let o of i.buffer)Vwe(n,o);i.buffer=[],i.mode="live"}}async parseFileToRepository(t){let n=await this.options.coordinator.parseFile(t);if(!n)return null;if(n.entityType==="NodeType"){let i=this.getEntityId(n,t),o={entityType:"NodeType",gitData:{...n.gitData,nodeType:{...n.gitData.nodeType,id:i}}};return this.convertGitToRepository(o)}return this.convertGitToRepository(n)}broadcastEntityUpdate(t,n){let i={type:"entity-update",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:t,data:n};this.broadcastToClients(i)}broadcastEntityDelete(t,n){let i={type:"entity-delete",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:t,id:n};this.broadcastToClients(i)}async buildEnvAndMappingsMessage(){let{locations:t,workspaceMappings:n,environments:i}=await this.options.coordinator.getMappingsSnapshot(),o=await this.getPlatformKind(),s={},a=t?.locations||[];for(let u of a)s[u]={};for(let u of a){let p=n?.[u];s[u]||(s[u]={}),s[u].__workspace__={database:p?.database??"",schema:p?.schema??""}}for(let u of i)for(let p of Object.keys(u.mappingDefinitions||{})){s[p]||(s[p]={});let c=u.mappingDefinitions[p];c&&(s[p][u.id]={database:c.database??"",schema:c.schema??""})}return{type:"env-and-mappings-updated",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,data:{mappings:s,environments:i.map(u=>({id:u.id,name:u.name,type:u.type,fileVersion:u.fileVersion})),defaultStorageMapping:t?.defaultStorageMapping||null,platformKind:o}}}async broadcastMappingsUpdate(){try{let t=await this.buildEnvAndMappingsMessage();this.broadcastToClients(t),ca.info("[RepositoryServer] Broadcasted env-and-mappings-updated")}catch(t){ca.error("[RepositoryServer] Failed to broadcast mappings update",{error:t instanceof Error?t.message:String(t)})}}broadcastToClients(t){let n=[];for(let[i,o]of this.clients.entries())if(o.mode==="live"){if(!Vwe(o.res,t)){ca.debug("[RepositoryServer] Client disconnected during broadcast",{clientId:i}),n.push(i);continue}}else{if(o.buffer.length>=this.MAX_CLIENT_BUFFER_SIZE){ca.error("[RepositoryServer] Client buffer exceeded limit, disconnecting",{clientId:i,bufferSize:o.buffer.length,limit:this.MAX_CLIENT_BUFFER_SIZE});try{o.res.end()}catch{}n.push(i);continue}o.buffer.push(t)}for(let i of n)this.cleanupClient(i)}getPackagesData(){let t=this.options.coordinator.readPackageCache();return t?Object.values(t):[]}sendPackagesToClient(t){let n={type:"snapshot-chunk",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:"Package",data:this.getPackagesData()};Vwe(t,n)}broadcastPackagesUpdate(){let t={type:"entity-bulk-update",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:"Package",data:this.getPackagesData()};this.broadcastToClients(t)}async sendEnvsAndMappingsToClient(t){try{let n=await this.buildEnvAndMappingsMessage();Vwe(t,n),ca.info("[RepositoryServer] Sent envs-and-mappings to snapshot client")}catch(n){ca.error("[RepositoryServer] Failed to send envs-and-mappings to snapshot client",{error:n instanceof Error?n.message:String(n)})}}convertGitToRepository(t){try{switch(t.entityType){case"Node":return JPd(t.gitData);case"Job":return Ueu(t.gitData);case"Macro":return $Pd(t.gitData);case"Subgraph":return XPd(t.gitData);case"NodeType":return zeu(t.gitData);case"Environment":case"Package":return t.gitData}}catch(n){return ca.error("[RepositoryServer] Failed to convert Git \u2192 Repository",{entityType:t.entityType,error:n instanceof Error?n.message:String(n)}),null}}async handleNodeWrite(t,n){try{let i=t.params.id,o=t.body;ca.info("[RepositoryServer] handleNodeWrite received",{nodeId:i,hasOperation:!!o.operation,operationKeys:o.operation?Object.keys(o.operation):[],operationName:o.operation?.name});let s={operation:{...o.operation,id:i}};ca.info("[RepositoryServer] handleNodeWrite after merge",{nodeId:i,operationKeys:Object.keys(s.operation),operationId:s.operation.id,operationName:s.operation.name});let a=jeu(s);await this.enqueue({type:"WriteNode",node:a,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Node write failed",{nodeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write node",details:o,nodeId:t.params.id})}}async handleNodeWriteV2(t,n){try{let i=t.params.id,{sql:o,name:s,location:a}=t.body;ca.info("[RepositoryServer] handleNodeWriteV2",{nodeId:i,name:s,location:a}),await this.enqueue({type:"WriteSQLNode",nodeId:i,sql:o,name:s,location:a,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] V2 node write failed",{nodeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write node",details:o})}}async handleJobCreate(t,n){try{let i=t.body,o=i.id,s=Qeu({name:i.name??"",includeSelector:i.includeSelector??"",excludeSelector:i.excludeSelector??"",version:2,id:o,jobCounter:o});await this.enqueue({type:"WriteJob",job:s,reply:()=>{}}),n.json({id:o})}catch(i){ca.error("[RepositoryServer] Job create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create job",details:o})}}async handleJobUpdate(t,n){try{let i=t.params.id,o=t.body;await this.enqueue({type:"UpdateJob",jobId:i,partialUpdate:o,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Job update failed",{jobId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update job",details:o,jobId:t.params.id})}}async handleMacroWrite(t,n){try{let i=t.params.id,o=t.body,s=ZPd({...o,id:i});await this.enqueue({type:"WriteMacro",macro:s,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Macro write failed",{macroId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write macro",details:o,macroId:t.params.id})}}async handleSubgraphCreate(t,n){try{ca.info("[RepositoryServer] Subgraph create request received",{body:t.body});let i=t.body,o=i.id;ca.info("[RepositoryServer] Converting subgraph",{subgraphId:o,repositorySubgraph:i});let s=Geu({...i,id:o});await this.enqueue({type:"WriteSubgraph",subgraph:s,reply:()=>{}}),n.json({id:o})}catch(i){ca.error("[RepositoryServer] Subgraph create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create subgraph",details:o})}}async handleSubgraphUpdate(t,n){try{let i=t.params.id,o=t.body,s=Geu({...o,id:i});await this.enqueue({type:"WriteSubgraph",subgraph:s,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Subgraph update failed",{subgraphId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update subgraph",details:o,subgraphId:t.params.id})}}async handleNodeTypeCreate(t,n){try{let i=t.body,o=crypto.randomUUID(),s={...i,id:o},a=Heu(s);await this.enqueue({type:"WriteNodeType",nodeType:a,reply:()=>{}}),n.json({id:o})}catch(i){ca.error("[RepositoryServer] NodeType create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create nodeType",details:o})}}async handleNodeTypeUpdate(t,n){try{let i=t.params.id,o=t.body;await this.enqueue({type:"UpdateNodeType",nodeTypeId:i,partialUpdate:o,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] NodeType update failed",{nodeTypeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update nodeType",details:o,nodeTypeId:t.params.id})}}async handleEnvironmentWrite(t,n){try{let i=t.body;await this.enqueue({type:"WriteEnvironment",env:i,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handlePackageWrite(t,n){try{let i=t.params.id,s={...t.body,id:i},a=e4d(s);await this.enqueue({type:"WritePackage",pkg:a,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleBulkNodesWrite(t,n){try{let o=t.body.nodes.map((s,a)=>{try{return jeu(s)}catch(u){throw new Error(`Failed to convert node at index ${a}: ${u instanceof Error?u.message:String(u)}`)}});await this.enqueue({type:"WriteBulkNodes",nodes:o,reply:()=>{}}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Bulk nodes write failed",{count:t.body.nodes.length,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write bulk nodes",details:o})}}async handleBulkNodesDelete(t,n){try{let{nodeIds:i}=t.body;if(!Array.isArray(i)||i.length===0){n.status(400).json({error:"nodeIds must be a non-empty array"});return}for(let o of i)await this.enqueue({type:"DeleteEntity",entityType:"Node",id:o,reply:()=>{}});n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Bulk nodes delete failed",{count:Array.isArray(t.body)?t.body.length:0,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to delete bulk nodes",details:o})}}async handleDelete(t,n,i){try{let o=n.params.id;await this.enqueue({type:"DeleteEntity",entityType:t,id:o,reply:()=>{}}),i.json({success:!0})}catch(o){let s=o instanceof Error?o.message:String(o);i.status(500).json({error:s})}}async handleCreateStorageLocation(t,n){try{let{name:i}=t.body,{locations:o,workspaceMappings:s,environments:a}=await this.options.coordinator.getMappingsSnapshot(),u=o?.locations||[];if(u.includes(i)){n.status(400).json({error:`Storage location '${i}' already exists`});return}await this.options.coordinator.writeLocations({locations:[...u,i],defaultStorageMapping:o?.defaultStorageMapping||null,fileVersion:1});let p={...s,[i]:{database:"",schema:""}};await this.options.coordinator.writeWorkspaceYml(p);for(let c of a){let l={...c,mappingDefinitions:{...c.mappingDefinitions,[i]:{database:"",schema:""}}};await this.options.coordinator.writeEnvironment(l)}n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Create storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleDeleteStorageLocation(t,n){try{let{name:i}=t.params,{locations:o,workspaceMappings:s,environments:a}=await this.options.coordinator.getMappingsSnapshot(),p=(o?.locations||[]).filter(l=>l!==i);await this.options.coordinator.writeLocations({locations:p,defaultStorageMapping:o?.defaultStorageMapping===i?null:o?.defaultStorageMapping||null,fileVersion:1});let c={...s};delete c[i],await this.options.coordinator.writeWorkspaceYml(c);for(let l of a){let d={...l.mappingDefinitions};delete d[i];let f={...l,mappingDefinitions:d};await this.options.coordinator.writeEnvironment(f)}n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Delete storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleSetDefaultStorageLocation(t,n){try{let{name:i}=t.body,{locations:o}=await this.options.coordinator.getMappingsSnapshot();await this.options.coordinator.writeLocations({locations:o?.locations||[],defaultStorageMapping:i,fileVersion:1}),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Set default storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleUpdateEnvironmentMappings(t,n){try{let{environmentId:i,workspaceId:o}=t.query,{mappings:s,name:a}=t.body;if(ca.info("[RepositoryServer] Update environment mappings",{environmentId:i,workspaceId:o,mappings:s,name:a}),i===o)await this.options.coordinator.writeWorkspaceYml(s);else{let{environments:u}=await this.options.coordinator.getMappingsSnapshot(),p=u.find(l=>l.id===i),c={type:"Environment",fileVersion:1,id:i,name:a||p?.name||`Environment ${i}`,mappingDefinitions:s};await this.options.coordinator.writeEnvironment(c)}n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Update environment mappings failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCheckout(t,n){try{let{branch:i,force:o}=t.body;await this.enqueue({type:"GitCheckout",branch:i,force:o??!1,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCommit(t,n){try{let{message:i,author:o}=t.body,s=await this.options.coordinator.gitCommit(i,o);n.json({commitSha:s})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitPush(t,n){try{let{branch:i,gitToken:o,gitUsername:s}=t.body;await this.options.coordinator.gitPush(i,o,s),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitStatus(t,n){try{let i=await this.options.coordinator.gitStatus();n.json({files:i.files})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitBranches(t,n){try{let i=await this.options.coordinator.gitBranches();n.json(i)}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitLog(t,n){try{let i=t.query.branch||"HEAD",o=t.query.limit?parseInt(t.query.limit,10):50,s=await this.options.coordinator.gitLog(i,o);n.json({commits:s})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitDiff(t,n){try{let i=t.query.file;if(!i||typeof i!="string"){n.status(400).json({error:"file query parameter required"});return}let o=await this.options.coordinator.gitDiff(i);n.json({diff:o})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCreateBranch(t,n){try{let{name:i}=t.body;if(!i||typeof i!="string"){n.status(400).json({error:"Branch name required"});return}await this.options.coordinator.gitCreateBranch(i),n.json({branch:i})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitAddAll(t,n){try{await this.options.coordinator.gitAddAll(),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleRescan(t,n){try{await this.options.coordinator.rescan(),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}handleUpdateConfig(t,n){try{let{content:i}=t.body;if(!i){n.status(400).json({error:"content is required"});return}this.writeCoaConfig(i),n.json({success:!0})}catch(i){ca.error("[RepositoryServer] Failed to update COA config",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleInstall(t,n){try{await this.enqueue({type:"CoaInstall",reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async processInstall(t){try{await this.runInstall(),t.reply()}catch(n){ca.error("[RepositoryServer] coa install failed",{error:n instanceof Error?n.message:String(n)}),t.reply(n instanceof Error?n:new Error(String(n)))}}processBroadcastPackagesUpdated(){this.broadcastPackagesUpdate()}getPathIndexKey(t,n){return`${t}:${n}`}findEntryByPath(t){for(let[n,i]of this.pathIndex.entries())if(i.path===t){let[o,s]=n.split(":");return{entityType:o,id:s}}}getEntityId(t,n){let i=S8.default.basename(n,S8.default.extname(n));switch(t.entityType){case"Node":if("id"in t.gitData&&typeof t.gitData.id=="string")return t.gitData.id;throw new Error(`Node file missing 'id' field: ${n}`);case"Job":case"Macro":case"Subgraph":case"Environment":{let o=i.lastIndexOf("-");if(o===-1)throw new Error(`${t.entityType} filename missing dash separator: ${n}`);return i.substring(o+1)}case"NodeType":{let o=S8.default.basename(S8.default.dirname(n)),s=o.indexOf("-");if(s===-1)throw new Error(`NodeType directory missing dash separator: ${n}`);return o.substring(s+1)}case"Package":return i;default:throw new Error(`Unknown entity type: ${t.entityType}`)}}async processChokidarBatch(t){let{changes:n,deletes:i,forceSnapshot:o}=t;ca.info("[RepositoryServer] Processing chokidar batch",{changes:n.length,deletes:i.length,forceSnapshot:o});let s=n.length+i.length,a=o||s>this.SNAPSHOT_THRESHOLD;a&&ca.info("[RepositoryServer] Will send snapshot instead of individual updates",{totalEvents:s,threshold:this.SNAPSHOT_THRESHOLD,forced:o});for(let u of n)try{let p=S8.default.basename(u);if(p==="locations.yml"||p==="workspace.yml"){await this.broadcastMappingsUpdate();continue}let c=await this.options.coordinator.parseFile(u);if(!c)continue;let l=this.getEntityId(c,u),d=this.getPathIndexKey(c.entityType,l);if(this.pathIndex.set(d,{path:u}),c.entityType==="Environment"){await this.broadcastMappingsUpdate();continue}if(c.entityType==="Package")continue;if(!a){let f=await this.parseFileToRepository(u);f&&this.broadcastEntityUpdate(c.entityType,f)}}catch(p){ca.error("[RepositoryServer] Failed to process file change",{path:u,error:p instanceof Error?p.message:String(p)})}for(let u of i)try{let p=this.findEntryByPath(u);if(!p){ca.debug("[RepositoryServer] Dropping programmatic delete event",{path:u});continue}let c=this.getPathIndexKey(p.entityType,p.id);this.pathIndex.delete(c),a||this.broadcastEntityDelete(p.entityType,p.id)}catch(p){ca.error("[RepositoryServer] Failed to process file delete",{path:u,error:p instanceof Error?p.message:String(p)})}if(a){let u=[];for(let[p,c]of this.pathIndex.entries()){let[l,d]=p.split(":");u.push({entityType:l,id:d,path:c.path})}ca.info("[RepositoryServer] Large batch - transitioning clients to snapshot mode",{entityCount:u.length,clientCount:this.clients.size});for(let p of this.clients.values())(p.mode==="live"||p.mode==="draining")&&(p.mode="snapshotting");this.sendSnapshotsAsync(u)}}async sendSnapshotsAsync(t){ca.info("[RepositoryServer] Broadcasting snapshots to all clients",{entityCount:t.length});for(let[n,i]of this.clients.entries())try{await this.sendSnapshotToClient(n,i.res,t)}catch(o){ca.error("[RepositoryServer] Failed to send snapshot to client",{clientId:n,error:o instanceof Error?o.message:String(o)}),this.clients.delete(n)}ca.info("[RepositoryServer] Snapshot broadcast complete")}async processSSEClientConnected(t){let{clientId:n,res:i}=t,o=[];for(let[s,a]of this.pathIndex.entries()){let[u,p]=s.split(":");o.push({entityType:u,id:p,path:a.path})}this.clients.set(n,{mode:"snapshotting",buffer:[],res:i}),t.reply();try{await this.sendSnapshotToClient(n,i,o)}catch(s){ca.error("[RepositoryServer] Snapshot failed",{clientId:n,error:s instanceof Error?s.message:String(s)}),this.clients.delete(n);try{i.end()}catch{}}}async processSSEClientDisconnected(t){this.cleanupClient(t.clientId)}cleanupClient(t){this.clients.delete(t);let n=this.keepaliveIntervals.get(t);n&&(clearInterval(n),this.keepaliveIntervals.delete(t))}async processWriteNode(t){let{node:n}=t,i=n.id,o=this.getPathIndexKey("Node",i),s=this.options.coordinator.getPathForNode(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeNode(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteSQLNode(t){let{nodeId:n,sql:i,name:o,location:s}=t,a=this.getPathIndexKey("Node",n),u=this.options.coordinator.getPathForSQLNode(o,s),c=this.pathIndex.get(a)?.path;this.pathIndex.set(a,{path:u});try{await this.options.coordinator.writeSQLNode(i,o,s),c&&c!==u&&await this.options.coordinator.deleteFile(c),t.reply()}catch(l){c?this.pathIndex.set(a,{path:c}):this.pathIndex.delete(a),t.reply(l instanceof Error?l:new Error(String(l)))}}async processWriteJob(t){let{job:n}=t,i=String(n.id),o=this.getPathIndexKey("Job",i),s=this.options.coordinator.getPathForJob(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeJob(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processUpdateJob(t){let{jobId:n,partialUpdate:i}=t,o=this.getPathIndexKey("Job",n),s=this.pathIndex.get(o);try{let a={...i,id:Number(n)};if(s){let l=await this.options.coordinator.parseFile(s.path);if(l&&l.entityType==="Job"){let d=Ueu(l.gitData);a=iQe({},d,i,{id:Number(n)})}}let u=Qeu(a),p=this.options.coordinator.getPathForJob(u),c=s?.path;this.pathIndex.set(o,{path:p}),await this.options.coordinator.writeJob(u),c&&c!==p&&await this.options.coordinator.deleteFile(c),t.reply()}catch(a){s?this.pathIndex.set(o,s):this.pathIndex.delete(o),t.reply(a instanceof Error?a:new Error(String(a)))}}async processWriteMacro(t){let{macro:n}=t,i=n.id,o=this.getPathIndexKey("Macro",i),s=this.options.coordinator.getPathForMacro(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeMacro(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteSubgraph(t){let{subgraph:n}=t,i=String(n.id),o=this.getPathIndexKey("Subgraph",i),s=this.options.coordinator.getPathForSubgraph(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeSubgraph(n),ca.info("[RepositoryServer] processWriteSubgraph completed",{id:i,newPath:s,oldPath:u}),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteNodeType(t){let{nodeType:n}=t,i=String(n.nodeType.id);if(i==="Source"){t.reply();return}let o=this.getPathIndexKey("NodeType",i),s=this.options.coordinator.getPathForNodeType(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeNodeType(n),u&&u!==s&&await this.options.coordinator.deleteDirectory(S8.default.dirname(u)),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processUpdateNodeType(t){let{nodeTypeId:n,partialUpdate:i}=t;if(n==="Source"){t.reply();return}let o=this.getPathIndexKey("NodeType",n),s=this.pathIndex.get(o);try{let a={...i,id:n};if(s){let l=S8.default.dirname(s.path),d=S8.default.join(l,"definition.yml"),f=await this.options.coordinator.parseFile(d);if(f&&f.entityType==="NodeType"){let h={...f.gitData,nodeType:{...f.gitData.nodeType,id:n}};a=iQe({},zeu(h),i,{id:n})}}let u=Heu(a),p=this.options.coordinator.getPathForNodeType(u),c=s?.path;this.pathIndex.set(o,{path:p}),await this.options.coordinator.writeNodeType(u),c&&c!==p&&await this.options.coordinator.deleteDirectory(S8.default.dirname(c)),t.reply()}catch(a){s?this.pathIndex.set(o,s):this.pathIndex.delete(o),t.reply(a instanceof Error?a:new Error(String(a)))}}async processWriteEnvironment(t){let{env:n}=t,i=String(n.id),o=this.getPathIndexKey("Environment",i),s=this.options.coordinator.getPathForEnvironment(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeEnvironment(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWritePackage(t){let{pkg:n}=t,i=n.packageID,o=this.getPathIndexKey("Package",i),s=this.options.coordinator.getPathForPackage(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s}),await this.options.coordinator.writePackage(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),await this.runInstall(),t.reply()}async processWriteBulkNodes(t){let{nodes:n}=t,i=[];for(let o of n){let s=o.id,a=this.getPathIndexKey("Node",s),u=this.options.coordinator.getPathForNode(o),p=this.pathIndex.get(a)?.path;this.pathIndex.set(a,{path:u}),p&&p!==u&&i.push({oldPath:p,newPath:u})}await this.options.coordinator.writeBulkNodes(n);for(let{oldPath:o}of i)await this.options.coordinator.deleteFile(o);t.reply()}async processDeleteEntity(t){let{entityType:n,id:i}=t,o=this.getPathIndexKey(n,i),s=this.pathIndex.get(o);if(!s){t.reply(new Error(`Entity not found: ${n}:${i}`));return}this.pathIndex.delete(o);try{n==="NodeType"?await this.options.coordinator.deleteDirectory(S8.default.dirname(s.path)):await this.options.coordinator.deleteFile(s.path)}catch(a){this.pathIndex.set(o,s),t.reply(a instanceof Error?a:new Error(String(a)));return}if(this.broadcastEntityDelete(n,i),t.reply(),n==="Package")try{await this.runInstall()}catch(a){ca.error("[RepositoryServer] coa install failed after package delete",{id:i,error:a instanceof Error?a.message:String(a)})}}async processWriteDataYml(t){try{await this.options.coordinator.writeDataYml(t.data),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)))}}async processWriteLocations(t){try{await this.options.coordinator.writeLocations(t.locations),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)))}}async processGitCheckout(t){try{let{branch:n,force:i}=t;await this.options.coordinator.gitCheckout(n,i),this.pathIndex.clear(),await this.options.coordinator.rescan(),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)));return}await this.runInstall()}writeCoaConfig(t){let n=S8.default.join(oNd.default.homedir(),".coa","config"),i=S8.default.dirname(n);ttu.default.mkdirSync(i,{recursive:!0,mode:448}),ttu.default.writeFileSync(n,t,{encoding:"utf-8",mode:384}),ca.info("[RepositoryServer] Updated COA config")}async runInstall(){let t=this.options.coordinator.getWorkspaceDir(),{stderr:n}=await tCE("coa",["install","-d",t]);n&&ca.warn("[RepositoryServer] coa install stderr",{stderr:n}),ca.info("[RepositoryServer] coa install completed"),this.processBroadcastPackagesUpdated()}enqueue(t){return new Promise((n,i)=>{let o={...t,reply:s=>{s instanceof Error?i(s):n(s)}};this.queue.push(o),this.processQueue()})}enqueueNoReply(t){this.queue.push(t),this.processQueue()}async processQueue(){if(!(this.processing||this.queue.length===0)){for(this.processing=!0;this.queue.length>0;){let t=this.queue.shift();try{await this.handleMessage(t)}catch(n){ca.error("[RepositoryServer] Message processing failed",{messageType:t.type,error:n instanceof Error?n.message:String(n)}),"reply"in t&&t.reply(n instanceof Error?n:new Error(String(n)))}}this.processing=!1}}async handleMessage(t){switch(t.type){case"WriteNode":await this.processWriteNode(t);break;case"WriteSQLNode":await this.processWriteSQLNode(t);break;case"WriteJob":await this.processWriteJob(t);break;case"UpdateJob":await this.processUpdateJob(t);break;case"WriteMacro":await this.processWriteMacro(t);break;case"WriteSubgraph":await this.processWriteSubgraph(t);break;case"WriteNodeType":await this.processWriteNodeType(t);break;case"UpdateNodeType":await this.processUpdateNodeType(t);break;case"WriteEnvironment":await this.processWriteEnvironment(t);break;case"WritePackage":await this.processWritePackage(t);break;case"WriteBulkNodes":await this.processWriteBulkNodes(t);break;case"DeleteEntity":await this.processDeleteEntity(t);break;case"WriteDataYml":await this.processWriteDataYml(t);break;case"WriteLocations":await this.processWriteLocations(t);break;case"GitCheckout":await this.processGitCheckout(t);break;case"ProcessChokidarBatch":await this.processChokidarBatch(t);break;case"BroadcastPackagesUpdated":this.processBroadcastPackagesUpdated();break;case"CoaInstall":await this.processInstall(t);break;case"SSEClientConnected":await this.processSSEClientConnected(t);break;case"SSEClientDisconnected":await this.processSSEClientDisconnected(t);break;default:{let n=t;throw new Error(`Unknown message type: ${n.type}`)}}}async readPlatformKindFromDataYml(){try{let t=await this.options.coordinator.loadDataYml(),n=jh.safeParse(t?.platformKind);return n.success?n.data:void 0}catch{return}}async getPlatformKind(){return await this.readPlatformKindFromDataYml()??"snowflake"}getDefaultSourceNodeType(t){let i=lNe(t).Source;if(!i)throw new Error(`Source node type not found in defaults for platform ${t}`);return i}async handleListApps(t,n){try{let i=await this.appManager.discoverApps();n.json({apps:i})}catch(i){ca.error("[RepositoryServer] Failed to list apps",{error:i}),n.status(500).json({error:{errorString:String(i)}})}}async handleAppProxy(t,n){let{appId:i}=t.params;if(!i){n.status(400).json({error:{errorString:"appId required"}});return}let o;try{o=await this.appManager.ensureRunning(i)}catch(p){ca.error("[RepositoryServer] Failed to start app for proxy",{appId:i,error:p}),n.status(502).json({error:{errorString:String(p)}});return}let s=`/api/v1/watch/apps/${i}/proxy`,a=t.originalUrl.slice(t.originalUrl.indexOf(s)+s.length)||"/",u=`${o}${a}`;try{let p={};t.headers["content-type"]&&(p["content-type"]=t.headers["content-type"]),t.headers.accept&&(p.accept=t.headers.accept);let c=await fetch(u,{method:t.method,headers:p,body:t.method!=="GET"&&t.method!=="HEAD"?JSON.stringify(t.body):void 0});if(n.status(c.status),c.headers.forEach((l,d)=>{d!=="transfer-encoding"&&n.setHeader(d,l)}),c.body){let l=c.body.getReader();try{for(;;){let{done:d,value:f}=await l.read();if(d)break;n.write(f)}}finally{l.releaseLock()}}n.end()}catch(p){ca.error("[RepositoryServer] App proxy error",{appId:i,error:p}),n.headersSent||n.status(502).json({error:{errorString:String(p)}})}}};var fY=require("fs"),t1e=yt(require("path"));var Eae=yt(require("crypto")),aNd=yt(require("fs")),O1=require("fs"),Up=yt(require("path"));var bae=Je("COA_WATCH"),rCE=mce.strip().extend({contents:mce.shape.contents.strip()});async function uNd(r,t,n,i="snowflake"){try{let o=await O1.promises.readFile(r,"utf-8"),s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16),u=Up.default.relative(t,r).split(Up.default.sep);if(u[0]==="nodes"&&r.endsWith(".sql"))return{entityType:"Node",data:await hxr({fileData:o,filePath:r,type:"File"},n,i),hash:s};if(u[0]==="nodes"&&r.endsWith(".yml"))return{entityType:"Node",data:Sp(r,o),hash:s};if(u[0]==="jobs"&&r.endsWith(".yml"))return{entityType:"Job",data:Sp(r,o),hash:s};if(u[0]==="macros"&&r.endsWith(".yml"))return{entityType:"Macro",data:Sp(r,o),hash:s};if(u[0]==="subgraphs"&&r.endsWith(".yml"))return{entityType:"Subgraph",data:Sp(r,o),hash:s};if(u[0]==="nodeTypes"&&u[u.length-1]==="definition.yml"){let p=await nCE(Up.default.dirname(r),n);if(p)return{entityType:"NodeType",data:p,hash:s}}else{if(u[0]==="environments"&&r.endsWith(".yml"))return{entityType:"Environment",data:Sp(r,o),hash:s};if(u[0]==="packages"&&r.endsWith(".yml"))return{entityType:"Package",data:Sp(r,o),hash:s}}return null}catch(o){return bae.error("[FileIO] Error parsing file",{filePath:r,error:o instanceof Error?o.message:String(o)}),null}}async function nCE(r,t){try{let n=Up.default.join(r,"definition.yml"),i=await O1.promises.readFile(n,"utf-8"),o=Sp(n,i),s=Up.default.join(r,"create.sql"),a=Up.default.join(r,"create.sql.j2"),u=Up.default.join(r,"run.sql"),p=Up.default.join(r,"run.sql.j2"),c=await O1.promises.readFile(s,"utf-8").catch(()=>null)||await O1.promises.readFile(a,"utf-8").catch(()=>null),l=await O1.promises.readFile(u,"utf-8").catch(()=>null)||await O1.promises.readFile(p,"utf-8").catch(()=>null);return{nodeType:o,create:c||"",run:l||""}}catch(n){return bae.error("[FileIO] Failed to parse NodeType",{nodeTypeDir:r,error:n instanceof Error?n.message:String(n)}),null}}async function rtu(r,t){_Z.parse(r);let n=r.operation.name,i=r.operation.locationName,o=BR(`${i}-${n}`),s=Up.default.join(t,"nodes",`${o}.yml`);await O1.promises.mkdir(Up.default.dirname(s),{recursive:!0});let a=UA(r,{sortKeys:!0});await O1.promises.writeFile(s,a,"utf-8");let u=Eae.createHash("sha256").update(a).digest("hex").substring(0,16);return{path:s,hash:u}}async function cNd(r,t){if(WH.parse(r),!r.name)throw new Error(`Job ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"jobs",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function lNd(r,t){if(TZ.parse(r),!r.name)throw new Error(`Macro ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"macros",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function pNd(r,t){if(IZ.parse(r),!r.name)throw new Error(`Subgraph ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"subgraphs",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function dNd(r,t){if(_2e.parse(r),!r.name)throw new Error(`Environment ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"environments",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function fNd(r,t){tbe.parse(r);let n=BR(r.name),i=Up.default.join(t,"packages",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function hNd(r,t){let{nodeType:n,create:i,run:o}=r;if(!n.name)throw new Error(`NodeType ${n.id} missing required name field`);let s=BR(`${n.name}-${n.id}`),a=Up.default.join(t,"nodeTypes",s);await O1.promises.mkdir(a,{recursive:!0});let u=Up.default.join(a,"definition.yml"),p=UA(n,{sortKeys:!0});if(await O1.promises.writeFile(u,p,"utf-8"),i){let l=Up.default.join(a,"create.sql.j2");await O1.promises.writeFile(l,i,"utf-8")}if(o){let l=Up.default.join(a,"run.sql.j2");await O1.promises.writeFile(l,o,"utf-8")}let c=Eae.createHash("sha256").update(p).digest("hex").substring(0,16);return{definitionPath:u,hash:c}}async function gNd(r){try{let t=Up.default.join(r,"data.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n)}catch(t){return bae.error("[FileIO] Failed to load data.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function ANd(r){try{let t=Up.default.join(r,"locations.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n)}catch(t){return bae.error("[FileIO] Failed to load locations.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function mNd(r){try{let t=Up.default.join(r,"environments"),n=await O1.promises.readdir(t),i=[];for(let o of n)if(o.endsWith(".yml"))try{let s=Up.default.join(t,o),a=await O1.promises.readFile(s,"utf-8"),u=Sp(s,a);u&&i.push(u)}catch(s){bae.warn("[FileIO] Failed to load environment file",{file:o,error:s instanceof Error?s.message:String(s)})}return i}catch(t){return bae.error("[FileIO] Failed to load environments directory",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),[]}}async function yNd(r){try{let t=Up.default.join(r,"workspace.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n).locations||null}catch(t){return t instanceof Error&&t.message.includes("ENOENT")||bae.error("[FileIO] Failed to load workspace.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function bNd(r,t){let n=Up.default.join(r,"workspace.yml"),i=UA({locations:t},{sortKeys:!0});await O1.promises.writeFile(n,i,"utf-8")}function ENd(r,t){let n=t.operation.locationName,i=t.operation.name,o=BR(`${n}-${i}`);return Up.default.join(r,"nodes",`${o}.yml`)}function ntu(r,t,n){let i=BR(`${n}-${t}`);return Up.default.join(r,"nodes",`${i}.sql`)}async function CNd(r,t,n,i){let o=ntu(i,t,n);await O1.promises.mkdir(Up.default.dirname(o),{recursive:!0}),await O1.promises.writeFile(o,r,"utf-8");let s=Eae.createHash("sha256").update(r).digest("hex").substring(0,16);return{path:o,hash:s}}function SNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"jobs",`${n}.yml`)}function vNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"macros",`${n}.yml`)}function TNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"subgraphs",`${n}.yml`)}function _Nd(r,t){let n=BR(`${t.nodeType.name}-${t.nodeType.id}`);return Up.default.join(r,"nodeTypes",n,"definition.yml")}function INd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"environments",`${n}.yml`)}function RNd(r,t){let n=BR(t.name);return Up.default.join(r,"packages",`${n}.yml`)}var iCE=".coa/cache",oCE="packages.json";function ONd(r){let t=Up.default.join(r,iCE,oCE);try{let n=JSON.parse(aNd.readFileSync(t,"utf-8"));if(typeof n!="object"||n===null)return bae.warn("[FileIO] Package cache is not a valid object",{cachePath:t}),null;let i={};for(let[o,s]of Object.entries(n)){let a=rCE.safeParse(s);a.success?i[o]=a.data:bae.warn("[FileIO] Skipping invalid package in cache",{alias:o})}return Object.keys(i).length>0?i:null}catch(n){return bae.error("[FileIO] Failed to read package cache",{cachePath:t,error:n instanceof Error?n.message:String(n)}),null}}var GNd=require("node:events"),HNd=require("node:fs"),Jio=require("node:fs/promises"),R0=yt(require("node:path"),1);var Zhe=require("node:fs/promises"),e1e=require("node:path"),PNd=require("node:stream"),r7={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},itu={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:r7.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(itu);var NNd="READDIRP_RECURSIVE_ERROR",aCE=new Set(["ENOENT","EPERM","EACCES","ELOOP",NNd]),wNd=[r7.DIR_TYPE,r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE,r7.FILE_TYPE],uCE=new Set([r7.DIR_TYPE,r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE]),cCE=new Set([r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE,r7.FILE_TYPE]),lCE=r=>aCE.has(r.code),pCE=process.platform==="win32",MNd=r=>!0,xNd=r=>{if(r===void 0)return MNd;if(typeof r=="function")return r;if(typeof r=="string"){let t=r.trim();return n=>n.basename===t}if(Array.isArray(r)){let t=r.map(n=>n.trim());return n=>t.some(i=>n.basename===i)}return MNd},otu=class extends PNd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let n={...itu,...t},{root:i,type:o}=n;this._fileFilter=xNd(n.fileFilter),this._directoryFilter=xNd(n.directoryFilter);let s=n.lstat?Zhe.lstat:Zhe.stat;pCE?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:itu.depth,this._wantsDir=o?uCE.has(o):!1,this._wantsFile=o?cCE.has(o):!1,this._wantsEverything=o===r7.EVERYTHING_TYPE,this._root=(0,e1e.resolve)(i),this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let n=this.parent,i=n&&n.files;if(i&&i.length>0){let{path:o,depth:s}=n,a=i.splice(0,t).map(p=>this._formatEntry(p,o)),u=await Promise.all(a);for(let p of u){if(!p)continue;if(this.destroyed)return;let c=await this._getEntryType(p);c==="directory"&&this._directoryFilter(p)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(p.fullPath,s+1)),this._wantsDir&&(this.push(p),t--)):(c==="file"||this._includeAsFile(p))&&this._fileFilter(p)&&this._wantsFile&&(this.push(p),t--)}}else{let o=this.parents.pop();if(!o){this.push(null);break}if(this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(t,n){let i;try{i=await(0,Zhe.readdir)(t,this._rdOptions)}catch(o){this._onError(o)}return{files:i,depth:n,path:t}}async _formatEntry(t,n){let i,o=this._isDirent?t.name:t;try{let s=(0,e1e.resolve)((0,e1e.join)(n,o));i={path:(0,e1e.relative)(this._root,s),fullPath:s,basename:o},i[this._statsProp]=this._isDirent?t:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(t){lCE(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let n=t[this._statsProp];if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let i=t.fullPath;try{let o=await(0,Zhe.realpath)(i),s=await(0,Zhe.lstat)(o);if(s.isFile())return"file";if(s.isDirectory()){let a=o.length;if(i.startsWith(o)&&i.substr(a,1)===e1e.sep){let u=new Error(`Circular symlink detected: "${i}" points to "${o}"`);return u.code=NNd,this._onError(u)}return"directory"}}catch(o){return this._onError(o),""}}}_includeAsFile(t){let n=t&&t[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function DNd(r,t={}){let n=t.entryType||t.type;if(n==="both"&&(n=r7.FILE_DIR_TYPE),n&&(t.type=n),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!wNd.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${wNd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=r,new otu(t)}var DFe=require("node:fs"),dY=require("node:fs/promises"),LNd=require("node:os"),OE=yt(require("node:path"),1),dCE="data",utu="end",kNd="close",Vio=()=>{};var Wio=process.platform,ctu=Wio==="win32",fCE=Wio==="darwin",hCE=Wio==="linux",gCE=Wio==="freebsd",qNd=(0,LNd.type)()==="OS400",P2={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},pY=P2,ACE="watch",mCE={lstat:dY.lstat,stat:dY.stat},NFe="listeners",Qio="errHandlers",Qyt="rawEmitters",yCE=[NFe,Qio,Qyt],bCE=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),ECE=r=>bCE.has(OE.extname(r).slice(1).toLowerCase()),atu=(r,t)=>{r instanceof Set?r.forEach(t):t(r)},rYt=(r,t,n)=>{let i=r[t];i instanceof Set||(r[t]=i=new Set([i])),i.add(n)},CCE=r=>t=>{let n=r[t];n instanceof Set?n.clear():delete r[t]},nYt=(r,t,n)=>{let i=r[t];i instanceof Set?i.delete(n):i===n&&delete r[t]},FNd=r=>r instanceof Set?r.size===0:!r,jio=new Map;function BNd(r,t,n,i,o){let s=(a,u)=>{n(r),o(a,u,{watchedPath:r}),u&&r!==u&&Gio(OE.resolve(r,u),NFe,OE.join(r,u))};try{return(0,DFe.watch)(r,{persistent:t.persistent},s)}catch(a){i(a);return}}var Gio=(r,t,n,i,o)=>{let s=jio.get(r);s&&atu(s[t],a=>{a(n,i,o)})},SCE=(r,t,n,i)=>{let{listener:o,errHandler:s,rawEmitter:a}=i,u=jio.get(t),p;if(!n.persistent)return p=BNd(r,n,o,s,a),p?p.close.bind(p):void 0;if(u)rYt(u,NFe,o),rYt(u,Qio,s),rYt(u,Qyt,a);else{if(p=BNd(r,n,Gio.bind(null,t,NFe),s,Gio.bind(null,t,Qyt)),!p)return;p.on(pY.ERROR,async c=>{let l=Gio.bind(null,t,Qio);if(u&&(u.watcherUnusable=!0),ctu&&c.code==="EPERM")try{await(await(0,dY.open)(r,"r")).close(),l(c)}catch{}else l(c)}),u={listeners:o,errHandlers:s,rawEmitters:a,watcher:p},jio.set(t,u)}return()=>{nYt(u,NFe,o),nYt(u,Qio,s),nYt(u,Qyt,a),FNd(u.listeners)&&(u.watcher.close(),jio.delete(t),yCE.forEach(CCE(u)),u.watcher=void 0,Object.freeze(u))}},stu=new Map,vCE=(r,t,n,i)=>{let{listener:o,rawEmitter:s}=i,a=stu.get(t),u=a&&a.options;return u&&(u.persistent<n.persistent||u.interval>n.interval)&&((0,DFe.unwatchFile)(t),a=void 0),a?(rYt(a,NFe,o),rYt(a,Qyt,s)):(a={listeners:o,rawEmitters:s,options:n,watcher:(0,DFe.watchFile)(t,n,(p,c)=>{atu(a.rawEmitters,d=>{d(pY.CHANGE,t,{curr:p,prev:c})});let l=p.mtimeMs;(p.size!==c.size||l>c.mtimeMs||l===0)&&atu(a.listeners,d=>d(r,p))})},stu.set(t,a)),()=>{nYt(a,NFe,o),nYt(a,Qyt,s),FNd(a.listeners)&&(stu.delete(t),(0,DFe.unwatchFile)(t),a.options=a.watcher=void 0,Object.freeze(a))}},Hio=class{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=n=>t._handleError(n)}_watchWithNodeFs(t,n){let i=this.fsw.options,o=OE.dirname(t),s=OE.basename(t);this.fsw._getWatchedDir(o).add(s);let u=OE.resolve(t),p={persistent:i.persistent};n||(n=Vio);let c;if(i.usePolling){let l=i.interval!==i.binaryInterval;p.interval=l&&ECE(s)?i.binaryInterval:i.interval,c=vCE(t,u,p,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=SCE(t,u,p,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(t,n,i){if(this.fsw.closed)return;let o=OE.dirname(t),s=OE.basename(t),a=this.fsw._getWatchedDir(o),u=n;if(a.has(s))return;let p=async(l,d)=>{if(this.fsw._throttle(ACE,t,5)){if(!d||d.mtimeMs===0)try{let f=await(0,dY.stat)(t);if(this.fsw.closed)return;let h=f.atimeMs,A=f.mtimeMs;if((!h||h<=A||A!==u.mtimeMs)&&this.fsw._emit(pY.CHANGE,t,f),(fCE||hCE||gCE)&&u.ino!==f.ino){this.fsw._closeFile(l),u=f;let E=this._watchWithNodeFs(t,p);E&&this.fsw._addPathCloser(l,E)}else u=f}catch{this.fsw._remove(o,s)}else if(a.has(s)){let f=d.atimeMs,h=d.mtimeMs;(!f||f<=h||h!==u.mtimeMs)&&this.fsw._emit(pY.CHANGE,t,d),u=d}}},c=this._watchWithNodeFs(t,p);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(pY.ADD,t,0))return;this.fsw._emit(pY.ADD,t,n)}return c}async _handleSymlink(t,n,i,o){if(this.fsw.closed)return;let s=t.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let u;try{u=await(0,dY.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(o)?this.fsw._symlinkPaths.get(s)!==u&&(this.fsw._symlinkPaths.set(s,u),this.fsw._emit(pY.CHANGE,i,t.stats)):(a.add(o),this.fsw._symlinkPaths.set(s,u),this.fsw._emit(pY.ADD,i,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(t,n,i,o,s,a,u){t=OE.join(t,"");let p=o?`${t}:${o}`:t;if(u=this.fsw._throttle("readdir",p,1e3),!u)return;let c=this.fsw._getWatchedDir(i.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>i.filterPath(f),directoryFilter:f=>i.filterDir(f)});if(d)return d.on(dCE,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,A=OE.join(t,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,A,h))){if(this.fsw.closed){d=void 0;return}(h===o||!o&&!c.has(h))&&(this.fsw._incrReadyCount(),A=OE.join(s,OE.relative(s,A)),this._addToNodeFs(A,n,i,a+1))}}).on(pY.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!d)return h();d.once(utu,()=>{if(this.fsw.closed){d=void 0;return}let A=u?u.clear():!1;f(void 0),c.getChildren().filter(E=>E!==t&&!l.has(E)).forEach(E=>{this.fsw._remove(t,E)}),d=void 0,A&&this._handleRead(t,!1,i,o,s,a,u)})})}async _handleDir(t,n,i,o,s,a,u){let p=this.fsw._getWatchedDir(OE.dirname(t)),c=p.has(OE.basename(t));!(i&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(pY.ADD_DIR,t,n),p.add(OE.basename(t)),this.fsw._getWatchedDir(t);let l,d,f=this.fsw.options.depth;if((f==null||o<=f)&&!this.fsw._symlinkPaths.has(u)){if(!s&&(await this._handleRead(t,i,a,s,t,o,l),this.fsw.closed))return;d=this._watchWithNodeFs(t,(h,A)=>{A&&A.mtimeMs===0||this._handleRead(h,!1,a,s,t,o,l)})}return d}async _addToNodeFs(t,n,i,o,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let u=this.fsw._getWatchHelpers(t);i&&(u.filterPath=p=>i.filterPath(p),u.filterDir=p=>i.filterDir(p));try{let p=await mCE[u.statMethod](u.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(u.watchPath,p))return a(),!1;let c=this.fsw.options.followSymlinks,l;if(p.isDirectory()){let d=OE.resolve(t),f=c?await(0,dY.realpath)(t):t;if(this.fsw.closed||(l=await this._handleDir(u.watchPath,p,n,o,s,u,f),this.fsw.closed))return;d!==f&&f!==void 0&&this.fsw._symlinkPaths.set(d,f)}else if(p.isSymbolicLink()){let d=c?await(0,dY.realpath)(t):t;if(this.fsw.closed)return;let f=OE.dirname(u.watchPath);if(this.fsw._getWatchedDir(f).add(u.watchPath),this.fsw._emit(pY.ADD,u.watchPath,p),l=await this._handleDir(f,p,n,o,t,u,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(OE.resolve(t),d)}else l=this._handleFile(u.watchPath,p,n);return a(),l&&this.fsw._addPathCloser(t,l),!1}catch(p){if(this.fsw._handleError(p))return a(),t}}};var ltu="/",TCE="//",VNd=".",_CE="..",ICE="string",RCE=/\\/g,WNd=/\/\//g,OCE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,wCE=/^\.[/\\]/;function Kio(r){return Array.isArray(r)?r:[r]}var ptu=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function MCE(r){return typeof r=="function"?r:typeof r=="string"?t=>r===t:r instanceof RegExp?t=>r.test(t):typeof r=="object"&&r!==null?t=>{if(r.path===t)return!0;if(r.recursive){let n=R0.relative(r.path,t);return n?!n.startsWith("..")&&!R0.isAbsolute(n):!1}return!1}:()=>!1}function xCE(r){if(typeof r!="string")throw new Error("string expected");r=R0.normalize(r),r=r.replace(/\\/g,"/");let t=!1;return r.startsWith("//")&&(t=!0),r=r.replace(WNd,"/"),t&&(r="/"+r),r}function UNd(r,t,n){let i=xCE(t);for(let o=0;o<r.length;o++){let s=r[o];if(s(i,n))return!0}return!1}function PCE(r,t){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Kio(r).map(o=>MCE(o));return t==null?(o,s)=>UNd(i,o,s):UNd(i,t)}var zNd=r=>{let t=Kio(r).flat();if(!t.every(n=>typeof n===ICE))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(KNd)},QNd=r=>{let t=r.replace(RCE,ltu),n=!1;return t.startsWith(TCE)&&(n=!0),t=t.replace(WNd,ltu),n&&(t=ltu+t),t},KNd=r=>QNd(R0.normalize(QNd(r))),jNd=(r="")=>t=>typeof t=="string"?KNd(R0.isAbsolute(t)?t:R0.join(r,t)):t,NCE=(r,t)=>R0.isAbsolute(r)?r:R0.join(t,r),DCE=Object.freeze(new Set),dtu=class{path;_removeWatcher;items;constructor(t,n){this.path=t,this._removeWatcher=n,this.items=new Set}add(t){let{items:n}=this;n&&t!==VNd&&t!==_CE&&n.add(t)}async remove(t){let{items:n}=this;if(!n||(n.delete(t),n.size>0))return;let i=this.path;try{await(0,Jio.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(R0.dirname(i),R0.basename(i))}}has(t){let{items:n}=this;if(n)return n.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Vio,this.items=DCE,Object.freeze(this)}},BCE="stat",LCE="lstat",ftu=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,n,i){this.fsw=i;let o=t;this.path=t=t.replace(wCE,""),this.watchPath=o,this.fullWatchPath=R0.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?BCE:LCE}entryPath(t){return R0.join(this.watchPath,R0.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:n}=t;if(n&&n.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,n)&&this.fsw._hasReadPermissions(n)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},Yio=class extends GNd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},o={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?Kio(t.ignored):Kio([]),awaitWriteFinish:n===!0?i:typeof n=="object"?{...i,...n}:!1};qNd&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let p=s.toLowerCase();p==="false"||p==="0"?o.usePolling=!1:p==="true"||p==="1"?o.usePolling=!0:o.usePolling=!!p}let a=process.env.CHOKIDAR_INTERVAL;a&&(o.interval=Number.parseInt(a,10));let u=0;this._emitReady=()=>{u++,u>=this._readyCount&&(this._emitReady=Vio,this._readyEmitted=!0,process.nextTick(()=>this.emit(P2.READY)))},this._emitRaw=(...p)=>this.emit(P2.RAW,...p),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Hio(this),Object.freeze(o)}_addIgnoredPath(t){if(ptu(t)){for(let n of this._ignoredPaths)if(ptu(n)&&n.path===t.path&&n.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let n of this._ignoredPaths)ptu(n)&&n.path===t&&this._ignoredPaths.delete(n)}add(t,n,i){let{cwd:o}=this.options;this.closed=!1,this._closePromise=void 0;let s=zNd(t);return o&&(s=s.map(a=>NCE(a,o))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let u=await this._nodeFsHandler._addToNodeFs(a,!i,void 0,0,n);return u&&this._emitReady(),u})).then(a=>{this.closed||a.forEach(u=>{u&&this.add(R0.dirname(u),R0.basename(n||u))})}),this}unwatch(t){if(this.closed)return this;let n=zNd(t),{cwd:i}=this.options;return n.forEach(o=>{!R0.isAbsolute(o)&&!this._closers.has(o)&&(i&&(o=R0.join(i,o)),o=R0.resolve(o)),this._closePath(o),this._addIgnoredPath(o),this._watched.has(o)&&this._addIgnoredPath({path:o,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(n=>n.forEach(i=>{let o=i();o instanceof Promise&&t.push(o)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((n,i)=>{let s=(this.options.cwd?R0.relative(this.options.cwd,i):i)||VNd;t[s]=n.getChildren().sort()}),t}emitWithAll(t,n){this.emit(t,...n),t!==P2.ERROR&&this.emit(P2.ALL,t,...n)}async _emit(t,n,i){if(this.closed)return;let o=this.options;ctu&&(n=R0.normalize(n)),o.cwd&&(n=R0.relative(o.cwd,n));let s=[n];i!=null&&s.push(i);let a=o.awaitWriteFinish,u;if(a&&(u=this._pendingWrites.get(n)))return u.lastChange=new Date,this;if(o.atomic){if(t===P2.UNLINK)return this._pendingUnlinks.set(n,[t,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((p,c)=>{this.emit(...p),this.emit(P2.ALL,...p),this._pendingUnlinks.delete(c)})},typeof o.atomic=="number"?o.atomic:100),this;t===P2.ADD&&this._pendingUnlinks.has(n)&&(t=P2.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(t===P2.ADD||t===P2.CHANGE)&&this._readyEmitted){let p=(c,l)=>{c?(t=P2.ERROR,s[0]=c,this.emitWithAll(t,s)):l&&(s.length>1?s[1]=l:s.push(l),this.emitWithAll(t,s))};return this._awaitWriteFinish(n,a.stabilityThreshold,t,p),this}if(t===P2.CHANGE&&!this._throttle(P2.CHANGE,n,50))return this;if(o.alwaysStat&&i===void 0&&(t===P2.ADD||t===P2.ADD_DIR||t===P2.CHANGE)){let p=o.cwd?R0.join(o.cwd,n):n,c;try{c=await(0,Jio.stat)(p)}catch{}if(!c||this.closed)return;s.push(c)}return this.emitWithAll(t,s),this}_handleError(t){let n=t&&t.code;return t&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(P2.ERROR,t),t||this.closed}_throttle(t,n,i){this._throttled.has(t)||this._throttled.set(t,new Map);let o=this._throttled.get(t);if(!o)throw new Error("invalid throttle");let s=o.get(n);if(s)return s.count++,!1;let a,u=()=>{let c=o.get(n),l=c?c.count:0;return o.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),l};a=setTimeout(u,i);let p={timeoutObject:a,clear:u,count:0};return o.set(n,p),p}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,n,i,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,u,p=t;this.options.cwd&&!R0.isAbsolute(t)&&(p=R0.join(this.options.cwd,t));let c=new Date,l=this._pendingWrites;function d(f){(0,HNd.stat)(p,(h,A)=>{if(h||!l.has(t)){h&&h.code!=="ENOENT"&&o(h);return}let E=Number(new Date);f&&A.size!==f.size&&(l.get(t).lastChange=E);let v=l.get(t);E-v.lastChange>=n?(l.delete(t),o(void 0,A)):u=setTimeout(d,a,A)})}l.has(t)||(l.set(t,{lastChange:c,cancelWait:()=>(l.delete(t),clearTimeout(u),i)}),u=setTimeout(d,a))}_isIgnored(t,n){if(this.options.atomic&&OCE.test(t))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(jNd(i)),u=[...[...this._ignoredPaths].map(jNd(i)),...s];this._userIgnored=PCE(u,void 0)}return this._userIgnored(t,n)}_isntIgnored(t,n){return!this._isIgnored(t,n)}_getWatchHelpers(t){return new ftu(t,this.options.followSymlinks,this)}_getWatchedDir(t){let n=R0.resolve(t);return this._watched.has(n)||this._watched.set(n,new dtu(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,n,i){let o=R0.join(t,n),s=R0.resolve(o);if(i=i??(this._watched.has(o)||this._watched.has(s)),!this._throttle("remove",o,100))return;!i&&this._watched.size===1&&this.add(t,n,!0),this._getWatchedDir(o).getChildren().forEach(f=>this._remove(o,f));let p=this._getWatchedDir(t),c=p.has(n);p.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let l=o;if(this.options.cwd&&(l=R0.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===P2.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=i?P2.UNLINK_DIR:P2.UNLINK;c&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(t){this._closeFile(t);let n=R0.dirname(t);this._getWatchedDir(n).remove(R0.basename(t))}_closeFile(t){let n=this._closers.get(t);n&&(n.forEach(i=>i()),this._closers.delete(t))}_addPathCloser(t,n){if(!n)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(n)}_readdirp(t,n){if(this.closed)return;let i={type:P2.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=DNd(t,i);return this._streams.add(o),o.once(kNd,()=>{o=void 0}),o.once(utu,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function kCE(r,t={}){let n=new Yio(t);return n.add(r),n}var YNd={watch:kCE,FSWatcher:Yio};var JNd=yt(require("path"));function jyt(r){if(JNd.default.basename(r).startsWith(".tmp-"))return!1;let n=r.substring(r.lastIndexOf("."));return n===".yml"||n===".yaml"||n===".sql"}function $Nd(r,t,n){let i=r==="."?".":r;return YNd.watch(i,{ignoreInitial:!0,persistent:!0,usePolling:!1,depth:99,ignored:[/(^|[\/\\])\../,/node_modules/]}).on("change",s=>{console.log(`[CHOKIDAR] change: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onChange(s)}).on("add",s=>{console.log(`[CHOKIDAR] add: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onAdd(s)}).on("unlink",s=>{console.log(`[CHOKIDAR] unlink: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onUnlink(s)}).on("error",t.onError).on("ready",t.onReady)}var XNd=require("node:fs/promises"),ZNd=require("node:path");async function eDd(r,t,n){let i=VK({baseDir:r}),o=n?["--force",t]:[t];await i.checkout(o)}async function tDd(r,t,n){let i=VK({baseDir:r});return n.name&&n.email&&(i=i.env("GIT_AUTHOR_NAME",n.name).env("GIT_AUTHOR_EMAIL",n.email).env("GIT_COMMITTER_NAME",n.name).env("GIT_COMMITTER_EMAIL",n.email)),await i.add("."),{commitSha:(await i.commit(t)).commit}}async function rDd(r,t,n){let i=VK({baseDir:r});try{let o=n||(await i.branch()).current;await i.push(["-u",t,o])}catch(o){let s=o instanceof Error?o.message:String(o),a=UCE(s);throw new Error(a)}}async function nDd(r){return{files:(await VK({baseDir:r}).status()).files.map(o=>({path:o.path,status:FCE(o.index+o.working_dir)}))}}async function iDd(r,t){let n=VK({baseDir:r}),o=(await n.status()).files.find(a=>a.path===t);if(o&&o.index==="?"&&o.working_dir==="?"){let a=(0,ZNd.join)(r,t),p=(await(0,XNd.readFile)(a,"utf-8")).split(`
|
|
10642
10642
|
`);return[`diff --git a/${t} b/${t}`,"new file mode 100644","--- /dev/null",`+++ b/${t}`,`@@ -0,0 +1,${p.length} @@`,...p.map(l=>`+${l}`)].join(`
|
|
10643
10643
|
`)}return await n.diff(["HEAD","--",t])}async function oDd(r){let n=await VK({baseDir:r}).branch(["-a"]),i=n.current,o=Object.keys(n.branches).filter(a=>!a.startsWith("remotes/")),s=Object.keys(n.branches).filter(a=>a.startsWith("remotes/origin/")).map(a=>a.replace("remotes/origin/",""));return{current:i,local:o,remote:s}}async function sDd(r,t,n){return(await VK({baseDir:r}).log([t,`--max-count=${n}`])).all.map(s=>({sha:s.hash,author:s.author_name,email:s.author_email,timestamp:new Date(s.date).getTime()/1e3,message:s.message}))}async function aDd(r,t){await VK({baseDir:r}).checkoutLocalBranch(t)}async function uDd(r){await VK({baseDir:r}).add(".")}async function cDd(r){return(await VK({baseDir:r}).getRemotes(!0)).find(o=>o.name==="origin")?.refs?.push??null}function FCE(r){let t=r[0],n=r[1];return t==="?"&&n==="?"||t==="A"?"added":t==="M"||n==="M"?"modified":t==="D"||n==="D"?"deleted":t==="R"?"renamed":t==="C"?"copied":"unknown"}function UCE(r){return r.replace(/https?:\/\/[^:@\s]+:[^@\s]+@/g,"https://***@")}function lDd(r,t){let n=encodeURIComponent(t.gitUsername||"token"),i=encodeURIComponent(t.gitToken),o=new URL(r);return o.username=n,o.password=i,o.toString()}var v8=Je("COA_WATCH"),$io=class{options;watcher=null;platformKind="snowflake";updateCallback;constructor(t){this.options=t,t.platformKind&&(this.platformKind=t.platformKind)}async init(){v8.info("[WorkspaceCoordinator] Initializing",{dir:this.options.dir}),this.options.platformKind||(this.platformKind="snowflake"),await this.ensureGitExclude(),await new Promise((t,n)=>{let i=!1;this.watcher=$Nd(this.options.dir,{onChange:o=>this.handleFileChange(o),onAdd:o=>this.handleFileAdd(o),onUnlink:o=>this.handleFileDelete(o),onError:o=>{v8.error("[WorkspaceCoordinator] Watcher error",{error:o instanceof Error?o.message:String(o)}),i||(i=!0,n(o instanceof Error?o:new Error(String(o))))},onReady:()=>{v8.info("[WorkspaceCoordinator] Watcher ready"),i||(i=!0,t()),this.rescan()}},void 0)}),v8.info("[WorkspaceCoordinator] Ready")}async ensureGitExclude(){let t=t1e.default.join(this.options.dir,".git","info","exclude");try{await fY.promises.mkdir(t1e.default.dirname(t),{recursive:!0});let n=await fY.promises.readFile(t,"utf-8").catch(()=>""),o=[".coa/","workspace.yml"].filter(s=>!n.includes(s));if(o.length>0){let s=n===""||n.endsWith(`
|
|
10644
10644
|
`)?"":`
|