@coalescesoftware/coa 5.3.2 → 5.3.3
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 +2 -2
- package/package.json +1 -1
package/coa.js
CHANGED
|
@@ -1181,7 +1181,7 @@ Content-Type: application/json; charset=utf-8\r
|
|
|
1181
1181
|
Content-Type: `+o.contentType+`\r
|
|
1182
1182
|
\r
|
|
1183
1183
|
`,m=`\r
|
|
1184
|
-
--`+l+"--",d=yT.getBlob(p,n,m);if(d===null)throw Jin();let f={name:o.fullPath},y=qM(s,t.host,t._protocol),g="POST",b=t.maxUploadRetryTime,S=new gT(y,g,KVe(t,r),b);return S.urlParams=f,S.headers=c,S.body=d.uploadData(),S.errorHandler=tse(e),S}var ese=class{constructor(e,r,n,i){this.current=e,this.total=r,this.finalized=!!n,this.metadata=i||null}};function _Bt(t,e){let r=null;try{r=t.getResponseHeader("X-Goog-Upload-Status")}catch{BO(!1)}return BO(!!r&&(e||["active"]).indexOf(r)!==-1),r}function D6a(t,e,r,n,i){let s=e.bucketOnlyServerUrl(),c=ion(e,n,i),u={name:c.fullPath},l=qM(s,t.host,t._protocol),o="POST",a={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n.size()}`,"X-Goog-Upload-Header-Content-Type":c.contentType,"Content-Type":"application/json; charset=utf-8"},p=kBt(c,r),m=t.maxUploadRetryTime;function d(y){_Bt(y);let g;try{g=y.getResponseHeader("X-Goog-Upload-URL")}catch{BO(!1)}return BO(WVe(g)),g}let f=new gT(l,o,d,m);return f.urlParams=u,f.headers=a,f.body=p,f.errorHandler=tse(e),f}function M6a(t,e,r,n){let i={"X-Goog-Upload-Command":"query"};function s(o){let a=_Bt(o,["active","final"]),p=null;try{p=o.getResponseHeader("X-Goog-Upload-Size-Received")}catch{BO(!1)}p||BO(!1);let m=Number(p);return BO(!isNaN(m)),new ese(m,n.size(),a==="final")}let c="POST",u=t.maxUploadRetryTime,l=new gT(r,c,s,u);return l.headers=i,l.errorHandler=tse(e),l}var Uin=256*1024;function q6a(t,e,r,n,i,s,c,u){let l=new ese(0,0);if(c?(l.current=c.current,l.total=c.total):(l.current=0,l.total=n.size()),n.size()!==l.total)throw YRa();let o=l.total-l.current,a=o;i>0&&(a=Math.min(a,i));let p=l.current,m=p+a,d="";a===0?d="finalize":o===a?d="upload, finalize":d="upload";let f={"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":`${l.current}`},y=n.slice(p,m);if(y===null)throw Jin();function g(A,T){let I=_Bt(A,["active","final"]),C=l.current+a,D=n.size(),P;return I==="final"?P=KVe(e,s)(A,T):P=null,new ese(C,D,I==="final",P)}let b="POST",S=e.maxUploadRetryTime,v=new gT(r,b,g,S);return v.headers=f,v.body=y.uploadData(),v.progressCallback=u||null,v.errorHandler=tse(t),v}var oon={STATE_CHANGED:"state_changed"},my={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function bBt(t){switch(t){case"running":case"pausing":case"canceling":return my.RUNNING;case"paused":return my.PAUSED;case"success":return my.SUCCESS;case"canceled":return my.CANCELED;case"error":return my.ERROR;default:return my.ERROR}}var TBt=class{constructor(e,r,n){if(ZRa(e)||r!=null||n!=null)this.next=e,this.error=r??void 0,this.complete=n??void 0;else{let s=e;this.next=s.next,this.error=s.error,this.complete=s.complete}}};function Xae(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}var jin=null,VVe=class{constructor(){this.errorText_="",this.sent_=!1,this.fetch_=Vin.default,this.errorCode_=pJ.NO_ERROR}async send(e,r,n,i){var s;if(this.sent_)throw $ae("cannot .send() more than once");this.sent_=!0;try{let c=await this.fetch_(e,{method:r,headers:i||{},body:n});this.headers_=c.headers,this.statusCode_=c.status,this.errorCode_=pJ.NO_ERROR,this.body_=await c.arrayBuffer()}catch(c){this.errorText_=(s=c)===null||s===void 0?void 0:s.message,this.statusCode_=0,this.errorCode_=pJ.NETWORK_ERROR}}getErrorCode(){if(this.errorCode_===void 0)throw $ae("cannot .getErrorCode() before receiving response");return this.errorCode_}getStatus(){if(this.statusCode_===void 0)throw $ae("cannot .getStatus() before receiving response");return this.statusCode_}getErrorText(){return this.errorText_}abort(){}getResponseHeader(e){if(!this.headers_)throw $ae("cannot .getResponseHeader() before receiving response");return this.headers_.get(e)}addUploadProgressListener(e){}removeUploadProgressListener(e){}},xBt=class extends VVe{getResponse(){if(!this.body_)throw $ae("cannot .getResponse() before receiving response");return Buffer.from(this.body_).toString("utf-8")}};function FO(){return jin?jin():new xBt}var NBt=class extends VVe{getResponse(){if(!this.body_)throw $ae("cannot .getResponse() before sending");return this.body_}};function w6a(){return new NBt}var d4e=class{constructor(e,r,n=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=e,this._blob=r,this._metadata=n,this._mappings=HVe(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=i=>{if(this._request=void 0,this._chunkMultiplier=1,i._codeEquals("canceled"))this._needToFetchStatus=!0,this.completeTransitions_();else{let s=this.isExponentialBackoffExpired();if(Qin(i.status,[]))if(s)i=Kin();else{this.sleepTime=Math.max(this.sleepTime*2,FRa),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=i,this._transition("error")}},this._metadataErrorHandler=i=>{this._request=void 0,i._codeEquals("canceled")?this.completeTransitions_():(this._error=i,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((i,s)=>{this._resolve=i,this._reject=s,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){let e=this._transferred;return r=>this._updateProgress(e+r)}_shouldDoResumable(e){return e.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(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([r,n])=>{switch(this._state){case"running":e(r,n);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((e,r)=>{let n=D6a(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),i=this._ref.storage._makeRequest(n,FO,e,r);this._request=i,i.getPromise().then(s=>{this._request=void 0,this._uploadUrl=s,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let e=this._uploadUrl;this._resolveToken((r,n)=>{let i=M6a(this._ref.storage,this._ref._location,e,this._blob),s=this._ref.storage._makeRequest(i,FO,r,n);this._request=s,s.getPromise().then(c=>{c=c,this._request=void 0,this._updateProgress(c.current),this._needToFetchStatus=!1,c.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let e=Uin*this._chunkMultiplier,r=new ese(this._transferred,this._blob.size()),n=this._uploadUrl;this._resolveToken((i,s)=>{let c;try{c=q6a(this._ref._location,this._ref.storage,n,this._blob,e,this._mappings,r,this._makeProgressCallback())}catch(l){this._error=l,this._transition("error");return}let u=this._ref.storage._makeRequest(c,FO,i,s,!1);this._request=u,u.getPromise().then(l=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(l.current),l.finalized?(this._metadata=l.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){Uin*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,r)=>{let n=non(this._ref.storage,this._ref._location,this._mappings),i=this._ref.storage._makeRequest(n,FO,e,r);this._request=i,i.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,r)=>{let n=_6a(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),i=this._ref.storage._makeRequest(n,FO,e,r);this._request=i,i.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){let r=this._transferred;this._transferred=e,this._transferred!==r&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let r=this._state==="paused";this._state=e,r&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Yin(),this._state=e,this._notifyObservers();break;case"error":this._state=e,this._notifyObservers();break;case"success":this._state=e,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 e=bBt(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,r,n,i){let s=new TBt(r||void 0,n||void 0,i||void 0);return this._addObserver(s),()=>{this._removeObserver(s)}}then(e,r){return this._promise.then(e,r)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){let r=this._observers.indexOf(e);r!==-1&&this._observers.splice(r,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(r=>{this._notifyObserver(r)})}_finishPromise(){if(this._resolve!==void 0){let e=!0;switch(bBt(this._state)){case my.SUCCESS:Xae(this._resolve.bind(null,this.snapshot))();break;case my.CANCELED:case my.ERROR:let r=this._reject;Xae(r.bind(null,this._error))();break;default:e=!1;break}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(bBt(this._state)){case my.RUNNING:case my.PAUSED:e.next&&Xae(e.next.bind(e,this.snapshot))();break;case my.SUCCESS:e.complete&&Xae(e.complete.bind(e))();break;case my.CANCELED:case my.ERROR:e.error&&Xae(e.error.bind(e,this._error))();break;default:e.error&&Xae(e.error.bind(e,this._error))()}}resume(){let e=this._state==="paused"||this._state==="pausing";return e&&this._transition("running"),e}pause(){let e=this._state==="running";return e&&this._transition("pausing"),e}cancel(){let e=this._state==="running"||this._state==="pausing";return e&&this._transition("canceling"),e}};var MM=class{constructor(e,r){this._service=e,r instanceof P0?this._location=r:this._location=P0.makeFromUrl(r,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,r){return new MM(e,r)}get root(){let e=new P0(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return ton(this._location.path)}get storage(){return this._service}get parent(){let e=f6a(this._location.path);if(e===null)return null;let r=new P0(this._location.bucket,e);return new MM(this._service,r)}_throwIfRoot(e){if(this._location.path==="")throw CBt(e)}};function P6a(t,e){t._throwIfRoot("getBytes");let r=C6a(t.storage,t._location,e);return t.storage.makeRequestWithTokens(r,w6a).then(n=>e!==void 0?n.slice(0,e):n)}function L6a(t,e,r){return t._throwIfRoot("uploadBytesResumable"),new d4e(t,new yT(e),r)}function z6a(t){let e={prefixes:[],items:[]};return aon(t,e).then(()=>e)}async function aon(t,e,r){let i=await son(t,{pageToken:r});e.prefixes.push(...i.prefixes),e.items.push(...i.items),i.nextPageToken!=null&&await aon(t,e,i.nextPageToken)}function son(t,e){e!=null&&typeof e.maxResults=="number"&&vBt("options.maxResults",1,1e3,e.maxResults);let r=e||{},n=I6a(t.storage,t._location,"/",r.pageToken,r.maxResults);return t.storage.makeRequestWithTokens(n,FO)}function F6a(t){t._throwIfRoot("getMetadata");let e=non(t.storage,t._location,HVe());return t.storage.makeRequestWithTokens(e,FO)}function B6a(t,e){t._throwIfRoot("updateMetadata");let r=O6a(t.storage,t._location,e,HVe());return t.storage.makeRequestWithTokens(r,FO)}function U6a(t){t._throwIfRoot("getDownloadURL");let e=E6a(t.storage,t._location,HVe());return t.storage.makeRequestWithTokens(e,FO).then(r=>{if(r===null)throw JRa();return r})}function j6a(t){t._throwIfRoot("deleteObject");let e=R6a(t.storage,t._location);return t.storage.makeRequestWithTokens(e,FO)}function uon(t,e){let r=h6a(t._location.path,e),n=new P0(t._location.bucket,r);return new MM(t.storage,n)}function G6a(t){return/^[A-Za-z]+:\/\//.test(t)}function V6a(t,e){return new MM(t,e)}function con(t,e){if(t instanceof f4e){let r=t;if(r._bucket==null)throw KRa();let n=new MM(r,r._bucket);return e!=null?con(n,e):n}else return e!==void 0?uon(t,e):t}function W6a(t,e){if(e&&G6a(e)){if(t instanceof f4e)return V6a(t,e);throw lJ("To use ref(service, url), the first argument must be a Storage instance.")}else return con(t,e)}function Gin(t,e){let r=e?.[Hin];return r==null?null:P0.makeFromBucketSpec(r,t)}function H6a(t,e,r,n={}){t.host=`${e}:${r}`,t._protocol="http";let{mockUserToken:i}=n;i&&(t._overrideAuthToken=typeof i=="string"?i:zBe(i,t.app.options.projectId))}var f4e=class{constructor(e,r,n,i,s){this.app=e,this._authProvider=r,this._appCheckProvider=n,this._url=i,this._firebaseVersion=s,this._bucket=null,this._host=Win,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=LRa,this._maxUploadRetryTime=zRa,this._requests=new Set,i!=null?this._bucket=P0.makeFromBucketSpec(i,this._host):this._bucket=Gin(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,this._url!=null?this._bucket=P0.makeFromBucketSpec(this._url,e):this._bucket=Gin(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){vBt("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){vBt("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let e=this._authProvider.getImmediate({optional:!0});if(e){let r=await e.getToken();if(r!==null)return r.accessToken}return null}async _getAppCheckToken(){let e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new MM(this,e)}_makeRequest(e,r,n,i,s=!0){if(this._deleted)return new SBt(Xin());{let c=o6a(e,this._appId,n,i,r,this._firebaseVersion,s);return this._requests.add(c),c.getPromise().then(()=>this._requests.delete(c),()=>this._requests.delete(c)),c}}async makeRequestWithTokens(e,r){let[n,i]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,r,n,i).getPromise()}},K6a="@firebase/storage",Y6a="0.9.12";var pon="storage";function lon(t,e){return t=gi(t),P6a(t,e)}function mon(t,e,r){return t=gi(t),L6a(t,e,r)}function don(t){return t=gi(t),F6a(t)}function fon(t,e){return t=gi(t),B6a(t,e)}function hon(t,e){return t=gi(t),son(t,e)}function yon(t){return t=gi(t),z6a(t)}function gon(t){return t=gi(t),U6a(t)}function YVe(t){return t=gi(t),j6a(t)}function y4e(t,e){return t=gi(t),W6a(t,e)}function bon(t,e){return uon(t,e)}function Son(t=E9(),e){t=gi(t);let n=XK(t,pon).getImmediate({identifier:e}),i=LBe("storage");return i&&DBt(n,...i),n}function DBt(t,e,r,n={}){H6a(t,e,r,n)}function J6a(t,{instanceIdentifier:e}){let r=t.getProvider("app").getImmediate(),n=t.getProvider("auth-internal"),i=t.getProvider("app-check-internal");return new f4e(r,n,i,e,GA)}function X6a(){Rg(new np(pon,J6a,"PUBLIC").setMultipleInstances(!0)),od(K6a,Y6a)}X6a();var rse=class{constructor(e,r,n){this._delegate=e,this.task=r,this.ref=n}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 JVe=class{constructor(e,r){this._delegate=e,this._ref=r,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 rse(this._delegate.snapshot,this,this._ref)}then(e,r){return this._delegate.then(n=>{if(e)return e(new rse(n,this,this._ref))},r)}on(e,r,n,i){let s;return r&&(typeof r=="function"?s=c=>r(new rse(c,this,this._ref)):s={next:r.next?c=>r.next(new rse(c,this,this._ref)):void 0,complete:r.complete||void 0,error:r.error||void 0}),this._delegate.on(e,s,n||void 0,i||void 0)}},XVe=class{constructor(e,r){this._delegate=e,this._service=r}get prefixes(){return this._delegate.prefixes.map(e=>new II(e,this._service))}get items(){return this._delegate.items.map(e=>new II(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}};var II=class{constructor(e,r){this._delegate=e,this.storage=r}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){let r=bon(this._delegate,e);return new II(r,this.storage)}get root(){return new II(this._delegate.root,this.storage)}get parent(){let e=this._delegate.parent;return e==null?null:new II(e,this.storage)}put(e,r){return this._throwIfRoot("put"),new JVe(mon(this._delegate,e,r),this)}putString(e,r=T3.RAW,n){this._throwIfRoot("putString");let i=OBt(r,e),s=Object.assign({},n);return s.contentType==null&&i.contentType!=null&&(s.contentType=i.contentType),new JVe(new d4e(this._delegate,new yT(i.data,!0),s),this)}listAll(){return yon(this._delegate).then(e=>new XVe(e,this.storage))}list(e){return hon(this._delegate,e||void 0).then(r=>new XVe(r,this.storage))}getMetadata(){return don(this._delegate)}updateMetadata(e){return fon(this._delegate,e)}getDownloadURL(){return gon(this._delegate)}delete(){return this._throwIfRoot("delete"),YVe(this._delegate)}_throwIfRoot(e){if(this._delegate._location.path==="")throw CBt(e)}};var $Ve=class{constructor(e,r){this.app=e,this._delegate=r}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(von(e))throw lJ("ref() expected a child path but got a URL, use refFromURL instead.");return new II(y4e(this._delegate,e),this)}refFromURL(e){if(!von(e))throw lJ("refFromURL() expected a full URL but got a child path, use ref() instead.");try{P0.makeFromUrl(e,this._delegate.host)}catch{throw lJ("refFromUrl() expected a valid full URL but got an invalid one.")}return new II(y4e(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,r,n={}){DBt(this._delegate,e,r,n)}};function von(t){return/^[A-Za-z]+:\/\//.test(t)}var $6a="@firebase/storage-compat",Q6a="0.1.20";var Z6a="storage-compat";function eka(t,{instanceIdentifier:e}){let r=t.getProvider("app-compat").getImmediate(),n=t.getProvider("storage").getImmediate({identifier:e});return new $Ve(r,n)}function tka(t){let e={TaskState:my,TaskEvent:oon,StringFormat:T3,Storage:$Ve,Reference:II};t.INTERNAL.registerComponent(new np(Z6a,eka,"PUBLIC").setServiceProps(e).setMultipleInstances(!0)),t.registerVersion($6a,Q6a)}tka(Fs);var $Sp=en(Ton());var nse={};Bl(nse,{CoalesceError:()=>Wl,isCoalesceError:()=>uka});var Wl=class extends Error{constructor(e){super(e)}statusCode(){return 500}toTRunError(){return{error:{errorString:this.message,errorDetail:""}}}toString(){return JSON.stringify(this.toTRunError())}handleExpressResponse(e){e.status(this.statusCode()).json(this.toTRunError())}};function uka(t){return typeof t=="object"&&t instanceof Wl}var xon=(n=>(n.development="development",n.qa="qa",n.production="production",n))(xon||{}),Non={["development"]:{apiKey:"AIzaSyAus_ACzfASXnKQPBNPFdsApkuUbiQGsvE",authDomain:"coalesce-a6346.firebaseapp.com",projectId:"coalesce-a6346",storageBucket:"coalesce-a6346.appspot.com",messagingSenderId:"236763625216",appId:"1:236763625216:web:8495f0a13152e1d63c25e5",measurementId:"G-DPT4YWV78T"},["qa"]:{apiKey:"AIzaSyDmn_9ToPIXVBzjTdyj1wny9XivH-g48T0",authDomain:"cls-qa.firebaseapp.com",projectId:"cls-qa",storageBucket:"cls-qa.appspot.com",messagingSenderId:"243490689213",appId:"1:243490689213:web:29972e04747e7d113b67d4",measurementId:"G-FRJ2PNVPT4"},["production"]:{apiKey:"AIzaSyAGVrKvXxw69cVVdlQ7NMa46rQyrM3GuJM",authDomain:"dev-etl-284121.firebaseapp.com",projectId:"dev-etl-284121",storageBucket:"dev-etl-284121.appspot.com",messagingSenderId:"96686924891",appId:"1:96686924891:web:4d9a88b3b69f7865084b7e",measurementId:"G-33CRZMHDGR"}},Ion=t=>Non[t],ise=()=>ku()?process.env.RUNTIME_ENVIRONMENT||process.env.NODE_ENVIRONMENT||"production":window.ENVIRONMENT??"development",V7=()=>{let t=ise();return Ion(t)},cka=()=>{let t=i=>typeof window<"u"&&window[i]||process.env[i],e=t("FIREBASE_AUTH_EMULATOR_HOST"),r=t("FIRESTORE_EMULATOR_HOST"),n=t("FIREBASE_STORAGE_EMULATOR_HOST");if(!!e!=!!r||!!e!=!!n)throw new Error(`Inconsistent Firebase emulator use! All three emulators must be used, or none! auth=${e} firestore=${r} storage=${n}`);return e?{auth:e,firestore:r,storage:n}:null},bT=cka(),eWe=(t,e)=>{if(!bT)return;console.log(`Using Firebase Auth emulator at ${bT.auth}`),t.auth().useEmulator(bT.auth),console.log(`Using Firestore emulator at ${bT.firestore} over ${e?"https":"http"}`);let[r,n]=bT.firestore.split(":");t.firestore().useEmulator(r,parseInt(n)),e&&t.firestore()._delegate._setSettings({...t.firestore()._delegate._getSettings(),ssl:!0}),console.log(`Using Firebase Storage emulator at ${bT.storage} over ${e?"https":"http"}`);let[i,s]=bT.storage.split(":");t.storage().useEmulator(i,parseInt(s)),e&&(t.storage()._delegate._protocol="https")},pka=(t=!0)=>{if(Fs.apps.length)Fs.app();else{let e=Fs.initializeApp(V7());eWe(e,t)}},UO=()=>Fs.auth(),wM=Fs,lka=Fs.auth.GoogleAuthProvider.PROVIDER_ID,mka=Fs.auth.GithubAuthProvider.PROVIDER_ID,dka=Fs.auth.EmailAuthProvider.PROVIDER_ID,fka=()=>Fs.app(),hka=Fs.firestore.DocumentReference,wa=()=>Fs.app().firestore(),ose=()=>Fs.firestore.FieldValue,qBt=()=>Fs.app().functions(),wBt=Fs.firestore.FieldValue.serverTimestamp(),W7=t=>{let e=t.firestore.FieldValue;return e||(e=ose()),e},PBt=()=>{let t=UO();if(!t.currentUser)throw new Wl("Unable to retrieve refresh token, no current user!");return bT?t.currentUser.getIdToken(!0):Promise.resolve(t.currentUser.refreshToken)};var N4e=en(Mc()),M3p=N4e.Record({version:N4e.String,hash:N4e.String}),dse={version:"5.3.2",hash:"0d996492f6ccd1a198ed4edc867ff081344ccfdb"};var j_a=u3(),Kn=(Ye=>(Ye.Runner="RUNNER",Ye.Steps="STEPS",Ye.RunnerBackend="RUNNER_BACKEND",Ye.TreeOperations="TREE_OPERATIONS",Ye.StepTypes="STEP_TYPES",Ye.Graph="GRAPH",Ye.UI="UI",Ye.Testing="TESTING",Ye.DNS="DNS",Ye.APP="APP",Ye.Perf="PERFORMANCE",Ye.Deploy="DEPLOY",Ye.Firebase="FIREBASE",Ye.Connection="CONNECTION",Ye.Environments="ENVIRONMENTS",Ye.Jobs="JOBS",Ye.SQLParsing="SQL_PARSING",Ye.StorageLocations="STORAGE_LOCATIONS",Ye.ENV="ENV",Ye.Problems="PROBLEM_SCANNER",Ye.Git="GIT",Ye.GitSettings="GIT_SETTINGS",Ye.Common="COMMON",Ye.SqlTesting="SQL_TESTING",Ye.Heartbeat="HEARTBEAT",Ye.Palette="PALETTE",Ye.Auth="AUTH",Ye.UserManagement="USER_MANAGEMENT",Ye.MetadataOperations="METADATA_OPERATIONS",Ye.Search="SEARCH",Ye.Workspaces="WORKSPACES",Ye.State="STATE",Ye.UserSettings="USER_SETTINGS",Ye.AdvancedDeploy="ADVANCED_DEPLOY",Ye.MetadataHydration="METADATA_HYDRATION",Ye.TemplateEditor="TEMPLATE_EDITOR",Ye.MappingGrid="MAPPING_GRID",Ye.Pendo="PENDO",Ye.Strumenta="STRUMENTA",Ye.NarrowMetadata="NARROW_METADATA",Ye.CLI_INTERNAL="CLI_INTERNAL",Ye.DRAG="DRAG",Ye.CLI="CLI",Ye.RunTransaction="RUN_TRANSACTION",Ye.RunResults="RUN_RESULTS",Ye.Packages="PACKAGES",Ye.Jest="JEST",Ye.ORG_SCANNER="ORG_SCANNER",Ye.Projects="PROJECTS",Ye.JSONParser="JSON_PARSER",Ye.OrgSettings="ORG_SETTINGS",Ye.PartnerConnect="PARTNER_CONNECT",Ye.OrgBootstrap="ORG_BOOTSTRAP",Ye.Presync="PRESYNC",Ye.folders="FOLDERS",Ye.orgs="ORGS",Ye.users="USERS",Ye.Versioning="VERSIONING",Ye.Listeners="LISTENERS",Ye.Docs="DOCS",Ye.ErrorOperations="ERROR_OPERATIONS",Ye.VersionControlActions="VERSION_CONTROL_ACTIONS",Ye.ColumnLineage="COLUMN_LINEAGE",Ye.SystemEmails="SYSTEM_EMAILS",Ye.UserActivation="USER_ACTIVATION",Ye.Secrets="SECRETS",Ye.OrgUpgrade="ORG_UPGRADE",Ye.PackageNamespaces="PACKAGE_NAMESPACES",Ye))(Kn||{}),C4e=(u=>(u.infoContext="infoContext",u.debugContext="debugContext",u.errorContext="errorContext",u.assertContext="assertContext",u.alertContext="alertContext",u.emergContext="emergContext",u.appContext="appContext",u))(C4e||{}),Ian=(i=>(i.Scheduler="Scheduler",i.CLI="CLI",i.Frontend="Frontend",i.JestTest="JestTest",i))(Ian||{}),Can={levels:{emerg:0,assert:1,alert:2,error:3,app:4,info:5,debug:6},colors:{emerg:"red",assert:"yellow",alert:"yellow",error:"cyan",app:"blue",info:"green",debug:"magenta"}},WO,G_a=(t,e)=>{WO=t,WO=="Frontend"?tUt=e.datadogFrontEndLogger:(WO=="CLI"||WO=="Scheduler"||WO=="JestTest")&&IWe(WO)},tUt=null,Va={},V_a=t=>{Va={...Va,...t}},W_a=t=>{let e={};Object.keys(Q7).forEach(r=>{e[r]={defaultMeta:t}}),CWe(e)},nUt=t=>({coalesceSoftwareVersion:dse?.version||"",service:t,env:process.env.REACT_APP_OWNER?process.env.REACT_APP_OWNER:"",reactAppCoalesceDev:process.env.REACT_APP_COALESCE_DEV||""}),iUt=null,IWe=t=>{let e=nUt(t);iUt={host:"http-intake.logs.datadoghq.com",path:`/v1/input/3ae2b6d484bfaf4631d5910b5020f683?ddtags=env:${e.env},coalesceSoftwareVersion:${e.coalesceSoftwareVersion}&ddsource=nodejs&service=${t}`,ssl:!0}},rUt=class extends j_a{constructor(r){super(r);this.baseContext=nUt(WO),this.levelMappings={emerg:"error",assert:"warn",alert:"warn",error:"warn",app:"info",info:"info",debug:"debug"}}log(r,n){tUt&&tUt.log(r,{...this.baseContext,...Va},this.levelMappings[r.level]),n()}},CWe=t=>{Object.keys(t).forEach(e=>{let r=I4e(e);t[e].defaultMeta={...r.defaultMeta,...t[e].defaultMeta};let n=t[e].transports||r.transports;r.configure({...r,...t[e],transports:n,level:t[e].level||r.level})})},oUt=t=>new vT.transports.Console({format:Oan(),level:t.level}),EWe=()=>new vT.transports.Http({...iUt,format:vT.format.combine(Oan(),vT.format.uncolorize()),level:"info",env:process.env.REACT_APP_OWNER}),OWe=t=>{let e=t??{};return new rUt(e)},RWe=t=>{let e=[];return e.push(oUt(t)),iUt&&e.push(EWe()),[OWe(),...e]},Ean=t=>{let e=nUt(WO);return{appEnv:H_a(),loggingArea:t,...e}},H_a=()=>{let t={firebaseEnv:ise(),RUNTIME_ENVIRONMENT:process.env.RUNTIME_ENVIRONMENT,NODE_ENVIRONMENT:process.env.NODE_ENVIRONMENT,START_RUN_URL:L0};return ku()||(t.windowInfo={frontendURLHost:window.location.host,ENVIRONMENT:window.ENVIRONMENT}),t},Oan=()=>vT.format.combine(vT.format.timestamp(),vT.format.colorize({colors:Can.colors}),vT.format.printf(t=>`|${t.timestamp}|[${t.loggingArea}]${t.orgID?`|(org:${t.orgID})`:""}${t.envID?`|(env:${t.envID})`:""}${t.userID?`|(user:${t.userID})`:""}${t.runCounter?`|run:${t.runCounter})`:""}(${t.nodeID?`|(node:${t.nodeID})`:""})|${t.level}:${t.message}`)),Q7={["GIT_SETTINGS"]:{level:"info"},["MAPPING_GRID"]:{level:"info"},["RUNNER"]:{level:"info"},["STEPS"]:{level:"info"},["RUNNER_BACKEND"]:{level:"info"},["GRAPH"]:{level:"info"},["STEP_TYPES"]:{level:"info"},["TESTING"]:{level:"info"},["UI"]:{level:"info"},["DNS"]:{level:"info"},["APP"]:{level:"info"},["PERFORMANCE"]:{level:"info"},["TREE_OPERATIONS"]:{level:"info"},["DEPLOY"]:{level:"info"},["FIREBASE"]:{level:"info"},["CONNECTION"]:{level:"info"},["ENVIRONMENTS"]:{level:"info"},["JOBS"]:{level:"info"},["SQL_PARSING"]:{level:"debug"},["STORAGE_LOCATIONS"]:{level:"info"},["ENV"]:{level:"info"},["GIT"]:{level:"info"},["STORAGE_LOCATIONS"]:{level:"info"},["COMMON"]:{level:"info"},["ORG_SCANNER"]:{level:"info"},["SQL_TESTING"]:{level:"alert"},["PROBLEM_SCANNER"]:{level:"error"},["HEARTBEAT"]:{level:"info"},["PALETTE"]:{level:"info"},["AUTH"]:{level:"info"},["USER_MANAGEMENT"]:{level:"info"},["METADATA_OPERATIONS"]:{level:"info"},["SEARCH"]:{level:"info"},["WORKSPACES"]:{level:"info"},["STATE"]:{level:"info"},["USER_SETTINGS"]:{level:"info"},["ADVANCED_DEPLOY"]:{level:"info"},["METADATA_HYDRATION"]:{level:"info"},["TEMPLATE_EDITOR"]:{level:"info"},["PENDO"]:{level:"info"},["STRUMENTA"]:{level:"info"},["CLI"]:{level:"info"},["NARROW_METADATA"]:{level:"info"},["CLI_INTERNAL"]:{level:"info"},["CLI"]:{level:"info"},["DRAG"]:{level:"info"},["RUN_TRANSACTION"]:{level:"info"},["RUN_RESULTS"]:{level:"info"},["PACKAGES"]:{level:"info"},["JEST"]:{level:"info"},["PROJECTS"]:{level:"info"},["JSON_PARSER"]:{level:"info"},["ORG_SETTINGS"]:{level:"info"},["PARTNER_CONNECT"]:{level:"info"},["ORG_BOOTSTRAP"]:{level:"info"},["PRESYNC"]:{level:"info"},["FOLDERS"]:{level:"info"},["ORGS"]:{level:"info"},["USERS"]:{level:"info"},["VERSIONING"]:{level:"info"},["LISTENERS"]:{level:"info"},["DOCS"]:{level:"info"},["ERROR_OPERATIONS"]:{level:"info"},["VERSION_CONTROL_ACTIONS"]:{level:"info"},["COLUMN_LINEAGE"]:{level:"info"},["SYSTEM_EMAILS"]:{level:"info"},["USER_ACTIVATION"]:{level:"info"},["SECRETS"]:{level:"info"},["ORG_UPGRADE"]:{level:"info"},["PACKAGE_NAMESPACES"]:{level:"info"}},aUt=(u=>(u.emerg="emerg",u.info="info",u.error="error",u.debug="debug",u.assert="assert",u.alert="alert",u.app="app",u))(aUt||{}),$u=(t,e,r,n,i,s)=>({orgID:t,envID:e,userID:r,runID:n,nodeID:i,workspaceID:s}),fJ=(t,e)=>{t.runID=e},K_a=(t,e,r,n)=>({orgID:t,envID:e,userID:r,runID:n}),sUt=(t,e)=>{t.envID=e},Y_a=(t,e)=>{t.userID=e},I4e=t=>{let e=Q7[t];return e.logger||(e.logger=vT.createLogger({levels:Can.levels,defaultMeta:Ean(t),level:e.level,transports:RWe(e)})),e.logger},Kt=t=>{let e=S=>{let v=kWe(S);return $_a(v).join(" ")},r=(S,v)=>{let A=I4e(t),T=e(v);A.log({level:S,message:T})},n=(S,v,A)=>{let T=v?{...v,envID:v.envID?.toString()}:{},I=I4e(t),C=e(A);I.log({level:S,message:C,...T})};return{info:(...S)=>{r("info",S)},infoContext:(S,...v)=>{n("info",S,v)},emerg:(...S)=>{r("emerg",S)},emergContext:(S,...v)=>{n("emerg",S,v)},assert:(...S)=>{r("assert",S)},assertContext:(S,...v)=>{n("assert",S,v)},alert:(...S)=>{r("alert",S)},alertContext:(S,...v)=>{n("alert",S,v)},debug:(...S)=>{r("debug",S)},debugContext:(S,...v)=>{n("debug",S,v)},error:(...S)=>{r("error",S)},errorContext:(S,...v)=>{n("error",S,v)},app:(...S)=>{r("app",S)},appContext:(S,...v)=>{n("app",S,v)}}},J_a=1e6,X_a=.8,$_a=t=>{let n=J_a*X_a/t.length/2;return t.map(s=>typeof s!="string"||s.length<n?s:s.slice(0,n))},Z7=t=>{let e;return t&&t.length>5?e="*"+t.substring(t.length-4,t.length):t.length?e="****":e="",e},Ran=(t,e)=>{let r=t.toUpperCase(),n=[];if(Q7[r]||n.push("invalid logging area"),aUt[e]||n.push("invalid log level"),n.length)throw n.forEach(u=>{console.error(u)}),new Error("Invalid logging area or log level"+n);let i=I4e(r),s=i.transports.filter(u=>u.name==="console"),c=i.transports;s.length||(c=[...c,oUt(Q7[r])]),c.filter(u=>u.name==="console")[0].level=e,i.configure({...i,transports:i.transports})},Q_a=()=>{Object.keys(Q7).forEach(t=>{Ran(t,"debug")})};var q3p=new Error("timeout while waiting for mutex to become available"),w3p=new Error("mutex already locked"),Z_a=new Error("request for lock canceled"),eDa=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(c){c(s)})}return new(r||(r=Promise))(function(s,c){function u(a){try{o(n.next(a))}catch(p){c(p)}}function l(a){try{o(n.throw(a))}catch(p){c(p)}}function o(a){a.done?s(a.value):i(a.value).then(u,l)}o((n=n.apply(t,e||[])).next())})},eL=class{constructor(e,r=Z_a){this._value=e,this._cancelError=r,this._weightedQueues=[],this._weightedWaiters=[]}acquire(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,n)=>{this._weightedQueues[e-1]||(this._weightedQueues[e-1]=[]),this._weightedQueues[e-1].push({resolve:r,reject:n}),this._dispatch()})}runExclusive(e,r=1){return eDa(this,void 0,void 0,function*(){let[n,i]=yield this.acquire(r);try{return yield e(n)}finally{i()}})}waitForUnlock(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),this._weightedWaiters[e-1].push(r),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatch()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatch()}cancel(){this._weightedQueues.forEach(e=>e.forEach(r=>r.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var e;for(let r=this._value;r>0;r--){let n=(e=this._weightedQueues[r-1])===null||e===void 0?void 0:e.shift();if(!n)continue;let i=this._value,s=r;this._value-=r,r=this._value+1,n.resolve([i,this._newReleaser(s)])}this._drainUnlockWaiters()}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){for(let e=this._value;e>0;e--)!this._weightedWaiters[e-1]||(this._weightedWaiters[e-1].forEach(r=>r()),this._weightedWaiters[e-1]=[])}},tDa=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(c){c(s)})}return new(r||(r=Promise))(function(s,c){function u(a){try{o(n.next(a))}catch(p){c(p)}}function l(a){try{o(n.throw(a))}catch(p){c(p)}}function o(a){a.done?s(a.value):i(a.value).then(u,l)}o((n=n.apply(t,e||[])).next())})},fse=class{constructor(e){this._semaphore=new eL(1,e)}acquire(){return tDa(this,void 0,void 0,function*(){let[,e]=yield this._semaphore.acquire();return e})}runExclusive(e){return this._semaphore.runExclusive(()=>e())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var usn=en(Mc()),csn=en(jan()),psn=en(require("fs")),lsn=en(tL());var HO=en(hse(),1),nvp=HO.default.v1,ivp=HO.default.v3,yJ=HO.default.v4,ovp=HO.default.v5,avp=HO.default.NIL,svp=HO.default.version,uvp=HO.default.validate,cvp=HO.default.stringify,pvp=HO.default.parse;var msn=require("crypto"),{exec:dMa}=require("child_process"),yse;function fMa(t){yse=t}var hMa=new Set([""," ","(",")","#","%","`","'",'"',",",".","|","+","+","!","?","{","}","/","\\",":","@","#",";"]),ku=()=>typeof window>"u",dsn=()=>window.location.hostname=="localhost",YWe=()=>process.env.GOOGLE_APPLICATION_CREDENTIALS!==void 0,yMa=Kt("RUNNER_BACKEND"),ll=Kt("COMMON"),gMa=t=>YWe()?Promise.resolve():t.delete().catch(e=>{yMa.error(`Error deleting firebase instance: ${e}`)}),fsn=()=>{let t;return process.env.PORT?parseInt(process.env.PORT):(t=8080,t)},L0=ku()||dsn()?process.env.SCHEDULER_ADDRESS||`http://localhost:${fsn().toString()}`:window.REACT_APP_GIT_PROXY_URL,bMa=(t,e)=>t.reduce((r,n)=>parseInt(r)>parseInt(n)?parseInt(r):parseInt(n),e);function hsn(t,e){return AT.has(t,e)}function ysn(t,e){return AT.get(t,e)}function rL(t,e,r){return AT.set(t,e,r)}function ur(t,e,r){return hsn(t,e)?ysn(t,e):r}var pp=t=>AT.cloneDeep(t),hUt=(t,e)=>(0,lsn.default)(t,e),SMa=t=>AT.uniqueId(t);function gse(t,e,r){if(!t||!e)return r;let n=Object.values(t).find(i=>e==i);return n||r}var yUt=(t,e)=>{try{CUt(t,r=>r.every(n=>typeof n[e]=="string"),{},"Unable to sort array, attributes being compared must all be strings. Returning original value.")}catch{return t}return t.sort((r,n)=>{let i=r[e].toUpperCase(),s=n[e].toUpperCase();return i<s?-1:i>s?1:0})},E2=t=>{let e=Object.values(t),r=i=>e.includes(i),n=i=>`Failed constraint check. Expected one of ${JSON.stringify(e)}, but received ${JSON.stringify(i)}`;return usn.Unknown.withConstraint(i=>r(i)||n(i))},vMa=(t,e)=>{let r=Object.getOwnPropertyNames(t),n=Object.getOwnPropertyNames(e);if(r.length!=n.length)return!1;for(let i=0;i<r.length;i++){let s=r[i];if(t[s]!==e[s])return!1}return!0},gsn=(t,e)=>new Date(e).getTime()-new Date(t).getTime(),AMa=t=>{let e=new Date().toISOString(),r=n=>{let i=new Date().toISOString();return{performanceTime:gsn(e,i),passThroughData:n}};return t().then(r,r)},TMa=()=>bsn("env")=="demo",xMa=()=>!!Ssn("id_token"),NMa=()=>window.location.href.includes("editor.structure.rest"),bsn=t=>{let e=window.location.href;return new URL(e).searchParams.get(t)},Ssn=t=>{let r=window.location.hash.substr(1).split("&"),n={};return r.forEach(i=>{let[s,c]=i.split("=");n[s]=c}),n[t]},IMa="us-west-2_c4Lg8pNfQ",CMa="mjn020f01m2uvvg38ujrt8gts",EMa="us-west-2:da18afd3-bfb8-4b1a-876a-6bbe7ec60669",vsn="us-west-2",OMa="cognito-idp."+vsn+".amazonaws.com/",N3=(t,e,r)=>({statusCode:t,error:{errorString:e,errorDetail:r},toString:()=>`${e} DETAIL:${r}`}),Asn=(t,e)=>({upper:t,lower:t-e}),RMa=(t,e,r)=>{let n=Asn(t,e),i=e*r;return{upper:n.upper-i,lower:n.lower-i}},gJ=(t,e,r,n)=>{let i=KO(),s=n();return e(r,t,"total elapsed time: ",KO()-i),s},Pa=(t,e,r,n,i="debugContext")=>{let s=KO();return JWe(t,e,r,s,n(),i)},gUt=(t,e,r,n,i)=>{let s=KO(),c=Kt(n);return i.catch(u=>{throw c.errorContext(r,`Promise in ${e} threw an error`,u,u.stack),u}).finally(()=>{let l=KO()-s;l>t&&c.assertContext(r,n,!1,`Promise in ${e} exceeded ${t} milliseconds.
|
|
1184
|
+
--`+l+"--",d=yT.getBlob(p,n,m);if(d===null)throw Jin();let f={name:o.fullPath},y=qM(s,t.host,t._protocol),g="POST",b=t.maxUploadRetryTime,S=new gT(y,g,KVe(t,r),b);return S.urlParams=f,S.headers=c,S.body=d.uploadData(),S.errorHandler=tse(e),S}var ese=class{constructor(e,r,n,i){this.current=e,this.total=r,this.finalized=!!n,this.metadata=i||null}};function _Bt(t,e){let r=null;try{r=t.getResponseHeader("X-Goog-Upload-Status")}catch{BO(!1)}return BO(!!r&&(e||["active"]).indexOf(r)!==-1),r}function D6a(t,e,r,n,i){let s=e.bucketOnlyServerUrl(),c=ion(e,n,i),u={name:c.fullPath},l=qM(s,t.host,t._protocol),o="POST",a={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n.size()}`,"X-Goog-Upload-Header-Content-Type":c.contentType,"Content-Type":"application/json; charset=utf-8"},p=kBt(c,r),m=t.maxUploadRetryTime;function d(y){_Bt(y);let g;try{g=y.getResponseHeader("X-Goog-Upload-URL")}catch{BO(!1)}return BO(WVe(g)),g}let f=new gT(l,o,d,m);return f.urlParams=u,f.headers=a,f.body=p,f.errorHandler=tse(e),f}function M6a(t,e,r,n){let i={"X-Goog-Upload-Command":"query"};function s(o){let a=_Bt(o,["active","final"]),p=null;try{p=o.getResponseHeader("X-Goog-Upload-Size-Received")}catch{BO(!1)}p||BO(!1);let m=Number(p);return BO(!isNaN(m)),new ese(m,n.size(),a==="final")}let c="POST",u=t.maxUploadRetryTime,l=new gT(r,c,s,u);return l.headers=i,l.errorHandler=tse(e),l}var Uin=256*1024;function q6a(t,e,r,n,i,s,c,u){let l=new ese(0,0);if(c?(l.current=c.current,l.total=c.total):(l.current=0,l.total=n.size()),n.size()!==l.total)throw YRa();let o=l.total-l.current,a=o;i>0&&(a=Math.min(a,i));let p=l.current,m=p+a,d="";a===0?d="finalize":o===a?d="upload, finalize":d="upload";let f={"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":`${l.current}`},y=n.slice(p,m);if(y===null)throw Jin();function g(A,T){let I=_Bt(A,["active","final"]),C=l.current+a,D=n.size(),P;return I==="final"?P=KVe(e,s)(A,T):P=null,new ese(C,D,I==="final",P)}let b="POST",S=e.maxUploadRetryTime,v=new gT(r,b,g,S);return v.headers=f,v.body=y.uploadData(),v.progressCallback=u||null,v.errorHandler=tse(t),v}var oon={STATE_CHANGED:"state_changed"},my={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function bBt(t){switch(t){case"running":case"pausing":case"canceling":return my.RUNNING;case"paused":return my.PAUSED;case"success":return my.SUCCESS;case"canceled":return my.CANCELED;case"error":return my.ERROR;default:return my.ERROR}}var TBt=class{constructor(e,r,n){if(ZRa(e)||r!=null||n!=null)this.next=e,this.error=r??void 0,this.complete=n??void 0;else{let s=e;this.next=s.next,this.error=s.error,this.complete=s.complete}}};function Xae(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}var jin=null,VVe=class{constructor(){this.errorText_="",this.sent_=!1,this.fetch_=Vin.default,this.errorCode_=pJ.NO_ERROR}async send(e,r,n,i){var s;if(this.sent_)throw $ae("cannot .send() more than once");this.sent_=!0;try{let c=await this.fetch_(e,{method:r,headers:i||{},body:n});this.headers_=c.headers,this.statusCode_=c.status,this.errorCode_=pJ.NO_ERROR,this.body_=await c.arrayBuffer()}catch(c){this.errorText_=(s=c)===null||s===void 0?void 0:s.message,this.statusCode_=0,this.errorCode_=pJ.NETWORK_ERROR}}getErrorCode(){if(this.errorCode_===void 0)throw $ae("cannot .getErrorCode() before receiving response");return this.errorCode_}getStatus(){if(this.statusCode_===void 0)throw $ae("cannot .getStatus() before receiving response");return this.statusCode_}getErrorText(){return this.errorText_}abort(){}getResponseHeader(e){if(!this.headers_)throw $ae("cannot .getResponseHeader() before receiving response");return this.headers_.get(e)}addUploadProgressListener(e){}removeUploadProgressListener(e){}},xBt=class extends VVe{getResponse(){if(!this.body_)throw $ae("cannot .getResponse() before receiving response");return Buffer.from(this.body_).toString("utf-8")}};function FO(){return jin?jin():new xBt}var NBt=class extends VVe{getResponse(){if(!this.body_)throw $ae("cannot .getResponse() before sending");return this.body_}};function w6a(){return new NBt}var d4e=class{constructor(e,r,n=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=e,this._blob=r,this._metadata=n,this._mappings=HVe(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=i=>{if(this._request=void 0,this._chunkMultiplier=1,i._codeEquals("canceled"))this._needToFetchStatus=!0,this.completeTransitions_();else{let s=this.isExponentialBackoffExpired();if(Qin(i.status,[]))if(s)i=Kin();else{this.sleepTime=Math.max(this.sleepTime*2,FRa),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=i,this._transition("error")}},this._metadataErrorHandler=i=>{this._request=void 0,i._codeEquals("canceled")?this.completeTransitions_():(this._error=i,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((i,s)=>{this._resolve=i,this._reject=s,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){let e=this._transferred;return r=>this._updateProgress(e+r)}_shouldDoResumable(e){return e.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(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([r,n])=>{switch(this._state){case"running":e(r,n);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((e,r)=>{let n=D6a(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),i=this._ref.storage._makeRequest(n,FO,e,r);this._request=i,i.getPromise().then(s=>{this._request=void 0,this._uploadUrl=s,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let e=this._uploadUrl;this._resolveToken((r,n)=>{let i=M6a(this._ref.storage,this._ref._location,e,this._blob),s=this._ref.storage._makeRequest(i,FO,r,n);this._request=s,s.getPromise().then(c=>{c=c,this._request=void 0,this._updateProgress(c.current),this._needToFetchStatus=!1,c.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let e=Uin*this._chunkMultiplier,r=new ese(this._transferred,this._blob.size()),n=this._uploadUrl;this._resolveToken((i,s)=>{let c;try{c=q6a(this._ref._location,this._ref.storage,n,this._blob,e,this._mappings,r,this._makeProgressCallback())}catch(l){this._error=l,this._transition("error");return}let u=this._ref.storage._makeRequest(c,FO,i,s,!1);this._request=u,u.getPromise().then(l=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(l.current),l.finalized?(this._metadata=l.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){Uin*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,r)=>{let n=non(this._ref.storage,this._ref._location,this._mappings),i=this._ref.storage._makeRequest(n,FO,e,r);this._request=i,i.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,r)=>{let n=_6a(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),i=this._ref.storage._makeRequest(n,FO,e,r);this._request=i,i.getPromise().then(s=>{this._request=void 0,this._metadata=s,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){let r=this._transferred;this._transferred=e,this._transferred!==r&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let r=this._state==="paused";this._state=e,r&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Yin(),this._state=e,this._notifyObservers();break;case"error":this._state=e,this._notifyObservers();break;case"success":this._state=e,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 e=bBt(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,r,n,i){let s=new TBt(r||void 0,n||void 0,i||void 0);return this._addObserver(s),()=>{this._removeObserver(s)}}then(e,r){return this._promise.then(e,r)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){let r=this._observers.indexOf(e);r!==-1&&this._observers.splice(r,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(r=>{this._notifyObserver(r)})}_finishPromise(){if(this._resolve!==void 0){let e=!0;switch(bBt(this._state)){case my.SUCCESS:Xae(this._resolve.bind(null,this.snapshot))();break;case my.CANCELED:case my.ERROR:let r=this._reject;Xae(r.bind(null,this._error))();break;default:e=!1;break}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(bBt(this._state)){case my.RUNNING:case my.PAUSED:e.next&&Xae(e.next.bind(e,this.snapshot))();break;case my.SUCCESS:e.complete&&Xae(e.complete.bind(e))();break;case my.CANCELED:case my.ERROR:e.error&&Xae(e.error.bind(e,this._error))();break;default:e.error&&Xae(e.error.bind(e,this._error))()}}resume(){let e=this._state==="paused"||this._state==="pausing";return e&&this._transition("running"),e}pause(){let e=this._state==="running";return e&&this._transition("pausing"),e}cancel(){let e=this._state==="running"||this._state==="pausing";return e&&this._transition("canceling"),e}};var MM=class{constructor(e,r){this._service=e,r instanceof P0?this._location=r:this._location=P0.makeFromUrl(r,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,r){return new MM(e,r)}get root(){let e=new P0(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return ton(this._location.path)}get storage(){return this._service}get parent(){let e=f6a(this._location.path);if(e===null)return null;let r=new P0(this._location.bucket,e);return new MM(this._service,r)}_throwIfRoot(e){if(this._location.path==="")throw CBt(e)}};function P6a(t,e){t._throwIfRoot("getBytes");let r=C6a(t.storage,t._location,e);return t.storage.makeRequestWithTokens(r,w6a).then(n=>e!==void 0?n.slice(0,e):n)}function L6a(t,e,r){return t._throwIfRoot("uploadBytesResumable"),new d4e(t,new yT(e),r)}function z6a(t){let e={prefixes:[],items:[]};return aon(t,e).then(()=>e)}async function aon(t,e,r){let i=await son(t,{pageToken:r});e.prefixes.push(...i.prefixes),e.items.push(...i.items),i.nextPageToken!=null&&await aon(t,e,i.nextPageToken)}function son(t,e){e!=null&&typeof e.maxResults=="number"&&vBt("options.maxResults",1,1e3,e.maxResults);let r=e||{},n=I6a(t.storage,t._location,"/",r.pageToken,r.maxResults);return t.storage.makeRequestWithTokens(n,FO)}function F6a(t){t._throwIfRoot("getMetadata");let e=non(t.storage,t._location,HVe());return t.storage.makeRequestWithTokens(e,FO)}function B6a(t,e){t._throwIfRoot("updateMetadata");let r=O6a(t.storage,t._location,e,HVe());return t.storage.makeRequestWithTokens(r,FO)}function U6a(t){t._throwIfRoot("getDownloadURL");let e=E6a(t.storage,t._location,HVe());return t.storage.makeRequestWithTokens(e,FO).then(r=>{if(r===null)throw JRa();return r})}function j6a(t){t._throwIfRoot("deleteObject");let e=R6a(t.storage,t._location);return t.storage.makeRequestWithTokens(e,FO)}function uon(t,e){let r=h6a(t._location.path,e),n=new P0(t._location.bucket,r);return new MM(t.storage,n)}function G6a(t){return/^[A-Za-z]+:\/\//.test(t)}function V6a(t,e){return new MM(t,e)}function con(t,e){if(t instanceof f4e){let r=t;if(r._bucket==null)throw KRa();let n=new MM(r,r._bucket);return e!=null?con(n,e):n}else return e!==void 0?uon(t,e):t}function W6a(t,e){if(e&&G6a(e)){if(t instanceof f4e)return V6a(t,e);throw lJ("To use ref(service, url), the first argument must be a Storage instance.")}else return con(t,e)}function Gin(t,e){let r=e?.[Hin];return r==null?null:P0.makeFromBucketSpec(r,t)}function H6a(t,e,r,n={}){t.host=`${e}:${r}`,t._protocol="http";let{mockUserToken:i}=n;i&&(t._overrideAuthToken=typeof i=="string"?i:zBe(i,t.app.options.projectId))}var f4e=class{constructor(e,r,n,i,s){this.app=e,this._authProvider=r,this._appCheckProvider=n,this._url=i,this._firebaseVersion=s,this._bucket=null,this._host=Win,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=LRa,this._maxUploadRetryTime=zRa,this._requests=new Set,i!=null?this._bucket=P0.makeFromBucketSpec(i,this._host):this._bucket=Gin(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,this._url!=null?this._bucket=P0.makeFromBucketSpec(this._url,e):this._bucket=Gin(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){vBt("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){vBt("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let e=this._authProvider.getImmediate({optional:!0});if(e){let r=await e.getToken();if(r!==null)return r.accessToken}return null}async _getAppCheckToken(){let e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new MM(this,e)}_makeRequest(e,r,n,i,s=!0){if(this._deleted)return new SBt(Xin());{let c=o6a(e,this._appId,n,i,r,this._firebaseVersion,s);return this._requests.add(c),c.getPromise().then(()=>this._requests.delete(c),()=>this._requests.delete(c)),c}}async makeRequestWithTokens(e,r){let[n,i]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,r,n,i).getPromise()}},K6a="@firebase/storage",Y6a="0.9.12";var pon="storage";function lon(t,e){return t=gi(t),P6a(t,e)}function mon(t,e,r){return t=gi(t),L6a(t,e,r)}function don(t){return t=gi(t),F6a(t)}function fon(t,e){return t=gi(t),B6a(t,e)}function hon(t,e){return t=gi(t),son(t,e)}function yon(t){return t=gi(t),z6a(t)}function gon(t){return t=gi(t),U6a(t)}function YVe(t){return t=gi(t),j6a(t)}function y4e(t,e){return t=gi(t),W6a(t,e)}function bon(t,e){return uon(t,e)}function Son(t=E9(),e){t=gi(t);let n=XK(t,pon).getImmediate({identifier:e}),i=LBe("storage");return i&&DBt(n,...i),n}function DBt(t,e,r,n={}){H6a(t,e,r,n)}function J6a(t,{instanceIdentifier:e}){let r=t.getProvider("app").getImmediate(),n=t.getProvider("auth-internal"),i=t.getProvider("app-check-internal");return new f4e(r,n,i,e,GA)}function X6a(){Rg(new np(pon,J6a,"PUBLIC").setMultipleInstances(!0)),od(K6a,Y6a)}X6a();var rse=class{constructor(e,r,n){this._delegate=e,this.task=r,this.ref=n}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 JVe=class{constructor(e,r){this._delegate=e,this._ref=r,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 rse(this._delegate.snapshot,this,this._ref)}then(e,r){return this._delegate.then(n=>{if(e)return e(new rse(n,this,this._ref))},r)}on(e,r,n,i){let s;return r&&(typeof r=="function"?s=c=>r(new rse(c,this,this._ref)):s={next:r.next?c=>r.next(new rse(c,this,this._ref)):void 0,complete:r.complete||void 0,error:r.error||void 0}),this._delegate.on(e,s,n||void 0,i||void 0)}},XVe=class{constructor(e,r){this._delegate=e,this._service=r}get prefixes(){return this._delegate.prefixes.map(e=>new II(e,this._service))}get items(){return this._delegate.items.map(e=>new II(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}};var II=class{constructor(e,r){this._delegate=e,this.storage=r}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){let r=bon(this._delegate,e);return new II(r,this.storage)}get root(){return new II(this._delegate.root,this.storage)}get parent(){let e=this._delegate.parent;return e==null?null:new II(e,this.storage)}put(e,r){return this._throwIfRoot("put"),new JVe(mon(this._delegate,e,r),this)}putString(e,r=T3.RAW,n){this._throwIfRoot("putString");let i=OBt(r,e),s=Object.assign({},n);return s.contentType==null&&i.contentType!=null&&(s.contentType=i.contentType),new JVe(new d4e(this._delegate,new yT(i.data,!0),s),this)}listAll(){return yon(this._delegate).then(e=>new XVe(e,this.storage))}list(e){return hon(this._delegate,e||void 0).then(r=>new XVe(r,this.storage))}getMetadata(){return don(this._delegate)}updateMetadata(e){return fon(this._delegate,e)}getDownloadURL(){return gon(this._delegate)}delete(){return this._throwIfRoot("delete"),YVe(this._delegate)}_throwIfRoot(e){if(this._delegate._location.path==="")throw CBt(e)}};var $Ve=class{constructor(e,r){this.app=e,this._delegate=r}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(von(e))throw lJ("ref() expected a child path but got a URL, use refFromURL instead.");return new II(y4e(this._delegate,e),this)}refFromURL(e){if(!von(e))throw lJ("refFromURL() expected a full URL but got a child path, use ref() instead.");try{P0.makeFromUrl(e,this._delegate.host)}catch{throw lJ("refFromUrl() expected a valid full URL but got an invalid one.")}return new II(y4e(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,r,n={}){DBt(this._delegate,e,r,n)}};function von(t){return/^[A-Za-z]+:\/\//.test(t)}var $6a="@firebase/storage-compat",Q6a="0.1.20";var Z6a="storage-compat";function eka(t,{instanceIdentifier:e}){let r=t.getProvider("app-compat").getImmediate(),n=t.getProvider("storage").getImmediate({identifier:e});return new $Ve(r,n)}function tka(t){let e={TaskState:my,TaskEvent:oon,StringFormat:T3,Storage:$Ve,Reference:II};t.INTERNAL.registerComponent(new np(Z6a,eka,"PUBLIC").setServiceProps(e).setMultipleInstances(!0)),t.registerVersion($6a,Q6a)}tka(Fs);var $Sp=en(Ton());var nse={};Bl(nse,{CoalesceError:()=>Wl,isCoalesceError:()=>uka});var Wl=class extends Error{constructor(e){super(e)}statusCode(){return 500}toTRunError(){return{error:{errorString:this.message,errorDetail:""}}}toString(){return JSON.stringify(this.toTRunError())}handleExpressResponse(e){e.status(this.statusCode()).json(this.toTRunError())}};function uka(t){return typeof t=="object"&&t instanceof Wl}var xon=(n=>(n.development="development",n.qa="qa",n.production="production",n))(xon||{}),Non={["development"]:{apiKey:"AIzaSyAus_ACzfASXnKQPBNPFdsApkuUbiQGsvE",authDomain:"coalesce-a6346.firebaseapp.com",projectId:"coalesce-a6346",storageBucket:"coalesce-a6346.appspot.com",messagingSenderId:"236763625216",appId:"1:236763625216:web:8495f0a13152e1d63c25e5",measurementId:"G-DPT4YWV78T"},["qa"]:{apiKey:"AIzaSyDmn_9ToPIXVBzjTdyj1wny9XivH-g48T0",authDomain:"cls-qa.firebaseapp.com",projectId:"cls-qa",storageBucket:"cls-qa.appspot.com",messagingSenderId:"243490689213",appId:"1:243490689213:web:29972e04747e7d113b67d4",measurementId:"G-FRJ2PNVPT4"},["production"]:{apiKey:"AIzaSyAGVrKvXxw69cVVdlQ7NMa46rQyrM3GuJM",authDomain:"dev-etl-284121.firebaseapp.com",projectId:"dev-etl-284121",storageBucket:"dev-etl-284121.appspot.com",messagingSenderId:"96686924891",appId:"1:96686924891:web:4d9a88b3b69f7865084b7e",measurementId:"G-33CRZMHDGR"}},Ion=t=>Non[t],ise=()=>ku()?process.env.RUNTIME_ENVIRONMENT||process.env.NODE_ENVIRONMENT||"production":window.ENVIRONMENT??"development",V7=()=>{let t=ise();return Ion(t)},cka=()=>{let t=i=>typeof window<"u"&&window[i]||process.env[i],e=t("FIREBASE_AUTH_EMULATOR_HOST"),r=t("FIRESTORE_EMULATOR_HOST"),n=t("FIREBASE_STORAGE_EMULATOR_HOST");if(!!e!=!!r||!!e!=!!n)throw new Error(`Inconsistent Firebase emulator use! All three emulators must be used, or none! auth=${e} firestore=${r} storage=${n}`);return e?{auth:e,firestore:r,storage:n}:null},bT=cka(),eWe=(t,e)=>{if(!bT)return;console.log(`Using Firebase Auth emulator at ${bT.auth}`),t.auth().useEmulator(bT.auth),console.log(`Using Firestore emulator at ${bT.firestore} over ${e?"https":"http"}`);let[r,n]=bT.firestore.split(":");t.firestore().useEmulator(r,parseInt(n)),e&&t.firestore()._delegate._setSettings({...t.firestore()._delegate._getSettings(),ssl:!0}),console.log(`Using Firebase Storage emulator at ${bT.storage} over ${e?"https":"http"}`);let[i,s]=bT.storage.split(":");t.storage().useEmulator(i,parseInt(s)),e&&(t.storage()._delegate._protocol="https")},pka=(t=!0)=>{if(Fs.apps.length)Fs.app();else{let e=Fs.initializeApp(V7());eWe(e,t)}},UO=()=>Fs.auth(),wM=Fs,lka=Fs.auth.GoogleAuthProvider.PROVIDER_ID,mka=Fs.auth.GithubAuthProvider.PROVIDER_ID,dka=Fs.auth.EmailAuthProvider.PROVIDER_ID,fka=()=>Fs.app(),hka=Fs.firestore.DocumentReference,wa=()=>Fs.app().firestore(),ose=()=>Fs.firestore.FieldValue,qBt=()=>Fs.app().functions(),wBt=Fs.firestore.FieldValue.serverTimestamp(),W7=t=>{let e=t.firestore.FieldValue;return e||(e=ose()),e},PBt=()=>{let t=UO();if(!t.currentUser)throw new Wl("Unable to retrieve refresh token, no current user!");return bT?t.currentUser.getIdToken(!0):Promise.resolve(t.currentUser.refreshToken)};var N4e=en(Mc()),M3p=N4e.Record({version:N4e.String,hash:N4e.String}),dse={version:"5.3.3",hash:"b77ec935e10ad10789eceb0a015ffd0719bd6f07"};var j_a=u3(),Kn=(Ye=>(Ye.Runner="RUNNER",Ye.Steps="STEPS",Ye.RunnerBackend="RUNNER_BACKEND",Ye.TreeOperations="TREE_OPERATIONS",Ye.StepTypes="STEP_TYPES",Ye.Graph="GRAPH",Ye.UI="UI",Ye.Testing="TESTING",Ye.DNS="DNS",Ye.APP="APP",Ye.Perf="PERFORMANCE",Ye.Deploy="DEPLOY",Ye.Firebase="FIREBASE",Ye.Connection="CONNECTION",Ye.Environments="ENVIRONMENTS",Ye.Jobs="JOBS",Ye.SQLParsing="SQL_PARSING",Ye.StorageLocations="STORAGE_LOCATIONS",Ye.ENV="ENV",Ye.Problems="PROBLEM_SCANNER",Ye.Git="GIT",Ye.GitSettings="GIT_SETTINGS",Ye.Common="COMMON",Ye.SqlTesting="SQL_TESTING",Ye.Heartbeat="HEARTBEAT",Ye.Palette="PALETTE",Ye.Auth="AUTH",Ye.UserManagement="USER_MANAGEMENT",Ye.MetadataOperations="METADATA_OPERATIONS",Ye.Search="SEARCH",Ye.Workspaces="WORKSPACES",Ye.State="STATE",Ye.UserSettings="USER_SETTINGS",Ye.AdvancedDeploy="ADVANCED_DEPLOY",Ye.MetadataHydration="METADATA_HYDRATION",Ye.TemplateEditor="TEMPLATE_EDITOR",Ye.MappingGrid="MAPPING_GRID",Ye.Pendo="PENDO",Ye.Strumenta="STRUMENTA",Ye.NarrowMetadata="NARROW_METADATA",Ye.CLI_INTERNAL="CLI_INTERNAL",Ye.DRAG="DRAG",Ye.CLI="CLI",Ye.RunTransaction="RUN_TRANSACTION",Ye.RunResults="RUN_RESULTS",Ye.Packages="PACKAGES",Ye.Jest="JEST",Ye.ORG_SCANNER="ORG_SCANNER",Ye.Projects="PROJECTS",Ye.JSONParser="JSON_PARSER",Ye.OrgSettings="ORG_SETTINGS",Ye.PartnerConnect="PARTNER_CONNECT",Ye.OrgBootstrap="ORG_BOOTSTRAP",Ye.Presync="PRESYNC",Ye.folders="FOLDERS",Ye.orgs="ORGS",Ye.users="USERS",Ye.Versioning="VERSIONING",Ye.Listeners="LISTENERS",Ye.Docs="DOCS",Ye.ErrorOperations="ERROR_OPERATIONS",Ye.VersionControlActions="VERSION_CONTROL_ACTIONS",Ye.ColumnLineage="COLUMN_LINEAGE",Ye.SystemEmails="SYSTEM_EMAILS",Ye.UserActivation="USER_ACTIVATION",Ye.Secrets="SECRETS",Ye.OrgUpgrade="ORG_UPGRADE",Ye.PackageNamespaces="PACKAGE_NAMESPACES",Ye))(Kn||{}),C4e=(u=>(u.infoContext="infoContext",u.debugContext="debugContext",u.errorContext="errorContext",u.assertContext="assertContext",u.alertContext="alertContext",u.emergContext="emergContext",u.appContext="appContext",u))(C4e||{}),Ian=(i=>(i.Scheduler="Scheduler",i.CLI="CLI",i.Frontend="Frontend",i.JestTest="JestTest",i))(Ian||{}),Can={levels:{emerg:0,assert:1,alert:2,error:3,app:4,info:5,debug:6},colors:{emerg:"red",assert:"yellow",alert:"yellow",error:"cyan",app:"blue",info:"green",debug:"magenta"}},WO,G_a=(t,e)=>{WO=t,WO=="Frontend"?tUt=e.datadogFrontEndLogger:(WO=="CLI"||WO=="Scheduler"||WO=="JestTest")&&IWe(WO)},tUt=null,Va={},V_a=t=>{Va={...Va,...t}},W_a=t=>{let e={};Object.keys(Q7).forEach(r=>{e[r]={defaultMeta:t}}),CWe(e)},nUt=t=>({coalesceSoftwareVersion:dse?.version||"",service:t,env:process.env.REACT_APP_OWNER?process.env.REACT_APP_OWNER:"",reactAppCoalesceDev:process.env.REACT_APP_COALESCE_DEV||""}),iUt=null,IWe=t=>{let e=nUt(t);iUt={host:"http-intake.logs.datadoghq.com",path:`/v1/input/3ae2b6d484bfaf4631d5910b5020f683?ddtags=env:${e.env},coalesceSoftwareVersion:${e.coalesceSoftwareVersion}&ddsource=nodejs&service=${t}`,ssl:!0}},rUt=class extends j_a{constructor(r){super(r);this.baseContext=nUt(WO),this.levelMappings={emerg:"error",assert:"warn",alert:"warn",error:"warn",app:"info",info:"info",debug:"debug"}}log(r,n){tUt&&tUt.log(r,{...this.baseContext,...Va},this.levelMappings[r.level]),n()}},CWe=t=>{Object.keys(t).forEach(e=>{let r=I4e(e);t[e].defaultMeta={...r.defaultMeta,...t[e].defaultMeta};let n=t[e].transports||r.transports;r.configure({...r,...t[e],transports:n,level:t[e].level||r.level})})},oUt=t=>new vT.transports.Console({format:Oan(),level:t.level}),EWe=()=>new vT.transports.Http({...iUt,format:vT.format.combine(Oan(),vT.format.uncolorize()),level:"info",env:process.env.REACT_APP_OWNER}),OWe=t=>{let e=t??{};return new rUt(e)},RWe=t=>{let e=[];return e.push(oUt(t)),iUt&&e.push(EWe()),[OWe(),...e]},Ean=t=>{let e=nUt(WO);return{appEnv:H_a(),loggingArea:t,...e}},H_a=()=>{let t={firebaseEnv:ise(),RUNTIME_ENVIRONMENT:process.env.RUNTIME_ENVIRONMENT,NODE_ENVIRONMENT:process.env.NODE_ENVIRONMENT,START_RUN_URL:L0};return ku()||(t.windowInfo={frontendURLHost:window.location.host,ENVIRONMENT:window.ENVIRONMENT}),t},Oan=()=>vT.format.combine(vT.format.timestamp(),vT.format.colorize({colors:Can.colors}),vT.format.printf(t=>`|${t.timestamp}|[${t.loggingArea}]${t.orgID?`|(org:${t.orgID})`:""}${t.envID?`|(env:${t.envID})`:""}${t.userID?`|(user:${t.userID})`:""}${t.runCounter?`|run:${t.runCounter})`:""}(${t.nodeID?`|(node:${t.nodeID})`:""})|${t.level}:${t.message}`)),Q7={["GIT_SETTINGS"]:{level:"info"},["MAPPING_GRID"]:{level:"info"},["RUNNER"]:{level:"info"},["STEPS"]:{level:"info"},["RUNNER_BACKEND"]:{level:"info"},["GRAPH"]:{level:"info"},["STEP_TYPES"]:{level:"info"},["TESTING"]:{level:"info"},["UI"]:{level:"info"},["DNS"]:{level:"info"},["APP"]:{level:"info"},["PERFORMANCE"]:{level:"info"},["TREE_OPERATIONS"]:{level:"info"},["DEPLOY"]:{level:"info"},["FIREBASE"]:{level:"info"},["CONNECTION"]:{level:"info"},["ENVIRONMENTS"]:{level:"info"},["JOBS"]:{level:"info"},["SQL_PARSING"]:{level:"debug"},["STORAGE_LOCATIONS"]:{level:"info"},["ENV"]:{level:"info"},["GIT"]:{level:"info"},["STORAGE_LOCATIONS"]:{level:"info"},["COMMON"]:{level:"info"},["ORG_SCANNER"]:{level:"info"},["SQL_TESTING"]:{level:"alert"},["PROBLEM_SCANNER"]:{level:"error"},["HEARTBEAT"]:{level:"info"},["PALETTE"]:{level:"info"},["AUTH"]:{level:"info"},["USER_MANAGEMENT"]:{level:"info"},["METADATA_OPERATIONS"]:{level:"info"},["SEARCH"]:{level:"info"},["WORKSPACES"]:{level:"info"},["STATE"]:{level:"info"},["USER_SETTINGS"]:{level:"info"},["ADVANCED_DEPLOY"]:{level:"info"},["METADATA_HYDRATION"]:{level:"info"},["TEMPLATE_EDITOR"]:{level:"info"},["PENDO"]:{level:"info"},["STRUMENTA"]:{level:"info"},["CLI"]:{level:"info"},["NARROW_METADATA"]:{level:"info"},["CLI_INTERNAL"]:{level:"info"},["CLI"]:{level:"info"},["DRAG"]:{level:"info"},["RUN_TRANSACTION"]:{level:"info"},["RUN_RESULTS"]:{level:"info"},["PACKAGES"]:{level:"info"},["JEST"]:{level:"info"},["PROJECTS"]:{level:"info"},["JSON_PARSER"]:{level:"info"},["ORG_SETTINGS"]:{level:"info"},["PARTNER_CONNECT"]:{level:"info"},["ORG_BOOTSTRAP"]:{level:"info"},["PRESYNC"]:{level:"info"},["FOLDERS"]:{level:"info"},["ORGS"]:{level:"info"},["USERS"]:{level:"info"},["VERSIONING"]:{level:"info"},["LISTENERS"]:{level:"info"},["DOCS"]:{level:"info"},["ERROR_OPERATIONS"]:{level:"info"},["VERSION_CONTROL_ACTIONS"]:{level:"info"},["COLUMN_LINEAGE"]:{level:"info"},["SYSTEM_EMAILS"]:{level:"info"},["USER_ACTIVATION"]:{level:"info"},["SECRETS"]:{level:"info"},["ORG_UPGRADE"]:{level:"info"},["PACKAGE_NAMESPACES"]:{level:"info"}},aUt=(u=>(u.emerg="emerg",u.info="info",u.error="error",u.debug="debug",u.assert="assert",u.alert="alert",u.app="app",u))(aUt||{}),$u=(t,e,r,n,i,s)=>({orgID:t,envID:e,userID:r,runID:n,nodeID:i,workspaceID:s}),fJ=(t,e)=>{t.runID=e},K_a=(t,e,r,n)=>({orgID:t,envID:e,userID:r,runID:n}),sUt=(t,e)=>{t.envID=e},Y_a=(t,e)=>{t.userID=e},I4e=t=>{let e=Q7[t];return e.logger||(e.logger=vT.createLogger({levels:Can.levels,defaultMeta:Ean(t),level:e.level,transports:RWe(e)})),e.logger},Kt=t=>{let e=S=>{let v=kWe(S);return $_a(v).join(" ")},r=(S,v)=>{let A=I4e(t),T=e(v);A.log({level:S,message:T})},n=(S,v,A)=>{let T=v?{...v,envID:v.envID?.toString()}:{},I=I4e(t),C=e(A);I.log({level:S,message:C,...T})};return{info:(...S)=>{r("info",S)},infoContext:(S,...v)=>{n("info",S,v)},emerg:(...S)=>{r("emerg",S)},emergContext:(S,...v)=>{n("emerg",S,v)},assert:(...S)=>{r("assert",S)},assertContext:(S,...v)=>{n("assert",S,v)},alert:(...S)=>{r("alert",S)},alertContext:(S,...v)=>{n("alert",S,v)},debug:(...S)=>{r("debug",S)},debugContext:(S,...v)=>{n("debug",S,v)},error:(...S)=>{r("error",S)},errorContext:(S,...v)=>{n("error",S,v)},app:(...S)=>{r("app",S)},appContext:(S,...v)=>{n("app",S,v)}}},J_a=1e6,X_a=.8,$_a=t=>{let n=J_a*X_a/t.length/2;return t.map(s=>typeof s!="string"||s.length<n?s:s.slice(0,n))},Z7=t=>{let e;return t&&t.length>5?e="*"+t.substring(t.length-4,t.length):t.length?e="****":e="",e},Ran=(t,e)=>{let r=t.toUpperCase(),n=[];if(Q7[r]||n.push("invalid logging area"),aUt[e]||n.push("invalid log level"),n.length)throw n.forEach(u=>{console.error(u)}),new Error("Invalid logging area or log level"+n);let i=I4e(r),s=i.transports.filter(u=>u.name==="console"),c=i.transports;s.length||(c=[...c,oUt(Q7[r])]),c.filter(u=>u.name==="console")[0].level=e,i.configure({...i,transports:i.transports})},Q_a=()=>{Object.keys(Q7).forEach(t=>{Ran(t,"debug")})};var q3p=new Error("timeout while waiting for mutex to become available"),w3p=new Error("mutex already locked"),Z_a=new Error("request for lock canceled"),eDa=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(c){c(s)})}return new(r||(r=Promise))(function(s,c){function u(a){try{o(n.next(a))}catch(p){c(p)}}function l(a){try{o(n.throw(a))}catch(p){c(p)}}function o(a){a.done?s(a.value):i(a.value).then(u,l)}o((n=n.apply(t,e||[])).next())})},eL=class{constructor(e,r=Z_a){this._value=e,this._cancelError=r,this._weightedQueues=[],this._weightedWaiters=[]}acquire(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,n)=>{this._weightedQueues[e-1]||(this._weightedQueues[e-1]=[]),this._weightedQueues[e-1].push({resolve:r,reject:n}),this._dispatch()})}runExclusive(e,r=1){return eDa(this,void 0,void 0,function*(){let[n,i]=yield this.acquire(r);try{return yield e(n)}finally{i()}})}waitForUnlock(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),this._weightedWaiters[e-1].push(r),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatch()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatch()}cancel(){this._weightedQueues.forEach(e=>e.forEach(r=>r.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var e;for(let r=this._value;r>0;r--){let n=(e=this._weightedQueues[r-1])===null||e===void 0?void 0:e.shift();if(!n)continue;let i=this._value,s=r;this._value-=r,r=this._value+1,n.resolve([i,this._newReleaser(s)])}this._drainUnlockWaiters()}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){for(let e=this._value;e>0;e--)!this._weightedWaiters[e-1]||(this._weightedWaiters[e-1].forEach(r=>r()),this._weightedWaiters[e-1]=[])}},tDa=function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(c){c(s)})}return new(r||(r=Promise))(function(s,c){function u(a){try{o(n.next(a))}catch(p){c(p)}}function l(a){try{o(n.throw(a))}catch(p){c(p)}}function o(a){a.done?s(a.value):i(a.value).then(u,l)}o((n=n.apply(t,e||[])).next())})},fse=class{constructor(e){this._semaphore=new eL(1,e)}acquire(){return tDa(this,void 0,void 0,function*(){let[,e]=yield this._semaphore.acquire();return e})}runExclusive(e){return this._semaphore.runExclusive(()=>e())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var usn=en(Mc()),csn=en(jan()),psn=en(require("fs")),lsn=en(tL());var HO=en(hse(),1),nvp=HO.default.v1,ivp=HO.default.v3,yJ=HO.default.v4,ovp=HO.default.v5,avp=HO.default.NIL,svp=HO.default.version,uvp=HO.default.validate,cvp=HO.default.stringify,pvp=HO.default.parse;var msn=require("crypto"),{exec:dMa}=require("child_process"),yse;function fMa(t){yse=t}var hMa=new Set([""," ","(",")","#","%","`","'",'"',",",".","|","+","+","!","?","{","}","/","\\",":","@","#",";"]),ku=()=>typeof window>"u",dsn=()=>window.location.hostname=="localhost",YWe=()=>process.env.GOOGLE_APPLICATION_CREDENTIALS!==void 0,yMa=Kt("RUNNER_BACKEND"),ll=Kt("COMMON"),gMa=t=>YWe()?Promise.resolve():t.delete().catch(e=>{yMa.error(`Error deleting firebase instance: ${e}`)}),fsn=()=>{let t;return process.env.PORT?parseInt(process.env.PORT):(t=8080,t)},L0=ku()||dsn()?process.env.SCHEDULER_ADDRESS||`http://localhost:${fsn().toString()}`:window.REACT_APP_GIT_PROXY_URL,bMa=(t,e)=>t.reduce((r,n)=>parseInt(r)>parseInt(n)?parseInt(r):parseInt(n),e);function hsn(t,e){return AT.has(t,e)}function ysn(t,e){return AT.get(t,e)}function rL(t,e,r){return AT.set(t,e,r)}function ur(t,e,r){return hsn(t,e)?ysn(t,e):r}var pp=t=>AT.cloneDeep(t),hUt=(t,e)=>(0,lsn.default)(t,e),SMa=t=>AT.uniqueId(t);function gse(t,e,r){if(!t||!e)return r;let n=Object.values(t).find(i=>e==i);return n||r}var yUt=(t,e)=>{try{CUt(t,r=>r.every(n=>typeof n[e]=="string"),{},"Unable to sort array, attributes being compared must all be strings. Returning original value.")}catch{return t}return t.sort((r,n)=>{let i=r[e].toUpperCase(),s=n[e].toUpperCase();return i<s?-1:i>s?1:0})},E2=t=>{let e=Object.values(t),r=i=>e.includes(i),n=i=>`Failed constraint check. Expected one of ${JSON.stringify(e)}, but received ${JSON.stringify(i)}`;return usn.Unknown.withConstraint(i=>r(i)||n(i))},vMa=(t,e)=>{let r=Object.getOwnPropertyNames(t),n=Object.getOwnPropertyNames(e);if(r.length!=n.length)return!1;for(let i=0;i<r.length;i++){let s=r[i];if(t[s]!==e[s])return!1}return!0},gsn=(t,e)=>new Date(e).getTime()-new Date(t).getTime(),AMa=t=>{let e=new Date().toISOString(),r=n=>{let i=new Date().toISOString();return{performanceTime:gsn(e,i),passThroughData:n}};return t().then(r,r)},TMa=()=>bsn("env")=="demo",xMa=()=>!!Ssn("id_token"),NMa=()=>window.location.href.includes("editor.structure.rest"),bsn=t=>{let e=window.location.href;return new URL(e).searchParams.get(t)},Ssn=t=>{let r=window.location.hash.substr(1).split("&"),n={};return r.forEach(i=>{let[s,c]=i.split("=");n[s]=c}),n[t]},IMa="us-west-2_c4Lg8pNfQ",CMa="mjn020f01m2uvvg38ujrt8gts",EMa="us-west-2:da18afd3-bfb8-4b1a-876a-6bbe7ec60669",vsn="us-west-2",OMa="cognito-idp."+vsn+".amazonaws.com/",N3=(t,e,r)=>({statusCode:t,error:{errorString:e,errorDetail:r},toString:()=>`${e} DETAIL:${r}`}),Asn=(t,e)=>({upper:t,lower:t-e}),RMa=(t,e,r)=>{let n=Asn(t,e),i=e*r;return{upper:n.upper-i,lower:n.lower-i}},gJ=(t,e,r,n)=>{let i=KO(),s=n();return e(r,t,"total elapsed time: ",KO()-i),s},Pa=(t,e,r,n,i="debugContext")=>{let s=KO();return JWe(t,e,r,s,n(),i)},gUt=(t,e,r,n,i)=>{let s=KO(),c=Kt(n);return i.catch(u=>{throw c.errorContext(r,`Promise in ${e} threw an error`,u,u.stack),u}).finally(()=>{let l=KO()-s;l>t&&c.assertContext(r,n,!1,`Promise in ${e} exceeded ${t} milliseconds.
|
|
1185
1185
|
Elapsed Milliseconds: ${l}`)})},KO=()=>ku()?Date.now():performance.now(),JWe=async(t,e,r,n,i,s="debugContext")=>{let c=Kt(r);return i.catch(u=>{throw c.errorContext(e,t,`
|
|
1186
1186
|
rejected with an error: `,u,u.stack),u}).finally(()=>{let u=KO();c[s](e,t,`
|
|
1187
1187
|
completed in ${u-n}ms`)})},kMa=(t,e,r,n)=>{let i=Date.now(),s=Kt(r),c=(i-e)/1e3;s.infoContext(n,`${t} completes in ${c} seconds`)},_Ma=(t,e)=>{let r=1,n=new Set([...e]);if(!n.has(t))return t;for(;n.has(t+r);)r++;return t+r},Tsn=(o=>(o.AG_Tree_Node="ag-tree-node",o.AG_Tree_Subgraph="ag-tree-subgraph",o.AG_Tree_Job="ag-tree-job",o.AG_Tree_Parent="ag-tree-parent",o.AG_SQL_Step_Menu_Column="ag-SQL-step-menu-column",o.AG_Column_Viewer_Column="ag-column-viewer-column",o.Step_Menu_Tab="step-menu-tab",o.Node_Test="node-test",o.Tabular_Config="tabular-config",o))(Tsn||{}),xsn=(t,e)=>t.filter(r=>r[e]!==void 0||r[e]!==null).sort((r,n)=>r[e]<n[e]?-1:r[e]>n[e]?1:0),bUt=new Set([" ","(",")","#","%","`","'",'"',",",".","|","+","+","!","?","{","}","/","\\"]),Nsn=t=>t.split("").every(r=>!bUt.has(r)),_4e=t=>t.split("").filter(n=>!bUt.has(n)).join(""),DMa=t=>Isn(t,()=>{}),Isn=(t,e)=>{let r;return ku()||(r=ur(window,t,e),rL(window,t,e)),()=>{ku()||rL(window,t,r)}},zr=(t,e,r,...n)=>os(t,e,{},r,...n),os=(t,e,r,n,...i)=>{let s=Kt(t);if(!e){let c=`orgID: ${yse}, ${n||"assertion failed"}`,u=[c,...i];try{throw new Error(c)}catch{s.assertContext(r,...u)}}},zM=(t,e,r,n)=>{if(!t)throw Kt(r).errorContext(n,e),new Error(e)},MMa=(t,e,r)=>zr("COMMON",Object.values(t).includes(e),`expected field missing from enum ${r}! (AssertEnumHasField)`),SUt=t=>t.length!==new Set(t).size,qMa=(t,e=null)=>{let r,n;return ll.info("enable injection point:",t.injectionName),t.shouldInject=e,t.injectionPromise=new Promise((i,s)=>{r=i,n=s}),{release:()=>{ll.info("releasing injection",t.injectionName),r(),t.shouldInject=null},releaseWithError:i=>{ll.info("releasing injection WITH error",t.injectionName,i),n(i),t.shouldInject=null}}},Csn=(t,e,...r)=>t.injectionPromise?t.shouldInject&&!t.shouldInject(e)?Promise.resolve(r):(ll.info("going into waiting :",t.injectionName),t.injectionPromise.then(()=>(ll.info("completed injection:",t.injectionName),r))):Promise.resolve(r),D4e=t=>({injectionName:t,injectionPromise:null,shouldInject:null}),HWe=class extends Error{constructor(r,n,i,s){let c=`Error: stdout:
|
|
@@ -3131,7 +3131,7 @@ code:
|
|
|
3131
3131
|
{% endif %}
|
|
3132
3132
|
{%- endmacro -%}`}};var J8=t=>{let e="";return Object.keys(t).forEach(r=>{e+=`${t[r].macroString}`}),e};var jh={};Bl(jh,{CloudCredsToBasic:()=>A9e,ConvertJobID:()=>GNt,DeployRequest:()=>xre,DevRunRequest:()=>HNt,HandleSnowflakeAuthType:()=>b9e,RDeployRunCLI:()=>R7c,RDeployRunDetails:()=>Z6r,RDeployRunWeb:()=>k7c,RDevRunRunDetails:()=>hzo,RDevRunWeb:()=>_7c,RDividedStepDataWithWorkspaceEdits:()=>fzo,RFromWorkspaceData:()=>Q6r,RReRunCLI:()=>S7c,RReRunDetails:()=>$6r,RReRunWeb:()=>v7c,RRefreshRunCLI:()=>g7c,RRefreshRunDetails:()=>X6r,RRefreshRunWeb:()=>b7c,RResetPasswordBody:()=>y7c,RRunSQLRequest:()=>M7c,RSnowflakeBasicAuthCredentials:()=>KNt,RSnowflakeCloudAuthCredentials:()=>H6r,RSnowflakeKeyPairAuthCredentials:()=>Y6r,RSnowflakeOAuthCredentials:()=>K6r,RTokenParam:()=>h7c,ReRunRequest:()=>v9e,RefreshRequest:()=>W6r,RunRequest:()=>Tre});var ir=en(Mc());var qp={};Bl(qp,{AuthenticateFirebaseTokenAndRetrieveTeamInfoForCLI:()=>I9c,AuthenticateFirebaseTokenAndRetrieveTeamInfoForScheduler:()=>ezo,BECLI_HandleDeploy:()=>P9c,BECLI_HandleReRun:()=>$9c,BECLI_HandleRefresh:()=>j9c,CheckIsValidAdminUpdate:()=>czo,CleanObjectForLogging:()=>z6r,CreateAndSetUserDoc:()=>lzo,CreateConnectionObjectFromUserInfo:()=>g9e,CreateOrUpdateUserShared:()=>Z9c,CreateQueryResponseObject:()=>FNt,CreateUserContext:()=>UNt,DEFAULT_PARALLELISM:()=>QLo,EErrorMessages:()=>$Lo,EPrivilegesAvailableToRoles:()=>szo,FinalizeDeployRunInfo:()=>k9c,FinalizeRefreshRunInfo:()=>_9c,FinishWithError:()=>A9c,FirebaseExport:()=>zNt,GetPrivilegesBasedOnUserRole:()=>uzo,GetRuntimeParametersObjectForRun:()=>jNt,HARD_MAX_PARALLELISM_SCHEDULER:()=>L6r,LogRequestInfo:()=>E9c,RunSQLWithoutScheduler:()=>nzo,RunnerBackendLogger:()=>ca,TimedSQLExecution:()=>BNt,ValidateBasicAuthHeader:()=>pzo,ValidateRequest:()=>O9c,ValidateRequestBody:()=>tzo,ValidateRequestQuery:()=>rzo,ValidationError:()=>aH,initFirebaseAdmin:()=>v9c});var Dl=en(Mc());var VWp=Kt("USER_MANAGEMENT"),Kpi=null;ku()&&(Kpi=zfr());var Ffr=async t=>await Kpi.auth().getUser(t);var CLo=en(Zli());var Y0t=en(A1i());var nbi=en(rbi()),mmt=en(l8e());var d8e=class{constructor(e){this.value=e}get sensitiveValue(){return this.value}toString(){return d8e.representation}toJSON(){return d8e.representation}[Symbol.for("nodejs.util.inspect.custom")](){return d8e.representation}},lm=d8e;lm.representation="[REDACTED]";var DXp=new fFe("tag:yaml.org,2002:str",{kind:"scalar",instanceOf:lm,represent:t=>t.toString()});var dmt=class{constructor(e){this.projectId=e;this.client=new nbi.SecretManagerServiceClient;this.BuildSecretName=e=>`projects/${this.projectId}/secrets/${e}`;this.BuildSecretNameLatestVersion=e=>`${this.BuildSecretName(e)}/versions/latest`;this.Get=async e=>{try{let[r]=await this.client.accessSecretVersion({name:this.BuildSecretNameLatestVersion(e)}),n=r.payload?.data?.toString();return n?new lm(n):null}catch(r){if(r.code===mmt.Status.NOT_FOUND)return null;throw r}};this.Set=async(e,r)=>{let n={parent:this.BuildSecretName(e),payload:{data:Buffer.from(r.sensitiveValue)}};try{await this.client.addSecretVersion(n)}catch(i){if(i.code===mmt.Status.NOT_FOUND){await this.client.createSecret({parent:`projects/${this.projectId}`,secretId:e,secret:{replication:{automatic:{}}}}),await this.client.addSecretVersion(n);return}throw i}};this.Delete=async e=>{try{await this.client.deleteSecret({name:this.BuildSecretName(e)})}catch(r){if(r.code===mmt.Status.NOT_FOUND)return;throw r}}}};var wDi=en(qDi());var T3r=class{constructor(e){this.Get=async e=>{let r=await this.client.get(e);return r===null?null:new lm(r)};this.Set=async(e,r)=>{await this.client.set(e,r.sensitiveValue)};this.Delete=async e=>{await this.client.del(e)};this.client=(0,wDi.createClient)({url:e})}},F8e=T3r;F8e.Create=async e=>{let r=new T3r(e);return await r.client.connect(),r};var B8e=class{constructor(e){this.secretStore=e;this.Get=async(e,r)=>{let n=await this.secretStore.Get(e.SecretName(r));if(n===null)return null;let i=new lm(e.runtype.check(JSON.parse(n.sensitiveValue)));return e.GetEntry(r,i)};this.Set=async(e,r,n)=>{let i=e.SecretName(r),s=null,c=await this.secretStore.Get(i);c!==null&&(s=new lm(e.runtype.check(JSON.parse(c.sensitiveValue))));let u=e.SetEntry(r,s,n);await this.secretStore.Set(i,new lm(JSON.stringify(u.sensitiveValue)))};this.Delete=async(e,r)=>{let n=e.SecretName(r),i=await this.secretStore.Get(n);if(i===null)return;let s=new lm(e.runtype.check(JSON.parse(i.sensitiveValue))),c=e.DeleteEntry(r,s);c===null?this.secretStore.Delete(n):this.secretStore.Set(n,new lm(JSON.stringify(c.sensitiveValue)))}}};var Ebe=class extends Error{constructor(r,n,i){super(i);this.name="ApiError",this.url=n.url,this.status=n.status,this.statusText=n.statusText,this.body=n.body,this.request=r}};var j0t=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},U8e=class{constructor(e){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,n)=>{this._resolve=r,this._reject=n;let i=u=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(u))},s=u=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(u))},c=u=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(u)};return Object.defineProperty(c,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(c,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(c,"isCancelled",{get:()=>this._isCancelled}),e(i,s,c)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let e of this._cancelHandlers)e()}catch(e){console.warn("Cancellation threw an error",e);return}this._cancelHandlers.length=0,this._reject?.(new j0t("Request aborted"))}}get isCancelled(){return this._isCancelled}};Symbol.toStringTag;var qC={BASE:"",VERSION:"1.0.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var N3r=t=>t!=null,j8e=t=>typeof t=="string",x3r=t=>j8e(t)&&t!=="",I3r=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),PDi=t=>t instanceof FormData,vBu=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ABu=t=>{let e=[],r=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},n=(i,s)=>{N3r(s)&&(Array.isArray(s)?s.forEach(c=>{n(i,c)}):typeof s=="object"?Object.entries(s).forEach(([c,u])=>{n(`${i}[${c}]`,u)}):r(i,s))};return Object.entries(t).forEach(([i,s])=>{n(i,s)}),e.length>0?`?${e.join("&")}`:""},TBu=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,n=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(s,c)=>e.path?.hasOwnProperty(c)?r(String(e.path[c])):s),i=`${t.BASE}${n}`;return e.query?`${i}${ABu(e.query)}`:i},xBu=t=>{if(t.formData){let e=new FormData,r=(n,i)=>{j8e(i)||I3r(i)?e.append(n,i):e.append(n,JSON.stringify(i))};return Object.entries(t.formData).filter(([n,i])=>N3r(i)).forEach(([n,i])=>{Array.isArray(i)?i.forEach(s=>r(n,s)):r(n,i)}),e}},G0t=async(t,e)=>typeof e=="function"?e(t):e,NBu=async(t,e)=>{let r=await G0t(e,t.TOKEN),n=await G0t(e,t.USERNAME),i=await G0t(e,t.PASSWORD),s=await G0t(e,t.HEADERS),c=Object.entries({Accept:"application/json",...s,...e.headers}).filter(([u,l])=>N3r(l)).reduce((u,[l,o])=>({...u,[l]:String(o)}),{});if(x3r(r)&&(c.Authorization=`Bearer ${r}`),x3r(n)&&x3r(i)){let u=vBu(`${n}:${i}`);c.Authorization=`Basic ${u}`}return e.body&&(e.mediaType?c["Content-Type"]=e.mediaType:I3r(e.body)?c["Content-Type"]=e.body.type||"application/octet-stream":j8e(e.body)?c["Content-Type"]="text/plain":PDi(e.body)||(c["Content-Type"]="application/json")),new Headers(c)},IBu=t=>{if(t.body)return t.mediaType?.includes("/json")?JSON.stringify(t.body):j8e(t.body)||I3r(t.body)||PDi(t.body)?t.body:JSON.stringify(t.body)},CBu=async(t,e,r,n,i,s,c)=>{let u=new AbortController,l={headers:s,body:n??i,method:e.method,signal:u.signal};return t.WITH_CREDENTIALS&&(l.credentials=t.CREDENTIALS),c(()=>u.abort()),await fetch(r,l)},EBu=(t,e)=>{if(e){let r=t.headers.get(e);if(j8e(r))return r}},OBu=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return e.toLowerCase().startsWith("application/json")?await t.json():await t.text()}catch(e){console.error(e)}},RBu=(t,e)=>{let n={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(n)throw new Ebe(t,e,n);if(!e.ok)throw new Ebe(t,e,"Generic Error")},Aee=(t,e)=>new U8e(async(r,n,i)=>{try{let s=TBu(t,e),c=xBu(e),u=IBu(e),l=await NBu(t,e);if(!i.isCancelled){let o=await CBu(t,e,s,u,c,l,i),a=await OBu(o),p=EBu(o,e.responseHeader),m={url:s,ok:o.ok,status:o.status,statusText:o.statusText,body:p??a};RBu(e,m),r(m.body)}}catch(s){n(s)}});var Tee=class{static getSecretOld(e,r,n){return Aee(qC,{method:"GET",url:"/scheduler/secret",query:{secretType:e,idToken:r,applicationContext:n},errors:{400:"Server error retreiving secret.",500:"Server error retreiving secret."}})}static setSecretOld(e,r,n,i){return Aee(qC,{method:"POST",url:"/scheduler/secret",query:{secretType:e,idToken:r,applicationContext:n},body:i,mediaType:"application/json",errors:{400:"Server error retreiving secret.",500:"Server error retreiving secret."}})}static deleteSecretOld(e,r,n){return Aee(qC,{method:"DELETE",url:"/scheduler/secret",query:{secretType:e,idToken:r,applicationContext:n},errors:{400:"Server error retreiving secret.",500:"Server error retreiving secret."}})}static secretExists(e,r){return Aee(qC,{method:"GET",url:"/scheduler/secret/{secretType}/{context}",path:{secretType:e,context:r},errors:{400:"Server error retreiving secret.",401:"User lacks authorization to perform this action.",500:"Server error retreiving secret."}})}static setSecret(e,r,n){return Aee(qC,{method:"POST",url:"/scheduler/secret/{secretType}/{context}",path:{secretType:e,context:r},body:n,mediaType:"application/json",errors:{400:"Server error retreiving secret.",401:"User lacks authorization to perform this action.",500:"Server error retreiving secret."}})}static deleteSecret(e,r){return Aee(qC,{method:"DELETE",url:"/scheduler/secret/{secretType}/{context}",path:{secretType:e,context:r},errors:{400:"Server error retreiving secret.",401:"User lacks authorization to perform this action.",500:"Server error retreiving secret."}})}};var V0t=class{constructor(e,r){this.auth=r;this.GetIdToken=async()=>{if(this.auth.currentUser===null)throw new Error("Unable to get current user!");return this.auth.currentUser.getIdToken(!0)};this.Exists=async(e,r)=>await Tee.secretExists(e.typeName,e.EncodeContext(r));this.Set=async(e,r,n)=>await Tee.setSecret(e.typeName,e.EncodeContext(r),{secretValue:n.sensitiveValue});this.Delete=async(e,r)=>await Tee.deleteSecret(e.typeName,e.EncodeContext(r));qC.BASE=e,qC.TOKEN=this.GetIdToken}};var G8e=en(Mc());var V8e=G8e.Record({orgId:G8e.String,userId:G8e.String}),W0t=(t,e,r)=>({DecodeContext:n=>t.check({[e]:n}),EncodeContext:n=>(t.check(n),encodeURIComponent(n[e])),GetEntry:(n,i)=>{t.check(n),r.check(i.sensitiveValue);let s=i.sensitiveValue[n[e]];return s?new lm(r.value.check(s)):null},SetEntry:(n,i,s)=>{t.check(n);let c=i?pp(r.check(i.sensitiveValue)):{};return c[n[e]]=r.value.check(s.sensitiveValue),new lm(c)},DeleteEntry:(n,i)=>{t.check(n),r.check(i.sensitiveValue);let s=i?pp(r.check(i.sensitiveValue)):{};return delete s[n[e]],typeof s=="object"&&(s===null||Object.keys(s).length===0)?null:s?new lm(s):null}});var Obe=en(Mc());var LDi=Obe.Record({projectId:Obe.String}),kBu=Obe.Intersect(V8e,LDi),zDi=t=>W0t(LDi,"projectId",t);var Rbe=en(Mc());var FDi=Rbe.Record({workspaceId:Rbe.String}),_Bu=Rbe.Intersect(V8e,FDi),kbe=t=>W0t(FDi,"workspaceId",t);var W8e=en(Mc());var BDi=W8e.Dictionary(W8e.String,W8e.String),H0t={typeName:"GitTokens",runtype:BDi,SecretName:t=>`${t.orgId}_${t.userId}_GitTokens`,...zDi(BDi)};var xee=en(Mc());var jDi=xee.Record({password:xee.String}),UDi=xee.Dictionary(jDi,xee.String),WV={typeName:"SnowflakeCredentials",runtype:UDi,SecretName:t=>`${t.orgId}_${t.userId}_SnowflakeCredentials`,...kbe(UDi)};var HV=en(Mc());var VDi=HV.Record({clientId:HV.String,clientSecret:HV.String}),GDi=HV.Dictionary(VDi,HV.String),K0t={typeName:"SnowflakeOAuth",runtype:GDi,SecretName:t=>`${t.orgId}_SnowflakeOAuth`,...kbe(GDi)};var KV=en(Mc());var HDi=KV.Record({access_token:KV.String,refresh_token:KV.String}),WDi=KV.Dictionary(HDi,KV.String),Nee={typeName:"SnowflakeTokens",runtype:WDi,SecretName:t=>`${t.orgId}_${t.userId}_SnowflakeTokens`,...kbe(WDi)};var DBu={[H0t.typeName]:H0t,[WV.typeName]:WV,[K0t.typeName]:K0t,[Nee.typeName]:Nee};var qBu=(0,Y0t.default)(async()=>process.env.USE_SECRET_STORE_REDIS==="true"?(console.log("Selected Redis secret store."),await F8e.Create("redis://secret-store-redis")):(console.log("Selected Google Secrets Manager secret store."),new dmt(V7().projectId))),H8e=(0,Y0t.default)(async()=>new B8e(await qBu())),KDi=(0,Y0t.default)(async()=>new V0t(L0,UO()));var ELo;ku()&&(ELo=S7o());var OLo=require("v8"),a9c=ILo(),FMl=a9c.lib.WordArray.random(128/8),yA=Kt("CONNECTION"),l9e=Kt("RUNNER_BACKEND");var RLo=async(t,e,r)=>{let n=new d9e(t,e,r,async()=>{throw new FS("Cannot reset connection")});return n.Start(),n.promise};var _6r=(t,e,r)=>async(n,i)=>{let{database:s,schema:c,locationName:u}=i,l=`SHOW ${e} IN "${s}"."${c}"`;try{(await r(l)).forEach(a=>{_Nt(n,s,c,[a])})}catch(o){let a=`Error showing objects for location "${u}", using database: "${s}", schema: "${c}". `;l9e.errorContext({orgID:t.orgID},a,o),_Nt(n,s,c,[],o);let p=mEe(o);throw new Error(a+p)}};var D6r=t=>async e=>(await t.execute({sqlText:e})).rows;var kLo=t=>{let e=D6r(t);return async r=>(await e(r)).map(i=>i.name)};var _Lo=(t,e,r,n)=>M6r(_6r(t,"OBJECTS",D6r(r)),e,n),DLo=(t,e,r,n)=>M6r(_6r(t,"VIEWS",kLo(r)),e,n),MLo=(t,e,r,n)=>M6r(_6r(t,"TABLES",kLo(r)),e,n);var qLo=(t,e,r)=>s9c(t,e,D6r(r)),s9c=async(t,e,r)=>{let n={},i=[];e.flatMap(c=>Object.values(c)).forEach(c=>{let{database:u,schema:l,locationName:o}=c;(!n[u]||!n[u][l])&&i.push(c),wLo(n,u,l,o)});let s=i.map(c=>async()=>{let{database:u,schema:l,locationName:o}=c;try{let a=`SHOW COLUMNS IN SCHEMA "${u}"."${l}"`,p=await r(a);_Nt(n,u,l,p)}catch(a){let p=`Error showing objects for location "${o}", using database: "${u}", schema: "${l}." `;l9e.errorContext({orgID:t.orgID},p,a),_Nt(n,u,l,[],a);let m=mEe(a);throw new Error(p+m)}});try{await FM(s,4)}catch(c){throw oHt(c)}return n},wLo=(t,e,r,n)=>{t[e]||(t[e]={}),t[e][r]||(t[e][r]={}),t[e][r][n]||(t[e][r][n]={objects:[]})},_Nt=(t,e,r,n,i)=>{Object.keys(t[e][r]).forEach(s=>{i?t[e][r][s].error=i:t[e][r][s].objects.push(...n)})},M6r=async(t,e,r)=>{let n={},i=[];Object.values(e).forEach(c=>{let{database:u,schema:l,locationName:o}=c;(!n[u]||!n[u][l])&&i.push(c),wLo(n,u,l,o)});let s=i.map(c=>()=>t(n,e[c.locationName]));try{return await vUt(s,4),n}catch(c){if(r)throw oHt(c);return l9e.error("At least one location had an error when running object list",c),n}},PLo=t=>`EXPLAIN USING text ${t}`;var BMl=D4e("CREATE_CONNECTION"),UMl=D4e("CREATE_CONNECTION_WAITING"),jMl=D4e("_WaitForValidConnection Has Connection"),q6r=t=>{let e=!0;return!t.accountName||!t.user?!1:e};var LLo=(t,e,r)=>{let{environmentID:n}=t;return new Promise((i,s)=>{let{teamInfo:c}=e;H8e().then(u=>u.Get(Nee,{orgId:c.fbTeamID,userId:c.fbUserID,workspaceId:n.toString()})).then(u=>{if(yA.infoContext(r,"get access token from secret (GetAccessTokenFromSecret)"),!u)throw new Error("Could not find tokens in Google Secrets Manager!");i(u.sensitiveValue)}).catch(u=>{yA.errorContext(r,"Error getting access token from secret (GetAccessTokenFromSecret)",u),s(u)})})},zLo=(t,e)=>{if(!q6r(t))throw yA.infoContext(e,"Error creating basic snowflake connection parameters (CreateSnowflakeConnectionBasic)",{user:Z7(t.user),accountName:Z7(t.accountName)}),new Sre("Invalid Connection Information, please correct your account or username and proceed.","Basic");let{accountName:r,user:n,password:i,role:s,warehouse:c}=t,u={account:r,username:n,password:i,application:"CoalesceIO_Coalesce"};return s&&(u.role=s),c&&(u.warehouse=c),u},FLo=(t,e)=>{if(!q6r(t))throw yA.infoContext(e,"Error creating basic snowflake connection (CreateSnowflakeConnectionKeyPair)",{user:Z7(t.user),accountName:Z7(t.accountName)}),new Sre("Invalid Connection Information, please correct your account or username and proceed.","KeyPair");let{accountName:r,user:n,warehouse:i,role:s}=t;return{authenticator:"SNOWFLAKE_JWT",privateKey:t.keyPairKey,privateKeyPass:t.keyPairPass,account:r,username:n,warehouse:i||"",application:"CoalesceIO_Coalesce",role:s||""}},BLo=async(t,e,r)=>{if(!q6r(t))throw yA.infoContext(e,"Error creating basic snowflake connection (CreateSnowflakeConnectionOAuth)",{user:Z7(t.user),accountName:Z7(t.accountName)}),new Sre("Invalid Connection Information, please correct your account or username and proceed.","OAuth");let n=await LLo(t,r,e),{accountName:i,user:s,warehouse:c}=t;return{authenticator:"OAUTH",account:i,username:s,token:n.access_token,warehouse:c||"",application:"CoalesceIO_Coalesce"}},ULo=t=>{try{return ELo.createConnection(t)}catch(e){throw new m9e(e)}},f9e=t=>RUt(t).catch(e=>{throw new m9e(e)}),jLo=parseInt(process.env.MAX_RESPONSE_SIZE||"20428800"),u9c=t=>t>jLo,DNt=class extends Error{constructor(r,n,i,s){super("Heap size exceeded");this.heapStats=r;this.currentSize=n;this.stmt=i;this.rows=s;this.makeResult=()=>{let r=this.stmt,n=r.getSessionState();return{rows:this.rows,stmt:this.stmt,status:"Transaction exceeded data limit, returned a subset of rows",queryID:r.getStatementId(),warehouse:n?.getCurrentWarehouse()||null}};this.makeErrorMessage=r=>{let n=bse(this.heapStats.total_heap_size),i=bse(r.heap_size_limit),s=bse(this.currentSize),c=bse(jLo);return`Chunk limit reached,
|
|
3133
3133
|
current heap size: ${n} MB, total heap size: ${i} MB,
|
|
3134
|
-
response size: ${s} MB, max response size: ${c} MB`}}},FS=class extends Wl{},Sre=class extends FS{constructor(r,n,i){super(r);this.authType=n;this.cause=i}statusCode(){return 401}toTRunError(){let r=`auth type: ${this.authType}`;if(this.cause){try{r+=` caused by: ${this.cause}`}catch{}try{this.cause.stack&&(r+=this.cause.stack)}catch{}}return{error:{errorString:this.message,errorDetail:r}}}},MNt=class extends FS{constructor(r){super("Could not identify the initial warehouse - possibly invalid credentials or warehouse");this.warehouse=r}statusCode(){return 400}toTRunError(){let r=this.warehouse?`Tried to set a warehouse of ${this.warehouse}`:"Did not set a warehouse";return{error:{errorString:this.message,errorDetail:`${r} and snowflake did not indicate a warehouse was used, but it should have`}}}},m9e=class extends Wl{constructor(r){let n="Snowflake execution error",i;typeof r=="object"&&r instanceof Error&&(n=r.message||n,i=r.stack);super(n);this.cause=r;this.getErrorDetail=()=>{if(this.cause.name==="OperationFailedError")try{let r=this.cause.data;if(r)return`name=${this.cause.name}, code=${this.cause.code}, data=${JSON.stringify(r)}`}catch{}if(this.cause.name==="NetworkError")try{let r=this.cause.cause;if(r&&r.message)return`name=${this.cause.name}, code=${this.cause.code}, cause=${r.message}`}catch{}try{return`name=${this.cause.name}, code=${this.cause.code}`}catch{}return""};this.getErrorData=()=>this.getSnowflakeErrorCode()==="390189"?{errorString:"Role not found",errorDetail:this.cause.message}:{errorString:this.message,errorDetail:this.getErrorDetail()};this.originalStack=i}statusCode(){switch(this.getSnowflakeErrorCode()){case"390189":case"390100":return 401;default:return super.statusCode()}}isCancel(){return this.getSnowflakeErrorCode()==="000604"}getSnowflakeErrorCode(){try{return this.cause.code}catch{return null}}toTRunError(){return{error:this.getErrorData()}}},rH=class extends m9e{constructor(r,n,i,s,c){super(r);this.options=n;this.requestID=i;this.queryID=s;this.warehouse=c}},c9c=(t,e)=>new Promise((r,n)=>{let i=[],s=0,c=t.streamRows(),u=t.getRequestId(),l=t.getStatementId(),o=t.getSessionState()?.getCurrentWarehouse();c.on("error",a=>{n(new rH(a,e,u,l,o))}).on("data",a=>{if(s+=k4e(a),i.push(a),u9c(s)){let m=OLo.getHeapStatistics(),d=new DNt(m,s,t,i);n(d),c.destroy()}}).on("end",()=>{r({rows:i,stmt:t,status:"Success",queryID:l,warehouse:o||null})})}),p9c=async(t,e,r,n)=>{let i=await t;try{return await c9c(i,e)}catch(s){if(typeof s=="object"&&s instanceof DNt){let c=s.makeErrorMessage(r);return l9e.alertContext(n,c),s.makeResult()}else{let c=s;throw typeof s=="object"&&s instanceof rH&&(c=s.toTRunError()),l9e.alertContext(n,"Error on streaming rows:",c),s}}},l9c=(t,e,r)=>{let n=KO(),i=OLo.getHeapStatistics(),{statement:s,resultStatementPromise:c}=m9c(t,e),u=p9c(c,e,i,r),l=JWe(`Back-end (retry=${e.requestId!==void 0}): ${e.sqlText}`,r,"PERFORMANCE",n,u);return{statement:s,resultPromise:l}},d9e=class{constructor(e,r,n,i,s=2){this.sfConn=e;this.options=r;this.logContext=n;this.resetFunc=i;this.maxAttempts=s;this.initialStatement=null;this.shouldResetConnection=e=>{let r=e.cause;return w6r(r)||b9c(r)||g9c(r)};this.handleRetry=async(e,r)=>{if(e.requestID!==void 0&&(r={...r,requestId:e.requestID}),this.shouldResetConnection(e))try{this.sfConn=await this.resetFunc()}catch(n){throw yA.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",n),e.cause}return r};this.tryCancel=async()=>{let e=this.initialStatement;e!==null&&await f9e(r=>e.cancel(r))};this.Cancel=async()=>{for(let e=0;e<20;e++)try{await this.tryCancel();return}catch(r){if(r.message?.includes("Identified SQL statement is not currently executing"))await nL(100);else throw r}await this.tryCancel()};this.Start=()=>{this._promise||(this._promise=this.queryWithRetries())};this.coalesceQueryID=yJ(),this._promise=null}makePendingQuery(e){return l9c(this.sfConn,e,this.logContext)}async queryWithRetries(){let e=0,r={...this.options};for(yA.debugContext(this.logContext,"Making request for CQID=",this.coalesceQueryID);;){e++;try{let n=this.makePendingQuery(r);this.initialStatement=n.statement;let i=await n.resultPromise;return yA.debugContext(this.logContext,"Successfully got result for CQID=",this.coalesceQueryID),i}catch(n){if(!(typeof n=="object"&&n instanceof rH))throw yA.errorContext(this.logContext,"Not retrying request CQID=",this.coalesceQueryID,"requestId=",r.requestId,"attemptCount=",e,"error=",n,"was unrecognized and not retryable"),n;let i=n.cause?n.cause:n;if(n.isCancel())throw yA.infoContext(this.logContext,"Not retrying request, it was canceled CQID=",this.coalesceQueryID,"attemptCount=",e,"error=",i),i;if(e>=this.maxAttempts)throw yA.infoContext(this.logContext,"Out of retries for request CQID=",this.coalesceQueryID,"attemptCount=",e,"error=",i),i;r=await this.handleRetry(n,r),yA.infoContext(this.logContext,"Retrying request CQID=",this.coalesceQueryID,"requestId=",r.requestId,"attemptCount=",e,"retryOptions=",r,"error=",n.cause?n.cause:n)}}}get promise(){if(this.Start(),!this._promise)throw new FS("Internal consistency error: _promise cannot be null after Start()!");return this._promise}},GLo=async(t,e,r)=>{let{firebase:n,teamInfo:i,teamInfo:{fbTeamID:s,fbUserID:c}}=e,{environmentID:u}=t;if(t.authenticator==="OAuth"){let l=await Z$t(n.firestore(),i,u),a=(await LLo(t,e,r)).refresh_token,p=Buffer.from(`${l.oauthClientID}:${l.oauthClientSecret}`).toString("base64"),m=CLo.default.stringify({grant_type:"refresh_token",refresh_token:a}),d=`https://${l.connectionAccount}.snowflakecomputing.com/oauth/token-request`,f={method:"post",url:d,headers:{Authorization:`Basic ${p}`,"Content-Type":"application/x-www-form-urlencoded"},data:m},y;try{y=await HLo(f)}catch(v){throw yA.errorContext(r,"RefreshAccessToken",v),new Sre("An error occured refreshing your OAuth refresh_token. Please ensure your OAuth Security Integration is still valid or reauthenticate.","OAuth",v)}let g={access_token:y.data.access_token,refresh_token:a},b=await H8e(),S={orgId:s,userId:c,workspaceId:u.toString()};await b.Set(Nee,S,new lm(g))}else throw new Sre("Cannot reset oauth connection on a non-oauth error!","OAuth")},qNt=class extends d9e{constructor(r,n,i,s,c,u=3){super(n,i,s,c,u);this.runningQueries=r;this.attachThen=r=>{this._promise=this.promise.then(n=>(r(n),n))}}async queryWithRetries(){this.runningQueries.set(this.coalesceQueryID,this);try{return await super.queryWithRetries()}finally{this.runningQueries.delete(this.coalesceQueryID)}}},m9c=(t,e)=>{let r,n,i=new Promise((c,u)=>{r=c,n=u});return{statement:t.execute({...e,streamResult:!0,complete:function(c,u){if(c){let l=u&&u.getRequestId(),o=u&&u.getStatementId(),a=u&&u.getSessionState()?.getCurrentWarehouse();n(new rH(c,e,l,o,a))}else r(u)}}),resultStatementPromise:i}},VLo=async(t,e,r,n,i)=>{let s=new d9e(t,e,r,i,n);return s.Start(),s.promise};var d9c="Unable to perform operation using terminated connection.",f9c=407002,h9c="ECONNRESET",y9c="OAuth access token expired.",w6r=t=>!!t.message.includes(y9c),g9c=t=>t.code===f9c||t.message===d9c,b9c=t=>t.cause&&t.cause.code&&t.cause.code===h9c;var wNt={describe:{boolean:{true:"Y",false:"N"},null:null},show:{nullable:{true:!0,NOT_NULL:!1}}};var vre=Kt("CONNECTION"),KLo=async(t,e,r)=>{let n;switch(t.authenticator){case"Basic":case"Cloud":n=zLo(t,r);break;case"KeyPair":n=FLo(t,r);break;case"OAuth":n=await BLo(t,r,e);break}return ULo(n)},LNt=class{constructor(e,r,n,i,s,c){this.sfConnection=e;this.logContext=r;this.connectionID=n;this.useCounter=i;this.parent=s;this.wasCanceled=!1;this.currentQueryTag=null;this.untrackedQuery=async e=>VLo(this.sfConnection,{sqlText:e},this.logContext,3,this.resetConnection);this.setQueryTag=async e=>{this.currentQueryTag=e;let r=this.currentQueryTag===null?"":this.currentQueryTag.replace("$","\\$");await this.untrackedQuery(`ALTER SESSION SET QUERY_TAG = $$${r}$$`)};this.resetConnection=async()=>{if(this.wasCanceled)throw new FS("not resetting canceled connection");let e=await this.resetFunc();return this.sfConnection=e,this.currentQueryTag&&await this.setQueryTag(this.currentQueryTag),e};this.execute=e=>this.executeAndGetRunning(e).promise;this.executeAndGetRunning=e=>{let r=this.makePendingQuery(e);return vre.debugContext(this.logContext,"Tracking snowflake query with CQID=",r.coalesceQueryID,"query=",e),r.Start(),r.attachThen(n=>{n.warehouse&&this.parent&&(this.parent.currentWarehouse=n.warehouse)}),r};this.cancel=async e=>{this.wasCanceled=!0;let r=this.runningQueries.get(e);r&&(r.promise.catch(()=>{}),await r.Cancel())};this.cancelAll=async()=>{this.wasCanceled=!0;let e=Array.from(this.runningQueries.values()).map(r=>r.Cancel());if(e.length)try{await QWe(e)}catch(r){vre.error("Got an unexpected failure during cancelAll(): ",r)}};this.runningQueries=new Map,c?this.resetFunc=c:s?this.resetFunc=()=>s.reinitialize().then(()=>s.sfConnection):this.resetFunc=()=>{throw new FS("Cannot reset the connection, no reset function provided")}}makePendingQuery(e){return new qNt(this.runningQueries,this.sfConnection,e,this.logContext,this.resetConnection)}},y9e=class{constructor(e,r,n,i){this.connectionID=e;this.userContext=r;this.teamInfoAndFirebase=n;this.logContext=i;this.inUse=!1;this.sfConnection=null;this.defaultWarehouse=null;this.currentWarehouse=null;this.useCount=0;this.assertConnected=async()=>{if(!this.inUse)throw os("CONNECTION",!1,this.logContext,"Connection was not acquired before connection check!"),new FS("Connection was not acquired before connection check!");if(await this.initPromise,this.sfConnection===null)throw os("CONNECTION",!1,this.logContext,"Connection was null after initPromise!"),new FS("Connection was null after initPromise!")};this.reinitialize=async()=>{this.initPromise=this.initialize(),await this.connectAndValidate(),await this.acquire(!0)};this.setup=async()=>{await this.connectAndValidate(),await this.setDefaultWarehouse()};this.teardown=async()=>{await f9e(e=>this.sfConnection.destroy(e))};this.acquire=async e=>{if(!e&&this.inUse)throw os("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new FS(`Cannot acquire in-use connection ${this.connectionID}`);this.inUse=!0,this.useCount++};this.setWarehouse=async e=>{await this.assertConnected(),await this.execute({sqlText:`USE WAREHOUSE "${e}"`})};this.release=async()=>{if(this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.defaultWarehouse),this.currentWarehouse=null,!this.inUse)throw os("CONNECTION",!1,this.logContext,`Cannot release connection ${this.connectionID} - not in use`),new FS(`Cannot release connection ${this.connectionID} - not in use`);this.inUse=!1};this.execute=async e=>(await Pa("Waiting for connection",this.logContext,"CONNECTION",()=>this.unwrap())).execute(e);this.executeAndGetRunning=async e=>(await Pa("Waiting for connection",this.logContext,"CONNECTION",()=>this.unwrap())).executeAndGetRunning(e);this.initPromise=this.initialize()}static async New(e,r,n,i){let s=new y9e(e,r,n,i);return await s.initPromise,await s.setup(),s}async initialize(){this.sfConnection=await KLo(this.userContext,this.teamInfoAndFirebase,this.logContext)}connect(){return f9e(e=>this.sfConnection.connect(e))}async resetOauth(){await GLo(this.userContext,this.teamInfoAndFirebase,this.logContext)}async connectAndValidate(){await this.initPromise;try{await this.connect()}catch(e){if(this.userContext.authenticator==="OAuth"&&w6r(e))await this.resetOauth(),this.initPromise=this.initialize(),await this.initPromise,await this.connect();else throw e}this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.currentWarehouse)}async setDefaultWarehouse(){let r=(await RLo(this.sfConnection,{sqlText:"SELECT 1 as coalesce_init"},this.logContext)).stmt;if(!r)throw os("CONNECTION",!!r,this.logContext,"Snowflake did not return a statement!"),new FS("Snowflake did not return a statement!");if(this.defaultWarehouse=r.getSessionState()?.getCurrentWarehouse()||null,!this.defaultWarehouse)throw vre.errorContext(this.logContext,"Could not identify the initial warehouse - possibly invalid credentials?"),new MNt(this.userContext.warehouse)}async unwrap(){return await this.assertConnected(),new LNt(this.sfConnection,this.logContext,this.connectionID,this.useCount,this)}},iH=class{constructor(e,r,n,i){this.userContext=e;this.teamInfo=r;this.logContext=n;this.maximumConnections=i;this.setup=async()=>{vre.infoContext(this.logContext,"Setting up",this.maximumConnections,"connections - for large values this may take some time"),await this.lock.runExclusive(async()=>{let e=[];for(let r=0;r<this.maximumConnections;r++)e.push(async()=>{let n=yJ(),i=await y9e.New(n,{...this.userContext},this.teamInfo,this.logContext);this.connections.set(n,i)});await e[0](),e.length>1&&await FM(e.slice(1),4)})};this.teardown=async()=>{this.shutdown=!0,await this.lock.runExclusive(async()=>{let e=[];for(let r of this.connections.values())e.push(r.teardown());await QWe(e)})};this.nextAvailableIHaveTheLock=()=>{for(let e of this.connections.values())if(!e.inUse)return e;return null};this.getConnection=async()=>{for(;!this.shutdown;){let e=await this.lock.runExclusive(async()=>{let r=this.nextAvailableIHaveTheLock();return r&&await r.acquire(),r});if(e)return e;await nL(500)}throw new Error("system shutting down before a connection was found")};this.withConnection=async e=>{vre.debugContext(this.logContext,"acquiring connection");let r=await this.getConnection();vre.debugContext(this.logContext,"got connection: ",r.connectionID);try{let n=await r.unwrap();return await e(n)}finally{await this.releaseConnection(r)}};this.releaseConnection=async e=>{await this.lock.runExclusive(async()=>{e.inUse?await e.release():vre.errorContext(this.logContext,"Got a releaseConnection() call on a connection that is not in use!")})};this.lock=new fse,this.connections=new Map,this.shutdown=!1,os("CONNECTION",i>0,this.logContext,"At least one connection is required!")}static async New(e,r,n,i){let s=new iH(e,r,n,i);return await s.setup(),s}},YLo=async(t,e,r)=>{let n=()=>KLo(t,e,r),i=await n();return await f9e(s=>i.connect(s)),new LNt(i,r,yJ(),0,null,n)};var oH=null;ku()&&(oH=zfr());var Are=Kt("AUTH"),XLo=Kt("USER_MANAGEMENT"),S9c=0,ca=Kt("RUNNER_BACKEND"),$Lo=(e=>(e.clientSecretError="Cannot read property 'currentSecretID' of undefined",e))($Lo||{}),QLo=$We("COALESCE_DEFAULT_PARALLELISM",16),L6r=$We("COALESCE_MAX_PARALLEISM_SCHEDULER",64),v9c=()=>{bT?(console.log("WARNING - Using the Firebase emulator for firebase-admin!"),oH.initializeApp({projectId:V7().projectId})):oH.initializeApp({credential:oH.credential.applicationDefault()}),zNt=oH},zNt=wM,A9c=(t,e,r)=>{if(typeof r=="object"&&r instanceof Wl){ca.errorContext(e,"FinishWithError",r.toTRunError()),r.handleExpressResponse(t);return}let n=500;r.statusCode&&(n=r.statusCode),ca.errorContext(e,"FinishWithError (nonstandard error)",r);let i={error:{errorString:r.message||r.error?.errorString,errorDetail:r.stack||r.error?.errorDetail}};t.status(n).json(i)},T9c=t=>new Promise((e,r)=>oH.auth().verifyIdToken(t).then(n=>{e({Firebase:zNt,uid:n.uid})}).catch(n=>{r(n)})),x9c=t=>new Promise((e,r)=>{let n=t+S9c++,i=wM.initializeApp(V7(),n);eWe(i,!1);let s;return t5(`${_J()}/scheduler/generateLoginToken?token=${t}`,null).then(c=>{let u=c.data.customToken;return s=c.data.uid,i.auth().signInWithCustomToken(u)}).then(()=>{e({Firebase:i,uid:s})}).catch(c=>{ca.error("GetOrSetupFirebase",c),r(c)})}),N9c=t=>t5(`https://securetoken.googleapis.com/v1/token?key=${V7().apiKey}`,{refresh_token:t,grant_type:"refresh_token"}).then(e=>e.data.id_token),ZLo=async(t,e,r)=>{let n,i,s;Are.debug("got auth request refresh:",t,"id token",e),e===void 0&&bT&&(e=t);let c=e!==void 0;return Are.debug("inAuthenticate, between 1st and 2nd",c,e),(c?Promise.resolve(e):N9c(t)).then(u=>(Are.debug("inAuthenticate, beore setting id token",c,u),n=u,Are.debug("inAuthenticate, setting up firebase 2",u),r(n))).then(u=>(i=u.Firebase,Are.debug("inAuthenticate, getting team data admin",e),CGt(i.firestore(),u.uid))).then(u=>{s=u;let l=uzo(u.fbRole);return Are.debug("inAuthenticate, finishing...",e),{teamInfo:u,firebase:i,idToken:n,UserRolePrivilegeChecker:l}}).then(u=>u).catch(u=>{let l=new Error("Unable to authenticate, please ensure your token is valid");l.name="401";let o=s?s.fbUserID:"",a=s?s.fbTeamID:"";throw Are.errorContext({userID:o,orgID:a},"AuthenticateFirebaseTokenAndRetrieveTeamInfo",u),l})},ezo=(t,e)=>ZLo(t,e,T9c),I9c=(t,e)=>ZLo(t,e,x9c),C9c=new Set(["password","code","codeVerifier","accessToken","token","id_token","clientSecret","authCode","snowflakePassword","newPassword","refresh_token","uid","keyPair"]),z6r=t=>(C9c.forEach(e=>{delete t[e]}),Object.keys(t).forEach(e=>{!!t[e]&&typeof t[e]=="object"&&!!Object.keys(t[e]).length&&z6r(t[e])}),t),E9c=(t,e,r)=>{let n={body:pp(r.body),query:pp(r.query),params:pp(r.params)},i=z6r(n);ca.debugContext(t,e,i)},aH=class extends Wl{constructor(r,n){super(r);this.validationErrorDetail=n}statusCode(){return 400}toTRunError(){return{error:{errorString:this.message,errorDetail:this.validationErrorDetail||""}}}},tzo=(t,e)=>{let r,n=t.body;if(n.isCompressed){if(!n.data)throw new aH("failed to decompress request body","Request body had no 'data' field to decompress");n=mzo(n.data)}if(r=S9e(e,n),!r.success)throw new aH("failed to validate request body",r.errorString);return r.value},rzo=(t,e)=>{let r=S9e(e,t.body);if(!r.success)throw new aH("failed to validate query params",r.errorString);return r.value},O9c=(t,e,r)=>{e&&rzo(t,e),r&&tzo(t,r)},FNt=(t,e)=>{let r=t?.stmt?.getColumns().map(i=>({Name:i.getName(),DataType:i.getType()}));return{runDetails:{compiledSQL:e,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:t.queryID,warehouse:t.warehouse},data:{columns:r,rows:t.rows,status:t.status}}},BNt=async(t,e,r)=>{let n=`Back-end: ${t}`;try{return await Pa(n,r,"PERFORMANCE",()=>e())}catch(i){let s=i;throw i.message==="Cannot read property 'currentSecretID' of undefined"&&(s=new Error("Missing password or client secret - please update your environment settings")),s}},R9c=t=>{if(typeof t=="string"){let e=parseInt(t);if(isNaN(e))throw new Error(`Cannot convert environment ID ${t} to a number`);return e}else return t},nzo=async(t,e,r,n)=>{let{teamInfo:i}=r;os("RUNNER_BACKEND",!!t.userContext,{orgID:i.fbTeamID,userID:i.fbUserID},"Missing user context in (SnowflakeRunHandlerFunction)");let s={...t.userContext,environmentID:R9c(t.userContext.environmentID)};s.environmentID!==void 0&&sUt(n,s.environmentID.toString());let c={sqlText:t.templateString};ca.debugContext(n,"RunSnowflakeRequest getting connection");let u=()=>e.GetConnectionAndRunQuery(c,s,r);ca.debugContext(n,"RunSnowflakeRequest executing template");let l=await BNt(t.templateString,u,n);return ca.debugContext(n,"RunSnowflakeRequest creating query response object"),FNt(l,t.templateString)},izo=t=>JSON.stringify(WNt(t)),ozo=(t,e,r,n)=>FQe(e,r,n).then(i=>(t.userCredentials={...t.userCredentials,snowflakeAccount:i},t)),k9c=(t,e,r,n)=>(zr("RUNNER_BACKEND",t.runType=="deploy","is a deploy run info"),ozo(t,e,r,n)),_9c=(t,e,r,n)=>(zr("RUNNER_BACKEND",t.runType=="refresh","is a refresh run info"),ozo(t,e,r,n)),F6r=(t,e)=>{let r=b9e(t,()=>{},i=>i.snowflakeKeyPairPath,()=>{},()=>{});return{snowflakeAccount:e.accountName,snowflakeKeyPairPath:r,snowflakeUsername:e.user,snowflakeRole:e.role,snowflakeWarehouse:e.warehouse,snowflakeAuthType:e.authenticator}},D9c=(t,e,r,n)=>{let i=F6r(t.userCredentials,e);return{runTimeParameters:t.runTimeParameters,runDetails:t.runDetails,userCredentials:i,runStatus:"running",userID:r,runType:"deploy",kubernetesJobUuid:n}},M9c=async(t,e,r,n,i,s,c,u,l)=>{try{await j6r(t,e,r,n,s,c,u),ca.appContext(u,"runDeploy finished successfully"),await Myn(t,e.fbTeamID,i,r)}catch(o){ca.errorContext(u,"Error during deploy inner promise (runDeployCompletion):",o);try{await qyn(t,e.fbTeamID,i,r,o.message)}catch(a){ca.errorContext(u,"Error during status release: ",a)}throw o}finally{l()}},q9c=async(t,e,r,n,i,s,c)=>{let u=bWt("orgRuns",t.firestore(),e.fbTeamID),{runCounter:l,CleanupHeartbeat:o}=await _yn(t,e.fbTeamID,n,r,u,c);fJ(c,l);let a={orgID:e.fbTeamID,envID:n.toString(),userID:e.fbUserID,runID:l};fJ(c,l),ca.appContext(c,"CreateRunDeployCounterAndPromise");let p=M9c(t,e,l,r,n,i,s,a,o);return{runCounter:l,runCompletion:p}},w9c=(t,e)=>{e=e===void 0?QLo:e;let s=(e-4)*2+4;return t<1?1:t<4?t:t<s?4+Math.floor((t-4)/2):e},B6r=(t,e)=>{let r=w9c(t,e),n=YWe()?L6r:1/0;return n<r?n:r},P9c=async(t,e,r,n,i)=>{let{teamInfo:s,teamInfo:{fbUserID:c},firebase:u}=e,l=u.firestore(),o=parseInt(t.runDetails.environmentID);ca.infoContext(r,"Deployment started");let a=Math.max(...Object.values(t.runDetails.dividedStepDataWithWorkspaceEdits).map(p=>Object.keys(p).length));try{let p=await UNt(l,s,o,n),m=g9e(p,c),d=await iH.New(p,e,r,B6r(a,t.runDetails.parallelism));t.runDetails=tQt(m,t.runDetails,c),ca.appContext(r,izo(p),"BECLI_HandleDeploy"),await U6r(d,c,r);let f=D9c(t,p,c,i);return q9c(u,s,f,o,d,p,r)}catch(p){throw ca.errorContext(r,"Error during deploy: ",p),p}},L9c=t=>{let{runDetails:e}=t;if(e.jobID&&(e.includeNodesSelector||e.excludeNodesSelector))throw new Error("Unable to process, don't provide a JobID and Node Include/Exclude Selector(s) for 1 Refresh Run")},z9c=(t,e)=>{for(let r in e)e[r]&&(t[r]=e[r])},F9c=(t,e,r,n)=>{let i=F6r(t.userCredentials,e),s={runTimeParameters:t.runTimeParameters,runDetails:{...t.runDetails,jobID:GNt(t.runDetails.jobID)},userCredentials:i,runStatus:"running",userID:r,runType:"refresh",kubernetesJobUuid:n};return SJ(s),s},g9e=(t,e)=>{let r={connectionDetails:{userID:e,user:t.user,role:t.role,warehouse:t.warehouse},connectionType:t.authenticator};return t.authenticator==="KeyPair"&&(r.connectionDetails.keyPair=t.keyPairKey),r},U6r=async(t,e,r)=>{let n=g9e(t.userContext,e),i={connectionType:n.connectionType,connectionDetails:Q$t(n.connectionDetails)};ca.infoContext(r,"testing snowflake connection:",i),await t.withConnection(async s=>{await s.execute({sqlText:"select 1 as coalesce_test"})})},UNt=async(t,e,r,n)=>{let i=await eQt(t,e,r),c={accountName:await FQe(t,e.fbTeamID,r),user:i.connectionDetails.user,role:i.connectionDetails.role,warehouse:i.connectionDetails.warehouse,environmentID:r,orgID:e.fbTeamID,authenticator:i.connectionType};return z9c(c,n),c},B9c=async(t,e,r,n,i,s,c,u,l,o,a,p)=>{try{ca.appContext(l,"startng runRefresh"),await G6r(t,e,i,r,n.toString(),s,c,u,o,a),ca.appContext(l,"runRefresh finished with no errors, releasing workspace status"),await wyn(t,e.fbTeamID,n,i)}catch(m){ca.errorContext(l,"Error during refresh:",m);try{await Pyn(t,e.fbTeamID,n,i)}catch(d){ca.errorContext(l,"Error during status release: ",d)}throw m}finally{p()}},azo=async(t,e,r,n,i,s,c,u,l,o)=>{ca.infoContext(u,"securing workspace status and starting refresh",n);let a=bWt("orgRuns",t.firestore(),e.fbTeamID),{runCounter:p,CleanupHeartbeat:m}=await Dyn(t,e.fbTeamID,n,r,a,u);fJ(u,p),ca.appContext(u,"CreateRunRefreshCounterAndPromise");let d=B9c(t,e,r,n,p,i,s,c,u,l,o,m);return{runCounter:p,runCompletion:d}},U9c=async(t,e,r,n,i)=>i?(ca.infoContext(n,"Refreshing job:",i),yQt(t,e,r,"jobs",i)):(ca.infoContext(n,"No job ID, refreshing all steps"),!0),j9c=async(t,e,r,n,i)=>{let{teamInfo:s,teamInfo:{fbTeamID:c,fbUserID:u},firebase:l}=e,o=l.firestore(),a=parseInt(t.runDetails.environmentID);t.runTimeParameters=await jNt(o,c,a,t.runTimeParameters),L9c(t);let p=GNt(t.runDetails.jobID),m=U9c(o,c,a,r,p);try{let d=await UNt(o,s,a,n),f=g9e(d,u);if(ca.appContext(r,izo(d),"BECLI_HandleRefresh"),!await m)throw N3(400,`Unable to start job ${p}`,`Job ${p} did not exist`);let y=F9c(t,d,u,i),{allWorkspaceData:g,stepsForRefresh:b}=await VNt(e,y,y.runDetails.environmentID),S=await iH.New(d,e,r,B6r(b.length,t.runDetails.parallelism));return await U6r(S,u,r),azo(l,s,y,a,S,f,d,r,g,b)}catch(d){throw ca.errorContext(r,"Error during refresh:",d),d}},szo=(n=>(n.canUpdateUser="canUpdateUser",n.canUpdateSuperUser="canUpdateSuperUser",n.canResetPassword="canResetPassword",n))(szo||{}),uzo=t=>{let e={["canUpdateUser"]:["Admin"],["canUpdateSuperUser"]:[],["canResetPassword"]:["Admin"]};return r=>e[r].includes(t)},JLo=(t,e)=>({isValid:t,error:{error:{errorDetail:e,errorString:e}}}),G9c=new Set(["firstName","lastName","role","activated","authDisabled","deleted","userID"]),V9c=(t,e,r)=>{if(t.fbHasSuperUserAccess===!0)return;if(Object.keys(r).some(c=>!G9c.has(c)))throw new Error("Error Updating User: Insufficient privileges to update specified user attributes");if(!!e&&t.fbTeamID!==e.currentTeam)throw new Error("Error Updating User: forbidden user information")},W9c=(t,e)=>{if(t.fbHasSuperUserAccess===!0)return;if(t.fbTeamID!==e.currentTeam)throw new Error("Error Creating User: forbidden user information")},czo=(t,e,r)=>{try{if(!!e.userID){let l=MT(H9c,e);zM(l.success,l.errorString||"One or more fields were not correctly filled out","USER_MANAGEMENT",{}),V9c(t.teamInfo,r,e)}else{let l=MT(K9c,e);zM(l.success,l.errorString||"One or more fields were not correctly filled out","USER_MANAGEMENT",{}),W9c(t.teamInfo,e)}let i=t.UserRolePrivilegeChecker("canUpdateUser"),s=!!r&&r.hasOwnProperty("hasSuperUserAccess"),u=!!e.hasOwnProperty("hasSuperUserAccess")&&(!r||!s||e.userID!==r.userID);zM(i&&!u,"Error: Insufficient privileges to update users","USER_MANAGEMENT",{})}catch(n){return XLo.error("Error during CheckIsValidAdminUpdate: ",n),JLo(!1,n.message)}return JLo(!0,"")},H9c=Dl.Record({firstName:Dl.String.optional(),lastName:Dl.String.optional(),role:Dl.String.optional(),activated:Dl.Boolean.optional(),authDisabled:Dl.Boolean.optional(),deleted:Dl.Boolean.optional(),currentTeam:Dl.String.optional(),email:Dl.String.optional(),userID:Dl.String.optional()}),K9c=Dl.Record({firstName:Dl.String,lastName:Dl.String,role:Dl.String,currentTeam:Dl.String,email:Dl.String,activated:Dl.Boolean.optional(),password:Dl.Optional(Dl.String),userID:Dl.String.optional()}),Y9c=async(t,e,r)=>{let i=await(await pX(t,e,r).get()).get("runTimeParameters");return G5e(i)},jNt=async(t,e,r,n)=>n?DQe(n):Y9c(t,e,r),pzo=(t,e)=>{zM(!!t,"Attempted to authenticate invalid auth header","AUTH",{});let[r,n]=t.split(" ");zM(r=="Basic",`Unexpected auth type in header: ${r}`,"AUTH",{}),zM(e===n,"Passed secret is invalid","AUTH",{})},J9c=async(t,e,r,n,i,s)=>{let c=F6r(e.userCredentials,n),u=await jNt(t,i.fbTeamID,parseInt(r.runDetails.environmentID),e.runTimeParameters);return{runStatus:"running",runType:"refresh",runDetails:r.runDetails,userCredentials:c,reRunID:e.runDetails.runID,runTimeParameters:u,userID:i.fbUserID,kubernetesJobUuid:s}},X9c=async(t,e,r,n,i,s)=>{let{firebase:c,teamInfo:u,teamInfo:{fbUserID:l,fbTeamID:o}}=r,a=c.firestore(),p=parseInt(e.runDetails.environmentID),m=await UNt(a,u,p,i),d=await J9c(a,t,e,m,u,s),{allWorkspaceData:f,stepsForRefresh:y}=await VNt(r,d,d.runDetails.environmentID),g=await iH.New(m,r,n,B6r(y.length,d.runDetails.parallelism));t.runTimeParameters=await jNt(a,o,p,t.runTimeParameters);let b=g9e(m,l);return await U6r(g,l,n),azo(c,u,d,p,g,b,m,n,f,y)},$9c=async(t,e,r,n,i,s)=>{if(ca.appContext(n,"BECLI_HandleRerun"),e.runStatus!=="failed")throw new Error("Only failed jobs can be re-run!");if(e.runType!=="refresh")throw new Error("Only refresh jobs can be re-run!");return X9c(t,e,r,n,i,s)},Q9c=t=>{let{password:e,userID:r,...n}=t;return r&&(n.userID=r),n},Z9c=async(t,{token:e,idToken:r},n)=>{let i=Q9c(t),s=new lm(t.password);try{let c=await ezo(e,r);n=$u(c.teamInfo.fbTeamID,void 0,c.teamInfo.fbUserID),ca.infoContext(n,"CreateOrUpdateUser validating payload",i.userID,i),SJ(i);let u=await t7c(i.userID,i,c.firebase);return ca.infoContext(n,"CreateOrUpdateUser role validation:",i),await e7c(c,i,u),ca.infoContext(n,"CreateOrUpdateUser running transaction:",i),await c.firebase.firestore().runTransaction(async l=>{let o=await s7c(i.userID,c.firebase,l);if(!!o&&o.deleted===!0)throw N3(403,"Error: cannot update deleted user","Invalid update to user");ca.infoContext(n,"CreateOrUpdateUser validating admin demotion:",i),await i7c(c.firebase,l,n,i,o),ca.infoContext(n,"CreateOrUpdateUser validating number of users:",i);let a=await u7c(i.currentTeam,c.firebase,l,i,o);return ca.infoContext(n,"CreateOrUpdateUser creating/setting user doc",i),await lzo(c.firebase,l,i.userID,i.email,a,s),ca.infoContext(n,"CreateOrUpdateUser validating disable or deletion",i),await m7c(i,o,n)})}catch(c){throw ca.alertContext(n,"CreateOrUpdateUser ERROR during transaction",c),c}},lzo=async(t,e,r,n,i,s)=>{if(r){let{authDisabled:c,...u}=i,l=lL(t.firestore(),r);await e.update(l,u)}else{let c=await t.auth().createUser({email:n,password:s.sensitiveValue});lL(t.firestore(),c.uid).set(i)}},e7c=(t,e,r)=>{let n=czo(t,e,r);if(n.isValid===!1)throw N3(400,n.error.error.errorString||"Unknown Error",n.error.error.errorDetail||"")},t7c=async(t,e,r)=>t?await n7c(t,r):r7c(e),r7c=t=>{let{firstName:e,lastName:r,role:n,currentTeam:i,email:s,activated:c}=t;if(!n||!e||!r||!i||!s)throw N3(422,"One or more fields were not correctly filled out for create",`422: role: ${n}, first name: ${e}, last name: ${r}, currentTeam: ${i}, email: ${s}, activated: ${c}`)},n7c=async(t,e)=>(await lL(e.firestore(),t).get()).data(),i7c=async(t,e,r,n,i)=>{if(!i)return;let s=i.currentTeam,c=o7c(n,i);if(ca.infoContext(r,`ValidateAdminDemotion does edit require admin demotion validation: ${c}`,n,s),c)return await a7c(s,e,t,r)},o7c=(t,e)=>{if(!e)return!1;let r=e.role==="Admin",n=r&&t.role==="User",i=r&&!!t.deleted,s=r&&t.authDisabled===!0;return ca.infoContext({userID:t.userID},`(CheckIfAdminIsBeingDemotedDeletedOrDisabled) demoted: ${n}, deleted: ${i}, disabled: ${s}`),n||i||s},a7c=async(t,e,r,n)=>{let i=await l7c(t,e,r,n);if(ca.infoContext(n,"CreateOrUpdateUser validating org will retain at least 1 admin"),i<=1)throw Error("ValidateAdminDemotion ERROR: number of admins in an org cannot go below one.")},s7c=async(t,e,r)=>{if(!t)return null;let n=lL(e.firestore(),t);return{...(await r.get(n)).data(),userID:t}},u7c=async(t,e,r,n,i)=>i?n:c7c(t,r,e,n),c7c=async(t,e,r,n)=>await p7c(t,e,r)===0?{...n,role:"Admin"}:n,p7c=async(t,e,r)=>{let n=r.firestore().collection("users").where("currentTeam","==",t).limit(1);return(await e.get(n)).size},l7c=async(t,e,r,n)=>{let i=r.firestore().collection("users").where("currentTeam","==",t).where("role","==","Admin"),s=await e.get(i),c=[];for(let u of s.docs){let l=u.data();try{(await Ffr(u.id)).disabled!==!0&&l.deleted!==!0&&c.push(l)}catch(o){if(XLo.errorContext(n,"Error getting user auth doc",o),o.message!=="There is no user record corresponding to the provided identifier.")throw o}}return c.length},m7c=async(t,e,r)=>{if(!e)return Promise.resolve();let n=!1;try{n=(await Ffr(e.userID)).disabled}catch{n=!0}return!!e&&t.deleted!==e.deleted?(ca.infoContext(r,"ValidateUserDisableOrDeletion handling deletion"),await d7c(t)):!!e&&t.authDisabled!==n?(ca.infoContext(r,`ValidateUserDisableOrDeletion handling disable/reenable. Will user be disabled after this takes effect? ${t.authDisabled}`,t),await f7c(t)):Promise.resolve()},d7c=async t=>await oH.auth().deleteUser(t.userID),f7c=async t=>t.authDisabled===void 0?Promise.resolve():await oH.auth().updateUser(t.userID,{disabled:t.authDisabled});var KNt=ir.Record({snowflakeUsername:ir.String,snowflakePassword:ir.String,snowflakeWarehouse:ir.String.optional(),snowflakeRole:ir.String.optional(),snowflakeAuthType:ir.Literal("Basic").optional()}),H6r=ir.Record({snowflakeUsername:ir.String,snowflakeWarehouse:ir.String.optional(),snowflakeRole:ir.String.optional(),snowflakeAuthType:ir.Literal("Cloud").optional()}),K6r=ir.Record({snowflakeWarehouse:ir.String.optional(),snowflakeAuthType:ir.Literal("OAuth").optional()}),Y6r=ir.Record({snowflakeUsername:ir.String,snowflakeKeyPairPath:ir.String,snowflakeKeyPairPass:ir.String,snowflakeWarehouse:ir.String.optional(),snowflakeRole:ir.String.optional(),snowflakeAuthType:ir.Literal("KeyPair").optional()}),J6r=ir.Union(KNt,Y6r),YNt=ir.Union(KNt,K6r,H6r),A9e=async(t,e,r,n)=>{if(n.snowflakeAuthType==="Cloud"){let s=await(await H8e()).Get(WV,{orgId:t,userId:e,workspaceId:r});if(!s)throw new Error("No Snowflake credentials found!");n.snowflakeAuthType="Basic",n.snowflakePassword=s.sensitiveValue.password}},h7c=ir.Record({token:ir.String}),y7c=ir.Record({newPassword:ir.String,editedUserID:ir.String}),Nre=(t,e)=>ir.Record({runDetails:t,userID:ir.String.optional(),parameters:ir.Unknown.optional(),userCredentials:e}),X6r=ir.Record({environmentID:ir.String,stepsInRun:ir.Number.optional(),jobID:ir.String.withConstraint(t=>{try{parseInt(t)}catch{return"${s} is not a string representing an integer"}return!0},{name:"NumericString"}).optional(),includeNodesSelector:ir.String.optional(),excludeNodesSelector:ir.String.optional(),forceIgnoreWorkspaceStatus:ir.Boolean.optional(),parallelism:ir.Number.optional()}),g7c=Nre(X6r,J6r),b7c=Nre(X6r,YNt),$6r=ir.Record({runID:ir.String}),S7c=Nre($6r,J6r),v7c=Nre($6r,YNt),A7c=ir.Unknown,T7c=ir.Unknown,dzo=ir.Union(ir.Number,ir.String),x7c=ir.Record({name:ir.String,isDisabled:ir.Boolean,version:ir.Number,metadata:A7c,packageInfo:T7c.optional()}),N7c=ir.Record({macroString:ir.String,macroCounter:ir.Number.optional(),id:ir.String.optional()}),I7c=ir.Record({jobCounter:ir.Number.optional(),name:ir.String.optional(),subgraphs:ir.Array(ir.Number).optional(),steps:ir.Array(dzo).optional()}),C7c=ir.Record({folderCounter:ir.String,name:ir.String,steps:ir.Array(ir.String)}),E7c=ir.Unknown,O7c=ir.Unknown,Q6r=ir.Record({steps:ir.Dictionary(E7c,ir.String),folders:ir.Dictionary(C7c,ir.String),jobs:ir.Dictionary(I7c,dzo),macros:ir.Dictionary(N7c,ir.String),stepTypes:ir.Dictionary(x7c,ir.String),userConnections:ir.Dictionary(ir.Dictionary(O7c,ir.String),ir.String).optional(),locations:ir.Unknown.optional(),defaultStorageMapping:ir.String.nullable().optional(),version:ir.Number.optional()}),V6r=ir.Dictionary(ir.Unknown,ir.String),fzo=ir.Record({addedTable:V6r,alteredTable:V6r,deletedTable:V6r}),Z6r=ir.Record({fromWorkspaceData:Q6r,deployCommit:ir.String,environmentID:ir.String.optional(),toWorkspaceID:ir.Number,dividedStepDataWithWorkspaceEdits:fzo,deployCommitMessage:ir.String,stepsInRun:ir.Number,parallelism:ir.Number.optional()}),R7c=Nre(Z6r,J6r),k7c=Nre(Z6r,YNt),hzo=ir.Record({environmentID:ir.String,operationType:E2(L2),isPreview:ir.Boolean,fromWorkspaceData:Q6r,parallelism:ir.Number}),_7c=Nre(hzo,YNt),D7c=ir.Record({user:ir.String.optional(),password:ir.String.optional(),keyPairKey:ir.String.optional(),authenticator:E2(Kg),warehouse:ir.String.optional(),role:ir.String.optional(),keyPairPass:ir.String.optional(),accountName:ir.String.optional(),database:ir.String.optional(),destinationSchema:ir.String.optional(),orgID:ir.String,environmentID:ir.Union(ir.Number,ir.String).optional(),keyPairPath:ir.String.optional()}),M7c=ir.Record({userContext:D7c,templateString:ir.String}),GNt=t=>{if(t!==void 0)try{return parseInt(t)}catch{throw new aH("jobID could not be converted to a number",`jobID=${t}`)}},b9e=(t,e,r,n,i)=>{let s=c=>()=>{throw new Error(`Unexpected credential type: ${c}`)};return ir.match(ir.when(KNt,e),ir.when(Y6r,r||s("keypair")),ir.when(K6r,n||s("oauth")),ir.when(H6r,i||s("cloud")))(t)},Tre=class{constructor(e){this.runDetails=e.runDetails,this.userCredentials=e.userCredentials,this.runTimeParameters=e.parameters||null}},W6r=class extends Tre{},xre=class extends Tre{},v9e=class extends Tre{},HNt=class extends Tre{};var C9e={};Bl(C9e,{RefreshEventHandler:()=>ukr,RefreshStepExecutor:()=>skr,_test_export:()=>B7c});var ekr=class{constructor(e){this.store=e;this.dispatch=e=>this.store.dispatch(e);this.getState=()=>this.store.getState();this.getStore=()=>this.store}},R3e=class extends ekr{constructor(r,n,i){super(r);this.firebase=n;this.logContext=i;this.GetLogContext=r=>({...this.logContext,nodeID:r});this.GetSkipHandler=()=>(r,n)=>{let i=this.getStepContext(r,n);return this.onStepSkip(i)};this.getAggregateQueryResultsIndex=r=>this.getState().runResults[r.stepID].history.map(s=>s.queryResultSequence.queryResults.length).reduce((s,c)=>s+c,0)-1;this.firebaseUpdateRunResultQueryResult=(r,n,i)=>{if(!this.firebase)return Promise.resolve();let s={...n,queryResultExecutionIndex:i},c=this.firebase.firestore();return DUt(()=>Zo.getOrgRunResultsCollectionRef(c,this.teamID,this.runID).doc(r).collection("queryResults").doc().set(s),3,this.Logger,this.GetLogContext(r),"run query result update")};this.reduxDispatchQueryResultSequenceIndex=(r,n,i)=>{this.dispatch(T9e(r.stepID,n,i))};this.reduxGetLastQueryResultIndex=r=>this.getRunResultData(r.stepID).history.slice(-1)[0].queryResultSequence.queryResults.length-1;this.reduxDispatchQueryResultSequence=r=>{let n={name:r.stageName,isRunning:!0};this.dispatch(nkr(r.stepID,n))};this.updateFirebaseQueryFailure=async r=>{try{await this.firebaseUpdateStageResult(r,this.reduxGetLastQueryResultIndex(r))}catch(n){this.Logger.errorContext(this.GetLogContext(r.stepID),"got an error trying to update firebase during error handling:",n,"re-throwing the original error")}};this.getStepContext=(r,n)=>{let s=this.getStepData(r).operation.name;return{stepID:r,stepName:s,runExecutionSequenceID:n}}}get teamID(){return this.logContext.orgID}get runID(){return this.logContext.runID}get envID(){return this.logContext.envID}reduxUpdateStepResult(r,n){this.dispatch(k3e(r.stepID,n));let i=n==="running";this.dispatch(ikr(r.stepID,i))}getQueryResultForStep(r,n){let i=this.getRunResultData(r.stepID);os("RUNNER_BACKEND",i.history.length>0,this.logContext,"should always have some history for this run since we just got a notification to update to firestore");let s=i.history.slice(-1)[0].queryResultSequence.queryResults,c=s[n];return os("DEPLOY",!!c,this.logContext,`attempting to update query result ${n} for step ${r.stepID}, which does not exist`,"existing queryResults:",s.map(u=>u.name)),c}async firebaseUpdateStageResult(r,n){if(!this.firebase)return;let i=this.getQueryResultForStep(r,n),s=this.getAggregateQueryResultsIndex(r);await this.firebaseUpdateRunResultQueryResult(r.stepID,i,s)}handleTemplateRenderingError(r){let n=x9e(r.error,new Date,null,null,void 0);(nHt(r.error)||iHt(r.error))&&this.dispatch(T9e(r.stepID,{...n,name:r.stepName},0))}reduxInitializeSteps(r){let n=r.length+1,i=this.getState(),s=r.reduce((c,u)=>{let l=gzo(i,u,n);return c[u]=l,c},{});this.dispatch(yzo(s))}async firebaseBulkUpdateInitialSteps(r){if(!this.firebase)return;let n=this.firebase.firestore(),i=500,s=n.batch(),c=Zo.getOrgRunResultsCollectionRef(n,this.logContext.orgID,this.logContext.runID),u=0;for(let l of r){u===i-1&&(await s.commit(),s=n.batch(),u=0);let o=this.getRunResultData(l).history[0],a={...o,runResultVersion:2,name:o.queryResultSequence.name,runExecutionSequenceID:o.runExecutionSequenceID},p=c.doc(l.toString());s.set(p,a),u++}await s.commit()}async initializeSteps(r){this.reduxInitializeSteps(r),await this.firebaseBulkUpdateInitialSteps(r)}formatErrorToResult(r){let n=null,i=null;return typeof r.error=="object"&&(n=r.error.queryID||null,i=r.error.warehouse||null),{...x9e(r.error,r.startTime,n,i,r.templateString),name:r.stageName,renderStartTime:r.renderStartTime,renderEndTime:r.renderEndTime,stageExecutionStartTime:r.stageExecutionStartTime,stageExecutionEndTime:r.stageExecutionEndTime}}ensureHasQueryResult(r){if(zr("DEPLOY",!!r.queryResult,"query result should always be returned for stage execution"),!r.queryResult)throw new Error("Got an empty query result for stage execution")}dispatchQueryFailure(r){let n=this.formatErrorToResult(r);this.Logger.errorContext(this.GetLogContext(r.stepID),"failed to execute run sql",r.error,"stack: ",r.error.stack||"<none found>");let i=this.reduxGetLastQueryResultIndex(r);return this.reduxDispatchQueryResultSequenceIndex(r,n,i),{error:n.error}}getStepData(r){let n=this.getState().steps,i=n&&n[r];if(i)return i;throw this.Logger.errorContext(this.GetLogContext(r),"Event Handler: could not get step data for step:",r),new Error(`DeployEventHandler: Could not get step data for step: ${r}`)}getRunResultData(r){return this.getState().runResults[r]}getQueryResultForUpdateSuccess(r){return{...r.queryResult,name:r.stageName,stageExecutionStartTime:r.stageExecutionStartTime,stageExecutionEndTime:r.stageExecutionEndTime,renderStartTime:r.renderStartTime,renderEndTime:r.renderEndTime}}getLastResultHistoryForFirestore(r){let n=this.getRunResultData(r.stepID).history,i=n.length-1;return n[i]}getResultsHistoryForFirestore(r){let n=this.getRunResultData(r.stepID).history;if(n.length===0)throw this.Logger.emergContext(this.GetLogContext(r.stepID),"Reached dropthrough case in firebaseUpdateStepResult. runResults history had a length of 0 for step",r.stepID,". runResultHistoryForStep:",n),new Error(`There was a problem when trying to update run results during while deploying step "${r.stepID}"`);if(n.length===1)return this.Logger.debugContext(this.GetLogContext(r.stepID),"There was only 1 history item for the step"),n[0];this.Logger.infoContext(this.GetLogContext(r.stepID),`There were ${n.length} history items for the step, combining them`);let i=[];n.forEach(u=>{let l=u.queryResultSequence.queryResults;i.push(...l)});let s=n.length-1,c=n[s];return c.queryResultSequence.queryResults=i,c}async firebaseSetInitialStepResult(r){if(!this.firebase)return;let n=this.getLastResultHistoryForFirestore(r);await JNt(this.firebase.firestore(),this.teamID,this.runID,r.stepID,n)}async firebaseUpdateStepResult(r){if(!this.firebase)return;let n=this.getResultsHistoryForFirestore(r);await JNt(this.firebase.firestore(),this.teamID,this.runID,r.stepID,n)}isFinalRunForStep(r){return!0}async onStepSkip(r){this.dispatch(tkr(r.stepID,r.runExecutionSequenceID)),this.reduxUpdateStepResult(r,"skipped"),this.getRunResultData(r.stepID)?await this.firebaseUpdateStepResult(r):await this.firebaseSetInitialStepResult(r)}async beforeStepExecution(r){this.dispatch(tkr(r.stepID,r.runExecutionSequenceID)),this.reduxUpdateStepResult(r,"running"),await this.firebaseSetInitialStepResult(r)}async afterStepExecutionSuccess(r){this.isFinalRunForStep(r)&&this.reduxUpdateStepResult(r,"complete"),await this.firebaseUpdateStepResult(r)}async afterStepExecutionFailure(r){this.handleTemplateRenderingError(r),this.dispatch(XNt("sqlTabActiveIndex","SQL")),this.reduxUpdateStepResult(r,"error");try{await this.firebaseUpdateStepResult(r)}catch(n){this.Logger.emergContext(this.GetLogContext(r.stepID),`Error in firebaseUpdateStepResult for stepCounter:${r.stepID}:`,n)}}sanityCheckContext(r){}async beforeStageExecution(r){this.sanityCheckContext(r),this.reduxDispatchQueryResultSequence(r)}async afterStageExecutionSuccess(r){this.sanityCheckContext(r),this.ensureHasQueryResult(r);let n=this.reduxGetLastQueryResultIndex(r);this.reduxDispatchQueryResultSequenceIndex(r,this.getQueryResultForUpdateSuccess(r),n),await this.firebaseUpdateStageResult(r,n)}async afterStageExecutionFailure(r){this.sanityCheckContext(r);let n=this.dispatchQueryFailure(r);throw await this.updateFirebaseQueryFailure(r),n}};var sH={};Bl(sH,{BaseStepExecutor:()=>Cre,CreateStepExecutorFromFactory:()=>L7c});var QMl=Kt("DEPLOY");var bzo=async(t,e)=>{let r=e.map(i=>{let s={...t.nodeMetadata,...i.dataForNodeMetadata,parameters:t.nodeMetadata.parameters};return QNt(i.sql,t.userContext,s,t.macrosString)});return(await Promise.allSettled(r)).map(i=>{if(i.status==="fulfilled")return i.value;throw i.reason})};var okr=class{constructor(e,r){this.parseResult=e;this.selectSQL=r}},$Nt=async(t,e,r,n,i,s)=>{let c=B5e("snowflake");if(r.steps[e].operation.type==="sourceInput")return null;try{let l=wue(e,r,"select",n,null,i),o=await F5e(c,t,l,s),a;try{let p="code:",m=o.runDetails.compiledSQL,d=m.indexOf(p),f=m.slice(d+p.length);try{return a=N6n(f),new okr(a,f)}catch(y){return Kt("STRUMENTA").info("STRUMENTACHECK: failed to parse with error:",y,f),null}}catch(p){return Kt("STRUMENTA").info("STRUMENTACHECK: failed to get select with error:",p),null}}catch(l){return Kt("STRUMENTA").error("failed to render with error",l),null}},Szo=async(t,e)=>{try{let r=await t;r&&(!!r.parseResult?.numberOfParserErrors&&!e?Kt("STRUMENTA").error("STRUMENTACHECK:STRUMENTA FAILED TO PARSE SELECT",r.selectSQL):Kt("STRUMENTA").info("STRUMENTACHECK:CHECKED",r.selectSQL))}catch(r){Kt("STRUMENTA").error("STRUMENTACHECK:ERROR DURING CHECKING",r)}},vzo=(t,e,r)=>{let n=t;return j6n(r)&&(n=U6n(n)),e&&(n=PLo(n)),n};var t8l=Kt("RUNNER");var xzo=(t,e,r)=>async n=>{let i=new Date;try{let s=`Front-end/runSQL/Local: ${n.templateString}`,c=async()=>{let l=await BNt(n.templateString,()=>t.execute({sqlText:n.templateString}),r);return Nzo(l,n.templateString,i)};return await Pa(s,r,"RUNNER_BACKEND",c)}catch(s){let c=s,u=null;throw typeof s=="object"&&s instanceof rH&&(u=s.queryID||null,c=s.cause),e.errorContext(r,"Got failure on template execution",c),{...DL(c),queryID:u}}};var P7c=t=>Object.fromEntries(Object.keys(t).sort().map(e=>[e,t[e]])),Cre=class{constructor(e,r){this.logContext=e;this.runInfo=r;this.getMacrosString=e=>{let r={...e.macros,...pR};return J8(r)}}async RunSQL(e,r){return this.Logger.debugContext(this.logContext,"template execution in BaseStepExecutor"),xzo(e,this.Logger,this.logContext)(r)}async executeStage(e,r,n){let i=null,s=null;try{await e.beforeStageExecution(r.context),await this.setQueryTag(e,r.context,n),e.Logger.debugContext(e.GetLogContext(r.context.stepID),"Executing stage",r.context.stageName),i=new Date;let c=await this.executeStageWithoutEvents(r,n);e.Logger.debugContext(e.GetLogContext(r.context.stepID),"Finished executing stage",r.context.stageName),s=new Date,zr("RUNNER",!c||c.hasOwnProperty("sql"),"query Result checked in executeStage has sql "),await e.afterStageExecutionSuccess({...r.context,queryResult:c,stageExecutionStartTime:i,stageExecutionEndTime:s})}catch(c){throw i&&!s&&(s=new Date),await e.afterStageExecutionFailure({...r.context,error:c,stageExecutionStartTime:i,stageExecutionEndTime:s}),c}finally{await this.unsetQueryTag(n)}}getJobID(){return null}createQueryTagObject(e,r){let n=null;try{n=e.getStepData(r.stepID).operation.locationName}catch(s){this.Logger.errorContext(this.logContext,"Error getting storage location for step",r.stepID,":",s)}let i=null;try{i=eIt(this.runInfo)}catch(s){this.Logger.errorContext(this.logContext,"Error getting job name for step",r.stepID,":",s)}return{runType:this.runTypeName,runID:this.logContext.runID.toString(),jobID:this.getJobID(),jobName:i,storageLocation:n,nodeID:r.stepID,nodeName:r.stepName,stageName:r.stageName}}async setQueryTag(e,r,n){let i={coalesce:P7c(this.createQueryTagObject(e,r))};await n.setQueryTag(JSON.stringify(i,void 0,1))}async unsetQueryTag(e){await e.setQueryTag(null)}async executeStep(e,r,n){if(this.preStepLog(e,r),A$t(e.getState().runResults,r.stepID))throw new Error("Steps are aleady running!");let i=this.getStrumentaTest(e.getState(),r);try{await e.beforeStepExecution(r);for await(let s of this.getStepStages(e,r))await this.executeStage(e,s,n);await e.afterStepExecutionSuccess(r),this.compareStrumentaTest(i,null),this.stepSuccessLog(e,r)}catch(s){let c={...r,error:s};throw await e.afterStepExecutionFailure(c),this.compareStrumentaTest(i,DL(s)),this.stepFailedLog(e,c),s}}async getStrumentaTest(e,r){return null}async compareStrumentaTest(e,r){return Szo(e,r)}stepSuccessLog(e,r){}stepFailedLog(e,r){}preStepLog(e,r){}},L7c=(t,e,r)=>async(n,i)=>{let s=t(n),c=e.getStepContext(n,i);await r.withConnection(async u=>{await s.executeStep(e,c,u)})};var tIt=Kt("RUNNER"),rIt=class{constructor(e){this.context=e}},z7c=(t,e)=>{let r=uX(t.stepTypesParsed,e.sqlType)?.config??null;if(r&&!ZNt(e,r))throw{error:{errorString:"Required attributes missing. Please check your config."}}},skr=class extends Cre{constructor(r,n,i,s,c,u){super(r,n);this.templateString=i;this.specifiedIndex=s;this.isPreview=c;this.userContext=u;this.IsFailedTestResult=r=>!this.isPreview&&kQe(r)&&C$t(r);this.handleFailedTestResult=(r,n)=>{let i=!!I$t(r),s=i?'Test failed with "Continue on Failure" option disabled':"Test failed - records matching fail condition were returned";return n.success=!1,n.error=QYe(s,s),i}}get runTypeName(){return"Refresh"}stepFailedLog(r,n){tIt.errorContext(r.GetLogContext(n.stepID),"Step execution failed (refresh stepExecutor):",n.error)}async getStrumentaTest(r,n){return $Nt(this.userContext,n.stepID,r,null,this.runInfo.runTimeParameters||{},this.getMacrosString(r))}getJobID(){let r=this.runInfo.runDetails.jobID;return r!==void 0?r.toString():null}async executeStageWithoutEvents({context:r},n){let{stageName:i,stageType:s,templateString:c}=r,l={...await this.RunSQL(n,{userContext:this.userContext,templateString:vzo(c,this.isPreview,s)}),name:i,type:s};if(this.IsFailedTestResult(l)&&this.handleFailedTestResult(r,l))throw new I9e(l);return l}get Logger(){return tIt}async*getStepStages(r,n){let i=r.getState(),s=wue(n.stepID,i,"run",this.specifiedIndex,null,this.runInfo.runTimeParameters||{}),c=i.steps[n.stepID].operation,u={...i.macros,...pR},l=J8(u);z7c(i,c);let o=r.GetLogContext(n.stepID),a=new Date;r.Logger.debugContext(o,"Step render completed");let p=await F5e(this.templateString,this.userContext,s,l),m=new Date;r.Logger.debugContext(o,"Rendered SQL for step");let d=Ire(p.runDetails.compiledSQL);if(d.error)throw d.error;for(let f of d.parsedSQLStages){let y={...n,stageName:f.name,startTime:new Date,renderStartTime:a,renderEndTime:m,nodeMetadata:s,stageType:f.type,continueOnFailure:f.continueOnFailure,templateString:f.code};if(!y.stageType)throw console.log("stageContext=",y),new Error("In refresh.getStepStages, no stage type on stage?!");yield new rIt(y)}}},I9e=class extends Error{constructor(r){super('Test failed with "continue on failure" set to false');this.result=r}},F7c=t=>typeof t=="object"&&t instanceof I9e,ukr=class extends R3e{constructor(){super(...arguments);this.getQueryResultForUpdateSuccess=r=>({...super.getQueryResultForUpdateSuccess(r),type:r.stageType})}get Logger(){return tIt}sanityCheckContext(r){if(!r.stageType)throw tIt.emerg("No stage type on this refresh!",r),new Error("Internal critial error: no stage type on this refresh!")}dispatchQueryFailure(r){if(F7c(r.error)){let n=r.error,i=this.reduxGetLastQueryResultIndex(r);return this.reduxDispatchQueryResultSequenceIndex(r,n.result,i),{error:{errorString:r.error.message,errorDetail:r.error.message}}}else return super.dispatchQueryFailure(r)}},B7c={RefreshStage:rIt,TestFailureError:I9e};var _3e={};Bl(_3e,{DeployEventHandler:()=>pkr,DeployStepExecutor:()=>ckr,IsQueryResultDeletingSourceMetadata:()=>j7c,_test_export:()=>V7c});var Izo=Kt("DEPLOY"),nIt=class{constructor(e,r,n){this.context=e;this.templateRunResult=r;this.stage=n}},ckr=class extends Cre{constructor(r,n,i,s,c,u,l){super(r,n);this.workspaceEdits=i;this.templateParams=s;this.stepID=c;this.userContext=u;this.phase=l;this.getRenderedSQLResults=async()=>{try{return this.renderedSQLResults.length||(this.renderedSQLResults=await bzo(this.templateParams,this.workspaceEdits),zr("DEPLOY",!!this.renderedSQLResults.length,`Error during getRenderedSQLResults: failed to populate run results for step ${this.stepID}.`)),this.renderedSQLResults}catch(r){throw this.Logger.error(`Error during getRenderedSQLResults: failed to render SQL for step ${this.stepID}.`,r),r}};this.renderedSQLResults=[]}get runTypeName(){return"Deploy"}stepFailedLog(r,n){Oc(r.GetLogContext(n.stepID)).error("Step execution failed (deploy stepExecutor):",n.error)}preStepLog(r,n){let s={...Ozo(this.templateParams),userContext:WNt(this.userContext)};Oc(r.GetLogContext(n.stepID)).info("Running step -- stepCounter:",n.stepID,"templateParams:",s,"deploy phase:",this.phase)}async getStrumentaTest(r,n){return $Nt(this.userContext,n.stepID,r,null,this.runInfo.runTimeParameters||{},this.getMacrosString(r))}get Logger(){return Izo}async executeStageWithoutEvents(r,n){return r.stage===null?Ezo(r.templateRunResult,r.context.startTime):this.RunSQL(n,{userContext:this.userContext,templateString:r.stage.code})}async*getStepStages(r,n){let i=r.GetLogContext(n.stepID),s=new Date;r.Logger.debugContext(i,"Rendering step");let c=await this.getRenderedSQLResults(),u=new Date;r.Logger.debugContext(i,"Step render completed");for(let l of G7c(c)){let{startTime:o,templateRunResult:a,parsedStage:p}=l,m=p?p.name:Czo.deletedSource,d={...n,stageName:m,startTime:o,renderStartTime:s,renderEndTime:u,nodeMetadata:this.templateParams.nodeMetadata,stageType:p?.type,continueOnFailure:p?.continueOnFailure,templateString:p?.code||"<no stage>"};yield new nIt(d,a,p)}}},Czo=(e=>(e.deletedSource="Deleting metadata for source input",e))(Czo||{}),j7c=t=>ur(t,["name"],"").includes("Deleting metadata for source input");function*G7c(t){for(let e of t){let r=new Date,n=Ire(e.runDetails.compiledSQL);if(n.error)throw n.error;if(!n.parsedSQLStages.length)yield{parsedStage:null,startTime:r,templateRunResult:e};else for(let i of n.parsedSQLStages)yield{parsedStage:i,startTime:r,templateRunResult:e}}}var pkr=class extends R3e{constructor(r,n,i,s,c){super(r,n,i);this.runInfo=s;this.phase=c;this.createNewStepDataForStepAdmin=r=>{let n=this.getStepData(r.stepID);if(!r.nodeMetadata.mapping)return n.operation;let i=n.operation.locationName,s,c=n.operation,u=this.GetLogContext(r.stepID);try{s=r.nodeMetadata.mapping,c=Sr(n.operation,l=>{l.database=s[i].database,l.schema=s[i].schema}),Oc(u).info("newStepData:",c,"stepCounter:",r.stepID)}catch(l){let o=`Error attempting to update the database/schema on deployed nodeID ${r.stepID}: ${c.name}, locations: ${s} error: ${l}`;throw Oc(u).emerg(o),new Error(o)}return c}}get Logger(){return Izo}get runDetails(){return this.runInfo.runDetails}getStepData(r){try{let n=this.runDetails.dividedStepDataWithWorkspaceEdits[this.phase][r];if(n)return n}catch{}try{let n=this.runDetails.fromWorkspaceData.steps[r];if(n)return n}catch{}return super.getStepData(r)}async firebaseUpdateSuccessfulDeployStage(r){if(!!this.firebase)if(this.phase==="deletedTable"){let n=this.runDetails.dividedStepDataWithWorkspaceEdits;!(r.stepID in n.addedTable)&&await hQt(this.firebase,this.teamID,this.envID,r.stepID)}else{let n=this.createNewStepDataForStepAdmin(r);await fQt(this.firebase,this.teamID,this.envID,r.stepID,n)}}isFinalRunForStep(r){let n=[];return this.phase==="deletedTable"&&(n.push(this.runDetails.dividedStepDataWithWorkspaceEdits.alteredTable),n.push(this.runDetails.dividedStepDataWithWorkspaceEdits.addedTable)),this.phase==="alteredTable"&&n.push(this.runDetails.dividedStepDataWithWorkspaceEdits.addedTable),!n.some(i=>r.stepID in i)}async afterStageExecutionSuccess(r){await super.afterStageExecutionSuccess(r);try{await this.firebaseUpdateSuccessfulDeployStage(r)}catch(n){let i=this.GetLogContext(r.stepID);throw this.Logger.errorContext(i,"Error setting firebase -- stepCounter:",r.stepID,"error:",n),new Error(`Failed to set firebase for step: ${this.teamID}, ${this.envID}, ${r.stepID}`)}}},V7c={DeployStage:nIt};var kzo=en(GCe());var Ml=Kt("PRESYNC"),E9e=async(t,e,r)=>await Pa(t,e,"PRESYNC",()=>r,"appContext"),_zo=async(t,e,r,n,i,s)=>{let c=performance.now(),u=e.steps,l=EQe(r.steps),{deletedEntityIDs:o,addedEntityIDs:a,entitiesWithPossibleEdits:p}=wle(l,u);Object.keys(r.locations).length||[...o,...a,...p].length&&Ml.errorContext(s,"There were no mappings/locations in the updated workspace data");let m={};o.forEach(b=>{m[b]=u[b]});let d={},f={added:[],edited:[],deleted:[]};if(a.length){let b=await E9e("ADDED NODES: GetUsedLocationsAndObjectLookup",s,mkr(dkr(l,[...o,...p]),P2(r.locations,t),n,i,s)),S=await E9e("ADDED NODES: get all columns from DB",s,Rzo(b.usedLocations,{},n,i,s)),v=hkr(S);Ml.appContext(s,"ADDED NODES: Total columns by schema: ",v.details,"ADDED NODES: Total columns from all schemas: ",v.totalObjects),gJ("ADDED NODES: SyncAddedNodes",Ml.appContext,s,()=>{a.forEach(A=>{s.nodeID=A,s.nodeName=ur(l,[A,"operation","name"],"unknown");let T=l[A],I=W7c(A,T,b,S,s);if(I){let{nodeToAdd:C,syncDetails:D}=I;d[A]=D,m[A]=C,f.added.push(A)}else f.deleted.push(A)})})}if(p.length){let b,S,v,A=P2(e.locations,t),T=P2(r.locations,t),[I,C]=await Promise.all([E9e("EDITED NODES: GetUsedLocationsAndObjectLookup for current (run in parallel)",s,mkr(dkr(u,o),A,n,i,s)),E9e("EDITED NODES: GetUsedLocationsAndObjectLookup for updated (run in parallel)",s,mkr(dkr(l,a),T,n,i,s))]);b=I,S=C,v=await E9e("EDITED NODES: GetUsedLocationsAndObjectLookup for updated",s,Rzo(b.usedLocations,S.usedLocations,n,i,s));let D=hkr(v);Ml.appContext(s,"EDITED NODES: Total columns by schema: ",D.details,"EDITED NODES: Total columns from all schemas: ",D.totalObjects),gJ("EDITED NODES: SyncEditedNodes",Ml.appContext,s,()=>{p.forEach(P=>{s.nodeID=P,s.nodeName=ur(l,[P,"operation","name"],"unknown");let M=u[P],E=l[P],{nodeToAdd:R,syncDetails:z}=H7c(P,M,E,b,S,A,T,v,i,s);z&&(d[P]=z),R?(f.edited.push(P),m[P]=R):f.deleted.push(P)})})}delete s.nodeID,delete s.nodeName;let y=[...o,...a,...p].length;Ml.infoContext(s,`Presync handled ${y} nodes in ${performance.now()-c}ms`),Ml.appContext(s,`
|
|
3134
|
+
response size: ${s} MB, max response size: ${c} MB`}}},FS=class extends Wl{},Sre=class extends FS{constructor(r,n,i){super(r);this.authType=n;this.cause=i}statusCode(){return 401}toTRunError(){let r=`auth type: ${this.authType}`;if(this.cause){try{r+=` caused by: ${this.cause}`}catch{}try{this.cause.stack&&(r+=this.cause.stack)}catch{}}return{error:{errorString:this.message,errorDetail:r}}}},MNt=class extends FS{constructor(r){super("Could not identify the initial warehouse - possibly invalid credentials or warehouse");this.warehouse=r}statusCode(){return 400}toTRunError(){let r=this.warehouse?`Tried to set a warehouse of ${this.warehouse}`:"Did not set a warehouse";return{error:{errorString:this.message,errorDetail:`${r} and snowflake did not indicate a warehouse was used, but it should have`}}}},m9e=class extends Wl{constructor(r){let n="Snowflake execution error",i;typeof r=="object"&&r instanceof Error&&(n=r.message||n,i=r.stack);super(n);this.cause=r;this.getErrorDetail=()=>{if(this.cause.name==="OperationFailedError")try{let r=this.cause.data;if(r)return`name=${this.cause.name}, code=${this.cause.code}, data=${JSON.stringify(r)}`}catch{}if(this.cause.name==="NetworkError")try{let r=this.cause.cause;if(r&&r.message)return`name=${this.cause.name}, code=${this.cause.code}, cause=${r.message}`}catch{}try{return`name=${this.cause.name}, code=${this.cause.code}`}catch{}return""};this.getErrorData=()=>this.getSnowflakeErrorCode()==="390189"?{errorString:"Role not found",errorDetail:this.cause.message}:{errorString:this.message,errorDetail:this.getErrorDetail()};this.originalStack=i}statusCode(){switch(this.getSnowflakeErrorCode()){case"390189":case"390100":return 401;default:return super.statusCode()}}isCancel(){return this.getSnowflakeErrorCode()==="000604"}getSnowflakeErrorCode(){try{return this.cause.code}catch{return null}}toTRunError(){return{error:this.getErrorData()}}},rH=class extends m9e{constructor(r,n,i,s,c){super(r);this.options=n;this.requestID=i;this.queryID=s;this.warehouse=c}},c9c=(t,e)=>new Promise((r,n)=>{let i=[],s=0,c=t.streamRows(),u=t.getRequestId(),l=t.getStatementId(),o=t.getSessionState()?.getCurrentWarehouse();c.on("error",a=>{n(new rH(a,e,u,l,o))}).on("data",a=>{if(s+=k4e(a),i.push(a),u9c(s)){let m=OLo.getHeapStatistics(),d=new DNt(m,s,t,i);n(d),c.destroy()}}).on("end",()=>{r({rows:i,stmt:t,status:"Success",queryID:l,warehouse:o||null})})}),p9c=async(t,e,r,n)=>{let i=await t;try{return await c9c(i,e)}catch(s){if(typeof s=="object"&&s instanceof DNt){let c=s.makeErrorMessage(r);return l9e.alertContext(n,c),s.makeResult()}else{let c=s;throw typeof s=="object"&&s instanceof rH&&(c=s.toTRunError()),l9e.alertContext(n,"Error on streaming rows:",c),s}}},l9c=(t,e,r)=>{let n=KO(),i=OLo.getHeapStatistics(),{statement:s,resultStatementPromise:c}=m9c(t,e),u=p9c(c,e,i,r),l=JWe(`Back-end (retry=${e.requestId!==void 0}): ${e.sqlText}`,r,"PERFORMANCE",n,u);return{statement:s,resultPromise:l}},d9e=class{constructor(e,r,n,i,s=2){this.sfConn=e;this.options=r;this.logContext=n;this.resetFunc=i;this.maxAttempts=s;this.initialStatement=null;this.shouldResetConnection=e=>{let r=e.cause;return w6r(r)||b9c(r)||g9c(r)};this.handleRetry=async(e,r)=>{if(e.requestID!==void 0&&(r={...r,requestId:e.requestID}),this.shouldResetConnection(e))try{this.sfConn=await this.resetFunc()}catch(n){throw yA.errorContext(this.logContext,"Resetting connect for request CQID=",this.coalesceQueryID,"Error running connection reset callback:",n),e.cause}return r};this.tryCancel=async()=>{let e=this.initialStatement;e!==null&&await f9e(r=>e.cancel(r))};this.Cancel=async()=>{for(let e=0;e<20;e++)try{await this.tryCancel();return}catch(r){if(r.message?.includes("Identified SQL statement is not currently executing"))await nL(100);else throw r}await this.tryCancel()};this.Start=()=>{this._promise||(this._promise=this.queryWithRetries())};this.coalesceQueryID=yJ(),this._promise=null}makePendingQuery(e){return l9c(this.sfConn,e,this.logContext)}async queryWithRetries(){let e=0,r={...this.options};for(yA.debugContext(this.logContext,"Making request for CQID=",this.coalesceQueryID);;){e++;try{let n=this.makePendingQuery(r);this.initialStatement=n.statement;let i=await n.resultPromise;return yA.debugContext(this.logContext,"Successfully got result for CQID=",this.coalesceQueryID),i}catch(n){if(!(typeof n=="object"&&n instanceof rH))throw yA.errorContext(this.logContext,"Not retrying request CQID=",this.coalesceQueryID,"requestId=",r.requestId,"attemptCount=",e,"error=",n,"was unrecognized and not retryable"),n;let i=n.cause?n.cause:n;if(n.isCancel())throw yA.infoContext(this.logContext,"Not retrying request, it was canceled CQID=",this.coalesceQueryID,"attemptCount=",e,"error=",i),i;if(e>=this.maxAttempts)throw yA.infoContext(this.logContext,"Out of retries for request CQID=",this.coalesceQueryID,"attemptCount=",e,"error=",i),i;r=await this.handleRetry(n,r),yA.infoContext(this.logContext,"Retrying request CQID=",this.coalesceQueryID,"requestId=",r.requestId,"attemptCount=",e,"retryOptions=",r,"error=",n.cause?n.cause:n)}}}get promise(){if(this.Start(),!this._promise)throw new FS("Internal consistency error: _promise cannot be null after Start()!");return this._promise}},GLo=async(t,e,r)=>{let{firebase:n,teamInfo:i,teamInfo:{fbTeamID:s,fbUserID:c}}=e,{environmentID:u}=t;if(t.authenticator==="OAuth"){let l=await Z$t(n.firestore(),i,u),a=(await LLo(t,e,r)).refresh_token,p=Buffer.from(`${l.oauthClientID}:${l.oauthClientSecret}`).toString("base64"),m=CLo.default.stringify({grant_type:"refresh_token",refresh_token:a}),d=`https://${l.connectionAccount}.snowflakecomputing.com/oauth/token-request`,f={method:"post",url:d,headers:{Authorization:`Basic ${p}`,"Content-Type":"application/x-www-form-urlencoded"},data:m},y;try{y=await HLo(f)}catch(v){throw yA.errorContext(r,"RefreshAccessToken",v),new Sre("An error occured refreshing your OAuth refresh_token. Please ensure your OAuth Security Integration is still valid or reauthenticate.","OAuth",v)}let g={access_token:y.data.access_token,refresh_token:a},b=await H8e(),S={orgId:s,userId:c,workspaceId:u.toString()};await b.Set(Nee,S,new lm(g))}else throw new Sre("Cannot reset oauth connection on a non-oauth error!","OAuth")},qNt=class extends d9e{constructor(r,n,i,s,c,u=3){super(n,i,s,c,u);this.runningQueries=r;this.attachThen=r=>{this._promise=this.promise.then(n=>(r(n),n))}}async queryWithRetries(){this.runningQueries.set(this.coalesceQueryID,this);try{return await super.queryWithRetries()}finally{this.runningQueries.delete(this.coalesceQueryID)}}},m9c=(t,e)=>{let r,n,i=new Promise((c,u)=>{r=c,n=u});return{statement:t.execute({...e,streamResult:!0,complete:function(c,u){if(c){let l=u&&u.getRequestId(),o=u&&u.getStatementId(),a=u&&u.getSessionState()?.getCurrentWarehouse();n(new rH(c,e,l,o,a))}else r(u)}}),resultStatementPromise:i}},VLo=async(t,e,r,n,i)=>{let s=new d9e(t,e,r,i,n);return s.Start(),s.promise};var d9c="Unable to perform operation using terminated connection.",f9c=407002,h9c="ECONNRESET",y9c="OAuth access token expired.",w6r=t=>!!t.message.includes(y9c),g9c=t=>t.code===f9c||t.message===d9c,b9c=t=>t.cause&&t.cause.code&&t.cause.code===h9c;var wNt={describe:{boolean:{true:"Y",false:"N"},null:null},show:{nullable:{true:!0,NOT_NULL:!1}}};var vre=Kt("CONNECTION"),KLo=async(t,e,r)=>{let n;switch(t.authenticator){case"Basic":case"Cloud":n=zLo(t,r);break;case"KeyPair":n=FLo(t,r);break;case"OAuth":n=await BLo(t,r,e);break}return ULo(n)},LNt=class{constructor(e,r,n,i,s,c){this.sfConnection=e;this.logContext=r;this.connectionID=n;this.useCounter=i;this.parent=s;this.wasCanceled=!1;this.currentQueryTag=null;this.settingQueryTag=!1;this.untrackedQuery=async e=>VLo(this.sfConnection,{sqlText:e},this.logContext,3,this.resetConnection);this.setQueryTag=async e=>{this.currentQueryTag=e;let r=this.currentQueryTag===null?"":this.currentQueryTag.replace("$","\\$");this.settingQueryTag=!0;try{await this.untrackedQuery(`ALTER SESSION SET QUERY_TAG = $$${r}$$`)}finally{this.settingQueryTag=!1}};this.resetConnection=async()=>{if(this.wasCanceled)throw new FS("not resetting canceled connection");let e=await this.resetFunc();return this.sfConnection=e,this.currentQueryTag&&!this.settingQueryTag&&await this.setQueryTag(this.currentQueryTag),e};this.execute=e=>this.executeAndGetRunning(e).promise;this.executeAndGetRunning=e=>{let r=this.makePendingQuery(e);return vre.debugContext(this.logContext,"Tracking snowflake query with CQID=",r.coalesceQueryID,"query=",e),r.Start(),r.attachThen(n=>{n.warehouse&&this.parent&&(this.parent.currentWarehouse=n.warehouse)}),r};this.cancel=async e=>{this.wasCanceled=!0;let r=this.runningQueries.get(e);r&&(r.promise.catch(()=>{}),await r.Cancel())};this.cancelAll=async()=>{this.wasCanceled=!0;let e=Array.from(this.runningQueries.values()).map(r=>r.Cancel());if(e.length)try{await QWe(e)}catch(r){vre.error("Got an unexpected failure during cancelAll(): ",r)}};this.runningQueries=new Map,c?this.resetFunc=c:s?this.resetFunc=()=>s.reinitialize().then(()=>s.sfConnection):this.resetFunc=()=>{throw new FS("Cannot reset the connection, no reset function provided")}}makePendingQuery(e){return new qNt(this.runningQueries,this.sfConnection,e,this.logContext,this.resetConnection)}},y9e=class{constructor(e,r,n,i){this.connectionID=e;this.userContext=r;this.teamInfoAndFirebase=n;this.logContext=i;this.inUse=!1;this.sfConnection=null;this.defaultWarehouse=null;this.currentWarehouse=null;this.useCount=0;this.assertConnected=async()=>{if(!this.inUse)throw os("CONNECTION",!1,this.logContext,"Connection was not acquired before connection check!"),new FS("Connection was not acquired before connection check!");if(await this.initPromise,this.sfConnection===null)throw os("CONNECTION",!1,this.logContext,"Connection was null after initPromise!"),new FS("Connection was null after initPromise!")};this.reinitialize=async()=>{this.initPromise=this.initialize(),await this.connectAndValidate(),await this.acquire(!0)};this.setup=async()=>{await this.connectAndValidate(),await this.setDefaultWarehouse()};this.teardown=async()=>{await f9e(e=>this.sfConnection.destroy(e))};this.acquire=async e=>{if(!e&&this.inUse)throw os("CONNECTION",!1,this.logContext,`Cannot acquire in-use connection ${this.connectionID}`),new FS(`Cannot acquire in-use connection ${this.connectionID}`);this.inUse=!0,this.useCount++};this.setWarehouse=async e=>{await this.assertConnected(),await this.execute({sqlText:`USE WAREHOUSE "${e}"`})};this.release=async()=>{if(this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.defaultWarehouse),this.currentWarehouse=null,!this.inUse)throw os("CONNECTION",!1,this.logContext,`Cannot release connection ${this.connectionID} - not in use`),new FS(`Cannot release connection ${this.connectionID} - not in use`);this.inUse=!1};this.execute=async e=>(await Pa("Waiting for connection",this.logContext,"CONNECTION",()=>this.unwrap())).execute(e);this.executeAndGetRunning=async e=>(await Pa("Waiting for connection",this.logContext,"CONNECTION",()=>this.unwrap())).executeAndGetRunning(e);this.initPromise=this.initialize()}static async New(e,r,n,i){let s=new y9e(e,r,n,i);return await s.initPromise,await s.setup(),s}async initialize(){this.sfConnection=await KLo(this.userContext,this.teamInfoAndFirebase,this.logContext)}connect(){return f9e(e=>this.sfConnection.connect(e))}async resetOauth(){await GLo(this.userContext,this.teamInfoAndFirebase,this.logContext)}async connectAndValidate(){await this.initPromise;try{await this.connect()}catch(e){if(this.userContext.authenticator==="OAuth"&&w6r(e))await this.resetOauth(),this.initPromise=this.initialize(),await this.initPromise,await this.connect();else throw e}this.currentWarehouse&&this.currentWarehouse!==this.defaultWarehouse&&await this.setWarehouse(this.currentWarehouse)}async setDefaultWarehouse(){let r=(await RLo(this.sfConnection,{sqlText:"SELECT 1 as coalesce_init"},this.logContext)).stmt;if(!r)throw os("CONNECTION",!!r,this.logContext,"Snowflake did not return a statement!"),new FS("Snowflake did not return a statement!");if(this.defaultWarehouse=r.getSessionState()?.getCurrentWarehouse()||null,!this.defaultWarehouse)throw vre.errorContext(this.logContext,"Could not identify the initial warehouse - possibly invalid credentials?"),new MNt(this.userContext.warehouse)}async unwrap(){return await this.assertConnected(),new LNt(this.sfConnection,this.logContext,this.connectionID,this.useCount,this)}},iH=class{constructor(e,r,n,i){this.userContext=e;this.teamInfo=r;this.logContext=n;this.maximumConnections=i;this.setup=async()=>{vre.infoContext(this.logContext,"Setting up",this.maximumConnections,"connections - for large values this may take some time"),await this.lock.runExclusive(async()=>{let e=[];for(let r=0;r<this.maximumConnections;r++)e.push(async()=>{let n=yJ(),i=await y9e.New(n,{...this.userContext},this.teamInfo,this.logContext);this.connections.set(n,i)});await e[0](),e.length>1&&await FM(e.slice(1),4)})};this.teardown=async()=>{this.shutdown=!0,await this.lock.runExclusive(async()=>{let e=[];for(let r of this.connections.values())e.push(r.teardown());await QWe(e)})};this.nextAvailableIHaveTheLock=()=>{for(let e of this.connections.values())if(!e.inUse)return e;return null};this.getConnection=async()=>{for(;!this.shutdown;){let e=await this.lock.runExclusive(async()=>{let r=this.nextAvailableIHaveTheLock();return r&&await r.acquire(),r});if(e)return e;await nL(500)}throw new Error("system shutting down before a connection was found")};this.withConnection=async e=>{vre.debugContext(this.logContext,"acquiring connection");let r=await this.getConnection();vre.debugContext(this.logContext,"got connection: ",r.connectionID);try{let n=await r.unwrap();return await e(n)}finally{await this.releaseConnection(r)}};this.releaseConnection=async e=>{await this.lock.runExclusive(async()=>{e.inUse?await e.release():vre.errorContext(this.logContext,"Got a releaseConnection() call on a connection that is not in use!")})};this.lock=new fse,this.connections=new Map,this.shutdown=!1,os("CONNECTION",i>0,this.logContext,"At least one connection is required!")}static async New(e,r,n,i){let s=new iH(e,r,n,i);return await s.setup(),s}},YLo=async(t,e,r)=>{let n=()=>KLo(t,e,r),i=await n();return await f9e(s=>i.connect(s)),new LNt(i,r,yJ(),0,null,n)};var oH=null;ku()&&(oH=zfr());var Are=Kt("AUTH"),XLo=Kt("USER_MANAGEMENT"),S9c=0,ca=Kt("RUNNER_BACKEND"),$Lo=(e=>(e.clientSecretError="Cannot read property 'currentSecretID' of undefined",e))($Lo||{}),QLo=$We("COALESCE_DEFAULT_PARALLELISM",16),L6r=$We("COALESCE_MAX_PARALLEISM_SCHEDULER",64),v9c=()=>{bT?(console.log("WARNING - Using the Firebase emulator for firebase-admin!"),oH.initializeApp({projectId:V7().projectId})):oH.initializeApp({credential:oH.credential.applicationDefault()}),zNt=oH},zNt=wM,A9c=(t,e,r)=>{if(typeof r=="object"&&r instanceof Wl){ca.errorContext(e,"FinishWithError",r.toTRunError()),r.handleExpressResponse(t);return}let n=500;r.statusCode&&(n=r.statusCode),ca.errorContext(e,"FinishWithError (nonstandard error)",r);let i={error:{errorString:r.message||r.error?.errorString,errorDetail:r.stack||r.error?.errorDetail}};t.status(n).json(i)},T9c=t=>new Promise((e,r)=>oH.auth().verifyIdToken(t).then(n=>{e({Firebase:zNt,uid:n.uid})}).catch(n=>{r(n)})),x9c=t=>new Promise((e,r)=>{let n=t+S9c++,i=wM.initializeApp(V7(),n);eWe(i,!1);let s;return t5(`${_J()}/scheduler/generateLoginToken?token=${t}`,null).then(c=>{let u=c.data.customToken;return s=c.data.uid,i.auth().signInWithCustomToken(u)}).then(()=>{e({Firebase:i,uid:s})}).catch(c=>{ca.error("GetOrSetupFirebase",c),r(c)})}),N9c=t=>t5(`https://securetoken.googleapis.com/v1/token?key=${V7().apiKey}`,{refresh_token:t,grant_type:"refresh_token"}).then(e=>e.data.id_token),ZLo=async(t,e,r)=>{let n,i,s;Are.debug("got auth request refresh:",t,"id token",e),e===void 0&&bT&&(e=t);let c=e!==void 0;return Are.debug("inAuthenticate, between 1st and 2nd",c,e),(c?Promise.resolve(e):N9c(t)).then(u=>(Are.debug("inAuthenticate, beore setting id token",c,u),n=u,Are.debug("inAuthenticate, setting up firebase 2",u),r(n))).then(u=>(i=u.Firebase,Are.debug("inAuthenticate, getting team data admin",e),CGt(i.firestore(),u.uid))).then(u=>{s=u;let l=uzo(u.fbRole);return Are.debug("inAuthenticate, finishing...",e),{teamInfo:u,firebase:i,idToken:n,UserRolePrivilegeChecker:l}}).then(u=>u).catch(u=>{let l=new Error("Unable to authenticate, please ensure your token is valid");l.name="401";let o=s?s.fbUserID:"",a=s?s.fbTeamID:"";throw Are.errorContext({userID:o,orgID:a},"AuthenticateFirebaseTokenAndRetrieveTeamInfo",u),l})},ezo=(t,e)=>ZLo(t,e,T9c),I9c=(t,e)=>ZLo(t,e,x9c),C9c=new Set(["password","code","codeVerifier","accessToken","token","id_token","clientSecret","authCode","snowflakePassword","newPassword","refresh_token","uid","keyPair"]),z6r=t=>(C9c.forEach(e=>{delete t[e]}),Object.keys(t).forEach(e=>{!!t[e]&&typeof t[e]=="object"&&!!Object.keys(t[e]).length&&z6r(t[e])}),t),E9c=(t,e,r)=>{let n={body:pp(r.body),query:pp(r.query),params:pp(r.params)},i=z6r(n);ca.debugContext(t,e,i)},aH=class extends Wl{constructor(r,n){super(r);this.validationErrorDetail=n}statusCode(){return 400}toTRunError(){return{error:{errorString:this.message,errorDetail:this.validationErrorDetail||""}}}},tzo=(t,e)=>{let r,n=t.body;if(n.isCompressed){if(!n.data)throw new aH("failed to decompress request body","Request body had no 'data' field to decompress");n=mzo(n.data)}if(r=S9e(e,n),!r.success)throw new aH("failed to validate request body",r.errorString);return r.value},rzo=(t,e)=>{let r=S9e(e,t.body);if(!r.success)throw new aH("failed to validate query params",r.errorString);return r.value},O9c=(t,e,r)=>{e&&rzo(t,e),r&&tzo(t,r)},FNt=(t,e)=>{let r=t?.stmt?.getColumns().map(i=>({Name:i.getName(),DataType:i.getType()}));return{runDetails:{compiledSQL:e,exported_refs:[],invalid_exported_refs:[],ref_usage:{invalid_ref:[],invalid_ref_link:[],invalid_ref_no_link:[],ref:[],ref_link:[],ref_no_link:[]},queryID:t.queryID,warehouse:t.warehouse},data:{columns:r,rows:t.rows,status:t.status}}},BNt=async(t,e,r)=>{let n=`Back-end: ${t}`;try{return await Pa(n,r,"PERFORMANCE",()=>e())}catch(i){let s=i;throw i.message==="Cannot read property 'currentSecretID' of undefined"&&(s=new Error("Missing password or client secret - please update your environment settings")),s}},R9c=t=>{if(typeof t=="string"){let e=parseInt(t);if(isNaN(e))throw new Error(`Cannot convert environment ID ${t} to a number`);return e}else return t},nzo=async(t,e,r,n)=>{let{teamInfo:i}=r;os("RUNNER_BACKEND",!!t.userContext,{orgID:i.fbTeamID,userID:i.fbUserID},"Missing user context in (SnowflakeRunHandlerFunction)");let s={...t.userContext,environmentID:R9c(t.userContext.environmentID)};s.environmentID!==void 0&&sUt(n,s.environmentID.toString());let c={sqlText:t.templateString};ca.debugContext(n,"RunSnowflakeRequest getting connection");let u=()=>e.GetConnectionAndRunQuery(c,s,r);ca.debugContext(n,"RunSnowflakeRequest executing template");let l=await BNt(t.templateString,u,n);return ca.debugContext(n,"RunSnowflakeRequest creating query response object"),FNt(l,t.templateString)},izo=t=>JSON.stringify(WNt(t)),ozo=(t,e,r,n)=>FQe(e,r,n).then(i=>(t.userCredentials={...t.userCredentials,snowflakeAccount:i},t)),k9c=(t,e,r,n)=>(zr("RUNNER_BACKEND",t.runType=="deploy","is a deploy run info"),ozo(t,e,r,n)),_9c=(t,e,r,n)=>(zr("RUNNER_BACKEND",t.runType=="refresh","is a refresh run info"),ozo(t,e,r,n)),F6r=(t,e)=>{let r=b9e(t,()=>{},i=>i.snowflakeKeyPairPath,()=>{},()=>{});return{snowflakeAccount:e.accountName,snowflakeKeyPairPath:r,snowflakeUsername:e.user,snowflakeRole:e.role,snowflakeWarehouse:e.warehouse,snowflakeAuthType:e.authenticator}},D9c=(t,e,r,n)=>{let i=F6r(t.userCredentials,e);return{runTimeParameters:t.runTimeParameters,runDetails:t.runDetails,userCredentials:i,runStatus:"running",userID:r,runType:"deploy",kubernetesJobUuid:n}},M9c=async(t,e,r,n,i,s,c,u,l)=>{try{await j6r(t,e,r,n,s,c,u),ca.appContext(u,"runDeploy finished successfully"),await Myn(t,e.fbTeamID,i,r)}catch(o){ca.errorContext(u,"Error during deploy inner promise (runDeployCompletion):",o);try{await qyn(t,e.fbTeamID,i,r,o.message)}catch(a){ca.errorContext(u,"Error during status release: ",a)}throw o}finally{l()}},q9c=async(t,e,r,n,i,s,c)=>{let u=bWt("orgRuns",t.firestore(),e.fbTeamID),{runCounter:l,CleanupHeartbeat:o}=await _yn(t,e.fbTeamID,n,r,u,c);fJ(c,l);let a={orgID:e.fbTeamID,envID:n.toString(),userID:e.fbUserID,runID:l};fJ(c,l),ca.appContext(c,"CreateRunDeployCounterAndPromise");let p=M9c(t,e,l,r,n,i,s,a,o);return{runCounter:l,runCompletion:p}},w9c=(t,e)=>{e=e===void 0?QLo:e;let s=(e-4)*2+4;return t<1?1:t<4?t:t<s?4+Math.floor((t-4)/2):e},B6r=(t,e)=>{let r=w9c(t,e),n=YWe()?L6r:1/0;return n<r?n:r},P9c=async(t,e,r,n,i)=>{let{teamInfo:s,teamInfo:{fbUserID:c},firebase:u}=e,l=u.firestore(),o=parseInt(t.runDetails.environmentID);ca.infoContext(r,"Deployment started");let a=Math.max(...Object.values(t.runDetails.dividedStepDataWithWorkspaceEdits).map(p=>Object.keys(p).length));try{let p=await UNt(l,s,o,n),m=g9e(p,c),d=await iH.New(p,e,r,B6r(a,t.runDetails.parallelism));t.runDetails=tQt(m,t.runDetails,c),ca.appContext(r,izo(p),"BECLI_HandleDeploy"),await U6r(d,c,r);let f=D9c(t,p,c,i);return q9c(u,s,f,o,d,p,r)}catch(p){throw ca.errorContext(r,"Error during deploy: ",p),p}},L9c=t=>{let{runDetails:e}=t;if(e.jobID&&(e.includeNodesSelector||e.excludeNodesSelector))throw new Error("Unable to process, don't provide a JobID and Node Include/Exclude Selector(s) for 1 Refresh Run")},z9c=(t,e)=>{for(let r in e)e[r]&&(t[r]=e[r])},F9c=(t,e,r,n)=>{let i=F6r(t.userCredentials,e),s={runTimeParameters:t.runTimeParameters,runDetails:{...t.runDetails,jobID:GNt(t.runDetails.jobID)},userCredentials:i,runStatus:"running",userID:r,runType:"refresh",kubernetesJobUuid:n};return SJ(s),s},g9e=(t,e)=>{let r={connectionDetails:{userID:e,user:t.user,role:t.role,warehouse:t.warehouse},connectionType:t.authenticator};return t.authenticator==="KeyPair"&&(r.connectionDetails.keyPair=t.keyPairKey),r},U6r=async(t,e,r)=>{let n=g9e(t.userContext,e),i={connectionType:n.connectionType,connectionDetails:Q$t(n.connectionDetails)};ca.infoContext(r,"testing snowflake connection:",i),await t.withConnection(async s=>{await s.execute({sqlText:"select 1 as coalesce_test"})})},UNt=async(t,e,r,n)=>{let i=await eQt(t,e,r),c={accountName:await FQe(t,e.fbTeamID,r),user:i.connectionDetails.user,role:i.connectionDetails.role,warehouse:i.connectionDetails.warehouse,environmentID:r,orgID:e.fbTeamID,authenticator:i.connectionType};return z9c(c,n),c},B9c=async(t,e,r,n,i,s,c,u,l,o,a,p)=>{try{ca.appContext(l,"startng runRefresh"),await G6r(t,e,i,r,n.toString(),s,c,u,o,a),ca.appContext(l,"runRefresh finished with no errors, releasing workspace status"),await wyn(t,e.fbTeamID,n,i)}catch(m){ca.errorContext(l,"Error during refresh:",m);try{await Pyn(t,e.fbTeamID,n,i)}catch(d){ca.errorContext(l,"Error during status release: ",d)}throw m}finally{p()}},azo=async(t,e,r,n,i,s,c,u,l,o)=>{ca.infoContext(u,"securing workspace status and starting refresh",n);let a=bWt("orgRuns",t.firestore(),e.fbTeamID),{runCounter:p,CleanupHeartbeat:m}=await Dyn(t,e.fbTeamID,n,r,a,u);fJ(u,p),ca.appContext(u,"CreateRunRefreshCounterAndPromise");let d=B9c(t,e,r,n,p,i,s,c,u,l,o,m);return{runCounter:p,runCompletion:d}},U9c=async(t,e,r,n,i)=>i?(ca.infoContext(n,"Refreshing job:",i),yQt(t,e,r,"jobs",i)):(ca.infoContext(n,"No job ID, refreshing all steps"),!0),j9c=async(t,e,r,n,i)=>{let{teamInfo:s,teamInfo:{fbTeamID:c,fbUserID:u},firebase:l}=e,o=l.firestore(),a=parseInt(t.runDetails.environmentID);t.runTimeParameters=await jNt(o,c,a,t.runTimeParameters),L9c(t);let p=GNt(t.runDetails.jobID),m=U9c(o,c,a,r,p);try{let d=await UNt(o,s,a,n),f=g9e(d,u);if(ca.appContext(r,izo(d),"BECLI_HandleRefresh"),!await m)throw N3(400,`Unable to start job ${p}`,`Job ${p} did not exist`);let y=F9c(t,d,u,i),{allWorkspaceData:g,stepsForRefresh:b}=await VNt(e,y,y.runDetails.environmentID),S=await iH.New(d,e,r,B6r(b.length,t.runDetails.parallelism));return await U6r(S,u,r),azo(l,s,y,a,S,f,d,r,g,b)}catch(d){throw ca.errorContext(r,"Error during refresh:",d),d}},szo=(n=>(n.canUpdateUser="canUpdateUser",n.canUpdateSuperUser="canUpdateSuperUser",n.canResetPassword="canResetPassword",n))(szo||{}),uzo=t=>{let e={["canUpdateUser"]:["Admin"],["canUpdateSuperUser"]:[],["canResetPassword"]:["Admin"]};return r=>e[r].includes(t)},JLo=(t,e)=>({isValid:t,error:{error:{errorDetail:e,errorString:e}}}),G9c=new Set(["firstName","lastName","role","activated","authDisabled","deleted","userID"]),V9c=(t,e,r)=>{if(t.fbHasSuperUserAccess===!0)return;if(Object.keys(r).some(c=>!G9c.has(c)))throw new Error("Error Updating User: Insufficient privileges to update specified user attributes");if(!!e&&t.fbTeamID!==e.currentTeam)throw new Error("Error Updating User: forbidden user information")},W9c=(t,e)=>{if(t.fbHasSuperUserAccess===!0)return;if(t.fbTeamID!==e.currentTeam)throw new Error("Error Creating User: forbidden user information")},czo=(t,e,r)=>{try{if(!!e.userID){let l=MT(H9c,e);zM(l.success,l.errorString||"One or more fields were not correctly filled out","USER_MANAGEMENT",{}),V9c(t.teamInfo,r,e)}else{let l=MT(K9c,e);zM(l.success,l.errorString||"One or more fields were not correctly filled out","USER_MANAGEMENT",{}),W9c(t.teamInfo,e)}let i=t.UserRolePrivilegeChecker("canUpdateUser"),s=!!r&&r.hasOwnProperty("hasSuperUserAccess"),u=!!e.hasOwnProperty("hasSuperUserAccess")&&(!r||!s||e.userID!==r.userID);zM(i&&!u,"Error: Insufficient privileges to update users","USER_MANAGEMENT",{})}catch(n){return XLo.error("Error during CheckIsValidAdminUpdate: ",n),JLo(!1,n.message)}return JLo(!0,"")},H9c=Dl.Record({firstName:Dl.String.optional(),lastName:Dl.String.optional(),role:Dl.String.optional(),activated:Dl.Boolean.optional(),authDisabled:Dl.Boolean.optional(),deleted:Dl.Boolean.optional(),currentTeam:Dl.String.optional(),email:Dl.String.optional(),userID:Dl.String.optional()}),K9c=Dl.Record({firstName:Dl.String,lastName:Dl.String,role:Dl.String,currentTeam:Dl.String,email:Dl.String,activated:Dl.Boolean.optional(),password:Dl.Optional(Dl.String),userID:Dl.String.optional()}),Y9c=async(t,e,r)=>{let i=await(await pX(t,e,r).get()).get("runTimeParameters");return G5e(i)},jNt=async(t,e,r,n)=>n?DQe(n):Y9c(t,e,r),pzo=(t,e)=>{zM(!!t,"Attempted to authenticate invalid auth header","AUTH",{});let[r,n]=t.split(" ");zM(r=="Basic",`Unexpected auth type in header: ${r}`,"AUTH",{}),zM(e===n,"Passed secret is invalid","AUTH",{})},J9c=async(t,e,r,n,i,s)=>{let c=F6r(e.userCredentials,n),u=await jNt(t,i.fbTeamID,parseInt(r.runDetails.environmentID),e.runTimeParameters);return{runStatus:"running",runType:"refresh",runDetails:r.runDetails,userCredentials:c,reRunID:e.runDetails.runID,runTimeParameters:u,userID:i.fbUserID,kubernetesJobUuid:s}},X9c=async(t,e,r,n,i,s)=>{let{firebase:c,teamInfo:u,teamInfo:{fbUserID:l,fbTeamID:o}}=r,a=c.firestore(),p=parseInt(e.runDetails.environmentID),m=await UNt(a,u,p,i),d=await J9c(a,t,e,m,u,s),{allWorkspaceData:f,stepsForRefresh:y}=await VNt(r,d,d.runDetails.environmentID),g=await iH.New(m,r,n,B6r(y.length,d.runDetails.parallelism));t.runTimeParameters=await jNt(a,o,p,t.runTimeParameters);let b=g9e(m,l);return await U6r(g,l,n),azo(c,u,d,p,g,b,m,n,f,y)},$9c=async(t,e,r,n,i,s)=>{if(ca.appContext(n,"BECLI_HandleRerun"),e.runStatus!=="failed")throw new Error("Only failed jobs can be re-run!");if(e.runType!=="refresh")throw new Error("Only refresh jobs can be re-run!");return X9c(t,e,r,n,i,s)},Q9c=t=>{let{password:e,userID:r,...n}=t;return r&&(n.userID=r),n},Z9c=async(t,{token:e,idToken:r},n)=>{let i=Q9c(t),s=new lm(t.password);try{let c=await ezo(e,r);n=$u(c.teamInfo.fbTeamID,void 0,c.teamInfo.fbUserID),ca.infoContext(n,"CreateOrUpdateUser validating payload",i.userID,i),SJ(i);let u=await t7c(i.userID,i,c.firebase);return ca.infoContext(n,"CreateOrUpdateUser role validation:",i),await e7c(c,i,u),ca.infoContext(n,"CreateOrUpdateUser running transaction:",i),await c.firebase.firestore().runTransaction(async l=>{let o=await s7c(i.userID,c.firebase,l);if(!!o&&o.deleted===!0)throw N3(403,"Error: cannot update deleted user","Invalid update to user");ca.infoContext(n,"CreateOrUpdateUser validating admin demotion:",i),await i7c(c.firebase,l,n,i,o),ca.infoContext(n,"CreateOrUpdateUser validating number of users:",i);let a=await u7c(i.currentTeam,c.firebase,l,i,o);return ca.infoContext(n,"CreateOrUpdateUser creating/setting user doc",i),await lzo(c.firebase,l,i.userID,i.email,a,s),ca.infoContext(n,"CreateOrUpdateUser validating disable or deletion",i),await m7c(i,o,n)})}catch(c){throw ca.alertContext(n,"CreateOrUpdateUser ERROR during transaction",c),c}},lzo=async(t,e,r,n,i,s)=>{if(r){let{authDisabled:c,...u}=i,l=lL(t.firestore(),r);await e.update(l,u)}else{let c=await t.auth().createUser({email:n,password:s.sensitiveValue});lL(t.firestore(),c.uid).set(i)}},e7c=(t,e,r)=>{let n=czo(t,e,r);if(n.isValid===!1)throw N3(400,n.error.error.errorString||"Unknown Error",n.error.error.errorDetail||"")},t7c=async(t,e,r)=>t?await n7c(t,r):r7c(e),r7c=t=>{let{firstName:e,lastName:r,role:n,currentTeam:i,email:s,activated:c}=t;if(!n||!e||!r||!i||!s)throw N3(422,"One or more fields were not correctly filled out for create",`422: role: ${n}, first name: ${e}, last name: ${r}, currentTeam: ${i}, email: ${s}, activated: ${c}`)},n7c=async(t,e)=>(await lL(e.firestore(),t).get()).data(),i7c=async(t,e,r,n,i)=>{if(!i)return;let s=i.currentTeam,c=o7c(n,i);if(ca.infoContext(r,`ValidateAdminDemotion does edit require admin demotion validation: ${c}`,n,s),c)return await a7c(s,e,t,r)},o7c=(t,e)=>{if(!e)return!1;let r=e.role==="Admin",n=r&&t.role==="User",i=r&&!!t.deleted,s=r&&t.authDisabled===!0;return ca.infoContext({userID:t.userID},`(CheckIfAdminIsBeingDemotedDeletedOrDisabled) demoted: ${n}, deleted: ${i}, disabled: ${s}`),n||i||s},a7c=async(t,e,r,n)=>{let i=await l7c(t,e,r,n);if(ca.infoContext(n,"CreateOrUpdateUser validating org will retain at least 1 admin"),i<=1)throw Error("ValidateAdminDemotion ERROR: number of admins in an org cannot go below one.")},s7c=async(t,e,r)=>{if(!t)return null;let n=lL(e.firestore(),t);return{...(await r.get(n)).data(),userID:t}},u7c=async(t,e,r,n,i)=>i?n:c7c(t,r,e,n),c7c=async(t,e,r,n)=>await p7c(t,e,r)===0?{...n,role:"Admin"}:n,p7c=async(t,e,r)=>{let n=r.firestore().collection("users").where("currentTeam","==",t).limit(1);return(await e.get(n)).size},l7c=async(t,e,r,n)=>{let i=r.firestore().collection("users").where("currentTeam","==",t).where("role","==","Admin"),s=await e.get(i),c=[];for(let u of s.docs){let l=u.data();try{(await Ffr(u.id)).disabled!==!0&&l.deleted!==!0&&c.push(l)}catch(o){if(XLo.errorContext(n,"Error getting user auth doc",o),o.message!=="There is no user record corresponding to the provided identifier.")throw o}}return c.length},m7c=async(t,e,r)=>{if(!e)return Promise.resolve();let n=!1;try{n=(await Ffr(e.userID)).disabled}catch{n=!0}return!!e&&t.deleted!==e.deleted?(ca.infoContext(r,"ValidateUserDisableOrDeletion handling deletion"),await d7c(t)):!!e&&t.authDisabled!==n?(ca.infoContext(r,`ValidateUserDisableOrDeletion handling disable/reenable. Will user be disabled after this takes effect? ${t.authDisabled}`,t),await f7c(t)):Promise.resolve()},d7c=async t=>await oH.auth().deleteUser(t.userID),f7c=async t=>t.authDisabled===void 0?Promise.resolve():await oH.auth().updateUser(t.userID,{disabled:t.authDisabled});var KNt=ir.Record({snowflakeUsername:ir.String,snowflakePassword:ir.String,snowflakeWarehouse:ir.String.optional(),snowflakeRole:ir.String.optional(),snowflakeAuthType:ir.Literal("Basic").optional()}),H6r=ir.Record({snowflakeUsername:ir.String,snowflakeWarehouse:ir.String.optional(),snowflakeRole:ir.String.optional(),snowflakeAuthType:ir.Literal("Cloud").optional()}),K6r=ir.Record({snowflakeWarehouse:ir.String.optional(),snowflakeAuthType:ir.Literal("OAuth").optional()}),Y6r=ir.Record({snowflakeUsername:ir.String,snowflakeKeyPairPath:ir.String,snowflakeKeyPairPass:ir.String,snowflakeWarehouse:ir.String.optional(),snowflakeRole:ir.String.optional(),snowflakeAuthType:ir.Literal("KeyPair").optional()}),J6r=ir.Union(KNt,Y6r),YNt=ir.Union(KNt,K6r,H6r),A9e=async(t,e,r,n)=>{if(n.snowflakeAuthType==="Cloud"){let s=await(await H8e()).Get(WV,{orgId:t,userId:e,workspaceId:r});if(!s)throw new Error("No Snowflake credentials found!");n.snowflakeAuthType="Basic",n.snowflakePassword=s.sensitiveValue.password}},h7c=ir.Record({token:ir.String}),y7c=ir.Record({newPassword:ir.String,editedUserID:ir.String}),Nre=(t,e)=>ir.Record({runDetails:t,userID:ir.String.optional(),parameters:ir.Unknown.optional(),userCredentials:e}),X6r=ir.Record({environmentID:ir.String,stepsInRun:ir.Number.optional(),jobID:ir.String.withConstraint(t=>{try{parseInt(t)}catch{return"${s} is not a string representing an integer"}return!0},{name:"NumericString"}).optional(),includeNodesSelector:ir.String.optional(),excludeNodesSelector:ir.String.optional(),forceIgnoreWorkspaceStatus:ir.Boolean.optional(),parallelism:ir.Number.optional()}),g7c=Nre(X6r,J6r),b7c=Nre(X6r,YNt),$6r=ir.Record({runID:ir.String}),S7c=Nre($6r,J6r),v7c=Nre($6r,YNt),A7c=ir.Unknown,T7c=ir.Unknown,dzo=ir.Union(ir.Number,ir.String),x7c=ir.Record({name:ir.String,isDisabled:ir.Boolean,version:ir.Number,metadata:A7c,packageInfo:T7c.optional()}),N7c=ir.Record({macroString:ir.String,macroCounter:ir.Number.optional(),id:ir.String.optional()}),I7c=ir.Record({jobCounter:ir.Number.optional(),name:ir.String.optional(),subgraphs:ir.Array(ir.Number).optional(),steps:ir.Array(dzo).optional()}),C7c=ir.Record({folderCounter:ir.String,name:ir.String,steps:ir.Array(ir.String)}),E7c=ir.Unknown,O7c=ir.Unknown,Q6r=ir.Record({steps:ir.Dictionary(E7c,ir.String),folders:ir.Dictionary(C7c,ir.String),jobs:ir.Dictionary(I7c,dzo),macros:ir.Dictionary(N7c,ir.String),stepTypes:ir.Dictionary(x7c,ir.String),userConnections:ir.Dictionary(ir.Dictionary(O7c,ir.String),ir.String).optional(),locations:ir.Unknown.optional(),defaultStorageMapping:ir.String.nullable().optional(),version:ir.Number.optional()}),V6r=ir.Dictionary(ir.Unknown,ir.String),fzo=ir.Record({addedTable:V6r,alteredTable:V6r,deletedTable:V6r}),Z6r=ir.Record({fromWorkspaceData:Q6r,deployCommit:ir.String,environmentID:ir.String.optional(),toWorkspaceID:ir.Number,dividedStepDataWithWorkspaceEdits:fzo,deployCommitMessage:ir.String,stepsInRun:ir.Number,parallelism:ir.Number.optional()}),R7c=Nre(Z6r,J6r),k7c=Nre(Z6r,YNt),hzo=ir.Record({environmentID:ir.String,operationType:E2(L2),isPreview:ir.Boolean,fromWorkspaceData:Q6r,parallelism:ir.Number}),_7c=Nre(hzo,YNt),D7c=ir.Record({user:ir.String.optional(),password:ir.String.optional(),keyPairKey:ir.String.optional(),authenticator:E2(Kg),warehouse:ir.String.optional(),role:ir.String.optional(),keyPairPass:ir.String.optional(),accountName:ir.String.optional(),database:ir.String.optional(),destinationSchema:ir.String.optional(),orgID:ir.String,environmentID:ir.Union(ir.Number,ir.String).optional(),keyPairPath:ir.String.optional()}),M7c=ir.Record({userContext:D7c,templateString:ir.String}),GNt=t=>{if(t!==void 0)try{return parseInt(t)}catch{throw new aH("jobID could not be converted to a number",`jobID=${t}`)}},b9e=(t,e,r,n,i)=>{let s=c=>()=>{throw new Error(`Unexpected credential type: ${c}`)};return ir.match(ir.when(KNt,e),ir.when(Y6r,r||s("keypair")),ir.when(K6r,n||s("oauth")),ir.when(H6r,i||s("cloud")))(t)},Tre=class{constructor(e){this.runDetails=e.runDetails,this.userCredentials=e.userCredentials,this.runTimeParameters=e.parameters||null}},W6r=class extends Tre{},xre=class extends Tre{},v9e=class extends Tre{},HNt=class extends Tre{};var C9e={};Bl(C9e,{RefreshEventHandler:()=>ukr,RefreshStepExecutor:()=>skr,_test_export:()=>B7c});var ekr=class{constructor(e){this.store=e;this.dispatch=e=>this.store.dispatch(e);this.getState=()=>this.store.getState();this.getStore=()=>this.store}},R3e=class extends ekr{constructor(r,n,i){super(r);this.firebase=n;this.logContext=i;this.GetLogContext=r=>({...this.logContext,nodeID:r});this.GetSkipHandler=()=>(r,n)=>{let i=this.getStepContext(r,n);return this.onStepSkip(i)};this.getAggregateQueryResultsIndex=r=>this.getState().runResults[r.stepID].history.map(s=>s.queryResultSequence.queryResults.length).reduce((s,c)=>s+c,0)-1;this.firebaseUpdateRunResultQueryResult=(r,n,i)=>{if(!this.firebase)return Promise.resolve();let s={...n,queryResultExecutionIndex:i},c=this.firebase.firestore();return DUt(()=>Zo.getOrgRunResultsCollectionRef(c,this.teamID,this.runID).doc(r).collection("queryResults").doc().set(s),3,this.Logger,this.GetLogContext(r),"run query result update")};this.reduxDispatchQueryResultSequenceIndex=(r,n,i)=>{this.dispatch(T9e(r.stepID,n,i))};this.reduxGetLastQueryResultIndex=r=>this.getRunResultData(r.stepID).history.slice(-1)[0].queryResultSequence.queryResults.length-1;this.reduxDispatchQueryResultSequence=r=>{let n={name:r.stageName,isRunning:!0};this.dispatch(nkr(r.stepID,n))};this.updateFirebaseQueryFailure=async r=>{try{await this.firebaseUpdateStageResult(r,this.reduxGetLastQueryResultIndex(r))}catch(n){this.Logger.errorContext(this.GetLogContext(r.stepID),"got an error trying to update firebase during error handling:",n,"re-throwing the original error")}};this.getStepContext=(r,n)=>{let s=this.getStepData(r).operation.name;return{stepID:r,stepName:s,runExecutionSequenceID:n}}}get teamID(){return this.logContext.orgID}get runID(){return this.logContext.runID}get envID(){return this.logContext.envID}reduxUpdateStepResult(r,n){this.dispatch(k3e(r.stepID,n));let i=n==="running";this.dispatch(ikr(r.stepID,i))}getQueryResultForStep(r,n){let i=this.getRunResultData(r.stepID);os("RUNNER_BACKEND",i.history.length>0,this.logContext,"should always have some history for this run since we just got a notification to update to firestore");let s=i.history.slice(-1)[0].queryResultSequence.queryResults,c=s[n];return os("DEPLOY",!!c,this.logContext,`attempting to update query result ${n} for step ${r.stepID}, which does not exist`,"existing queryResults:",s.map(u=>u.name)),c}async firebaseUpdateStageResult(r,n){if(!this.firebase)return;let i=this.getQueryResultForStep(r,n),s=this.getAggregateQueryResultsIndex(r);await this.firebaseUpdateRunResultQueryResult(r.stepID,i,s)}handleTemplateRenderingError(r){let n=x9e(r.error,new Date,null,null,void 0);(nHt(r.error)||iHt(r.error))&&this.dispatch(T9e(r.stepID,{...n,name:r.stepName},0))}reduxInitializeSteps(r){let n=r.length+1,i=this.getState(),s=r.reduce((c,u)=>{let l=gzo(i,u,n);return c[u]=l,c},{});this.dispatch(yzo(s))}async firebaseBulkUpdateInitialSteps(r){if(!this.firebase)return;let n=this.firebase.firestore(),i=500,s=n.batch(),c=Zo.getOrgRunResultsCollectionRef(n,this.logContext.orgID,this.logContext.runID),u=0;for(let l of r){u===i-1&&(await s.commit(),s=n.batch(),u=0);let o=this.getRunResultData(l).history[0],a={...o,runResultVersion:2,name:o.queryResultSequence.name,runExecutionSequenceID:o.runExecutionSequenceID},p=c.doc(l.toString());s.set(p,a),u++}await s.commit()}async initializeSteps(r){this.reduxInitializeSteps(r),await this.firebaseBulkUpdateInitialSteps(r)}formatErrorToResult(r){let n=null,i=null;return typeof r.error=="object"&&(n=r.error.queryID||null,i=r.error.warehouse||null),{...x9e(r.error,r.startTime,n,i,r.templateString),name:r.stageName,renderStartTime:r.renderStartTime,renderEndTime:r.renderEndTime,stageExecutionStartTime:r.stageExecutionStartTime,stageExecutionEndTime:r.stageExecutionEndTime}}ensureHasQueryResult(r){if(zr("DEPLOY",!!r.queryResult,"query result should always be returned for stage execution"),!r.queryResult)throw new Error("Got an empty query result for stage execution")}dispatchQueryFailure(r){let n=this.formatErrorToResult(r);this.Logger.errorContext(this.GetLogContext(r.stepID),"failed to execute run sql",r.error,"stack: ",r.error.stack||"<none found>");let i=this.reduxGetLastQueryResultIndex(r);return this.reduxDispatchQueryResultSequenceIndex(r,n,i),{error:n.error}}getStepData(r){let n=this.getState().steps,i=n&&n[r];if(i)return i;throw this.Logger.errorContext(this.GetLogContext(r),"Event Handler: could not get step data for step:",r),new Error(`DeployEventHandler: Could not get step data for step: ${r}`)}getRunResultData(r){return this.getState().runResults[r]}getQueryResultForUpdateSuccess(r){return{...r.queryResult,name:r.stageName,stageExecutionStartTime:r.stageExecutionStartTime,stageExecutionEndTime:r.stageExecutionEndTime,renderStartTime:r.renderStartTime,renderEndTime:r.renderEndTime}}getLastResultHistoryForFirestore(r){let n=this.getRunResultData(r.stepID).history,i=n.length-1;return n[i]}getResultsHistoryForFirestore(r){let n=this.getRunResultData(r.stepID).history;if(n.length===0)throw this.Logger.emergContext(this.GetLogContext(r.stepID),"Reached dropthrough case in firebaseUpdateStepResult. runResults history had a length of 0 for step",r.stepID,". runResultHistoryForStep:",n),new Error(`There was a problem when trying to update run results during while deploying step "${r.stepID}"`);if(n.length===1)return this.Logger.debugContext(this.GetLogContext(r.stepID),"There was only 1 history item for the step"),n[0];this.Logger.infoContext(this.GetLogContext(r.stepID),`There were ${n.length} history items for the step, combining them`);let i=[];n.forEach(u=>{let l=u.queryResultSequence.queryResults;i.push(...l)});let s=n.length-1,c=n[s];return c.queryResultSequence.queryResults=i,c}async firebaseSetInitialStepResult(r){if(!this.firebase)return;let n=this.getLastResultHistoryForFirestore(r);await JNt(this.firebase.firestore(),this.teamID,this.runID,r.stepID,n)}async firebaseUpdateStepResult(r){if(!this.firebase)return;let n=this.getResultsHistoryForFirestore(r);await JNt(this.firebase.firestore(),this.teamID,this.runID,r.stepID,n)}isFinalRunForStep(r){return!0}async onStepSkip(r){this.dispatch(tkr(r.stepID,r.runExecutionSequenceID)),this.reduxUpdateStepResult(r,"skipped"),this.getRunResultData(r.stepID)?await this.firebaseUpdateStepResult(r):await this.firebaseSetInitialStepResult(r)}async beforeStepExecution(r){this.dispatch(tkr(r.stepID,r.runExecutionSequenceID)),this.reduxUpdateStepResult(r,"running"),await this.firebaseSetInitialStepResult(r)}async afterStepExecutionSuccess(r){this.isFinalRunForStep(r)&&this.reduxUpdateStepResult(r,"complete"),await this.firebaseUpdateStepResult(r)}async afterStepExecutionFailure(r){this.handleTemplateRenderingError(r),this.dispatch(XNt("sqlTabActiveIndex","SQL")),this.reduxUpdateStepResult(r,"error");try{await this.firebaseUpdateStepResult(r)}catch(n){this.Logger.emergContext(this.GetLogContext(r.stepID),`Error in firebaseUpdateStepResult for stepCounter:${r.stepID}:`,n)}}sanityCheckContext(r){}async beforeStageExecution(r){this.sanityCheckContext(r),this.reduxDispatchQueryResultSequence(r)}async afterStageExecutionSuccess(r){this.sanityCheckContext(r),this.ensureHasQueryResult(r);let n=this.reduxGetLastQueryResultIndex(r);this.reduxDispatchQueryResultSequenceIndex(r,this.getQueryResultForUpdateSuccess(r),n),await this.firebaseUpdateStageResult(r,n)}async afterStageExecutionFailure(r){this.sanityCheckContext(r);let n=this.dispatchQueryFailure(r);throw await this.updateFirebaseQueryFailure(r),n}};var sH={};Bl(sH,{BaseStepExecutor:()=>Cre,CreateStepExecutorFromFactory:()=>L7c});var QMl=Kt("DEPLOY");var bzo=async(t,e)=>{let r=e.map(i=>{let s={...t.nodeMetadata,...i.dataForNodeMetadata,parameters:t.nodeMetadata.parameters};return QNt(i.sql,t.userContext,s,t.macrosString)});return(await Promise.allSettled(r)).map(i=>{if(i.status==="fulfilled")return i.value;throw i.reason})};var okr=class{constructor(e,r){this.parseResult=e;this.selectSQL=r}},$Nt=async(t,e,r,n,i,s)=>{let c=B5e("snowflake");if(r.steps[e].operation.type==="sourceInput")return null;try{let l=wue(e,r,"select",n,null,i),o=await F5e(c,t,l,s),a;try{let p="code:",m=o.runDetails.compiledSQL,d=m.indexOf(p),f=m.slice(d+p.length);try{return a=N6n(f),new okr(a,f)}catch(y){return Kt("STRUMENTA").info("STRUMENTACHECK: failed to parse with error:",y,f),null}}catch(p){return Kt("STRUMENTA").info("STRUMENTACHECK: failed to get select with error:",p),null}}catch(l){return Kt("STRUMENTA").error("failed to render with error",l),null}},Szo=async(t,e)=>{try{let r=await t;r&&(!!r.parseResult?.numberOfParserErrors&&!e?Kt("STRUMENTA").error("STRUMENTACHECK:STRUMENTA FAILED TO PARSE SELECT",r.selectSQL):Kt("STRUMENTA").info("STRUMENTACHECK:CHECKED",r.selectSQL))}catch(r){Kt("STRUMENTA").error("STRUMENTACHECK:ERROR DURING CHECKING",r)}},vzo=(t,e,r)=>{let n=t;return j6n(r)&&(n=U6n(n)),e&&(n=PLo(n)),n};var t8l=Kt("RUNNER");var xzo=(t,e,r)=>async n=>{let i=new Date;try{let s=`Front-end/runSQL/Local: ${n.templateString}`,c=async()=>{let l=await BNt(n.templateString,()=>t.execute({sqlText:n.templateString}),r);return Nzo(l,n.templateString,i)};return await Pa(s,r,"RUNNER_BACKEND",c)}catch(s){let c=s,u=null;throw typeof s=="object"&&s instanceof rH&&(u=s.queryID||null,c=s.cause),e.errorContext(r,"Got failure on template execution",c),{...DL(c),queryID:u}}};var P7c=t=>Object.fromEntries(Object.keys(t).sort().map(e=>[e,t[e]])),Cre=class{constructor(e,r){this.logContext=e;this.runInfo=r;this.getMacrosString=e=>{let r={...e.macros,...pR};return J8(r)}}async RunSQL(e,r){return this.Logger.debugContext(this.logContext,"template execution in BaseStepExecutor"),xzo(e,this.Logger,this.logContext)(r)}async executeStage(e,r,n){let i=null,s=null;try{await e.beforeStageExecution(r.context),await this.setQueryTag(e,r.context,n),e.Logger.debugContext(e.GetLogContext(r.context.stepID),"Executing stage",r.context.stageName),i=new Date;let c=await this.executeStageWithoutEvents(r,n);e.Logger.debugContext(e.GetLogContext(r.context.stepID),"Finished executing stage",r.context.stageName),s=new Date,zr("RUNNER",!c||c.hasOwnProperty("sql"),"query Result checked in executeStage has sql "),await e.afterStageExecutionSuccess({...r.context,queryResult:c,stageExecutionStartTime:i,stageExecutionEndTime:s})}catch(c){throw i&&!s&&(s=new Date),await e.afterStageExecutionFailure({...r.context,error:c,stageExecutionStartTime:i,stageExecutionEndTime:s}),c}finally{await this.unsetQueryTag(n)}}getJobID(){return null}createQueryTagObject(e,r){let n=null;try{n=e.getStepData(r.stepID).operation.locationName}catch(s){this.Logger.errorContext(this.logContext,"Error getting storage location for step",r.stepID,":",s)}let i=null;try{i=eIt(this.runInfo)}catch(s){this.Logger.errorContext(this.logContext,"Error getting job name for step",r.stepID,":",s)}return{runType:this.runTypeName,runID:this.logContext.runID.toString(),jobID:this.getJobID(),jobName:i,storageLocation:n,nodeID:r.stepID,nodeName:r.stepName,stageName:r.stageName}}async setQueryTag(e,r,n){let i={coalesce:P7c(this.createQueryTagObject(e,r))};await n.setQueryTag(JSON.stringify(i,void 0,1))}async unsetQueryTag(e){await e.setQueryTag(null)}async executeStep(e,r,n){if(this.preStepLog(e,r),A$t(e.getState().runResults,r.stepID))throw new Error("Steps are aleady running!");let i=this.getStrumentaTest(e.getState(),r);try{await e.beforeStepExecution(r);for await(let s of this.getStepStages(e,r))await this.executeStage(e,s,n);await e.afterStepExecutionSuccess(r),this.compareStrumentaTest(i,null),this.stepSuccessLog(e,r)}catch(s){let c={...r,error:s};throw await e.afterStepExecutionFailure(c),this.compareStrumentaTest(i,DL(s)),this.stepFailedLog(e,c),s}}async getStrumentaTest(e,r){return null}async compareStrumentaTest(e,r){return Szo(e,r)}stepSuccessLog(e,r){}stepFailedLog(e,r){}preStepLog(e,r){}},L7c=(t,e,r)=>async(n,i)=>{let s=t(n),c=e.getStepContext(n,i);await r.withConnection(async u=>{await s.executeStep(e,c,u)})};var tIt=Kt("RUNNER"),rIt=class{constructor(e){this.context=e}},z7c=(t,e)=>{let r=uX(t.stepTypesParsed,e.sqlType)?.config??null;if(r&&!ZNt(e,r))throw{error:{errorString:"Required attributes missing. Please check your config."}}},skr=class extends Cre{constructor(r,n,i,s,c,u){super(r,n);this.templateString=i;this.specifiedIndex=s;this.isPreview=c;this.userContext=u;this.IsFailedTestResult=r=>!this.isPreview&&kQe(r)&&C$t(r);this.handleFailedTestResult=(r,n)=>{let i=!!I$t(r),s=i?'Test failed with "Continue on Failure" option disabled':"Test failed - records matching fail condition were returned";return n.success=!1,n.error=QYe(s,s),i}}get runTypeName(){return"Refresh"}stepFailedLog(r,n){tIt.errorContext(r.GetLogContext(n.stepID),"Step execution failed (refresh stepExecutor):",n.error)}async getStrumentaTest(r,n){return $Nt(this.userContext,n.stepID,r,null,this.runInfo.runTimeParameters||{},this.getMacrosString(r))}getJobID(){let r=this.runInfo.runDetails.jobID;return r!==void 0?r.toString():null}async executeStageWithoutEvents({context:r},n){let{stageName:i,stageType:s,templateString:c}=r,l={...await this.RunSQL(n,{userContext:this.userContext,templateString:vzo(c,this.isPreview,s)}),name:i,type:s};if(this.IsFailedTestResult(l)&&this.handleFailedTestResult(r,l))throw new I9e(l);return l}get Logger(){return tIt}async*getStepStages(r,n){let i=r.getState(),s=wue(n.stepID,i,"run",this.specifiedIndex,null,this.runInfo.runTimeParameters||{}),c=i.steps[n.stepID].operation,u={...i.macros,...pR},l=J8(u);z7c(i,c);let o=r.GetLogContext(n.stepID),a=new Date;r.Logger.debugContext(o,"Step render completed");let p=await F5e(this.templateString,this.userContext,s,l),m=new Date;r.Logger.debugContext(o,"Rendered SQL for step");let d=Ire(p.runDetails.compiledSQL);if(d.error)throw d.error;for(let f of d.parsedSQLStages){let y={...n,stageName:f.name,startTime:new Date,renderStartTime:a,renderEndTime:m,nodeMetadata:s,stageType:f.type,continueOnFailure:f.continueOnFailure,templateString:f.code};if(!y.stageType)throw console.log("stageContext=",y),new Error("In refresh.getStepStages, no stage type on stage?!");yield new rIt(y)}}},I9e=class extends Error{constructor(r){super('Test failed with "continue on failure" set to false');this.result=r}},F7c=t=>typeof t=="object"&&t instanceof I9e,ukr=class extends R3e{constructor(){super(...arguments);this.getQueryResultForUpdateSuccess=r=>({...super.getQueryResultForUpdateSuccess(r),type:r.stageType})}get Logger(){return tIt}sanityCheckContext(r){if(!r.stageType)throw tIt.emerg("No stage type on this refresh!",r),new Error("Internal critial error: no stage type on this refresh!")}dispatchQueryFailure(r){if(F7c(r.error)){let n=r.error,i=this.reduxGetLastQueryResultIndex(r);return this.reduxDispatchQueryResultSequenceIndex(r,n.result,i),{error:{errorString:r.error.message,errorDetail:r.error.message}}}else return super.dispatchQueryFailure(r)}},B7c={RefreshStage:rIt,TestFailureError:I9e};var _3e={};Bl(_3e,{DeployEventHandler:()=>pkr,DeployStepExecutor:()=>ckr,IsQueryResultDeletingSourceMetadata:()=>j7c,_test_export:()=>V7c});var Izo=Kt("DEPLOY"),nIt=class{constructor(e,r,n){this.context=e;this.templateRunResult=r;this.stage=n}},ckr=class extends Cre{constructor(r,n,i,s,c,u,l){super(r,n);this.workspaceEdits=i;this.templateParams=s;this.stepID=c;this.userContext=u;this.phase=l;this.getRenderedSQLResults=async()=>{try{return this.renderedSQLResults.length||(this.renderedSQLResults=await bzo(this.templateParams,this.workspaceEdits),zr("DEPLOY",!!this.renderedSQLResults.length,`Error during getRenderedSQLResults: failed to populate run results for step ${this.stepID}.`)),this.renderedSQLResults}catch(r){throw this.Logger.error(`Error during getRenderedSQLResults: failed to render SQL for step ${this.stepID}.`,r),r}};this.renderedSQLResults=[]}get runTypeName(){return"Deploy"}stepFailedLog(r,n){Oc(r.GetLogContext(n.stepID)).error("Step execution failed (deploy stepExecutor):",n.error)}preStepLog(r,n){let s={...Ozo(this.templateParams),userContext:WNt(this.userContext)};Oc(r.GetLogContext(n.stepID)).info("Running step -- stepCounter:",n.stepID,"templateParams:",s,"deploy phase:",this.phase)}async getStrumentaTest(r,n){return $Nt(this.userContext,n.stepID,r,null,this.runInfo.runTimeParameters||{},this.getMacrosString(r))}get Logger(){return Izo}async executeStageWithoutEvents(r,n){return r.stage===null?Ezo(r.templateRunResult,r.context.startTime):this.RunSQL(n,{userContext:this.userContext,templateString:r.stage.code})}async*getStepStages(r,n){let i=r.GetLogContext(n.stepID),s=new Date;r.Logger.debugContext(i,"Rendering step");let c=await this.getRenderedSQLResults(),u=new Date;r.Logger.debugContext(i,"Step render completed");for(let l of G7c(c)){let{startTime:o,templateRunResult:a,parsedStage:p}=l,m=p?p.name:Czo.deletedSource,d={...n,stageName:m,startTime:o,renderStartTime:s,renderEndTime:u,nodeMetadata:this.templateParams.nodeMetadata,stageType:p?.type,continueOnFailure:p?.continueOnFailure,templateString:p?.code||"<no stage>"};yield new nIt(d,a,p)}}},Czo=(e=>(e.deletedSource="Deleting metadata for source input",e))(Czo||{}),j7c=t=>ur(t,["name"],"").includes("Deleting metadata for source input");function*G7c(t){for(let e of t){let r=new Date,n=Ire(e.runDetails.compiledSQL);if(n.error)throw n.error;if(!n.parsedSQLStages.length)yield{parsedStage:null,startTime:r,templateRunResult:e};else for(let i of n.parsedSQLStages)yield{parsedStage:i,startTime:r,templateRunResult:e}}}var pkr=class extends R3e{constructor(r,n,i,s,c){super(r,n,i);this.runInfo=s;this.phase=c;this.createNewStepDataForStepAdmin=r=>{let n=this.getStepData(r.stepID);if(!r.nodeMetadata.mapping)return n.operation;let i=n.operation.locationName,s,c=n.operation,u=this.GetLogContext(r.stepID);try{s=r.nodeMetadata.mapping,c=Sr(n.operation,l=>{l.database=s[i].database,l.schema=s[i].schema}),Oc(u).info("newStepData:",c,"stepCounter:",r.stepID)}catch(l){let o=`Error attempting to update the database/schema on deployed nodeID ${r.stepID}: ${c.name}, locations: ${s} error: ${l}`;throw Oc(u).emerg(o),new Error(o)}return c}}get Logger(){return Izo}get runDetails(){return this.runInfo.runDetails}getStepData(r){try{let n=this.runDetails.dividedStepDataWithWorkspaceEdits[this.phase][r];if(n)return n}catch{}try{let n=this.runDetails.fromWorkspaceData.steps[r];if(n)return n}catch{}return super.getStepData(r)}async firebaseUpdateSuccessfulDeployStage(r){if(!!this.firebase)if(this.phase==="deletedTable"){let n=this.runDetails.dividedStepDataWithWorkspaceEdits;!(r.stepID in n.addedTable)&&await hQt(this.firebase,this.teamID,this.envID,r.stepID)}else{let n=this.createNewStepDataForStepAdmin(r);await fQt(this.firebase,this.teamID,this.envID,r.stepID,n)}}isFinalRunForStep(r){let n=[];return this.phase==="deletedTable"&&(n.push(this.runDetails.dividedStepDataWithWorkspaceEdits.alteredTable),n.push(this.runDetails.dividedStepDataWithWorkspaceEdits.addedTable)),this.phase==="alteredTable"&&n.push(this.runDetails.dividedStepDataWithWorkspaceEdits.addedTable),!n.some(i=>r.stepID in i)}async afterStageExecutionSuccess(r){await super.afterStageExecutionSuccess(r);try{await this.firebaseUpdateSuccessfulDeployStage(r)}catch(n){let i=this.GetLogContext(r.stepID);throw this.Logger.errorContext(i,"Error setting firebase -- stepCounter:",r.stepID,"error:",n),new Error(`Failed to set firebase for step: ${this.teamID}, ${this.envID}, ${r.stepID}`)}}},V7c={DeployStage:nIt};var kzo=en(GCe());var Ml=Kt("PRESYNC"),E9e=async(t,e,r)=>await Pa(t,e,"PRESYNC",()=>r,"appContext"),_zo=async(t,e,r,n,i,s)=>{let c=performance.now(),u=e.steps,l=EQe(r.steps),{deletedEntityIDs:o,addedEntityIDs:a,entitiesWithPossibleEdits:p}=wle(l,u);Object.keys(r.locations).length||[...o,...a,...p].length&&Ml.errorContext(s,"There were no mappings/locations in the updated workspace data");let m={};o.forEach(b=>{m[b]=u[b]});let d={},f={added:[],edited:[],deleted:[]};if(a.length){let b=await E9e("ADDED NODES: GetUsedLocationsAndObjectLookup",s,mkr(dkr(l,[...o,...p]),P2(r.locations,t),n,i,s)),S=await E9e("ADDED NODES: get all columns from DB",s,Rzo(b.usedLocations,{},n,i,s)),v=hkr(S);Ml.appContext(s,"ADDED NODES: Total columns by schema: ",v.details,"ADDED NODES: Total columns from all schemas: ",v.totalObjects),gJ("ADDED NODES: SyncAddedNodes",Ml.appContext,s,()=>{a.forEach(A=>{s.nodeID=A,s.nodeName=ur(l,[A,"operation","name"],"unknown");let T=l[A],I=W7c(A,T,b,S,s);if(I){let{nodeToAdd:C,syncDetails:D}=I;d[A]=D,m[A]=C,f.added.push(A)}else f.deleted.push(A)})})}if(p.length){let b,S,v,A=P2(e.locations,t),T=P2(r.locations,t),[I,C]=await Promise.all([E9e("EDITED NODES: GetUsedLocationsAndObjectLookup for current (run in parallel)",s,mkr(dkr(u,o),A,n,i,s)),E9e("EDITED NODES: GetUsedLocationsAndObjectLookup for updated (run in parallel)",s,mkr(dkr(l,a),T,n,i,s))]);b=I,S=C,v=await E9e("EDITED NODES: GetUsedLocationsAndObjectLookup for updated",s,Rzo(b.usedLocations,S.usedLocations,n,i,s));let D=hkr(v);Ml.appContext(s,"EDITED NODES: Total columns by schema: ",D.details,"EDITED NODES: Total columns from all schemas: ",D.totalObjects),gJ("EDITED NODES: SyncEditedNodes",Ml.appContext,s,()=>{p.forEach(P=>{s.nodeID=P,s.nodeName=ur(l,[P,"operation","name"],"unknown");let M=u[P],E=l[P],{nodeToAdd:R,syncDetails:z}=H7c(P,M,E,b,S,A,T,v,i,s);z&&(d[P]=z),R?(f.edited.push(P),m[P]=R):f.deleted.push(P)})})}delete s.nodeID,delete s.nodeName;let y=[...o,...a,...p].length;Ml.infoContext(s,`Presync handled ${y} nodes in ${performance.now()-c}ms`),Ml.appContext(s,`
|
|
3135
3135
|
**** Before presync ****
|
|
3136
3136
|
deleted:
|
|
3137
3137
|
-- ${o.join(`
|