sml-cli 2026.3.0-rc.6 → 2026.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -668,7 +668,7 @@ ${r}`,hYr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),gYr=Obj
668
668
  `:""}var KIr=YIr,XIr={dump:KIr};function oUe(n,r){return function(){throw new Error("Function yaml."+n+" is removed in js-yaml 4. Use yaml."+r+" instead, which is now safe by default.")}}var ZIr=Mb,ekr=H2t,tkr=X2t,jae=nEt,rkr=iEt,nkr=nUe,qae=DEt.load,ikr=DEt.loadAll,skr=XIr.dump,Bae=Dx,akr={binary:lEt,float:rEt,map:K2t,null:Z2t,pairs:fEt,set:pEt,timestamp:oEt,bool:eEt,int:tEt,merge:cEt,omap:uEt,seq:Y2t,str:Q2t},okr=oUe("safeLoad","load"),ckr=oUe("safeLoadAll","loadAll"),lkr=oUe("safeDump","dump"),$ae={Type:ZIr,Schema:ekr,FAILSAFE_SCHEMA:tkr,JSON_SCHEMA:jae,CORE_SCHEMA:rkr,DEFAULT_SCHEMA:nkr,load:qae,loadAll:ikr,dump:skr,YAMLException:Bae,types:akr,safeLoad:okr,safeLoadAll:ckr,safeDump:lkr};var JL=class n{static create(){return new n}parse(r){let i=qae(r.rawContent,{schema:jae});return{...r,data:i,compilationOutput:[]}}};var ukr={yaml:JL.create(),yml:JL.create(),json:Nae.create(),env:Pae.create()},CB=class n{constructor(r=ukr){this.mappings=r}static create(){return new n}parseRawContent(r,i="yaml"){let o={rawContent:r,relativePath:`name.${i}`};return this.parse(o).data}parse(r){let i=Ro.getExtensionFromPath(r.relativePath);return i?(this.mappings[i]||this.defaultParser()).parse(r):this.defaultParser().parse(r)}defaultParser(){return{parse(r){return{...r,data:r.rawContent,compilationOutput:[]}},parseRawContent(r){return r}}}};var fkr=n=>n.trim()===""||n.trim().startsWith("#")?!0:/^[A-Za-z_]+[A-Za-z0-9_]*=(.*)$/.test(n),Jae=class{getErrors(r){let i=[];return r.split(/\r?\n/).forEach((l,p)=>{fkr(l)||i.push(`Invalid format at line ${p+1}: "${l}"`)}),i}};var Uae=class{getErrors(r){try{return JSON.parse(r),[]}catch(i){return typeof i=="string"?[i]:i instanceof Error?[i.message]:[`${i}`]}}};var tQ=class{getErrors(r){let i=[];try{$ae.load(r)}catch(o){o instanceof Bae?i.push(o.message):i.push(`Unknown yaml parsing error: ${qd.getErrorMessage(o)}`)}return i}};var pkr={yml:new tQ,yaml:new tQ,json:new Uae,env:new Jae},Wae=class{constructor(r=pkr){this.mappings=r}getValidator(r){let i=this.getExtensionFromPath(r);return i?this.mappings[i]||this.dummyValidator():this.dummyValidator()}dummyValidator(){return{getErrors:()=>[]}}getExtensionFromPath(r){let i=r.lastIndexOf("/"),o=i===-1?0:i+1,l=r.substring(o),p=l.lastIndexOf(".");if(!(p===-1||p===l.length-1))return l.substring(p+1)}};var Ik=class{static traverse(r,i){r.files.forEach(i),r.folders.flatMap(o=>this.traverse(o,i))}};var cUe={unknownObjectTypeWarning:"Unknown object type. File will be skipped.",notSupportedObjectTypeError:n=>`Not supported object type ${n}`},EB=class{getType(r,i){let o=r.data;if(!o||!o.object_type){r.compilationOutput.push({message:cUe.unknownObjectTypeWarning,severity:"warning"}),i.file(r).addWarning(cUe.unknownObjectTypeWarning);return}if(!Object.values(dl).filter(p=>isNaN(Number(p))).includes(o.object_type)){i.file(r).addError(cUe.notSupportedObjectTypeError(o.object_type));return}return o.object_type}};var dkr=n=>Pa.hasProps("rawContent")&&(n.rawContent||"").length>0,Vae=n=>({relativePath:n.relativePath,compilationOutput:[],origin:n.origin,type:"Unknown",data:n.data,rawContent:n.rawContent,packageName:n.packageName}),UL=class{constructor(r={}){this.compilerSettings=r.compilerSettings||{amlFileExtensions:["yaml","yml"]},this.fileTypeValidationFactory=r.fileTypeValidationFactory||new Wae,this.yamlObjectTypeExtractor=r.yamlObjectTypeExtractor||new EB,this.fileParser=r.fileParser||new CB}parseFolderStructure(r,i){let o=r.files.find(b=>b.relativePath===W6.relativePath),l=o?this.parseFile(o,i):void 0,p=l?.data;o&&(r.files=r.files.filter(b=>b.relativePath!==W6.relativePath)??[]);let _=this.parseFolderStructureInternal(r,i,p);return l&&_.files.push(l),_}parseFolderStructureInternal(r,i,o,l=1){if(l>=50){let _=`Max folder depth exceed. Max folder depth is 50. Current folder path: ${r.path}`;throw i.global().addError(_),new V6(_)}let p={path:r.path,origin:r.origin,files:[],folders:[],packageName:r.packageName};return p.files=r.files.map(_=>this.parseFile(_,i,o)),p.folders=r.folders.map(_=>this.parseFolderStructureInternal(_,i,o,l+1)),p}getTextFile(r){return{...r,type:rh.Text,data:void 0}}getEnvFile(r,i){return{...r,type:rh.Environment,data:i}}parseFile(r,i,o){let l=[...this.compilerSettings.amlFileExtensions,RL,...CO];if(!this.hasValidExtension(l,r))return i.file(r).addInfo("File is not recognized as atscale file and will be skipped"),Vae(r);let p=this.compilerSettings.amlFileExtensions.includes(Ro.getExtensionFromPath(r.relativePath)||""),_=R1.isEnvFile(r);if(_&&!Ro.isFileOnRootLevel(r.relativePath)&&i.file(r).addWarning("Environment files should be on root level"),dkr(r)){let T=this.fileTypeValidationFactory.getValidator(r.relativePath).getErrors(r.rawContent);if(T.length>0)return T.forEach(j=>{i.file(r).addWarning(j)}),_?this.getEnvFile(r):p?this.getTextFile(r):Vae(r);let E={},k;try{E=this.fileParser.parse(r);let j=Ro.getExtensionFromPath(r.relativePath)||"";k=CO.includes(j)?void 0:this.yamlObjectTypeExtractor.getType(E,i),E=this.handleEnvironmentVariableInParsedFile({file:E,objectType:k,environmentVariables:o,validatorOutput:i})}catch(j){return i.file(r).addError(`File content is invalid. It cannot be parsed. ${qd.getErrorMessage(j)}`),_?this.getEnvFile(r):p?this.getTextFile(r):Vae(r)}return k?{...r,type:k,data:E.data}:_?this.getEnvFile(r,E.data):R1.isTextFile(r)||p?this.getTextFile(r):Vae(r)}else return _?(i.file(r).addWarning("Environment file is empty"),this.getEnvFile(r)):R1.isTextFile(r)?this.getTextFile(r):(i.file(r).addInfo("File has no rawContent and will be skipped"),Vae(r))}extractYamlFiles(r){let i=[];return Ik.traverse(r,o=>{if(R1.isYamlFile(o)&&this.hasValidExtension(this.compilerSettings.amlFileExtensions,o)){if(this.isFileTypeCatalog(o.type)&&o.origin!=="R")return;i.push(o)}}),i}hasValidExtension(r,i){let o=Ro.getExtensionFromPath(i.relativePath);return!!o&&r.includes(o)}getYamlFilesWithValidObjectType(r,i){let o=[];return r.forEach(l=>{R1.isYamlFile(l)&&this.yamlObjectTypeExtractor.getType(l,i)&&o.push(l)}),o}isFileTypeCatalog(r){return r===rh.Catalog}handleEnvironmentVariableInParsedFile({file:r,objectType:i,environmentVariables:o,validatorOutput:l}){if(!Exe(r.rawContent))return r;if(i&&!GJe.includes(i))return l.file(r).addError(`Variable placeholders (e.g., \${VARIABLE_NAME}) were detected in a ${i} file. Variable replacement is only supported for the following file types: ${GJe.join(", ")}.`),r;if(!o)return l.file(r).addError("Referenced variables were detected, but the .env file is absent. Please create the .env file with the necessary variables."),r;let _=r.data;try{_=this.replaceVariablesInData(r.data,o)}catch(b){return l.file(r).addError(qd.getErrorMessage(b)),r}return{...r,data:_}}replaceVariablesInData(r,i){return wxe(r,r.object_type,i)}};var cC="package.yml";var _kr=n=>`${n} is required`,lUe=class n{constructor(r){this.ErrorConstructor=r}forError(r){return new n(r)}should(r,i){if(!r)throw new this.ErrorConstructor(i)}exists(r,i){this.should(r!=null,i),typeof r=="number"&&this.should(!isNaN(r),i)}notEmpty(r,i){let o=r!=null&&r.trim()!=="";this.should(o,i)}allRequired(r){r.forEach(([i,o])=>{let l=_kr(o);typeof i=="string"&&this.notEmpty(i,l),this.exists(i,l)})}ensure(r,i){if(this.exists(r,i),!r)throw new this.ErrorConstructor(i);return r}ensureType(r,i,o){if(i(r))return r;throw new this.ErrorConstructor(o)}},zae=new lUe(Error),wB=zae;var mkr=function(n,r,i,o){function l(p){return p instanceof i?p:new i(function(_){_(p)})}return new(i||(i=Promise))(function(p,_){function b(k){try{E(o.next(k))}catch(j){_(j)}}function T(k){try{E(o.throw(k))}catch(j){_(j)}}function E(k){k.done?p(k.value):l(k.value).then(b,T)}E((o=o.apply(n,r||[])).next())})},hkr=n=>n?n instanceof Error?n.message:typeof n=="string"?n:`${n}`:"unknown error",kk={getErrorMessage(n,r){let i=hkr(n);return r?.removeStartString&&i.startsWith(r.removeStartString)?i.substring(r.removeStartString.length).trim():i},getError(n){return new Error(this.getErrorMessage(n))},hasErrorCode:n=>{if(!n)return!1;let r=n.code;return r?typeof r=="string":!1},executeQueryOrThrow(n){return mkr(this,void 0,void 0,function*(){try{return yield n()}catch(r){let i;if(r.response)try{i=(yield r.response.json()).message}catch(o){i=`Could not get json error. Error ${kk.getErrorMessage(o)}. Original error: ${kk.getErrorMessage(r)}`}else i=`Error: ${kk.getErrorMessage(r)}`;throw new Error(i)}})}},Fxe=kk;var FEt=function(n,r,i,o){function l(p){return p instanceof i?p:new i(function(_){_(p)})}return new(i||(i=Promise))(function(p,_){function b(k){try{E(o.next(k))}catch(j){_(j)}}function T(k){try{E(o.throw(k))}catch(j){_(j)}}function E(k){k.done?p(k.value):l(k.value).then(b,T)}E((o=o.apply(n,r||[])).next())})},uUe=class{wait(r=50){return FEt(this,void 0,void 0,function*(){return new Promise(i=>{setTimeout(()=>i(),r)})})}returnDelayed(r,i=300){return FEt(this,void 0,void 0,function*(){return yield this.wait(i),r})}},Uon=new uUe;var gkr={cloneFunctions:!1},rQ=class n{static deep(r,i={}){let o=Object.assign(Object.assign({},gkr),i);if(r==null)return r;let l=typeof r=="function";if(!l&&!(typeof r=="object"))return r;if(l)return o.cloneFunctions?r:void 0;if(Array.isArray(r))return r.map(_=>n.deep(_,o));if(r instanceof Date)return new Date(r.getTime());{let _={},b=Object.keys(r);for(let T of b)_[T]=n.deep(r[T],o);return _}}static cleanEmptyProperties(r){let i={};for(let o in r){let l=r[o];l===""||l===void 0||l===null||(typeof l=="object"?i[o]=n.cleanEmptyProperties(l):i[o]=l)}return i}};var ykr=/token/i,vkr=/password/i,bkr=/secret/i,REt=[ykr,vkr,bkr],fUe=class{constructor(){this.undefinedString="[undefined]",this.functionString="[function]",this.circularString="[Circular]",this.obfuscatedString="***"}obfuscate(r){return typeof r=="string"?r==null?this.obfuscatedString:r.length<=6?this.obfuscatedString:r.length<=9?`${this.obfuscatedString}${r.substring(r.length-3)}`:`${r.substring(0,3)}${this.obfuscatedString}${r.substring(r.length-3)}`:this.obfuscatedString}getMaxObjectDepthError(r){return`Max object depth (${r.maxObjectDepth}) exceeded. Current depth: ${r.currentDepth}`}obfuscateObject(r,i,o,l=1){if(l>i.maxObjectDepth)return this.getMaxObjectDepthError({maxObjectDepth:i.maxObjectDepth,currentDepth:l});if(r instanceof Date)return r.toISOString();if(r instanceof Map){let p={};for(let[_,b]of r.entries()){let T=typeof _=="string"?_:i.jsonSerialize(_);REt.some(E=>E.test(T))?p[T]=this.obfuscate(b):p[T]=this.obfuscateObject(b,i,o,l+1)}return p}if(r instanceof Set)return Array.from(r).map(p=>this.obfuscateObject(p,i,o,l+1));if(typeof r=="bigint")return r.toString();if(r===void 0)return i.serializeUndefined?this.undefinedString:r;if(typeof r=="function")return i.serializeFunctions?this.functionString:r;if(typeof r=="symbol")return i.serializeSymbols?r.toString():r;if(Array.isArray(r))return r.map(p=>this.obfuscateObject(p,i,o,l+1));if(r!==null&&typeof r=="object"){if(o.has(r))return this.circularString;o.add(r);let p={};for(let[_,b]of Object.entries(r))_.toLowerCase()!=="prototype"&&(typeof b=="function"&&!i.serializeFunctions||(typeof b=="string"&&REt.some(T=>T.test(_))?p[_]=this.obfuscate(b):p[_]=this.obfuscateObject(b,i,o,l+1)));return p}return r}safeToString(r,i){let l=Object.assign({serializeUndefined:!0,serializeFunctions:!1,serializeSymbols:!1,rethrowErrors:!1,maxObjectDepth:10,jsonSerialize:JSON.stringify},i??{});try{let p=new WeakSet,_=this.obfuscateObject(r,l,p);return l.jsonSerialize(_,null,l.space)}catch(p){let _=`Error serializing object: ${Fxe.getErrorMessage(p)}`;if(l.rethrowErrors)throw Error(_);return _}}},Kon=new fUe;var Skr="4d2cacb5-5b53-4da4-b120-709089990e91",pUe=class{generateNew(){return DB()}generateNewPredictable(r){return jL(r,Skr)}validate(r){return z6(r)}parse(r){return SB(r)}},dUe=new pUe;var Dkr=(n,r)=>{let i=r===void 0?"string":r,o=Object.keys(n).map(l=>n[l]);if(i==="string")return o;if(i==="number")return o.map(l=>parseInt(l)).filter(l=>!isNaN(l));throw new Error(`result type "${r}" is not supported in EnumUtil.getAllValues`)},xkr={getAllValues:Dkr},MEt=xkr;var WL;(function(n){n.Second="s",n.Minute="m",n.Hour="h",n.Day="d",n.Week="w"})(WL||(WL={}));var mcn=MEt.getAllValues(WL,"string");var hcn=[{unit:WL.Week,factor:1},{unit:WL.Day,factor:7},{unit:WL.Hour,factor:24},{unit:WL.Minute,factor:60},{unit:WL.Second,factor:60}];var jEt="\\",_Ue="/",LEt=[_Ue,jEt],mUe=class{constructor(){this._pathSeparator=typeof process<"u"&&process.platform==="win32"?jEt:_Ue,this._pathSeparatorChanged=!1}get pathSeparator(){return this._pathSeparator}set pathSeparator(r){wB.should(!this._pathSeparatorChanged,`Path separator is already changed to ${this._pathSeparator}. For protection it can be set only once.`),wB.should(LEt.includes(r),`Cannot set pathSeparator to '${r}'. It is invalid. It should be one of: ${LEt.join(",")}`),this._pathSeparatorChanged=!0,this._pathSeparator=r}joinTwo(r,i){if(r==="")return i;if(i==="")return r;let o=r.endsWith(this.pathSeparator)?r.slice(void 0,r.length-1):r,l=i.startsWith(this.pathSeparator)?i.slice(1):i;return`${o}${this.pathSeparator}${l}`}join(...r){return wB.ensure(r.length>1,"Cannot join path for less than two paths"),r.slice(1).reduce((i,o)=>this.joinTwo(i,o),r[0])}areEqual(r,i){if(r===i)return!0;if(r===void 0||i===void 0)return!1;let o=r.startsWith(this.pathSeparator)?r.substring(1):r,l=i.startsWith(this.pathSeparator)?i.substring(1):i;return o.endsWith(this.pathSeparator)&&(o=o.substring(0,o.length-1)),l.endsWith(this.pathSeparator)&&(l=l.substring(0,l.length-1)),o===l}getExtensionFromPath(r){let i=r.lastIndexOf(this.pathSeparator),o=i===-1?0:i+1,l=r.substring(o),p=l.lastIndexOf(".");if(!(p===-1||p===l.length-1))return l.substring(p+1)}getFileNameFromPath(r){let i=r.lastIndexOf(this.pathSeparator);return i!==-1?r.substring(i+1):r}getFileNameFromPathWithoutExtension(r){let i=this.getFileNameFromPath(r),o=this.getExtensionFromPath(r);return o?i.replace("."+o,""):i}isFileOnRootLevel(r){let i=r.lastIndexOf(this.pathSeparator);return i===-1?!0:!r.substring(0,i).length}getPath(r,i){let o=this.pathSeparator===_Ue,l=`${r}${i}`;return r.endsWith(this.pathSeparator)&&i.startsWith(this.pathSeparator)&&(l=`${r}${i.slice(1)}`),!r.endsWith(this.pathSeparator)&&!i.startsWith(this.pathSeparator)&&(l=`${r}${this.pathSeparator}${i}`),o&&!l.startsWith(this.pathSeparator)?`${this.pathSeparator}${l}`:l}getPathWithoutFileName(r){if(this.isFileOnRootLevel(r))return this.pathSeparator;let i=r.lastIndexOf(this.pathSeparator);return r.substring(0,i)}rewriteFolderPath(r,i){wB.ensure(r.startsWith(this.pathSeparator)&&r.endsWith(this.pathSeparator),"Path is not a folder path");let l=[...r.split(this.pathSeparator).filter(p=>p!=="").slice(0,-1),i];return`${this.pathSeparator}${l.join(this.pathSeparator)}${this.pathSeparator}`}getFolderPath(r,i){return`${r}${i}${this.pathSeparator}`}getFolders(r){let i=this.isFolderPath(r),o=r.split(this.pathSeparator).filter(l=>l!=="");return i?o:o.slice(0,-1)}isFolderPath(r){return r.endsWith(this.pathSeparator)}getParentFolderPath(r){let i=this.isFolderPath(r),o=this.getFolders(r);return o=i?o.slice(0,-1):o,`${o.join(this.pathSeparator)}${this.pathSeparator}`}},Tkr=new mUe;var hUe;(function(n){n.Info="Info",n.Warning="Warning",n.Error="Error"})(hUe||(hUe={}));var gUe=class extends Txe{constructor(r){super(r),this.version(1).stores({logs:`++id,
669
669
  timestamp,
670
670
  level,
671
- loggerName`})}},Ckr=new gUe("LogsDB");var qEt;(function(n){n.GsheetApiFetch="GsheetApiFetch",n.GsheetApiWrite="GsheetApiWrite",n.EngineQuery="EngineQuery",n.PrepareData="PrepareData"})(qEt||(qEt={}));function yUe(n){return n=n.replace(/^(https:\/\/|git@)/,""),n=n.replace(":","/"),n.replace(/\.git$/,"").toLowerCase()}var Rxe=class{constructor(r,i={}){this.data=r,this.cloneOptions=i}get clonedData(){return rQ.deep(this.data,this.cloneOptions)}with(r){let i=Object.assign(this.clonedData,r),o=Object.getPrototypeOf(this).constructor;return new o(i,this.cloneOptions)}mutate(r){let i=r(this.clonedData);return this.with(i)}build(){return this.clonedData}};var Q6=class n extends Rxe{static from(r,i={}){return new n(r,i)}static fromPartial(r,i={}){return new n(r,i)}};var Mxe;(function(n){n.Root="R",n.PackagesRoot="PR",n.Package="P"})(Mxe||(Mxe={}));var Gae="package.yml";var Lxe=class{constructor(r,i={}){this.data=r;this.cloneOptions=i}get clonedData(){return rQ.deep(this.data,this.cloneOptions)}with(r){let i=Object.assign(this.clonedData,r),o=Object.getPrototypeOf(this).constructor;return new o(i,this.cloneOptions)}mutate(r){let i=r(this.clonedData);return this.with(i)}build(){return this.clonedData}};var jxe=class n extends Lxe{static from(r,i={}){return new n(r,i)}static fromPartial(r,i={}){return new n(r,i)}};var nQ=class n extends jxe{static create(){let r={url:"http://shared-repo.git",name:"shared",branch:"develop",version:"1"};return new n(r)}with(r){return super.with(r)}version(r){return this.with({version:r})}name(r){return this.with({name:r})}withTestIdentifier(r){return this.with({branch:`branch-${r}`,name:r,url:`url-${r}`,version:`commit-${r}`})}static newCommit(r,i){return{name:r,commit:i}}};var wkr={added:[],modified:[],deleted:[]},qxe=class n extends Q6{static create(){return new n(wkr)}getPackages(...r){return r.map(i=>nQ.create().withTestIdentifier(i).build())}with(r){return super.with(r)}withModified(...r){return this.with({modified:this.getPackages(...r)})}withDeleted(...r){return this.with({deleted:this.getPackages(...r)})}withAdded(...r){return this.with({added:this.getPackages(...r)})}};var Bxe=class{constructor(r,i){this.fileService=r;this.logger=i}parsePackageConfig(r,i=!1){let o={packages:[],version:1};try{let l=CB.create().parseRawContent(r,"yml");if(typeof l!="object")throw Error("Invalid package format.");return l}catch(l){let p=`Error parsing packages config file. Original error: ${qd.getErrorMessage(l)}`;if(this.logger.error(p),i)throw Error(p);return o}}async getPackages(r){let i=[],o=Ro.getPath(r,cC);if(await this.fileService.doesFileExist(o))try{let p=await this.fileService.readFile(o);return this.parsePackageConfig(p).packages}catch(p){return this.logger.error(`Error reading packages config file. Original error: ${qd.getErrorMessage(p)}`),i}return i}getPackagesDiff(r,i){let o=qxe.create().build();return i.forEach(l=>{r.find(_=>_.name===l.name)||o.added.push(l)}),r.forEach(l=>{let p=i.find(_=>_.name===l.name);p?this.arePackagesEqual(l,p)||o.modified.push(p):o.deleted.push(l)}),o}arePackagesEqual(r,i){return r.url===i.url&&r.branch===i.branch&&r.name===i.name&&r.version===i.version}getPackageRepoPath(r,i){return`/${r.replace(new RegExp("/","g"),"").trim()}${i}_package`}parseVersion(r){return us.ensure(r.startsWith("commit:"),"invalid package version. Supported values: 'commit:sha'"),{commitId:r.replace("commit:","").trim()}}getNewCommitVersion(r){return`commit:${r}`}};var vUe=class{constructor(r){this.validator=r}add(r,i){this.validator.addGlobalOutput(r,i)}addError(r){this.add("error",r)}addWarning(r){this.add("warning",r)}addInfo(r){this.add("info",r)}},bUe=class{constructor(r,i){this.validator=r;this.file=i}get relativePath(){return typeof this.file=="string"?this.file:this.file.relativePath}add(r,i,o){this.validator.addFileOutput(this.relativePath,r,i,o)}addRaw(r){this.validator.addFileOutputRaw(this.relativePath,r)}addError(r,i){this.add("error",r,{fixAction:i})}addErrorWithContext(r,i){this.add("error",r,{context:i})}addWarning(r,i){this.add("warning",r,{fixAction:i})}addWarningWithContext(r,i){this.add("warning",r,{context:i})}addInfo(r){this.add("info",r)}},Mo=class n{constructor(r,i){this.hasGlobalMessage=r=>this.globalOutput.some(o=>o.message===r);this.hasFileWarningMessage=r=>this.filesOutput.some(o=>o.compilationOutput.some(l=>l.message===r&&l.severity==="warning"));this.hasFileErrorMessage=r=>this.filesOutput.some(o=>o.compilationOutput.some(l=>l.message===r&&l.severity==="error"));this.hasFileInfoMessage=r=>this.filesOutput.some(i=>i.compilationOutput.some(o=>o.message===r&&o.severity==="info"));this.globalOutput=r?.globalOutput||[],this.filesOutput=r?.filesOutput||[],this.validationSource=i}static create(r,i){return new n(r,i)}static createForEngine(){return new n(void 0,"engine")}addFileOutput(r,i,o,l){this.addFileOutputRaw(r,{severity:i,message:o,context:l?.context,fixAction:l?.fixAction,validationSource:this.validationSource})}addFileOutputRaw(r,i){let o=this.filesOutput.find(l=>l.relativePath===r);if(!o)this.filesOutput.push({relativePath:r,compilationOutput:[i]});else{if(o.compilationOutput.some(({message:p,severity:_})=>p===i.message&&_===i.severity))return;o.compilationOutput.push(i)}}addGlobalOutput(r,i){this.globalOutput.push({severity:r,message:i,validationSource:this.validationSource})}global(){return new vUe(this)}file(r){return new bUe(this,r)}getFileOutput(r,i){let o=typeof r=="string"?r:r.relativePath,l=this.filesOutput.find(p=>p.relativePath===o)?.compilationOutput||[];return i?l.filter(p=>p.severity===i):l}getFilesWithErrors(){return this.filesOutput.filter(r=>r.compilationOutput.some(i=>i.severity==="error"))}append(r){r.globalOutput.length>0&&this.globalOutput.push(...r.globalOutput),r.filesOutput.forEach(i=>{i.compilationOutput.forEach(o=>{this.file(i).addRaw(o)})})}get hasErrors(){return this.globalOutput.some(r=>r.severity==="error")||this.filesOutput.flatMap(r=>r.compilationOutput).some(r=>r.severity==="error")}get hasWarnings(){return this.globalOutput.some(r=>r.severity==="warning")||this.filesOutput.flatMap(r=>r.compilationOutput).some(r=>r.severity==="warning")}get hasInfos(){return this.globalOutput.some(r=>r.severity==="info")||this.filesOutput.flatMap(r=>r.compilationOutput).some(r=>r.severity==="info")}getFileOutputErrorCount(r){return this.getFileOutput(r,"error").length}get output(){return{filesOutput:this.filesOutput,globalOutput:this.globalOutput}}};var BEt="packages",$xe=class{constructor(r){this.getRepoNameFromFolderPath=r=>r.replace(/^\/|\/$/g,"");this.fileService=r.fileService,this.logger=r.logger,this.compilerSettings=r.compilerSettings||{amlFileExtensions:["yaml","yml"]},this.repoParser=r.repoParser||new UL,this.packageParser=r.packageParser||new Bxe(this.fileService,this.logger)}async parseFolder(r,i=Mo.create()){let o=await this.parseFolderRec(r,"",i,"R",ML,{}),l=await this.packageParser.getPackages(r);l.length>0&&await this.parsePackageFolders(o,i,l,r);let p=this.repoParser.parseFolderStructure(o,i);return p.origin="R",p}getPackagesRootFolder(){return{files:[],folders:[],origin:"PR",path:Ro.getFolderPath("",BEt),packageName:ML}}async parsePackageFolders(r,i,o,l){let p=this.getPackagesRootFolder();for(let _=0;_<o.length;_++){let b=o[_],T=Ro.getFolderPath(Ro.getFolderPath("",BEt),b.name),E={files:[],folders:[],origin:"P",path:T,packageName:b.name},k=this.packageParser.getPackageRepoPath(l,b.name),j=await this.fileService.isFolderExist(k);if(p.folders.push(E),j){let z={},X=await this.parseFolderRec(this.packageParser.getPackageRepoPath(this.getRepoNameFromFolderPath(l),b.name),"",i,"P",b.name,z,b.url);this.addPackageFiles(E,X,T)}}o.length>0&&r.folders.push(p)}addPackageFiles(r,i,o){i.files.forEach(l=>r.files.push({...l,relativePath:Ro.join(o,l.relativePath)})),i.folders.forEach(l=>{r.folders.push({...l,files:[],folders:[],path:Ro.join(o,l.path)})}),r.folders.forEach((l,p)=>{this.addPackageFiles(l,i.folders[p],o)})}async parseFolderRec(r,i,o,l,p,_,b){let T=Ro.getPath(r,i),E=await this.fileService.getFolders(T),k=await this.fileService.getFiles(T),j=await Promise.all(E.map(X=>this.parseFolderRec(r,Ro.getFolderPath(i,X),o,l,p,_,b)));return{files:await Promise.all(k.map(X=>{let ue=Ro.join(i,X);return this.parseFile(r,ue,o,l,p,_,b)})),folders:j,path:i,origin:l,packageName:p}}async parseFile(r,i,o,l,p,_,b){let T=Ro.getPath(r,i),E=Ro.getExtensionFromPath(i),k=E!==void 0&&this.compilerSettings.amlFileExtensions.includes(E),j=E!==void 0&&CO.includes(E),z=E!==void 0&&E===RL;if(!k&&!j&&!z){let De={compilationOutput:[],relativePath:i,type:rh.Unknown,origin:l,packageName:p};return o.file(De).addInfo("File is not recognized as atscale file and will be skipped"),De}let X;j?X=rh.Text:z?X=rh.Environment:X=rh.Unknown;let ue=await this.fileService.readFile(T);return{compilationOutput:[],type:X,rawContent:ue,relativePath:i,origin:l,packageName:p,packageUrl:b?this.getNormalizedGitUrl(_,b):void 0}}getNormalizedGitUrl(r,i){return r[i]||(r[i]=Cxe(i)),r[i]}};var $Et=n=>Pa.hasProps(n,"isFolderValidator");var Jxe=class{constructor(){this.validators=[]}addValidator(r){return this.validators.push({validator:r,canProceedOnError:!0}),this}addRequiredValidator(r){return this.validators.push({validator:r,canProceedOnError:!1}),this}addValidatorIfNoErrorsSoFar(r,i=!1){return this.validators.push({validator:r,canProceedOnError:i,requireNoErrors:!0}),this}validate(r,i){let o=Mo.create();for(let l=0;l<this.validators.length;l++){let p=this.validators[l];if(p.requireNoErrors&&o.hasErrors)break;let _;try{$Et(p.validator)?_=p.validator.validateFolderStructure(i):_=p.validator.validate(r)}catch(b){let T=qd.getErrorMessage(b);_=Mo.create(),_.addGlobalOutput("error",T)}if(o.append(_),!p.canProceedOnError&&_.hasErrors)break}return o}};var Pk=(ue=>(ue.Int="int",ue.Decimal="decimal",ue.Long="long",ue.Double="double",ue.Float="float",ue.String="string",ue.DateTime="datetime",ue.Date="date",ue.Boolean="boolean",ue.BigInt="bigint",ue.TinyInt="tinyint",ue.Number="number",ue.TimeStamp="timestamp",ue.Numeric="numeric",ue))(Pk||{}),Y6=(o=>(o.Numeric="numeric",o.Number="number",o.Decimal="decimal",o))(Y6||{});var iQ=(j=>(j.Year="year",j.HalfYear="halfyear",j.Trimester="trimester",j.Quarter="quarter",j.Month="month",j.Week="week",j.Day="day",j.Hour="hour",j.Minute="minute",j.Second="second",j.Undefined="undefined",j))(iQ||{});var sQ=(De=>(De.GeneralNumber="general number",De.Standard="standard",De.Scientific="scientific",De.Fixed="fixed",De.Percent="percent",De.GeneralDate="general date",De.LongDate="long date",De.MediumDate="medium date",De.ShortDate="short date",De.LongTime="long time",De.MediumTime="medium time",De.ShortTime="short time",De.YesNo="yes/no",De.TrueFalse="true/false",De.OnOff="on/off",De))(sQ||{});var Ikr=["version","unique_name","object_type","label","packages"],Gfn=[...Ikr,"name","description","url","branch"];var IO=(n,r)=>n.object_type===r,_l={isConnection(n){return IO(n,"connection")},isDataset(n){return IO(n,"dataset")},isDimension(n){return IO(n,"dimension")},isRowSecurity(n){return IO(n,"row_security")},isMetric(n){return IO(n,"metric")},isModel(n){return IO(n,"model")},isCompositeModel(n){return IO(n,"composite_model")},isMetricCalc(n){return IO(n,"metric_calc")},isCatalog(n){return IO(n,"catalog")},isGlobalSettings(n){return IO(n,"global_settings")}};var Zl=class n{static isSimpleColumn(r){return Pa.hasProps(r,"data_type")&&Pa.hasNoProps(r,"parent_column")}static isCalculatedColumn(r){return n.isSimpleColumn(r)&&(Pa.hasProps(r,"sql")||Pa.hasProps(r,"dialects"))}static isDerivedColumn(r){return Pa.hasProps(r,"data_type","parent_column")}static isMapColumn(r){return Pa.hasProps(r,"map")}static hasColumnDataTypeProp(r){return this.isSimpleColumn(r)||this.isDerivedColumn(r)}static hasDatasetSqlProp(r){return Pa.hasProps(r,"sql")}static isAlternateSql(r){return Pa.hasProps(r,"sql")&&Pa.hasNoProps(r,"connection_id")&&Pa.hasNoProps(r,"table")}static isAlternateTable(r){return Pa.hasProps(r,"connection_id")&&Pa.hasProps(r,"table")&&Pa.hasNoProps(r,"sql")}};var Bd;(function(n){n.assertEqual=l=>l;function r(l){}n.assertIs=r;function i(l){throw new Error}n.assertNever=i,n.arrayToEnum=l=>{let p={};for(let _ of l)p[_]=_;return p},n.getValidEnumValues=l=>{let p=n.objectKeys(l).filter(b=>typeof l[l[b]]!="number"),_={};for(let b of p)_[b]=l[b];return n.objectValues(_)},n.objectValues=l=>n.objectKeys(l).map(function(p){return l[p]}),n.objectKeys=typeof Object.keys=="function"?l=>Object.keys(l):l=>{let p=[];for(let _ in l)Object.prototype.hasOwnProperty.call(l,_)&&p.push(_);return p},n.find=(l,p)=>{for(let _ of l)if(p(_))return _},n.isInteger=typeof Number.isInteger=="function"?l=>Number.isInteger(l):l=>typeof l=="number"&&isFinite(l)&&Math.floor(l)===l;function o(l,p=" | "){return l.map(_=>typeof _=="string"?`'${_}'`:_).join(p)}n.joinValues=o,n.jsonStringifyReplacer=(l,p)=>typeof p=="bigint"?p.toString():p})(Bd||(Bd={}));var SUe;(function(n){n.mergeShapes=(r,i)=>({...r,...i})})(SUe||(SUe={}));var Vo=Bd.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),VL=n=>{switch(typeof n){case"undefined":return Vo.undefined;case"string":return Vo.string;case"number":return isNaN(n)?Vo.nan:Vo.number;case"boolean":return Vo.boolean;case"function":return Vo.function;case"bigint":return Vo.bigint;case"symbol":return Vo.symbol;case"object":return Array.isArray(n)?Vo.array:n===null?Vo.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Vo.promise:typeof Map<"u"&&n instanceof Map?Vo.map:typeof Set<"u"&&n instanceof Set?Vo.set:typeof Date<"u"&&n instanceof Date?Vo.date:Vo.object;default:return Vo.unknown}},Ra=Bd.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),kkr=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Z2=class extends Error{constructor(r){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=r}get errors(){return this.issues}format(r){let i=r||function(p){return p.message},o={_errors:[]},l=p=>{for(let _ of p.issues)if(_.code==="invalid_union")_.unionErrors.map(l);else if(_.code==="invalid_return_type")l(_.returnTypeError);else if(_.code==="invalid_arguments")l(_.argumentsError);else if(_.path.length===0)o._errors.push(i(_));else{let b=o,T=0;for(;T<_.path.length;){let E=_.path[T];T===_.path.length-1?(b[E]=b[E]||{_errors:[]},b[E]._errors.push(i(_))):b[E]=b[E]||{_errors:[]},b=b[E],T++}}};return l(this),o}toString(){return this.message}get message(){return JSON.stringify(this.issues,Bd.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(r=i=>i.message){let i={},o=[];for(let l of this.issues)l.path.length>0?(i[l.path[0]]=i[l.path[0]]||[],i[l.path[0]].push(r(l))):o.push(r(l));return{formErrors:o,fieldErrors:i}}get formErrors(){return this.flatten()}};Z2.create=n=>new Z2(n);var Hae=(n,r)=>{let i;switch(n.code){case Ra.invalid_type:n.received===Vo.undefined?i="Required":i=`Expected ${n.expected}, received ${n.received}`;break;case Ra.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,Bd.jsonStringifyReplacer)}`;break;case Ra.unrecognized_keys:i=`Unrecognized key(s) in object: ${Bd.joinValues(n.keys,", ")}`;break;case Ra.invalid_union:i="Invalid input";break;case Ra.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${Bd.joinValues(n.options)}`;break;case Ra.invalid_enum_value:i=`Invalid enum value. Expected ${Bd.joinValues(n.options)}, received '${n.received}'`;break;case Ra.invalid_arguments:i="Invalid function arguments";break;case Ra.invalid_return_type:i="Invalid function return type";break;case Ra.invalid_date:i="Invalid date";break;case Ra.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(i=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?i=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?i=`Invalid input: must end with "${n.validation.endsWith}"`:Bd.assertNever(n.validation):n.validation!=="regex"?i=`Invalid ${n.validation}`:i="Invalid";break;case Ra.too_small:n.type==="array"?i=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?i=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?i=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:i="Invalid input";break;case Ra.too_big:n.type==="array"?i=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?i=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?i=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?i=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?i=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:i="Invalid input";break;case Ra.custom:i="Invalid input";break;case Ra.invalid_intersection_types:i="Intersection results could not be merged";break;case Ra.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case Ra.not_finite:i="Number must be finite";break;default:i=r.defaultError,Bd.assertNever(n)}return{message:i}},WEt=Hae;function Pkr(n){WEt=n}function Wxe(){return WEt}var Vxe=n=>{let{data:r,path:i,errorMaps:o,issueData:l}=n,p=[...i,...l.path||[]],_={...l,path:p},b="",T=o.filter(E=>!!E).slice().reverse();for(let E of T)b=E(_,{data:r,defaultError:b}).message;return{...l,path:p,message:l.message||b}},Nkr=[];function ic(n,r){let i=Vxe({issueData:r,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Wxe(),Hae].filter(o=>!!o)});n.common.issues.push(i)}var XS=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,i){let o=[];for(let l of i){if(l.status==="aborted")return Lu;l.status==="dirty"&&r.dirty(),o.push(l.value)}return{status:r.value,value:o}}static async mergeObjectAsync(r,i){let o=[];for(let l of i)o.push({key:await l.key,value:await l.value});return n.mergeObjectSync(r,o)}static mergeObjectSync(r,i){let o={};for(let l of i){let{key:p,value:_}=l;if(p.status==="aborted"||_.status==="aborted")return Lu;p.status==="dirty"&&r.dirty(),_.status==="dirty"&&r.dirty(),p.value!=="__proto__"&&(typeof _.value<"u"||l.alwaysSet)&&(o[p.value]=_.value)}return{status:r.value,value:o}}},Lu=Object.freeze({status:"aborted"}),VEt=n=>({status:"dirty",value:n}),xx=n=>({status:"valid",value:n}),DUe=n=>n.status==="aborted",xUe=n=>n.status==="dirty",Qae=n=>n.status==="valid",zxe=n=>typeof Promise<"u"&&n instanceof Promise,Sl;(function(n){n.errToObj=r=>typeof r=="string"?{message:r}:r||{},n.toString=r=>typeof r=="string"?r:r?.message})(Sl||(Sl={}));var fA=class{constructor(r,i,o,l){this._cachedPath=[],this.parent=r,this.data=i,this._path=o,this._key=l}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},JEt=(n,r)=>{if(Qae(r))return{success:!0,data:r.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let i=new Z2(n.common.issues);return this._error=i,this._error}}};function tf(n){if(!n)return{};let{errorMap:r,invalid_type_error:i,required_error:o,description:l}=n;if(r&&(i||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return r?{errorMap:r,description:l}:{errorMap:(_,b)=>_.code!=="invalid_type"?{message:b.defaultError}:typeof b.data>"u"?{message:o??b.defaultError}:{message:i??b.defaultError},description:l}}var rf=class{constructor(r){this.spa=this.safeParseAsync,this._def=r,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(r){return VL(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:VL(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new XS,ctx:{common:r.parent.common,data:r.data,parsedType:VL(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){let i=this._parse(r);if(zxe(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(r){let i=this._parse(r);return Promise.resolve(i)}parse(r,i){let o=this.safeParse(r,i);if(o.success)return o.data;throw o.error}safeParse(r,i){var o;let l={common:{issues:[],async:(o=i?.async)!==null&&o!==void 0?o:!1,contextualErrorMap:i?.errorMap},path:i?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:VL(r)},p=this._parseSync({data:r,path:l.path,parent:l});return JEt(l,p)}async parseAsync(r,i){let o=await this.safeParseAsync(r,i);if(o.success)return o.data;throw o.error}async safeParseAsync(r,i){let o={common:{issues:[],contextualErrorMap:i?.errorMap,async:!0},path:i?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:VL(r)},l=this._parse({data:r,path:o.path,parent:o}),p=await(zxe(l)?l:Promise.resolve(l));return JEt(o,p)}refine(r,i){let o=l=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(l):i;return this._refinement((l,p)=>{let _=r(l),b=()=>p.addIssue({code:Ra.custom,...o(l)});return typeof Promise<"u"&&_ instanceof Promise?_.then(T=>T?!0:(b(),!1)):_?!0:(b(),!1)})}refinement(r,i){return this._refinement((o,l)=>r(o)?!0:(l.addIssue(typeof i=="function"?i(o,l):i),!1))}_refinement(r){return new eE({schema:this,typeName:eu.ZodEffects,effect:{type:"refinement",refinement:r}})}superRefine(r){return this._refinement(r)}optional(){return Nk.create(this,this._def)}nullable(){return Z6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return X6.create(this,this._def)}promise(){return HL.create(this,this._def)}or(r){return FB.create([this,r],this._def)}and(r){return RB.create(this,r,this._def)}transform(r){return new eE({...tf(this._def),schema:this,typeName:eu.ZodEffects,effect:{type:"transform",transform:r}})}default(r){let i=typeof r=="function"?r:()=>r;return new BB({...tf(this._def),innerType:this,defaultValue:i,typeName:eu.ZodDefault})}brand(){return new Yxe({typeName:eu.ZodBranded,type:this,...tf(this._def)})}catch(r){let i=typeof r=="function"?r:()=>r;return new fQ({...tf(this._def),innerType:this,catchValue:i,typeName:eu.ZodCatch})}describe(r){let i=this.constructor;return new i({...this._def,description:r})}pipe(r){return Yae.create(this,r)}readonly(){return dQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Okr=/^c[^\s-]{8,}$/i,Fkr=/^[a-z][a-z0-9]*$/,Rkr=/[0-9A-HJKMNP-TV-Z]{26}/,Mkr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Lkr=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jkr=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,qkr=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Bkr=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,$kr=n=>n.precision?n.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${n.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${n.precision}}Z$`):n.precision===0?n.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):n.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function Jkr(n,r){return!!((r==="v4"||!r)&&qkr.test(n)||(r==="v6"||!r)&&Bkr.test(n))}var zL=class n extends rf{constructor(){super(...arguments),this._regex=(r,i,o)=>this.refinement(l=>r.test(l),{validation:i,code:Ra.invalid_string,...Sl.errToObj(o)}),this.nonempty=r=>this.min(1,Sl.errToObj(r)),this.trim=()=>new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==Vo.string){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.string,received:p.parsedType}),Lu}let o=new XS,l;for(let p of this._def.checks)if(p.kind==="min")r.data.length<p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty());else if(p.kind==="max")r.data.length>p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty());else if(p.kind==="length"){let _=r.data.length>p.value,b=r.data.length<p.value;(_||b)&&(l=this._getOrReturnCtx(r,l),_?ic(l,{code:Ra.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message}):b&&ic(l,{code:Ra.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message}),o.dirty())}else if(p.kind==="email")Lkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"email",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="emoji")jkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"emoji",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="uuid")Mkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"uuid",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="cuid")Okr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"cuid",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="cuid2")Fkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"cuid2",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="ulid")Rkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"ulid",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="url")try{new URL(r.data)}catch{l=this._getOrReturnCtx(r,l),ic(l,{validation:"url",code:Ra.invalid_string,message:p.message}),o.dirty()}else p.kind==="regex"?(p.regex.lastIndex=0,p.regex.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"regex",code:Ra.invalid_string,message:p.message}),o.dirty())):p.kind==="trim"?r.data=r.data.trim():p.kind==="includes"?r.data.includes(p.value,p.position)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:{includes:p.value,position:p.position},message:p.message}),o.dirty()):p.kind==="toLowerCase"?r.data=r.data.toLowerCase():p.kind==="toUpperCase"?r.data=r.data.toUpperCase():p.kind==="startsWith"?r.data.startsWith(p.value)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:{startsWith:p.value},message:p.message}),o.dirty()):p.kind==="endsWith"?r.data.endsWith(p.value)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:{endsWith:p.value},message:p.message}),o.dirty()):p.kind==="datetime"?$kr(p).test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:"datetime",message:p.message}),o.dirty()):p.kind==="ip"?Jkr(r.data,p.version)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"ip",code:Ra.invalid_string,message:p.message}),o.dirty()):Bd.assertNever(p);return{status:o.value,value:r.data}}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...Sl.errToObj(r)})}url(r){return this._addCheck({kind:"url",...Sl.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...Sl.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...Sl.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...Sl.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...Sl.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...Sl.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...Sl.errToObj(r)})}datetime(r){var i;return typeof r=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:r}):this._addCheck({kind:"datetime",precision:typeof r?.precision>"u"?null:r?.precision,offset:(i=r?.offset)!==null&&i!==void 0?i:!1,...Sl.errToObj(r?.message)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...Sl.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i?.position,...Sl.errToObj(i?.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...Sl.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...Sl.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...Sl.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...Sl.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...Sl.errToObj(i)})}get isDatetime(){return!!this._def.checks.find(r=>r.kind==="datetime")}get isEmail(){return!!this._def.checks.find(r=>r.kind==="email")}get isURL(){return!!this._def.checks.find(r=>r.kind==="url")}get isEmoji(){return!!this._def.checks.find(r=>r.kind==="emoji")}get isUUID(){return!!this._def.checks.find(r=>r.kind==="uuid")}get isCUID(){return!!this._def.checks.find(r=>r.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(r=>r.kind==="cuid2")}get isULID(){return!!this._def.checks.find(r=>r.kind==="ulid")}get isIP(){return!!this._def.checks.find(r=>r.kind==="ip")}get minLength(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxLength(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}};zL.create=n=>{var r;return new zL({checks:[],typeName:eu.ZodString,coerce:(r=n?.coerce)!==null&&r!==void 0?r:!1,...tf(n)})};function Ukr(n,r){let i=(n.toString().split(".")[1]||"").length,o=(r.toString().split(".")[1]||"").length,l=i>o?i:o,p=parseInt(n.toFixed(l).replace(".","")),_=parseInt(r.toFixed(l).replace(".",""));return p%_/Math.pow(10,l)}var AB=class n extends rf{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==Vo.number){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.number,received:p.parsedType}),Lu}let o,l=new XS;for(let p of this._def.checks)p.kind==="int"?Bd.isInteger(r.data)||(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.invalid_type,expected:"integer",received:"float",message:p.message}),l.dirty()):p.kind==="min"?(p.inclusive?r.data<p.value:r.data<=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_small,minimum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),l.dirty()):p.kind==="max"?(p.inclusive?r.data>p.value:r.data>=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_big,maximum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),l.dirty()):p.kind==="multipleOf"?Ukr(r.data,p.value)!==0&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.not_multiple_of,multipleOf:p.value,message:p.message}),l.dirty()):p.kind==="finite"?Number.isFinite(r.data)||(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.not_finite,message:p.message}),l.dirty()):Bd.assertNever(p);return{status:l.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,Sl.toString(i))}gt(r,i){return this.setLimit("min",r,!1,Sl.toString(i))}lte(r,i){return this.setLimit("max",r,!0,Sl.toString(i))}lt(r,i){return this.setLimit("max",r,!1,Sl.toString(i))}setLimit(r,i,o,l){return new n({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:o,message:Sl.toString(l)}]})}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:Sl.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Sl.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Sl.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Sl.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Sl.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:Sl.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:Sl.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Sl.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Sl.toString(r)})}get minValue(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}get isInt(){return!!this._def.checks.find(r=>r.kind==="int"||r.kind==="multipleOf"&&Bd.isInteger(r.value))}get isFinite(){let r=null,i=null;for(let o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(i===null||o.value>i)&&(i=o.value):o.kind==="max"&&(r===null||o.value<r)&&(r=o.value)}return Number.isFinite(i)&&Number.isFinite(r)}};AB.create=n=>new AB({checks:[],typeName:eu.ZodNumber,coerce:n?.coerce||!1,...tf(n)});var IB=class n extends rf{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce&&(r.data=BigInt(r.data)),this._getType(r)!==Vo.bigint){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.bigint,received:p.parsedType}),Lu}let o,l=new XS;for(let p of this._def.checks)p.kind==="min"?(p.inclusive?r.data<p.value:r.data<=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_small,type:"bigint",minimum:p.value,inclusive:p.inclusive,message:p.message}),l.dirty()):p.kind==="max"?(p.inclusive?r.data>p.value:r.data>=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_big,type:"bigint",maximum:p.value,inclusive:p.inclusive,message:p.message}),l.dirty()):p.kind==="multipleOf"?r.data%p.value!==BigInt(0)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.not_multiple_of,multipleOf:p.value,message:p.message}),l.dirty()):Bd.assertNever(p);return{status:l.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,Sl.toString(i))}gt(r,i){return this.setLimit("min",r,!1,Sl.toString(i))}lte(r,i){return this.setLimit("max",r,!0,Sl.toString(i))}lt(r,i){return this.setLimit("max",r,!1,Sl.toString(i))}setLimit(r,i,o,l){return new n({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:o,message:Sl.toString(l)}]})}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Sl.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Sl.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Sl.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Sl.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:Sl.toString(i)})}get minValue(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}};IB.create=n=>{var r;return new IB({checks:[],typeName:eu.ZodBigInt,coerce:(r=n?.coerce)!==null&&r!==void 0?r:!1,...tf(n)})};var kB=class extends rf{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==Vo.boolean){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.boolean,received:o.parsedType}),Lu}return xx(r.data)}};kB.create=n=>new kB({typeName:eu.ZodBoolean,coerce:n?.coerce||!1,...tf(n)});var PB=class n extends rf{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==Vo.date){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.date,received:p.parsedType}),Lu}if(isNaN(r.data.getTime())){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_date}),Lu}let o=new XS,l;for(let p of this._def.checks)p.kind==="min"?r.data.getTime()<p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_small,message:p.message,inclusive:!0,exact:!1,minimum:p.value,type:"date"}),o.dirty()):p.kind==="max"?r.data.getTime()>p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_big,message:p.message,inclusive:!0,exact:!1,maximum:p.value,type:"date"}),o.dirty()):Bd.assertNever(p);return{status:o.value,value:new Date(r.data.getTime())}}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:Sl.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:Sl.toString(i)})}get minDate(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r!=null?new Date(r):null}get maxDate(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r!=null?new Date(r):null}};PB.create=n=>new PB({checks:[],coerce:n?.coerce||!1,typeName:eu.ZodDate,...tf(n)});var oQ=class extends rf{_parse(r){if(this._getType(r)!==Vo.symbol){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.symbol,received:o.parsedType}),Lu}return xx(r.data)}};oQ.create=n=>new oQ({typeName:eu.ZodSymbol,...tf(n)});var NB=class extends rf{_parse(r){if(this._getType(r)!==Vo.undefined){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.undefined,received:o.parsedType}),Lu}return xx(r.data)}};NB.create=n=>new NB({typeName:eu.ZodUndefined,...tf(n)});var OB=class extends rf{_parse(r){if(this._getType(r)!==Vo.null){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.null,received:o.parsedType}),Lu}return xx(r.data)}};OB.create=n=>new OB({typeName:eu.ZodNull,...tf(n)});var GL=class extends rf{constructor(){super(...arguments),this._any=!0}_parse(r){return xx(r.data)}};GL.create=n=>new GL({typeName:eu.ZodAny,...tf(n)});var K6=class extends rf{constructor(){super(...arguments),this._unknown=!0}_parse(r){return xx(r.data)}};K6.create=n=>new K6({typeName:eu.ZodUnknown,...tf(n)});var Ok=class extends rf{_parse(r){let i=this._getOrReturnCtx(r);return ic(i,{code:Ra.invalid_type,expected:Vo.never,received:i.parsedType}),Lu}};Ok.create=n=>new Ok({typeName:eu.ZodNever,...tf(n)});var cQ=class extends rf{_parse(r){if(this._getType(r)!==Vo.undefined){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.void,received:o.parsedType}),Lu}return xx(r.data)}};cQ.create=n=>new cQ({typeName:eu.ZodVoid,...tf(n)});var X6=class n extends rf{_parse(r){let{ctx:i,status:o}=this._processInputParams(r),l=this._def;if(i.parsedType!==Vo.array)return ic(i,{code:Ra.invalid_type,expected:Vo.array,received:i.parsedType}),Lu;if(l.exactLength!==null){let _=i.data.length>l.exactLength.value,b=i.data.length<l.exactLength.value;(_||b)&&(ic(i,{code:_?Ra.too_big:Ra.too_small,minimum:b?l.exactLength.value:void 0,maximum:_?l.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:l.exactLength.message}),o.dirty())}if(l.minLength!==null&&i.data.length<l.minLength.value&&(ic(i,{code:Ra.too_small,minimum:l.minLength.value,type:"array",inclusive:!0,exact:!1,message:l.minLength.message}),o.dirty()),l.maxLength!==null&&i.data.length>l.maxLength.value&&(ic(i,{code:Ra.too_big,maximum:l.maxLength.value,type:"array",inclusive:!0,exact:!1,message:l.maxLength.message}),o.dirty()),i.common.async)return Promise.all([...i.data].map((_,b)=>l.type._parseAsync(new fA(i,_,i.path,b)))).then(_=>XS.mergeArray(o,_));let p=[...i.data].map((_,b)=>l.type._parseSync(new fA(i,_,i.path,b)));return XS.mergeArray(o,p)}get element(){return this._def.type}min(r,i){return new n({...this._def,minLength:{value:r,message:Sl.toString(i)}})}max(r,i){return new n({...this._def,maxLength:{value:r,message:Sl.toString(i)}})}length(r,i){return new n({...this._def,exactLength:{value:r,message:Sl.toString(i)}})}nonempty(r){return this.min(1,r)}};X6.create=(n,r)=>new X6({type:n,minLength:null,maxLength:null,exactLength:null,typeName:eu.ZodArray,...tf(r)});function aQ(n){if(n instanceof lC){let r={};for(let i in n.shape){let o=n.shape[i];r[i]=Nk.create(aQ(o))}return new lC({...n._def,shape:()=>r})}else return n instanceof X6?new X6({...n._def,type:aQ(n.element)}):n instanceof Nk?Nk.create(aQ(n.unwrap())):n instanceof Z6?Z6.create(aQ(n.unwrap())):n instanceof kO?kO.create(n.items.map(r=>aQ(r))):n}var lC=class n extends rf{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let r=this._def.shape(),i=Bd.objectKeys(r);return this._cached={shape:r,keys:i}}_parse(r){if(this._getType(r)!==Vo.object){let E=this._getOrReturnCtx(r);return ic(E,{code:Ra.invalid_type,expected:Vo.object,received:E.parsedType}),Lu}let{status:o,ctx:l}=this._processInputParams(r),{shape:p,keys:_}=this._getCached(),b=[];if(!(this._def.catchall instanceof Ok&&this._def.unknownKeys==="strip"))for(let E in l.data)_.includes(E)||b.push(E);let T=[];for(let E of _){let k=p[E],j=l.data[E];T.push({key:{status:"valid",value:E},value:k._parse(new fA(l,j,l.path,E)),alwaysSet:E in l.data})}if(this._def.catchall instanceof Ok){let E=this._def.unknownKeys;if(E==="passthrough")for(let k of b)T.push({key:{status:"valid",value:k},value:{status:"valid",value:l.data[k]}});else if(E==="strict")b.length>0&&(ic(l,{code:Ra.unrecognized_keys,keys:b}),o.dirty());else if(E!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let E=this._def.catchall;for(let k of b){let j=l.data[k];T.push({key:{status:"valid",value:k},value:E._parse(new fA(l,j,l.path,k)),alwaysSet:k in l.data})}}return l.common.async?Promise.resolve().then(async()=>{let E=[];for(let k of T){let j=await k.key;E.push({key:j,value:await k.value,alwaysSet:k.alwaysSet})}return E}).then(E=>XS.mergeObjectSync(o,E)):XS.mergeObjectSync(o,T)}get shape(){return this._def.shape()}strict(r){return Sl.errToObj,new n({...this._def,unknownKeys:"strict",...r!==void 0?{errorMap:(i,o)=>{var l,p,_,b;let T=(_=(p=(l=this._def).errorMap)===null||p===void 0?void 0:p.call(l,i,o).message)!==null&&_!==void 0?_:o.defaultError;return i.code==="unrecognized_keys"?{message:(b=Sl.errToObj(r).message)!==null&&b!==void 0?b:T}:{message:T}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(r){return new n({...this._def,shape:()=>({...this._def.shape(),...r})})}merge(r){return new n({unknownKeys:r._def.unknownKeys,catchall:r._def.catchall,shape:()=>({...this._def.shape(),...r._def.shape()}),typeName:eu.ZodObject})}setKey(r,i){return this.augment({[r]:i})}catchall(r){return new n({...this._def,catchall:r})}pick(r){let i={};return Bd.objectKeys(r).forEach(o=>{r[o]&&this.shape[o]&&(i[o]=this.shape[o])}),new n({...this._def,shape:()=>i})}omit(r){let i={};return Bd.objectKeys(this.shape).forEach(o=>{r[o]||(i[o]=this.shape[o])}),new n({...this._def,shape:()=>i})}deepPartial(){return aQ(this)}partial(r){let i={};return Bd.objectKeys(this.shape).forEach(o=>{let l=this.shape[o];r&&!r[o]?i[o]=l:i[o]=l.optional()}),new n({...this._def,shape:()=>i})}required(r){let i={};return Bd.objectKeys(this.shape).forEach(o=>{if(r&&!r[o])i[o]=this.shape[o];else{let p=this.shape[o];for(;p instanceof Nk;)p=p._def.innerType;i[o]=p}}),new n({...this._def,shape:()=>i})}keyof(){return zEt(Bd.objectKeys(this.shape))}};lC.create=(n,r)=>new lC({shape:()=>n,unknownKeys:"strip",catchall:Ok.create(),typeName:eu.ZodObject,...tf(r)});lC.strictCreate=(n,r)=>new lC({shape:()=>n,unknownKeys:"strict",catchall:Ok.create(),typeName:eu.ZodObject,...tf(r)});lC.lazycreate=(n,r)=>new lC({shape:n,unknownKeys:"strip",catchall:Ok.create(),typeName:eu.ZodObject,...tf(r)});var FB=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o=this._def.options;function l(p){for(let b of p)if(b.result.status==="valid")return b.result;for(let b of p)if(b.result.status==="dirty")return i.common.issues.push(...b.ctx.common.issues),b.result;let _=p.map(b=>new Z2(b.ctx.common.issues));return ic(i,{code:Ra.invalid_union,unionErrors:_}),Lu}if(i.common.async)return Promise.all(o.map(async p=>{let _={...i,common:{...i.common,issues:[]},parent:null};return{result:await p._parseAsync({data:i.data,path:i.path,parent:_}),ctx:_}})).then(l);{let p,_=[];for(let T of o){let E={...i,common:{...i.common,issues:[]},parent:null},k=T._parseSync({data:i.data,path:i.path,parent:E});if(k.status==="valid")return k;k.status==="dirty"&&!p&&(p={result:k,ctx:E}),E.common.issues.length&&_.push(E.common.issues)}if(p)return i.common.issues.push(...p.ctx.common.issues),p.result;let b=_.map(T=>new Z2(T));return ic(i,{code:Ra.invalid_union,unionErrors:b}),Lu}}get options(){return this._def.options}};FB.create=(n,r)=>new FB({options:n,typeName:eu.ZodUnion,...tf(r)});var Uxe=n=>n instanceof MB?Uxe(n.schema):n instanceof eE?Uxe(n.innerType()):n instanceof LB?[n.value]:n instanceof jB?n.options:n instanceof qB?Object.keys(n.enum):n instanceof BB?Uxe(n._def.innerType):n instanceof NB?[void 0]:n instanceof OB?[null]:null,Gxe=class n extends rf{_parse(r){let{ctx:i}=this._processInputParams(r);if(i.parsedType!==Vo.object)return ic(i,{code:Ra.invalid_type,expected:Vo.object,received:i.parsedType}),Lu;let o=this.discriminator,l=i.data[o],p=this.optionsMap.get(l);return p?i.common.async?p._parseAsync({data:i.data,path:i.path,parent:i}):p._parseSync({data:i.data,path:i.path,parent:i}):(ic(i,{code:Ra.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),Lu)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(r,i,o){let l=new Map;for(let p of i){let _=Uxe(p.shape[r]);if(!_)throw new Error(`A discriminator value for key \`${r}\` could not be extracted from all schema options`);for(let b of _){if(l.has(b))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(b)}`);l.set(b,p)}}return new n({typeName:eu.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:l,...tf(o)})}};function TUe(n,r){let i=VL(n),o=VL(r);if(n===r)return{valid:!0,data:n};if(i===Vo.object&&o===Vo.object){let l=Bd.objectKeys(r),p=Bd.objectKeys(n).filter(b=>l.indexOf(b)!==-1),_={...n,...r};for(let b of p){let T=TUe(n[b],r[b]);if(!T.valid)return{valid:!1};_[b]=T.data}return{valid:!0,data:_}}else if(i===Vo.array&&o===Vo.array){if(n.length!==r.length)return{valid:!1};let l=[];for(let p=0;p<n.length;p++){let _=n[p],b=r[p],T=TUe(_,b);if(!T.valid)return{valid:!1};l.push(T.data)}return{valid:!0,data:l}}else return i===Vo.date&&o===Vo.date&&+n==+r?{valid:!0,data:n}:{valid:!1}}var RB=class extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r),l=(p,_)=>{if(DUe(p)||DUe(_))return Lu;let b=TUe(p.value,_.value);return b.valid?((xUe(p)||xUe(_))&&i.dirty(),{status:i.value,value:b.data}):(ic(o,{code:Ra.invalid_intersection_types}),Lu)};return o.common.async?Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([p,_])=>l(p,_)):l(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}};RB.create=(n,r,i)=>new RB({left:n,right:r,typeName:eu.ZodIntersection,...tf(i)});var kO=class n extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.array)return ic(o,{code:Ra.invalid_type,expected:Vo.array,received:o.parsedType}),Lu;if(o.data.length<this._def.items.length)return ic(o,{code:Ra.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Lu;!this._def.rest&&o.data.length>this._def.items.length&&(ic(o,{code:Ra.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());let p=[...o.data].map((_,b)=>{let T=this._def.items[b]||this._def.rest;return T?T._parse(new fA(o,_,o.path,b)):null}).filter(_=>!!_);return o.common.async?Promise.all(p).then(_=>XS.mergeArray(i,_)):XS.mergeArray(i,p)}get items(){return this._def.items}rest(r){return new n({...this._def,rest:r})}};kO.create=(n,r)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new kO({items:n,typeName:eu.ZodTuple,rest:null,...tf(r)})};var Hxe=class n extends rf{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.object)return ic(o,{code:Ra.invalid_type,expected:Vo.object,received:o.parsedType}),Lu;let l=[],p=this._def.keyType,_=this._def.valueType;for(let b in o.data)l.push({key:p._parse(new fA(o,b,o.path,b)),value:_._parse(new fA(o,o.data[b],o.path,b))});return o.common.async?XS.mergeObjectAsync(i,l):XS.mergeObjectSync(i,l)}get element(){return this._def.valueType}static create(r,i,o){return i instanceof rf?new n({keyType:r,valueType:i,typeName:eu.ZodRecord,...tf(o)}):new n({keyType:zL.create(),valueType:r,typeName:eu.ZodRecord,...tf(i)})}},lQ=class extends rf{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.map)return ic(o,{code:Ra.invalid_type,expected:Vo.map,received:o.parsedType}),Lu;let l=this._def.keyType,p=this._def.valueType,_=[...o.data.entries()].map(([b,T],E)=>({key:l._parse(new fA(o,b,o.path,[E,"key"])),value:p._parse(new fA(o,T,o.path,[E,"value"]))}));if(o.common.async){let b=new Map;return Promise.resolve().then(async()=>{for(let T of _){let E=await T.key,k=await T.value;if(E.status==="aborted"||k.status==="aborted")return Lu;(E.status==="dirty"||k.status==="dirty")&&i.dirty(),b.set(E.value,k.value)}return{status:i.value,value:b}})}else{let b=new Map;for(let T of _){let E=T.key,k=T.value;if(E.status==="aborted"||k.status==="aborted")return Lu;(E.status==="dirty"||k.status==="dirty")&&i.dirty(),b.set(E.value,k.value)}return{status:i.value,value:b}}}};lQ.create=(n,r,i)=>new lQ({valueType:r,keyType:n,typeName:eu.ZodMap,...tf(i)});var uQ=class n extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.set)return ic(o,{code:Ra.invalid_type,expected:Vo.set,received:o.parsedType}),Lu;let l=this._def;l.minSize!==null&&o.data.size<l.minSize.value&&(ic(o,{code:Ra.too_small,minimum:l.minSize.value,type:"set",inclusive:!0,exact:!1,message:l.minSize.message}),i.dirty()),l.maxSize!==null&&o.data.size>l.maxSize.value&&(ic(o,{code:Ra.too_big,maximum:l.maxSize.value,type:"set",inclusive:!0,exact:!1,message:l.maxSize.message}),i.dirty());let p=this._def.valueType;function _(T){let E=new Set;for(let k of T){if(k.status==="aborted")return Lu;k.status==="dirty"&&i.dirty(),E.add(k.value)}return{status:i.value,value:E}}let b=[...o.data.values()].map((T,E)=>p._parse(new fA(o,T,o.path,E)));return o.common.async?Promise.all(b).then(T=>_(T)):_(b)}min(r,i){return new n({...this._def,minSize:{value:r,message:Sl.toString(i)}})}max(r,i){return new n({...this._def,maxSize:{value:r,message:Sl.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}};uQ.create=(n,r)=>new uQ({valueType:n,minSize:null,maxSize:null,typeName:eu.ZodSet,...tf(r)});var Qxe=class n extends rf{constructor(){super(...arguments),this.validate=this.implement}_parse(r){let{ctx:i}=this._processInputParams(r);if(i.parsedType!==Vo.function)return ic(i,{code:Ra.invalid_type,expected:Vo.function,received:i.parsedType}),Lu;function o(b,T){return Vxe({data:b,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Wxe(),Hae].filter(E=>!!E),issueData:{code:Ra.invalid_arguments,argumentsError:T}})}function l(b,T){return Vxe({data:b,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Wxe(),Hae].filter(E=>!!E),issueData:{code:Ra.invalid_return_type,returnTypeError:T}})}let p={errorMap:i.common.contextualErrorMap},_=i.data;if(this._def.returns instanceof HL){let b=this;return xx(async function(...T){let E=new Z2([]),k=await b._def.args.parseAsync(T,p).catch(X=>{throw E.addIssue(o(T,X)),E}),j=await Reflect.apply(_,this,k);return await b._def.returns._def.type.parseAsync(j,p).catch(X=>{throw E.addIssue(l(j,X)),E})})}else{let b=this;return xx(function(...T){let E=b._def.args.safeParse(T,p);if(!E.success)throw new Z2([o(T,E.error)]);let k=Reflect.apply(_,this,E.data),j=b._def.returns.safeParse(k,p);if(!j.success)throw new Z2([l(k,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new n({...this._def,args:kO.create(r).rest(K6.create())})}returns(r){return new n({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,o){return new n({args:r||kO.create([]).rest(K6.create()),returns:i||K6.create(),typeName:eu.ZodFunction,...tf(o)})}},MB=class extends rf{get schema(){return this._def.getter()}_parse(r){let{ctx:i}=this._processInputParams(r);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}};MB.create=(n,r)=>new MB({getter:n,typeName:eu.ZodLazy,...tf(r)});var LB=class extends rf{_parse(r){if(r.data!==this._def.value){let i=this._getOrReturnCtx(r);return ic(i,{received:i.data,code:Ra.invalid_literal,expected:this._def.value}),Lu}return{status:"valid",value:r.data}}get value(){return this._def.value}};LB.create=(n,r)=>new LB({value:n,typeName:eu.ZodLiteral,...tf(r)});function zEt(n,r){return new jB({values:n,typeName:eu.ZodEnum,...tf(r)})}var jB=class n extends rf{_parse(r){if(typeof r.data!="string"){let i=this._getOrReturnCtx(r),o=this._def.values;return ic(i,{expected:Bd.joinValues(o),received:i.parsedType,code:Ra.invalid_type}),Lu}if(this._def.values.indexOf(r.data)===-1){let i=this._getOrReturnCtx(r),o=this._def.values;return ic(i,{received:i.data,code:Ra.invalid_enum_value,options:o}),Lu}return xx(r.data)}get options(){return this._def.values}get enum(){let r={};for(let i of this._def.values)r[i]=i;return r}get Values(){let r={};for(let i of this._def.values)r[i]=i;return r}get Enum(){let r={};for(let i of this._def.values)r[i]=i;return r}extract(r){return n.create(r)}exclude(r){return n.create(this.options.filter(i=>!r.includes(i)))}};jB.create=zEt;var qB=class extends rf{_parse(r){let i=Bd.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(r);if(o.parsedType!==Vo.string&&o.parsedType!==Vo.number){let l=Bd.objectValues(i);return ic(o,{expected:Bd.joinValues(l),received:o.parsedType,code:Ra.invalid_type}),Lu}if(i.indexOf(r.data)===-1){let l=Bd.objectValues(i);return ic(o,{received:o.data,code:Ra.invalid_enum_value,options:l}),Lu}return xx(r.data)}get enum(){return this._def.values}};qB.create=(n,r)=>new qB({values:n,typeName:eu.ZodNativeEnum,...tf(r)});var HL=class extends rf{unwrap(){return this._def.type}_parse(r){let{ctx:i}=this._processInputParams(r);if(i.parsedType!==Vo.promise&&i.common.async===!1)return ic(i,{code:Ra.invalid_type,expected:Vo.promise,received:i.parsedType}),Lu;let o=i.parsedType===Vo.promise?i.data:Promise.resolve(i.data);return xx(o.then(l=>this._def.type.parseAsync(l,{path:i.path,errorMap:i.common.contextualErrorMap})))}};HL.create=(n,r)=>new HL({type:n,typeName:eu.ZodPromise,...tf(r)});var eE=class extends rf{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===eu.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(r){let{status:i,ctx:o}=this._processInputParams(r),l=this._def.effect||null,p={addIssue:_=>{ic(o,_),_.fatal?i.abort():i.dirty()},get path(){return o.path}};if(p.addIssue=p.addIssue.bind(p),l.type==="preprocess"){let _=l.transform(o.data,p);return o.common.issues.length?{status:"dirty",value:o.data}:o.common.async?Promise.resolve(_).then(b=>this._def.schema._parseAsync({data:b,path:o.path,parent:o})):this._def.schema._parseSync({data:_,path:o.path,parent:o})}if(l.type==="refinement"){let _=b=>{let T=l.refinement(b,p);if(o.common.async)return Promise.resolve(T);if(T instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return b};if(o.common.async===!1){let b=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});return b.status==="aborted"?Lu:(b.status==="dirty"&&i.dirty(),_(b.value),{status:i.value,value:b.value})}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(b=>b.status==="aborted"?Lu:(b.status==="dirty"&&i.dirty(),_(b.value).then(()=>({status:i.value,value:b.value}))))}if(l.type==="transform")if(o.common.async===!1){let _=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!Qae(_))return _;let b=l.transform(_.value,p);if(b instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:b}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(_=>Qae(_)?Promise.resolve(l.transform(_.value,p)).then(b=>({status:i.value,value:b})):_);Bd.assertNever(l)}};eE.create=(n,r,i)=>new eE({schema:n,typeName:eu.ZodEffects,effect:r,...tf(i)});eE.createWithPreprocess=(n,r,i)=>new eE({schema:r,effect:{type:"preprocess",transform:n},typeName:eu.ZodEffects,...tf(i)});var Nk=class extends rf{_parse(r){return this._getType(r)===Vo.undefined?xx(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}};Nk.create=(n,r)=>new Nk({innerType:n,typeName:eu.ZodOptional,...tf(r)});var Z6=class extends rf{_parse(r){return this._getType(r)===Vo.null?xx(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}};Z6.create=(n,r)=>new Z6({innerType:n,typeName:eu.ZodNullable,...tf(r)});var BB=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o=i.data;return i.parsedType===Vo.undefined&&(o=this._def.defaultValue()),this._def.innerType._parse({data:o,path:i.path,parent:i})}removeDefault(){return this._def.innerType}};BB.create=(n,r)=>new BB({innerType:n,typeName:eu.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...tf(r)});var fQ=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o={...i,common:{...i.common,issues:[]}},l=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return zxe(l)?l.then(p=>({status:"valid",value:p.status==="valid"?p.value:this._def.catchValue({get error(){return new Z2(o.common.issues)},input:o.data})})):{status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new Z2(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};fQ.create=(n,r)=>new fQ({innerType:n,typeName:eu.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...tf(r)});var pQ=class extends rf{_parse(r){if(this._getType(r)!==Vo.nan){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.nan,received:o.parsedType}),Lu}return{status:"valid",value:r.data}}};pQ.create=n=>new pQ({typeName:eu.ZodNaN,...tf(n)});var Wkr=Symbol("zod_brand"),Yxe=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o=i.data;return this._def.type._parse({data:o,path:i.path,parent:i})}unwrap(){return this._def.type}},Yae=class n extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.common.async)return(async()=>{let p=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return p.status==="aborted"?Lu:p.status==="dirty"?(i.dirty(),VEt(p.value)):this._def.out._parseAsync({data:p.value,path:o.path,parent:o})})();{let l=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return l.status==="aborted"?Lu:l.status==="dirty"?(i.dirty(),{status:"dirty",value:l.value}):this._def.out._parseSync({data:l.value,path:o.path,parent:o})}}static create(r,i){return new n({in:r,out:i,typeName:eu.ZodPipeline})}},dQ=class extends rf{_parse(r){let i=this._def.innerType._parse(r);return Qae(i)&&(i.value=Object.freeze(i.value)),i}};dQ.create=(n,r)=>new dQ({innerType:n,typeName:eu.ZodReadonly,...tf(r)});var GEt=(n,r={},i)=>n?GL.create().superRefine((o,l)=>{var p,_;if(!n(o)){let b=typeof r=="function"?r(o):typeof r=="string"?{message:r}:r,T=(_=(p=b.fatal)!==null&&p!==void 0?p:i)!==null&&_!==void 0?_:!0,E=typeof b=="string"?{message:b}:b;l.addIssue({code:"custom",...E,fatal:T})}}):GL.create(),Vkr={object:lC.lazycreate},eu;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(eu||(eu={}));var zkr=(n,r={message:`Input not instance of ${n.name}`})=>GEt(i=>i instanceof n,r),HEt=zL.create,QEt=AB.create,Gkr=pQ.create,Hkr=IB.create,YEt=kB.create,Qkr=PB.create,Ykr=oQ.create,Kkr=NB.create,Xkr=OB.create,Zkr=GL.create,ePr=K6.create,tPr=Ok.create,rPr=cQ.create,nPr=X6.create,iPr=lC.create,sPr=lC.strictCreate,aPr=FB.create,oPr=Gxe.create,cPr=RB.create,lPr=kO.create,uPr=Hxe.create,fPr=lQ.create,pPr=uQ.create,dPr=Qxe.create,_Pr=MB.create,mPr=LB.create,hPr=jB.create,gPr=qB.create,yPr=HL.create,UEt=eE.create,vPr=Nk.create,bPr=Z6.create,SPr=eE.createWithPreprocess,DPr=Yae.create,xPr=()=>HEt().optional(),TPr=()=>QEt().optional(),CPr=()=>YEt().optional(),EPr={string:(n=>zL.create({...n,coerce:!0})),number:(n=>AB.create({...n,coerce:!0})),boolean:(n=>kB.create({...n,coerce:!0})),bigint:(n=>IB.create({...n,coerce:!0})),date:(n=>PB.create({...n,coerce:!0}))},wPr=Lu,Cl=Object.freeze({__proto__:null,defaultErrorMap:Hae,setErrorMap:Pkr,getErrorMap:Wxe,makeIssue:Vxe,EMPTY_PATH:Nkr,addIssueToContext:ic,ParseStatus:XS,INVALID:Lu,DIRTY:VEt,OK:xx,isAborted:DUe,isDirty:xUe,isValid:Qae,isAsync:zxe,get util(){return Bd},get objectUtil(){return SUe},ZodParsedType:Vo,getParsedType:VL,ZodType:rf,ZodString:zL,ZodNumber:AB,ZodBigInt:IB,ZodBoolean:kB,ZodDate:PB,ZodSymbol:oQ,ZodUndefined:NB,ZodNull:OB,ZodAny:GL,ZodUnknown:K6,ZodNever:Ok,ZodVoid:cQ,ZodArray:X6,ZodObject:lC,ZodUnion:FB,ZodDiscriminatedUnion:Gxe,ZodIntersection:RB,ZodTuple:kO,ZodRecord:Hxe,ZodMap:lQ,ZodSet:uQ,ZodFunction:Qxe,ZodLazy:MB,ZodLiteral:LB,ZodEnum:jB,ZodNativeEnum:qB,ZodPromise:HL,ZodEffects:eE,ZodTransformer:eE,ZodOptional:Nk,ZodNullable:Z6,ZodDefault:BB,ZodCatch:fQ,ZodNaN:pQ,BRAND:Wkr,ZodBranded:Yxe,ZodPipeline:Yae,ZodReadonly:dQ,custom:GEt,Schema:rf,ZodSchema:rf,late:Vkr,get ZodFirstPartyTypeKind(){return eu},coerce:EPr,any:Zkr,array:nPr,bigint:Hkr,boolean:YEt,date:Qkr,discriminatedUnion:oPr,effect:UEt,enum:hPr,function:dPr,instanceof:zkr,intersection:cPr,lazy:_Pr,literal:mPr,map:fPr,nan:Gkr,nativeEnum:gPr,never:tPr,null:Xkr,nullable:bPr,number:QEt,object:iPr,oboolean:CPr,onumber:TPr,optional:vPr,ostring:xPr,pipeline:DPr,preprocess:SPr,promise:yPr,record:uPr,set:pPr,strictObject:sPr,string:HEt,symbol:Ykr,transformer:UEt,tuple:lPr,undefined:Kkr,union:aPr,unknown:ePr,void:rPr,NEVER:wPr,ZodIssueCode:Ra,quotelessJson:kkr,ZodError:Z2});var L1=Cl.string().min(1),tE=Cl.string().max(0),_Q=Cl.object({unique_name:Cl.string()}),APr=_Q.extend({from:Cl.object({dataset:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({dimension:L1,level:Cl.string()})}),IPr=_Q.extend({from:Cl.object({dataset:L1,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({dimension:tE,level:tE})}),kPr=_Q.extend({from:Cl.object({dataset:L1,join_columns:Cl.array(Cl.string())}),to:Cl.object({row_security:tE})}),PPr=_Q.extend({from:Cl.object({dataset:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({row_security:L1})}),KEt=_Q.extend({from:Cl.object({dataset:L1,hierarchy:Cl.string(),level:Cl.string(),join_columns:Cl.array(Cl.string())}),to:Cl.object({row_security:tE})}),XEt=_Q.extend({from:Cl.object({dataset:tE,hierarchy:tE,level:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({row_security:L1})}),NPr=Cl.object({from:Cl.object({dataset:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({level:L1})}),OPr=Cl.object({from:Cl.object({dataset:L1,join_columns:Cl.array(Cl.string())}),to:Cl.object({level:tE})}),FPr=XEt.extend({to:Cl.object({level:Cl.string(),dimension:Cl.string()})}),RPr=KEt.extend({to:Cl.object({level:tE,dimension:tE})}),ZEt=APr.or(IPr),ewt=PPr.or(kPr),twt=NPr.or(OPr),rwt=FPr.or(RPr),nwt=XEt.or(KEt);var ki=class{static isOrphanRelation(r){return twt.safeParse(r).success||rwt.safeParse(r).success||nwt.safeParse(r).success}static isSnowflakeRelation(r){return r.type==="snowflake"}static isEmbeddedRelation(r){return r.type==="embedded"}static isSecurityRelation(r){return Pa.hasProps(r.to,"row_security")&&Pa.hasNoProps(r.to,"level")}static isLevelWithMultipleDatasets(r){return Pa.hasProps(r,"shared_degenerate_columns")}static isLevelFromOneDataset(r){return!Pa.hasProps(r,"shared_degenerate_columns")}static isRegularRelation(r){return Pa.hasProps(r.to,"level")&&Pa.hasNoProps(r.to,"row_security")}static hasHierarchyProp(r){return Pa.hasProps(r.from,"hierarchy")&&Pa.hasNoProps(r.to,"row_security")}static isModelRegularRelationship(r){return Pa.hasProps(r.to,"dimension","level")&&Pa.hasNoProps(r.from,"hierarchy")}};var mQ=class{static isCalcMetric=r=>Pa.hasProps(r,"expression")&&Pa.hasNoProps(r,"dataset","column");static isRegularMetric=r=>Pa.hasProps(r,"dataset","column")&&Pa.hasNoProps(r,"expression")};var Ic=class{static isSecurityRelation=r=>Pa.hasProps(r.to,"row_security")&&Pa.hasNoProps(r.to,"level");static isRegularRelation=r=>Pa.hasProps(r.to,"level")&&Pa.hasNoProps(r.to,"row_security");static hasDimensionProp=r=>Pa.hasProps(r.to,"dimension")&&Pa.hasNoProps(r.to,"row_security");static hasNoHierarchyProp=r=>Pa.hasNoProps(r.from,"hierarchy");static isOrphanRelation=r=>ZEt.safeParse(r).success||ewt.safeParse(r).success};var hQ=class{static hasDatasetProp(r){return Pa.hasProps(r,"dataset")}};function QL(n){return"dimension"in n}function gQ(n){return"row_security"in n}function YL(n){return"dimension"in n&&"name"in n}var vQ=n=>["count distinct","sum distinct","estimated count distinct","count non-null"].includes(n);var iwt;(function(n){n.Yes="yes",n.No="no",n.Always="always"})(iwt||(iwt={}));var swt;(function(n){n.Time="time",n.Standard="standard"})(swt||(swt={}));var awt;(function(n){n.Year="year",n.HalfYear="halfyear",n.Trimester="trimester",n.Quarter="quarter",n.Month="month",n.Week="week",n.Day="day",n.Hour="hour",n.Minute="minute",n.Second="second",n.Undefined="undefined"})(awt||(awt={}));var Xae;(function(n){n.Embedded="embedded",n.Snowflake="snowflake"})(Xae||(Xae={}));var owt;(function(n){n.RightOpenInterval="right_open_interval",n.LeftOpenInterval="left_open_interval",n.Closed="closed"})(owt||(owt={}));var cwt=50,pA=class{constructor(){this.filterRelationships=r=>r?.filter(i=>{if(i.type===Xae.Snowflake)return i.from.dataset.length>0;if(ki.isRegularRelation(i))return i.from.dataset.length>0&&i.to.dimension.length>0;if(ki.isSecurityRelation(i))return i.from.dataset.length>0&&i.to.row_security})||[]}sortYamlModels(r){let i={connections:new Map,datasets:new Map,dimensions:new Map,measures:new Map,models:new Map,calculations:new Map,rowSecurity:new Map,compositeModels:new Map};return r.forEach(o=>{this.setYamlFileToRepoObjects(i,o)}),i}getModelDimensions(r,i){let o=this.getMapElementsByList(this.getUnique(r),i);return o.forEach(l=>{this.addEmbeddedDimensions(i,l,o)}),o}getModelRowSecurityList(r,i){return this.getMapElementsByList(this.getUnique(r),i)}getCatalogUsedDimensions(r){let i=[],o=this.sortYamlModels(this.getYamlFilesWithoutDetachedRelationships(r));o.models.forEach(p=>{let _=this.getModelDimensions(p.relationships.filter(Ic.isRegularRelation).map(b=>b.to.dimension).concat(p.dimensions||[]),o.dimensions);i.push(..._)});let l=this.getUnique(i.map(p=>p.unique_name));return r.filter(({data:{unique_name:p}})=>l.includes(p))}addEmbeddedDimensions(r,i,o,l=[],p=0){if(p>cwt)throw new V6(`Max recursive depth exceeded. Dimension Path: ${l.join(" -> ")}`);if(l.includes(i.unique_name))return;let _=[];if(i.relationships?.forEach(b=>{b.type===Xae.Embedded&&ki.isRegularRelation(b)&&_.push(b.to.dimension)}),_.length){let b=this.getMapElementsByList(_,r);b.forEach(T=>this.addEmbeddedDimensions(r,T,o,[...l,i.unique_name],p++)),b.forEach(T=>{o.some(k=>k.unique_name===T.unique_name)||o.push(T)})}}getMapElementsByList(r,i,o){let l=[];return r.reduce((p,_)=>{let b=i.get(_);return o||zae.exists(b,`Yaml Item "${_}" do not exist.`),b&&p.push(b),p},l)}getMetricsByList(r,i,o){let l=[];return r.reduce((p,_)=>{let b=i.get(_.unique_name);return o||zae.exists(b,`Yaml Item "${_.unique_name}" do not exist.`),b&&p.push(b),p},l)}getModelDatasets(r,i,o,l){let p=i.reduce((k,j)=>[...k,...j.level_attributes],[]),_=p.filter(ki.isLevelFromOneDataset).map(({dataset:k})=>k),b=p.filter(ki.isLevelWithMultipleDatasets).flatMap(({shared_degenerate_columns:k})=>k).map(({dataset:k})=>k),T=[..._,...b,...o.map(k=>k.from.dataset),...l.map(k=>k.dataset)],E=this.getUnique(T);return this.getMapElementsByList(E,r)}getAllDatasets(r){return Array.from(r.values())}getYamlFilesWithoutDetachedRelationships(r){return r.map(i=>{let o=i.data;return!o.relationships||o.relationships.length===0?i:{...i,data:{...o,relationships:this.filterRelationships(o.relationships)}}})}getAllDataWarehouseConnectionsUsedInRepo(r){let i=new Map;return Array.from(r.models.values()).forEach(o=>{if(o.unique_name){let l=this.getAllConnectionUniqueNamesUsedInModel(o,r).map(p=>r.connections.get(p)).filter(this.filterUndefined).map(p=>p.as_connection);i.set(o.unique_name,this.getUnique(l))}}),i}getAllEmbeddedRelationshipsFromProject(r){return r.dimensions?.reduce((i,o)=>(o.embeddedRelationshipsMetadata&&i.push(...o.embeddedRelationshipsMetadata),i),[])??[]}getModelDatasetsUniqueNamesUsedInAnyChildObject(r,i){let o=r.relationships.map(T=>T.from.dataset),l=[],p=[];r.relationships.forEach(T=>{Ic.isRegularRelation(T)&&l.push(T.to.dimension),Ic.isSecurityRelation(T)&&p.push(T.to.row_security)});let _=l.map(T=>i.dimensions.get(T)).filter(T=>T!==void 0).flatMap(T=>this.getDimensionDatasetUniqueNamesInAnyChildObject(T,i)),b=p.map(T=>i.rowSecurity.get(T)).filter(T=>T!==void 0).flatMap(T=>T?.dataset);return this.getUnique([...o,..._,...b])}setYamlFileToRepoObjects(r,i){let o=i.data.unique_name;switch(zae.ensure(!r.models.has(o),`${i.data.object_type} with uniqueName ${o} already exists`),i.data.object_type){case Hh.Connection:r.connections.set(o,i.data);break;case Hh.Dataset:r.datasets.set(o,i.data);break;case Hh.Dimension:r.dimensions.set(o,i.data);break;case Hh.RowSecurity:r.rowSecurity.set(o,i.data);break;case Hh.Metric:r.measures.set(o,i.data);break;case Hh.MetricCalc:r.calculations.set(o,i.data);break;case Hh.Model:r.models.set(o,i.data);break;case Hh.CompositeModel:r.compositeModels.set(o,i.data);break}}getDimensionDatasetUniqueNamesInAnyChildObject(r,i,o=[],l=1){if(o.some(z=>z.unique_name===r.unique_name))return[];if(l>cwt)return[];let p=this.filterUndefinedArray(r.relationships?.map(z=>z.from.dataset)),_=[],b=[],T=[];(r.relationships||[]).forEach(z=>{_.push(z.from.dataset),ki.isRegularRelation(z)&&ki.isEmbeddedRelation(z)&&b.push(z.to.dimension),ki.isSecurityRelation(z)&&T.push(z.to.row_security)});let E=b.map(z=>i.dimensions.get(z)).filter(this.filterUndefined).flatMap(z=>this.getDimensionDatasetUniqueNamesInAnyChildObject(z,i,[...o,r],l++)),k=T.map(z=>i.rowSecurity.get(z)).filter(this.filterUndefined).flatMap(z=>z.dataset),j=r.hierarchies.flatMap(z=>z.levels.flatMap(X=>{let ue=r.level_attributes.find(ht=>ht.unique_name===X.unique_name),De=ue?ki.isLevelWithMultipleDatasets(ue)?ue.shared_degenerate_columns.map(({dataset:ht})=>ht):[ue.dataset]:[],Je=this.filterUndefinedArray(X.aliases?.map(ht=>ht.dataset)),$e=this.filterUndefinedArray(X.secondary_attributes?.map(ht=>ht.dataset)),Ke=this.filterUndefinedArray(X.metrics?.map(ht=>ht.dataset));return this.filterUndefinedArray([...De,...Je,...$e,...Ke,...k])}));return this.getUnique([...p,...j,..._,...E])}getAllConnectionUniqueNamesUsedInModel(r,i){return this.getUnique(this.getModelDatasetsUniqueNamesUsedInAnyChildObject(r,i).map(o=>i.datasets.get(o)).filter(this.filterUndefined).map(o=>o.connection_id))}filterUndefinedArray(r){return r===void 0?[]:r.filter(this.filterUndefined)}filterUndefined(r){return r!==void 0}getUnique(r){return Array.from(new Set(r))}};var rl=class{static groupBy(r,i){return r.reduce((o,l)=>{let p=JSON.stringify(i(l)),_=o.get(p)||[];return _.push(l),o.set(p,_),o},new Map)}static appendErrorsIfDuplicates(r,i,o){this.processDuplicates(r,l=>{let p=o(l[0],l.length);i.addError(p)})}static appendErrorsWithContextIfDuplicates(r,i,o,l){let{getContext:p,hierarchyUniqueName:_}=l;this.processDuplicates(r,b=>{let T=o(b[0],b.length),E=p(b[0],_);i.addErrorWithContext(T,E)})}static processDuplicates(r,i){Array.from(r.values()).filter(o=>o.length>1).forEach(i)}static checkIfDuplicateNameExists(r){return new Set(r).size!==r.length}static findCommonElement(r){if(r.length<2)return null;let i=[...r],o=i.splice(0,1)[0];for(let l of o)if(i.every(p=>p.has(l)))return l;return null}};var lwt={duplicateCalcGroupNameInDimension:()=>"There are Calculation Groups with duplicated names",duplicateCalcGroupNamesInDimensions:(n,r)=>`Calculation Group${n.length>1?"s":""} ${n.join(", ")} also occur in dimension: ${r}`},Kxe=class n{constructor(r){this.yamlQueries=r}static create(r=new pA){return new n(r)}validate(r){let i=Mo.create(),o=this.yamlQueries.getCatalogUsedDimensions(r),l=this.getMapCalcGroup(o);return this.validateCalcGroupNames(l,o,i),i}getMapCalcGroup(r){return r.reduce((i,o)=>{let l=o.data,p=l.unique_name,_=l.calculation_groups?.map(T=>T.unique_name)||[],b=[...i.get(p)||[],..._];return i.set(p,b),i},new Map)}validateCalcGroupNames(r,i,o){r.forEach((l,p)=>{let _=us.ensure(i.find(b=>b.data.unique_name===p),"Dimension file not exist");rl.checkIfDuplicateNameExists(l)&&o.file(_).addError(lwt.duplicateCalcGroupNameInDimension()),r.forEach((b,T)=>{if(p!==T){let E=b.filter(k=>l.includes(k));E.length>0&&o.file(_).addError(lwt.duplicateCalcGroupNamesInDimensions(E,T))}})})}};var MPr={getMultiDwError:(n,r)=>`Multi data-warehouse connections are used in model "${n}". Only one datawarehouse should be used per model. Data-warehouse connection ids: ${r.join(",")}`},Xxe=class n{constructor(r){this.yamlQueries=r}static create(r=new pA){return new n(r)}validate(r){let i=this.yamlQueries.sortYamlModels(r),o=this.yamlQueries.getAllDataWarehouseConnectionsUsedInRepo(i),l=Mo.create();return o.forEach((p,_)=>{p.length>1&&l.global().addError(MPr.getMultiDwError(_,p))}),l}};var PO=(n,r)=>n.object_type===r,uC={isConnection(n){return PO(n,Hh.Connection)},isDataset(n){return PO(n,Hh.Dataset)},isDimension(n){return PO(n,Hh.Dimension)},isRowSecurity(n){return PO(n,Hh.RowSecurity)},isMetric(n){return PO(n,Hh.Metric)},isModel(n){return PO(n,Hh.Model)},isCompositeModel(n){return PO(n,Hh.CompositeModel)},isMetricCalc(n){return PO(n,Hh.MetricCalc)},isCatalog(n){return PO(n,Hh.Catalog)},isGlobalSettings(n){return PO(n,Hh.GlobalSettings)}};var KL=n=>n.filter(r=>uC.isModel(r.data)||uC.isCompositeModel(r.data)),NO=n=>n.filter(r=>uC.isDimension(r.data)),Zxe=n=>n.reduce((r,i)=>(r.set(i.data.unique_name,i),r),new Map);var eTe=class{getDependencyCycleError(r){return`Dependency cycle detected ${r.join(" -> ")}`}checkDependencyCycles(r,i){try{let o=new Set;r.forEach(l=>{this.traverseDimensions(l,r,i,o)})}catch(o){let l=qd.getErrorMessage(o);i.addGlobalOutput("warning",`Dimension cycle dependency check failed. ${l}`)}}traverseDimensions(r,i,o,l,p=[]){let _=p.indexOf(r.data.unique_name),b=[...p,r.data.unique_name];if(_>=0){o.file(r).addWarning(this.getDependencyCycleError(b.slice(_)));return}l.has(r.data.unique_name)||(l.add(r.data.unique_name),r.data.relationships&&(r.data.relationships||[]).forEach(T=>{if(ki.isRegularRelation(T)&&ki.isEmbeddedRelation(T)){let E=i.find(k=>k.data.unique_name===T.to.dimension);if(!E)return;this.traverseDimensions(E,i,o,l,b)}}))}};var CUe={getDuplicateDegenerateDimensionsWarning(n,r){return`The "${n}" combination is used in multiple degenerate dimensions: ${nh(r)}.`},getRelationshipInDimensionError:({object:n,orphanType:r})=>`There is an unrelated ${r} in the dimension - "${n||"unknown"}".`},tTe=class n{constructor(r,i=new eTe){this.yamlDegenerateDimensionUtil=r;this.dimensionCircularReferenceValidator=i}static create(r){return new n(r)}validate(r){let i=Mo.create();return this.verifyDimensionFiles(r,i),i}verifyDimensionFiles(r,i,o=NO){let l=o(r);this.verifyDegenerateDimensions(l,i),this.dimensionCircularReferenceValidator.checkDependencyCycles(l,i)}verifyDegenerateDimensions(r,i){this.yamlDegenerateDimensionUtil.getDuplicatedDegenerateDimensions(r).forEach((l,p)=>{l.length>1&&l.forEach(_=>i.file(_).addWarning(CUe.getDuplicateDegenerateDimensionsWarning(p,l.map(b=>b.data.unique_name))))})}};var bQ={missing:"Missing file with name catalog, in the root folder",moreThanOne:"There are more than one files from type catalog in the root folder",notInRoot:"file is not located in the root folder",objectTypeMissing:"object_type is missing",notCorrectObjType:"the file name suggests its object_type to be catalog",notCorrectFileName:"the file object_type suggests its name to be catalog"},uwt={atscaleFileDeprecated:"atscale.yml is deprecated, please rename the file to catalog.yml"},rTe={deprecated:["atscale.yaml","atscale.yml"],unique:["catalog.yaml","catalog.yml"],get all(){return[...this.unique,...this.deprecated]}},nTe=class n{constructor(){this.isFolderValidator=!0}static create(){return new n}validateFolderStructure(r){let i=Mo.create();return this.verifyCatalogFile(r,i),i}validateFileObjectType(r,i){!r.data||Pa.hasNoProps(r.data,"object_type")?i.file(r).addError(bQ.objectTypeMissing):_l.isCatalog(r.data)||i.file(r).addError(bQ.notCorrectObjType)}getCountFromRoot(r,i,o){let l=0;return r.forEach(p=>{let _=Ro.getFileNameFromPath(p.relativePath);i.includes(_)&&(this.validateFileObjectType(p,o),l++)}),l}checkSubFoldersForCatalogFiles(r,i){if(!Ro.isFileOnRootLevel(r.relativePath)&&r.origin==="R"){let o=Ro.getFileNameFromPath(r.relativePath);rTe.all.includes(o)&&i.file(r).addError(bQ.notInRoot)}}validateFileNamesByObjectType(r,i){if(r.data?.object_type==="catalog"){let o=Ro.getFileNameFromPath(r.relativePath);rTe.all.includes(o)||i.file(r).addError(bQ.notCorrectFileName)}}isNoCatalogFiles(r,i){return r===0&&i===0}isTooManyCatalogFiles(r,i){return r>1||i>1||r===1&&i===1}isOnlyDeprecatedCatalogFile(r,i){return r===0&&i===1}handleTooManyCatalogFiles(r){r.addGlobalOutput("error",bQ.moreThanOne),r.addGlobalOutput("warning",uwt.atscaleFileDeprecated)}handleDeprecatedCatalogFile(r,i){i.addGlobalOutput("warning",uwt.atscaleFileDeprecated),this.processFiles(r,i)}processFiles(r,i){Ik.traverse(r,o=>{this.checkSubFoldersForCatalogFiles(o,i),this.validateFileNamesByObjectType(o,i)})}async verifyCatalogFile(r,i){let o=this.getCountFromRoot(r.files,rTe.unique,i),l=this.getCountFromRoot(r.files,rTe.deprecated,i);this.isNoCatalogFiles(o,l)?i.addGlobalOutput("error",bQ.missing):this.isTooManyCatalogFiles(o,l)?this.handleTooManyCatalogFiles(i):this.isOnlyDeprecatedCatalogFile(o,l)?this.handleDeprecatedCatalogFile(r,i):this.processFiles(r,i)}};var iTe=_u(eoe()),DQ=(n,r)=>n?.toLocaleLowerCase()===r?.toLocaleLowerCase(),fwt=n=>(0,iTe.uniqWith)(n,iTe.isEqual).length===1;function pwt(n){return n.map(r=>XL(r,n))}function XL(n,r){return _l.isCompositeModel(n.data)?{...n,data:LPr(n,r)}:n}function LPr(n,r){let i={relationships:[],metrics:n.data.metrics??[],object_type:"model",label:n.data.label,unique_name:n.data.unique_name,dimensions:[]};return n.data.models.forEach(o=>{let l=r.find(_=>_.data.unique_name===o);if(!l)throw new Error(`No object found with unique name ${o}`);let p=l.data;i.metrics=i.metrics.concat(p.metrics),i.dimensions=i.dimensions?.concat(p.dimensions??[]),i.relationships=i.relationships.concat(p.relationships),i.overrides=jPr(i,p)}),n.data.aggregates&&(i.aggregates=(i.aggregates??[]).concat(n.data.aggregates)),i.dimensions?.length||(i.dimensions=void 0),(!i.overrides||!Object.values(i.overrides).length)&&(i.overrides=void 0),i}function jPr(n,r){return{...n.overrides,...r.overrides}}var oTe=_u(eoe());var Vdn={error:"Display an error message and return nothing",repeat:"Include repeated values in query results",empty:"Include empty cells in query results"},OO=["sum","average","minimum","maximum","count distinct","sum distinct","estimated count distinct","count non-null","stddev_samp","stddev_pop","var_samp","var_pop","percentile"],sTe=["sum","minimum","maximum"],toe=OO.filter(n=>n!=="percentile"),zdn="sum",aTe={int:OO,long:OO,float:OO,double:OO,decimal:OO,bigint:OO,tinyint:OO,number:OO,numeric:OO,datetime:toe,date:toe,boolean:toe,string:toe,timestamp:toe};var BPr={median:[.5],quartiles:[.25,.5,.75,1],deciles:[.1,.2,.3,.4,.5,.6,.7,.8,.9,1]},xQ=n=>n.custom_quantiles??(n.named_quantiles&&BPr[n.named_quantiles]),TQ=(n,r)=>{let i=`${n} PCTL`;if(r==1)return`${i}100`;let o=String(Math.round(r*100));return o=o.toString().padStart(2,"0"),`${i}-${o}`},CQ=(n,r)=>`${n}_instance_${r}`;var $B=class{static isLevelHidden(r,i){return r.is_hidden??i.is_hidden??void 0}};var EUe=class n{getRelationshipsPaths(){}static create(){return new n}resolve(r){return r}addRolePlay(r){return roe.for(r)}},wUe=class n{constructor(r){this.model=r}static for(r){return new n(r)}getRelationshipsPaths(){}resolve(r){return(this.model.overrides||{})[r]?.query_name||r}addRolePlay(r){return roe.for(r)}},roe=class n{constructor(r){this.rolePlays=r}static for(r){return new n([r])}getRelationshipsPaths(){return this.rolePlays.map(r=>r.relationshipUniqueName)}resolve(r){return[...this.rolePlays].reverse().map(i=>i.rolePlay).reduce((i,o)=>o.replace("{0}",i),r)}addRolePlay(r){return new n([...this.rolePlays,r])}},AUe=class n{static create(){return new n}resolveMetric(r){return`[Measures].[${r}]`}resolveDimension(r){return`[${r}]`}resolveHierarchy(r,i){return`${this.resolveDimension(r)}.[${i}]`}resolveLevel(r,i,o){return`${this.resolveHierarchy(r,i)}.[${o}]`}resolveSecondaryAttribute(r,i){return`${this.resolveDimension(r)}.[${i}].[${i}]`}resolveLevelAlias(r,i){return`${this.resolveDimension(r)}.[${i}].[${i}]`}resolveCalculationGroup(r,i){return`${this.resolveDimension(r)}.[${i}]`}resolveCalculationMember(r,i,o){return`${this.resolveDimension(r)}.[${i}].[${o}]`}},cTe=class{constructor(){this.fullQueryNameResolver=AUe.create()}buildQueryableItemsForCompositeModel(r,i,o){let l=this.getModelMeasures(r,o),p=i.map(b=>this.buildQueryableItems(b,o)),_=r.data;return{metrics:l,dimensions:(0,oTe.default)(p).flatMap("dimensions").uniqBy("fullQueryName").value(),childModelsMetrics:(0,oTe.default)(p).flatMap("metrics").uniqBy("fullQueryName").value(),aggregates:_.aggregates||[],rowSecurities:(0,oTe.default)(p).flatMap("rowSecurities").uniqBy("fullQueryName").value()}}buildQueryableItems(r,i){let o={dimensions:[],metrics:[],aggregates:[],rowSecurities:[]},l=r.data;return o.metrics=this.getModelMeasures(r,i),l.dimensions?.forEach(p=>{this.populateDegenDimension(r,p,o,i)}),l.relationships?.filter(Ic.isRegularRelation).map(p=>({modelDimUniqueName:p.to.dimension,level:p.to.level,rolePlay:p.role_play,relationshipName:p.unique_name})).forEach(({modelDimUniqueName:p,level:_,rolePlay:b,relationshipName:T})=>{this.populateModelRelationDimension(r,p,_,b?{rolePlay:b,relationshipUniqueName:T}:void 0,o,i)}),l.relationships?.filter(Ic.isSecurityRelation).forEach(p=>{this.populateRowSecurity(r,p.to.row_security,o,i)}),o.aggregates=l.aggregates||[],o}getItem(r,i){return i.get(r)}getQueryName(r,i){return _l.isCompositeModel(r)?i:(r.overrides||{})[i]?.query_name||i}getModelMeasures(r,i){return r.data.metrics?r.data.metrics.map(o=>{let l=this.getItem(o.unique_name,i);if(!l||!["metric_calc","metric"].includes(l.data.object_type))return;let p=this.getQueryName(r.data,o.unique_name),_=l.data.object_type==="metric_calc"?"MetricCalc":"Metric",b=l.data;return _l.isMetric(b)&&b.calculation_method==="percentile"?xQ(b)?.map(E=>{let k=CQ(p,E);return{queryName:k,fullQueryName:this.fullQueryNameResolver.resolveMetric(k),uniqueName:o.unique_name,label:TQ(l.data.label,E),description:l.data.description,file:l,fileChain:[],type:_,folder:o.folder}})??[]:{queryName:p,fullQueryName:this.fullQueryNameResolver.resolveMetric(p),uniqueName:o.unique_name,label:l.data.label,description:l.data.description,file:l,fileChain:[],type:_,folder:o.folder}}).flat().filter(wO):[]}populateDegenDimension(r,i,o,l){this.populateDimension(r,i,void 0,o,l,wUe.for(r.data))}populateModelRelationDimension(r,i,o,l,p,_){let b=l?roe.for(l):EUe.create();this.populateDimension(r,i,o,p,_,b)}populateRowSecurity(r,i,o,l){let p=this.getItem(i,l);if(!p||p.data.object_type!=="row_security"||o.rowSecurities.some(T=>T.uniqueName===i))return;let _=i,b={uniqueName:i,queryName:_,fullQueryName:_,label:p.data.label||i,description:p.data.description,file:p,fileChain:[p]};o.rowSecurities.push(b)}populateDimension(r,i,o,l,p,_,b=[]){let T=this.getItem(i,p);if(!T||T.data.object_type!=="dimension")return;let E=_.resolve(i),k=T.data.hierarchies.filter(De=>o===void 0?!0:De.levels.find(Je=>Je.unique_name===o)).map(De=>{let Je=_.resolve(De.unique_name);return{queryName:Je,fullQueryName:this.fullQueryNameResolver.resolveHierarchy(E,Je),uniqueName:De.unique_name,label:_.resolve(De.label),description:De.description,folder:De.folder,levels:De.levels.map($e=>{$e.metrics?.forEach(cr=>{let Mr=this.fullQueryNameResolver.resolveMetric(cr.unique_name);l.metrics.filter(this.isModelQueryableDimensionMetric).some(ar=>ar.uniqueName===cr.unique_name&&ar.dimension===T.data.unique_name&&ar.level===$e.unique_name)||l.metrics.push({file:{data:{calculation_method:cr.calculation_method}},fileChain:[...b],queryName:cr.unique_name,fullQueryName:Mr,label:_.resolve(cr.label),type:"DimensionalMetric",uniqueName:cr.unique_name,description:cr.description,folder:cr.folder,dimension:T.data.unique_name,level:$e.unique_name})});let Ke=T.data.level_attributes.find(qL($e.unique_name)),ht=_.resolve($e.unique_name);return{queryName:ht,fullQueryName:this.fullQueryNameResolver.resolveLevel(E,Je,ht),uniqueName:$e.unique_name,label:Ke?.label?_.resolve(Ke.label):"",description:Ke?.description,isHidden:Ke&&$B.isLevelHidden($e,Ke),relationshipsPath:_.getRelationshipsPaths(),secondaryAttributes:($e.secondary_attributes||[]).map(cr=>{let Mr=_.resolve(cr.unique_name);return{queryName:Mr,fullQueryName:this.fullQueryNameResolver.resolveSecondaryAttribute(E,Mr),uniqueName:cr.unique_name,label:_.resolve(cr.label),description:cr.description,folder:cr.folder,isHidden:cr.is_hidden,relationshipsPath:_.getRelationshipsPaths()}}),aliases:($e.aliases||[]).map(cr=>{let Mr=_.resolve(cr.unique_name);return{queryName:Mr,fullQueryName:this.fullQueryNameResolver.resolveLevelAlias(E,Mr),uniqueName:cr.unique_name,label:_.resolve(cr.label),description:cr.description,folder:cr.folder,isHidden:cr.is_hidden,relationshipsPath:_.getRelationshipsPaths()}})}})}}),j=this.populateCalculationGroups(T.data.calculation_groups,i),z=this.fullQueryNameResolver.resolveDimension(E),X=l.dimensions.find(De=>De.fullQueryName===z);if(X){k.forEach(De=>{X.hierarchies.some($e=>$e.fullQueryName===De.fullQueryName)||X.hierarchies.push(De)});return}let ue={queryName:E,fullQueryName:z,uniqueName:i,label:_.resolve(T.data.label),description:T.data.description,hierarchies:k,file:T,fileChain:[...b],calculationGroups:j};l.dimensions.push(ue),T.data.relationships?.forEach(De=>{if(ki.isSecurityRelation(De)||!ki.isEmbeddedRelation(De))return;let Je=De.role_play?_.addRolePlay({rolePlay:De.role_play,relationshipUniqueName:De.unique_name}):_;this.populateDimension(r,De.to.dimension,De.to.level,l,p,Je,[...b,T])})}populateCalculationGroups(r,i){return r?r.map(o=>{let l=o.calculated_members.map(p=>({uniqueName:p.unique_name,queryName:p.unique_name,fullQueryName:this.fullQueryNameResolver.resolveCalculationMember(i,o.unique_name,p.unique_name),label:p.unique_name,description:p.description}));return{uniqueName:o.unique_name,queryName:o.unique_name,fullQueryName:this.fullQueryNameResolver.resolveCalculationGroup(i,o.unique_name),label:o.label,folder:o.folder,calculationMembers:l}}):[]}isModelQueryableDimensionMetric(r){return r.type==="DimensionalMetric"}};var $Pr=(n,r)=>`dataset: "${n}" and key_columns: ${nh(r)}`,JB=class{constructor(){this.getDuplicatedDegenerateDimensions=r=>{let i=this.groupByDatasetAndKeyColumn(r);return this.getDuplicatedDimensions(i)}}groupByDatasetAndKeyColumn(r){let i=new Map;return r.filter(o=>o.data.is_degenerate).forEach(o=>{o.data.level_attributes.forEach(l=>{if(ki.isLevelFromOneDataset(l)){let p=$Pr(l.dataset,l.key_columns);i.has(p)||i.set(p,[]);let _=i.get(p);_&&_.push(o)}})}),i}getDuplicatedDimensions(r){return new Map([...r].filter(([i,o])=>o.length>1))}};var kUe={getCalcMeasureCycleReferenceError:n=>`Cycle calculated measure reference detected. Reference path: ${n.map(r=>r.data.unique_name).join("->")}`,getMeasureIsNotFoundByUniqueName:n=>`Cannot check cycle reference for measure with unique_name: ${n}. It was not found in the resolved queryable items`,getMeasureIsNotFoundByQueryName:n=>`Cannot check cycle reference for measure with model context resolved queryName: ${n}. It was not found in the resolved queryable items`},lTe=class n{static create(){return new n}validate(r,i,o){let l=[];i.data.metrics.forEach(p=>{let _=r.find(T=>T.uniqueName===p.unique_name);if(!_){o.file(i).addWarning(kUe.getMeasureIsNotFoundByUniqueName(p.unique_name));return}if(_.type!=="MetricCalc")return;let b=this.getLongestCycleDependency(_,r,o.file(i),l);b&&l.push(b)}),l.forEach(p=>o.file(i).addError(kUe.getCalcMeasureCycleReferenceError(p)))}getLongestCycleDependency(r,i,o,l,p=[],_=0){if(us.ensure(_<50,"YamlModelCalcMeasuresCycleRefValidator max depth exceeded"),l.flatMap(E=>E).some(E=>E.data.unique_name===r.uniqueName))return;let b=[...p,r.file];if(p.find(E=>E.data.unique_name===r.uniqueName))return b;let T=r.file.data.expression;if(T){let E=uA(T),k=[];return E.forEach(j=>{let z=i.find(ue=>ue.queryName.toLowerCase()===j.toLowerCase());if(!z){o.addWarning(kUe.getMeasureIsNotFoundByQueryName(j));return}if(z.type!=="MetricCalc")return;let X=this.getLongestCycleDependency(z,i,o,l,b,_+1);X&&k.length<X.length&&(k=X)}),k.length>0?k:void 0}}};var UB={missingModels:"Missing Model files in folder structure",getDuplicateMetricError(n,r){return`Duplicate query name detected in context of a model "${n.unique_name}". Query name: "${r[0]?.queryName}".`},getCalcMeasureContainsANonExistingMeasure:(n,r)=>`Calculated metric "${n}" expression contains a non-existing metric: "${r}".`,getDuplicatedDegeneratedDimensionsInModelError:(n,r)=>`Degenerate dimensions: ${nh(n)} are referred in the model, however, they have duplicated "${r}" combination. Please remove duplicates.`,getDuplicatedDegeneratedDimensionsInMultipleModelsError:(n,r,i)=>`Degenerate dimensions: ${nh(n)} are referred in models: ${nh(r)}, however, they have duplicated ${i} combination. Please remove duplicates.`,getRelationshipInModelError:({object:n,orphanType:r})=>`There is an unrelated ${r} in the model - "${n||"unknown"}".`},uTe=class n{constructor(r,i,o){this.yamlDegenerateDimensionUtil=r;this.yamlModelQueryNameResolver=i;this.yamlModelCalcMeasuresCycleRefValidator=o}static create(r=new JB,i=new cTe,o=lTe.create()){return new n(r,i,o)}validate(r){let i=Mo.create();return this.verifyModelFiles(r,i),i}async verifyModelFiles(r,i,o=KL,l=Zxe){if(!r.find(b=>_l.isModel(b.data))){i.addGlobalOutput("error",UB.missingModels);return}let p=l(r),_=o(r);_.forEach(b=>{let T=XL(b,r),{metrics:E}=this.yamlModelQueryNameResolver.buildQueryableItems(T,p);this.verifyAllQueryNameMetricsDuplicates(E,T,i),this.verifyModelCalculationMeasures({metrics:b.data.metrics||[],queryableMetrics:E,modelFile:T,allItems:p,validatorOutput:i}),this.verifyDegenerateDimensionsInAModel(T,r,i)}),this.verifyDegenerateDimensionsInAllModels(_,r,i)}verifyDegenerateDimensionsInAModel(r,i,o,l=NO){if(!r.data?.dimensions)return;this.yamlDegenerateDimensionUtil.getDuplicatedDegenerateDimensions(l(i)).forEach((_,b)=>{let T=this.findDegenerateDimsUsedInSingleModel(_,r);T.length>1&&o.file(r).addWarning(UB.getDuplicatedDegeneratedDimensionsInModelError(T,b))})}findDegenerateDimsUsedInSingleModel(r,i){return r.reduce((o,l)=>{let p=i.data.dimensions?.find(_=>_===l.data.unique_name);return p&&o.push(p),o},[])}verifyDegenerateDimensionsInAllModels(r,i,o,l=NO){this.yamlDegenerateDimensionUtil.getDuplicatedDegenerateDimensions(l(i)).forEach((_,b)=>{let{degenerateDimsUsedInModels:T,modelsWithDuplicatedDegenerateDims:E}=this.findDuplicatedDegenerateDimsInMultipleModels(_,r,i),k=Array.from(new Set(T)),j=Array.from(new Set(E));k.length>1&&j.forEach(z=>{o.file(z).addWarning(UB.getDuplicatedDegeneratedDimensionsInMultipleModelsError(k,j.map(X=>X.data.unique_name),b))})})}findDuplicatedDegenerateDimsInMultipleModels(r,i,o){let l=[],p=[];return r.forEach(_=>{i.forEach(b=>{let T=XL(b,o);T.data.dimensions&&T.data.dimensions.find(k=>k===_.data.unique_name)&&(l.push(_.data.unique_name),p.push(T))})}),{degenerateDimsUsedInModels:l,modelsWithDuplicatedDegenerateDims:p}}verifyQueryNameMetricsDuplicates(r,i,o){let l=rl.groupBy(r,p=>[p.queryName.toLowerCase()]);Array.from(l.values()).filter(p=>p.length>1).forEach(p=>o.file(i).addError(UB.getDuplicateMetricError(i.data,p)))}verifyAllQueryNameMetricsDuplicates(r,i,o){let l=Mo.create();this.verifyQueryNameMetricsDuplicates(r,i,l),o.append(l),l.hasErrors||this.yamlModelCalcMeasuresCycleRefValidator.validate(r,i,o)}verifyModelCalculationMeasures({metrics:r,queryableMetrics:i,modelFile:o,allItems:l,validatorOutput:p}){this.getModelCalculatedMetrics(l,r.map(_=>_.unique_name)).forEach(_=>{this.verifyExpressionMeasures(_.data,i,o,p)})}getModelCalculatedMetrics(r,i){return i.reduce((o,l)=>{let p=r.get(l);return p&&_l.isMetricCalc(p.data)&&o.push(p),o},[])}verifyExpressionMeasures(r,i,o,l){uA(r.expression).forEach(p=>{i.some(b=>DQ(b.queryName,p))||l.file(o).addError(UB.getCalcMeasureContainsANonExistingMeasure(r.unique_name,p))})}};var ZL={missing:"Missing file with name global_settings, in the root folder",moreThanOne:"There is more than one global_settings file in the root folder",exists:"File with type global_settings exists in non global settings repository",otherYamlFiles:"Unknown yml file(s) exist in the global settings repository. Delete all yml/yaml files except the file with the name global_settings.yml/yaml",objectTypeMissing:"object_type is missing",notCorrectObjType:"the file name suggests its object_type to be global_settings",notCorrectFileName:"the file object_type suggests its name to be global_settings",notInRoot:"file is not located in the root folder"},fTe=["global_settings.yaml","global_settings.yml"],pTe=class n{constructor(r){this.isGlobalSettingsRepo=r;this.isFolderValidator=!0}static create(r){return new n(r)}validateFolderStructure(r){let i=Mo.create();return this.verifyGlobalSettingsFile(r,i),i}verifyGlobalSettingsFile(r,i){if(!this.isGlobalSettingsRepo){this.doesGlobalSettingsFileExist(r)&&i.addGlobalOutput("error",ZL.exists);return}let o=this.getCountFromRoot(r.files,fTe,i),l=o===0,p=o>1;l&&i.addGlobalOutput("error",ZL.missing),p&&i.addGlobalOutput("error",ZL.moreThanOne),this.otherYamlFilesExist(r)&&i.addGlobalOutput("error",ZL.otherYamlFiles),Ik.traverse(r,_=>{this.validateGlobalSettingsFile(_,i),this.validateFileNameByObjectType(_,i)})}doesGlobalSettingsFileExist(r){let i=!1;return Ik.traverse(r,o=>{o.data?.object_type==="global_settings"&&(i=!0)}),i}getCountFromRoot(r,i,o){let l=0;return r.forEach(p=>{let _=Ro.getFileNameFromPath(p.relativePath);i.includes(_)&&(this.validateFileObjectType(p,o),l++)}),l}validateFileObjectType(r,i){!r.data||Pa.hasNoProps(r.data,"object_type")?i.file(r).addError(ZL.objectTypeMissing):_l.isGlobalSettings(r.data)||i.file(r).addError(ZL.notCorrectObjType)}otherYamlFilesExist(r){let i=!1;return Ik.traverse(r,o=>{let l=Ro.getExtensionFromPath(o.relativePath),p=l&&["yaml","yml"].includes(l),_=Ro.getFileNameFromPath(o.relativePath),b=fTe.includes(_);p&&!b&&(i=!0)}),i}validateGlobalSettingsFile(r,i){if(!Ro.isFileOnRootLevel(r.relativePath)&&r.origin==="R"){let o=Ro.getFileNameFromPath(r.relativePath);fTe.includes(o)&&i.file(r).addError(ZL.notInRoot)}}validateFileNameByObjectType(r,i){if(r.data?.object_type==="global_settings"){let o=Ro.getFileNameFromPath(r.relativePath);fTe.includes(o)||i.file(r).addError(ZL.notCorrectFileName)}}};var JPr=[{major:1,minor:1,changes:{dimension:{calculation_groups:[{precedence:!0,is_hidden:!0,calculated_members:[{is_hidden:!0}]}]}}},{major:1,minor:2,changes:{catalog:{hidden_models:!0}}},{major:1,minor:3,changes:{catalog:{aggregate_store:{as_connection:!0,row_count_limit:!0,total_row_count_limit:!0}},dimension:{relationships:[{m2m:!0}]}}},{major:1,minor:4,changes:{composite_model:{aggregates:!0}}},{major:1,minor:5,changes:{metric:{compression:!0,named_quantiles:!0,custom_quantiles:!0},dimension:{hierarchies:[{levels:[{secondary_attributes:[{is_excel_pivot_table_property:!0,is_user_defined_property:!0}],aliases:[{is_excel_pivot_table_property:!0,is_user_defined_property:!0}]}]}]}}},{major:1,minor:6,changes:{catalog:{description:!0},model:{aggregates:[{attributes:[{row_security:!0}]}]}}}],UPr={newPropertiesDetected:(n,r)=>`Property with path: "${n}" was introduced in version "${r}"`},dTe=class n{constructor(r){this.smlSpecChanges=r}static create(r=JPr){return new n(r)}validate(r){let i=us.ensure(r.find(p=>p.data.object_type==="catalog"),"File with object_type catalog not found."),o=Mo.create(),l=this.smlSpecChanges.filter(p=>+`${p.major}.${p.minor}`>i.data.version);return l.length===0||r.forEach(p=>{l.filter(_=>_.changes[p.data.object_type]).forEach(_=>{this.getCommonKeyPaths(p.data,_.changes[p.data.object_type]).forEach(b=>{o.file(p).addError(UPr.newPropertiesDetected(b,`${_.major}.${_.minor}`),{type:"UpdateVersion",version:{major:_.major,minor:_.minor}})})})}),o}getCommonKeyPaths(r,i,o=""){let l=[];for(let p in r)if(Object.prototype.hasOwnProperty.call(i,p)){let _=r[p],b=i[p],T=o?`${o} -> ${p}`:p;if(this.isObject(_)&&!this.isObject(b)&&l.push(T),!this.isObject(_)&&!this.isObject(b)&&_!==void 0&&l.push(T),Array.isArray(_)&&Array.isArray(b))_.forEach((E,k)=>{let j=`${T}[${k}]`,z=this.getCommonKeyPaths(E,b[0],j);l.push(...z)});else if(this.isObject(_)&&_!==null&&this.isObject(b)&&b!==null){let E=this.getCommonKeyPaths(_,b,T);l.push(...E)}}return l}isObject(r){return typeof r=="object"}};var _Te=class n{constructor(){this.isFolderValidator=!0}static create(){return new n}validateFolderStructure(r){let i=Mo.create();return r.files.some(o=>o.relativePath===".gitmodules")&&i.addGlobalOutput("warning",`Git submodules are no longer supported. A '.gitmodules' file is detected in the repository. Consider using ${cC} file`),i}};var mTe={$id:"https://www.atscale.com/ml/package.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"package",type:"object",required:["version","packages"],properties:{version:{type:"number"},packages:{type:"array",items:{type:"object",required:["name","url","branch","version"],properties:{name:{type:"string",pattern:"^[a-zA-Z-_]*$",minLength:3,maxLength:128,errorMessage:{pattern:"should contains only a-z, A-Z, - or _ no spaces are allowed"}},url:{type:"string",pattern:"^(https?):\\/\\/[^\\s/$.?#].[^\\s]*$",maxLength:2048,errorMessage:{pattern:"should be valid with protocol http or https"}},version:{type:"string",pattern:"^commit:[a-fA-F0-9]{8,40}$",errorMessage:{pattern:"should start with 'commit:', followed by 8 to 40 characters that can only be letters (a-f, A-F) or digits (0-9)"}},branch:{type:"string",minLength:1}}}}}};var tkt=_u(vVe()),rkt=_u(MVe());var u7=class n extends Error{constructor(i){let o=i.join(",");super(o);this.errors=i}static fromAvjError(i){let l=us.ensure(i,"No errors provided").map(p=>p.message||p.keyword);return new n(l)}static single(i){return new n([i])}};var QTe=class{filterAnyOfErrors(r){try{let i=r.filter(p=>p.keyword==="anyOf");if(i.length===0)return r;let o=i.map(p=>r.find(b=>b.schemaPath.startsWith(p.schemaPath))??p);return[...r.filter(p=>i.every(_=>!p.schemaPath.startsWith(_.schemaPath)&&p.keyword!=="anyOf")),...o]}catch{return r}}formatErrors(r,i){return this.filterAnyOfErrors(r).reduce((l,p)=>{let _=this.formatSingleError(p,i);return l.push(_),l},[])}formatSingleError(r,i,o=""){let l=this.splitInstancePath(r.instancePath),[p,_]=l;if(!p)return o?`${o}${r.message}`:r.message;if(!_)return o=`${o}${p} ${r.message}`,o;let{subYamlObject:b,newErrorMessage:T,newInstancePath:E}=this.isIndex(_)?this.updateDataFromCollection(i,p,_,l,o):this.updateDataFromObject(i,p,_,l,o);return r.instancePath=E,this.formatSingleError(r,b,T)}updateDataFromCollection(r,i,o,l,p){let _=r[i][parseInt(o)],b=this.getDataName(_,o),T=l.slice(l.indexOf(o)+1).join("/"),E=`${p}${i}[${b}]`+this.getMessageSeparator(T);return{subYamlObject:_,newErrorMessage:E,newInstancePath:T}}updateDataFromObject(r,i,o,l,p){let _=r[i],b=l.slice(l.indexOf(o)).join("/"),T=`${p}${i}`+this.getMessageSeparator(b);return{subYamlObject:_,newErrorMessage:T,newInstancePath:b}}isIndex(r){return typeof r=="string"&&!Number.isNaN(parseInt(r))}getDataName(r,i){return r?Pa.hasProps(r,"name")?`name=${r.name}`:Pa.hasProps(r,"label")?`label=${r.label}`:Pa.hasProps(r,"unique_name")?`unique_name=${r.unique_name}`:`index: ${i}`:`index: ${i}`}getMessageSeparator(r){return this.splitInstancePath(r).length<=1?" ":" -> "}splitInstancePath(r){return r.split("/").filter(Boolean)}};var _C=class{constructor(r,i=new QTe){this.errorFormatter=i;this.ajv=new rkt.default(r),(0,tkt.default)(this.ajv)}compileSchema(r){return this.ajv.getSchema(r.$id)||this.ajv.addMetaSchema(r),this.compiledValidate=this.ajv.compile(r),this}validate(r){if(this.compiledValidate=us.ensure(this.compiledValidate,"Add compile schema before validating"),!this.compiledValidate(r.data)){let o=us.ensure(this.compiledValidate.errors,"AJV validation must contains errors"),l=this.errorFormatter.formatErrors(o,r.data);throw new u7(l)}return this}};var Xy=class{constructor(r,i){this.schemaValidator=r;this.jsonSchema=i}validateAML(r){try{this.schemaValidator.compileSchema(this.jsonSchema).validate(r)}catch(i){return i instanceof u7?{isValid:!1,errors:i.errors}:{isValid:!1,errors:[qd.getErrorMessage(i)]}}return{isValid:!0,errors:[]}}ensureRule(r,i){if(!r)throw u7.single(i)}};var Roe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var t4r={packagePropValueShouldBeUnique:(n,r)=>`package ${r} '${n}' should be unique`,packageNameShouldBeCorrect:n=>`packages[name=${n}] name should contains only a-z, A-Z, - or _ no spaces are allowed`,packageUrlShouldBeCorrect:n=>`packages[name=${n}] url should be valid with protocol http or https`,packageVersionShouldBeCorrect:n=>`packages[name=${n}] version should start with 'commit:', followed by 8 to 40 characters that can only be letters (a-f, A-F) or digits (0-9)`},r4r=[cC,cC.replace(".yml",".yaml")],YTe=class n{constructor(){this.isFolderValidator=!0}static create(){return new n}validateFolderStructure(r){let i=Mo.create();return r.files.forEach(o=>{let l=Ro.getFileNameFromPath(o.relativePath);if(r4r.includes(l)&&R1.isRawFile(o)){let _=JL.create().parse(o);R1.isPackageFile(_.data)&&this.validate(_.data).forEach(T=>i.addFileOutput(o.relativePath,T.severity,T.message))}}),i}validate(r){let i=[],o=new Roe(new _C({allErrors:!0}),mTe),l={data:r,relativePath:"",rawContent:"",compilationOutput:[]},p=o.validateAML(l);p.isValid||p.errors.forEach(T=>i.push({severity:"error",message:T}));let _=rl.groupBy(r.packages||[],T=>[T.name]);this.appendErrors("name",_,i);let b=rl.groupBy(r.packages||[],T=>[T.url]);return this.appendErrors("url",b,i),i}appendErrors(r,i,o){Array.from(i.values()).filter(l=>l.length>1).forEach(l=>l.forEach(p=>o.push({severity:"error",message:t4r.packagePropValueShouldBeUnique(p[r],r)})))}};var qk=class n{constructor(){this.getLevelContext=r=>({type:"level",level:r.itemUniqueName,hierarchy:r.hierarchyUniqueName,message:r.message,validationType:r.validationType});this.getLevelAttributeContext=r=>({type:"level-attribute",levelAttribute:r.itemUniqueName,message:r.message,validationType:r.validationType});this.getSecondaryAttributeContext=r=>({type:"secondary-attribute",secondaryAttribute:r.itemUniqueName,message:r.message,validationType:r.validationType});this.getLevelAliasContext=r=>({type:"level-alias",levelAlias:r.itemUniqueName,message:r.message,validationType:r.validationType})}static create(){return new n}};var Moe=class{constructor(){this.parentheses={"(":")","[":"]"};this.ignoredSymbolsInSquareParenthesis=new Set([")","("])}areParenthesesValid(r){let i=[],o=YH(r);for(let l of o)if(!(i[i.length-1]==="["&&this.ignoredSymbolsInSquareParenthesis.has(l))){if(l in this.parentheses)i.push(l);else if(this.isClosingParenthesis(l)){let _=i.pop();if(_===void 0||this.parentheses[_]!==l)return!1}}return!i.length}isClosingParenthesis(r){return Object.values(this.parentheses).some(i=>i===r)}};var Loe=class{validateObject(){return Mo.create()}};var LO=Object.freeze({major:1,minor:6});var jVe={noVisibleModels:n=>`No models to deploy. All models are hidden: "${n.join('", "')}"`,getDuplicateHiddenModelNames:(n,r)=>`Model "${n}" is used ${r} times in the hidden_models`,aggregateStoreCountLimit:"row_count_limit must be less than or equal to total_row_count_limit"},KTe=class{constructor(r,i){this.yamlModelValidator=r;this.yamlCommonReferenceValidator=i}validateObject(r,i){let o=Mo.create();this.yamlModelValidator.validateDatasetsProperties(o,r,i);let l=+`${LO.major}.${LO.minor}`;return r.data.version!==l&&o.file(r).addWarning(`Your current SML version is different from the latest supported version. Latest supported version: "${l}"`,{type:"UpdateVersion",version:{major:LO.major,minor:LO.minor}}),this.validateHiddenModels(r,i,o),this.validateAggregateStore(r,o),o}validateHiddenModels(r,i,o){if(!r.data.hidden_models)return;let l=rl.groupBy(r.data.hidden_models,_=>[_]);rl.appendErrorsIfDuplicates(l,o.file(r),jVe.getDuplicateHiddenModelNames);let p=!1;r.data.hidden_models.forEach(_=>{this.yamlCommonReferenceValidator.validateAndGetReferencedObject(_,i,r,"model",o)||(p=!0)}),p||this.validateAfterHiddenModelsThereIsAtLeastOneModelLeft(r,i,o)}validateAfterHiddenModelsThereIsAtLeastOneModelLeft(r,i,o){if(!r.data.hidden_models||r.data.hidden_models.length===0)return;let l=[];i.forEach(_=>{["composite_model","model"].includes(_.data.object_type)&&l.push(_.data.unique_name)}),l.filter(_=>!r.data.hidden_models?.includes(_)).length===0&&o.file(r).addError(jVe.noVisibleModels(r.data.hidden_models))}validateAggregateStore(r,i){let o=r.data.aggregate_store;!o?.row_count_limit||!o.total_row_count_limit||o.row_count_limit>o.total_row_count_limit&&i.file(r).addError(jVe.aggregateStoreCountLimit)}};var $Q=["bigint","int","long","date","datetime","timestamp"];var ih={referenceObjectNotExist:(n,r)=>`${n} "${r}" does not exist`,incorrectReference:(n,r,i)=>`Incorrect ${n} reference. ${n} "${r}" points to ${i}`,detachedRelationships:(n,r)=>`Relationship in ${n} has detached ${r} and will be skipped for the compilation`,invalidDatasetRelationship:(n,r,i)=>`Invalid relationship in Dataset ${n} located in ${r}. One or more connection columns are missing: ${i}`,invalidDimensionRelationship:(n,r,i)=>`Invalid relationship. The dimension "${n}" in "${r}" has no attribute: "${i}"`,invalidRelationshipPath:(n,r,i)=>`Invalid relationship path: ${n}. Object "${r}" in "${i}" has not existing relationship_path`,invalidRowSecurityRelationship:n=>`Invalid relationship. There is no row security with ${n}`,mismatchedRelationshipKeys:(n,r,i,o)=>`Invalid relationship. The number of join_columns in dataset ${n} (${r}) does not match the number of key_columns in level attribute ${i} (${o})`,getLevelDoesNotExistInDimensionError:(n,r)=>`Constraint_translation -> level "${n}" does not exist in dimension "${r}"`,getConstraintTranslationColumnsNotMatch:n=>`Constraint_translation -> from_columns number of items does not match the number of key_columns in level "${n}"`,getColumnNotExistInFactTable:(n,r)=>`Constraint_translation -> column "${n}" does not exist in dataset "${r}"`,getLevelMissingConstraintTranslationRank:(n,r,i)=>`Constraint_translation in relationship "${i}" references level "${n}" from "${r}". The level_attribute "${n}" must have a constraint_translation_rank property`,getFromColumnsNotMatchingKeyColumnTypes:(n,r,i,o)=>`Column type mismatch. Constraint_translation -> from_column "${i.name}" in relationship "${r}" has type "${i.data_type}" but key_column "${o.name}" in level "${n}" has type "${o.data_type}"`,getScdMissingColumn:(n,r,i)=>`Invalid relationship scd column "${r}". Relationship: "${n}". The target dataset "${i}" does not have column ${r}`,getScdColumnIsNotSimple:(n,r)=>`Invalid relationship "${n}" scd column "${r}". Column is not simple column. Mapped or derived columns are not allowed`,getScdInvalidColumnDataType:(n,r,i)=>`Relationship "${n}" scd_column "${r.name}" has invalid datatype: "${r.data_type}". Allowed types are: ${i.join(", ")}`,getScdTargetLevelIsNotFromOneDataset:(n,r,i)=>` Relationship "${n}" has SCD(Slowly Changing Dimension) incompatible reference to dimension ${r}, level ${i}. The level is not one dataset level.`,getScdTargetLevelHasNoSCDProps:(n,r,i)=>` Relationship "${n}" has scd_column set, but the referenced dimension ${r}, level ${i} is not configured to be Slowly Changing Dimension (has no scd_properties set).`,getScdRelationshipWithoutScdColumnToLevelWithScd:(n,r,i)=>`Relationship "${n}" has missing scd_column. The target level is marked as slowly changing dimension. Dimension: "${r}", Level: "${i}" `,getScdRelationshipIncompatibleDataType:(n,r)=>`Relationship "${n}" has SCD(Slowly Changing Dimension) incompatible type with the level. ScdColumn is ${r.scdColumn}:${r.scdDataType}, level scd effective start is ${r.effectiveStartColumn}:${r.effectiveStartDataType}`},joe=class{constructor(){this.validateScdRelationship=(r,i,o)=>{let l=Mo.create(),p=l.file(r),_=this.validateAndGetReferencedObject(i.to.dimension,o,r,"dimension",Mo.create()),b=_!==void 0?_.data.level_attributes?.find(k=>k.unique_name===i.to.level):void 0;if(!i.from.scd_column)return b&&ki.isLevelFromOneDataset(b)&&b.scd_properties!==void 0&&p.addError(ih.getScdRelationshipWithoutScdColumnToLevelWithScd(i.unique_name,i.to.dimension,i.to.level)),l;let T,E=this.validateAndGetReferencedObject(i.from.dataset,o,r,"dataset",Mo.create());if(E){let j=E.data.columns.find(z=>z.name===i.from.scd_column);j?Zl.isSimpleColumn(j)?$Q.includes(j.data_type)?T=j.data_type:p.addError(ih.getScdInvalidColumnDataType(i.unique_name,j,$Q)):p.addError(ih.getScdColumnIsNotSimple(i.unique_name,i.from.scd_column)):p.addError(ih.getScdMissingColumn(i.unique_name,i.from.scd_column,i.from.dataset))}if(_&&b)if(ki.isLevelFromOneDataset(b)){if(!b.scd_properties)p.addError(ih.getScdTargetLevelHasNoSCDProps(i.unique_name,i.to.dimension,i.to.level));else if(T!==void 0){let k=o.get(b.dataset);if(!k||k.data.object_type!=="dataset")return l;let j=k.data.columns.find(z=>z.name===b.scd_properties.effective_start.column);if(!j||!Zl.isSimpleColumn(j))return l;j.data_type!==T&&p.addError(ih.getScdRelationshipIncompatibleDataType(i.unique_name,{scdColumn:i.from.scd_column,scdDataType:T,effectiveStartColumn:j.name,effectiveStartDataType:j.data_type}))}}else p.addError(ih.getScdTargetLevelIsNotFromOneDataset(i.unique_name,i.to.dimension,i.to.level));return l}}validateAndGetReferencedObject(r,i,o,l,p){let _=i.get(r);if(!_){p.file(o).addError(ih.referenceObjectNotExist(l,r));return}if(_.data.object_type!==l){p.file(o).addError(ih.incorrectReference(l,r,_.data.object_type));return}return _}validateRelationships(r,i,o){let l=Mo.create(),{relationships:p}=r.data;return p&&p.forEach(_=>{if(ki.isRegularRelation(_)){let b=_.type==="snowflake"?r.data.unique_name:_.to.dimension;this.validateDetachedRelationship(l,r,_.from.dataset,"dataset"),this.validateDetachedRelationship(l,r,b,"dimension"),_.from.dataset.length&&b.length&&(l.append(this.validateLeftRelations(r,_,i,o)),l.append(this.validateRightRelations(r,_,i,o)),l.append(this.validateMismatchedRelationKeys(r,_,i,o)))}Ic.isRegularRelation(_)&&(_.constraint_translation&&l.append(this.validateConstraintTranslationInRelationships(_,r,i)),l.append(this.validateScdRelationship(r,_,i))),ki.isSecurityRelation(_)&&(this.validateDetachedRelationship(l,r,_.from.dataset,"dataset"),this.validateDetachedRelationship(l,r,_.to.row_security,"row_security"),_.from.dataset.length&&_.to.row_security.length&&(l.append(this.validateLeftRelations(r,_,i,o)),l.append(this.validateRightRelations(r,_,i,o))))}),l}validateConstraintTranslationRank(r,i,o,l){let p=Mo.create();return r.constraint_translation_rank===void 0&&p.file(i).addError(ih.getLevelMissingConstraintTranslationRank(l,o.to.dimension,o.unique_name)),p}validateNumberOfFromColumnsAndKeyColumns(r,i,o,l){let p=Mo.create();return r.key_columns.length!==o.length&&p.file(i).addError(ih.getConstraintTranslationColumnsNotMatch(l)),p}validateFromColumnsVsKeyColumnTypes(r,i,o,l,p){let _=Mo.create(),b=this.getFromColumnsWithTypes(r,o,p),T=this.getKeyColumnsWithTypes(r,l,i,_);if(T.length===b.length)for(let E=0;E<T.length;E++){let k=T[E],j=b[E];Zl.hasColumnDataTypeProp(k)&&Zl.hasColumnDataTypeProp(j)&&k.data_type!==j.data_type&&_.file(i).addError(ih.getFromColumnsNotMatchingKeyColumnTypes(l.unique_name,o.unique_name,j,k))}return _}validateColumnExistsInFactTable(r,i,o,l){let p=Mo.create(),_=r.get(o.from.dataset);return l.forEach(b=>{_&&_l.isDataset(_.data)&&(_.data.columns.find(E=>E.name===b)||p.file(i).addError(ih.getColumnNotExistInFactTable(b,_.data.unique_name)))}),p}getFromColumnsWithTypes(r,i,o){let l=[],p=r.get(i.from.dataset);return o.forEach(_=>{if(p&&_l.isDataset(p.data)){let b=p.data.columns.find(T=>T.name===_);b&&l.push(b)}}),l}getKeyColumnsWithTypes(r,i,o,l){let p=r.get(i.dataset);if(!p||!_l.isDataset(p.data))return l.file(o).addError(ih.referenceObjectNotExist("dataset",i.dataset)),[];let _=p.data.columns;return i.key_columns.flatMap(b=>{let T=_.find(E=>E.name===b);return T?[T]:[]})}validateConstraintTranslationInRelationships(r,i,o){let l=Mo.create();if(Ic.isRegularRelation(r)&&r.constraint_translation){let{level:p,from_columns:_}=r.constraint_translation,b=o.get(r.to.dimension);if(!b||!_l.isDimension(b.data))return l.file(i).addError(ih.referenceObjectNotExist("dimension",r.to.dimension)),l;let T=b.data.level_attributes.find(E=>E.unique_name===p);if(!T)return l.file(i).addError(ih.getLevelDoesNotExistInDimensionError(p,r.to.dimension)),l;ki.isLevelFromOneDataset(T)&&(l.append(this.validateConstraintTranslationRank(T,i,r,p)),l.append(this.validateNumberOfFromColumnsAndKeyColumns(T,i,_,p)),l.append(this.validateFromColumnsVsKeyColumnTypes(o,i,r,T,_))),l.append(this.validateColumnExistsInFactTable(o,i,r,_))}return l}validateRelationshipsReferences(r,i,o){if(_l.isModel(i.data)){let l=[...i.data.relationships];o.forEach(p=>{if(_l.isDimension(p.data)&&p.data.relationships){let _=p.data.relationships.filter(b=>ki.isEmbeddedRelation(b));l.push(..._)}}),i.data.drillthroughs&&i.data.drillthroughs.forEach(p=>this.validateReferencePath(r,i,p,l)),i.data.aggregates&&i.data.aggregates.forEach(p=>this.validateReferencePath(r,i,p,l))}return r}validateReferencePath(r,i,o,l){let p=[];return o.attributes?.filter(YL).forEach(_=>{_.relationships_path&&p.push(..._.relationships_path)}),p.forEach(_=>{l.some(b=>b.unique_name===_)||r.file(i).addError(ih.invalidRelationshipPath(_,o.unique_name,i.relativePath))}),r}validateAttributesReferences(r,i,o,l){l.forEach(p=>{let _=this.validateAndGetReferencedObject(p.dimension,o,i,"dimension",r);if(!_)return;let b=_.data,T=b.level_attributes.some(E=>E.unique_name===p.name);T=T||b.hierarchies.flatMap(E=>E.levels).flatMap(E=>[...E.secondary_attributes||[],...E.aliases||[],...E.metrics||[]]).some(E=>E?.unique_name===p.name),T||r.file(i).addError(`Dimension ${_.data.unique_name} has no referenced object ${p.name}`)})}validatePerspectiveDimensionReferences(r,i,o,l){l.forEach(p=>{this.validateAndGetReferencedObject(p.name,o,i,"dimension",r)})}validateMetricReferences(r,i,o,l){l.forEach(p=>{o.get(p)||r.file(i).addError(ih.referenceObjectNotExist("Metric or CalcMetric",p))})}validateDetachedRelationship(r,i,o,l){o?.length||r.file(i).addWarning(ih.detachedRelationships(i.data.unique_name,l))}validateLeftRelations(r,i,o,l){let p=Mo.create(),_=this.validateAndGetReferencedObject(i.from.dataset,o,r,"dataset",p);return _&&(l.add(i.from.dataset),!i.from.join_columns.every(T=>_.data.columns.some(E=>T===E.name))&&p.file(r).addError(ih.invalidDatasetRelationship(_.data.unique_name,_.relativePath,i.from.join_columns))),p}validateRightRelations(r,i,o,l){let p=Mo.create();if(ki.isSecurityRelation(i)||Ic.isSecurityRelation(i)){let _=this.validateAndGetReferencedObject(i.to.row_security,o,r,"row_security",p);return _&&(l.add(i.to.row_security),_||p.file(r).addError(ih.invalidRowSecurityRelationship(i.to.row_security))),p}else{let _=i.type==="snowflake"?r.data.unique_name:i.to.dimension,b=this.validateAndGetReferencedObject(_,o,r,"dimension",p);return b&&(l.add(_),!b.data.level_attributes.some(E=>E.unique_name===i.to.level)&&p.file(r).addError(ih.invalidDimensionRelationship(b.data.unique_name,b.relativePath,i.to.level))),p}}validateMismatchedRelationKeys(r,i,o,l){let p=Mo.create(),_=ki.isSnowflakeRelation(i)?r.data.unique_name:i.to.dimension,b=this.validateAndGetReferencedObject(_,o,r,"dimension",p);if(!b)return p;l.add(_);let{join_columns:T}=i.from,{level_attributes:E}=b.data,k=E.find(qL(i.to.level));if(!k)return p;let{key_columns:j}=k;if(T.length!==j.length){let z=ih.mismatchedRelationshipKeys(i.from.dataset,T.length,i.to.level,j.length);p.file(r).addError(z)}return p}};var qoe={getDuplicateMetricUniqueNames:(n,r)=>`Metric ${n.unique_name} is used ${r} times in composite model and its dependency models`,getDuplicateDimensionUniqueNames:(n,r)=>`Dimension ${n} is used ${r} times in composite model's dependency models`,getDuplicateQueryNameOverrides:(n,r)=>`Query name ${n} is used ${r} times in the overrides of composite model's dependency models`,commonRelationshipDimension:"Composite model's dependency models don't have a common dimension"};var XTe=class{constructor(r,i){this.yamlCommonReferenceValidator=r;this.yamlModelAggregateValidator=i}validateObject(r,i,o){let l=r.data,p=Mo.create();this.validateMetrics(r,l.metrics,i,o,p),this.validateModels(r,l,i,o,p);let _=Array.from(i.values()),b=XL(r,_);return this.yamlModelAggregateValidator.validateAggregates(p,b,i),p}validateMetrics(r,i,o,l,p){i?.forEach(_=>{this.yamlCommonReferenceValidator.validateAndGetReferencedObject(_.unique_name,o,r,"metric_calc",p)&&l.add(_.unique_name)})}validateModels(r,i,o,l,p){let _=i.metrics||[],b=[],T=[],E=[];i.models.forEach(j=>{let z=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(j,o,r,"model",p);if(!z)return;let X=z.data;_=_.concat(X.metrics),b=b.concat(X.dimensions||[]),T=T.concat(Object.values(X.overrides||[]).map(ue=>ue.query_name)),E.push(new Set(X.relationships.map(ue=>Ic.isRegularRelation(ue)?ue.to.dimension:"").filter(ue=>ue))),l.add(j)});let k=p.file(r);this.validateUniqueMetrics(k,_),this.validateUniqueDegenerateDimensions(k,b),this.validateUniqueQueryNameOverrides(k,T),this.validateCommonRelationshipDimension(k,E)}validateUniqueMetrics(r,i){let o=rl.groupBy(i,l=>[l.unique_name]);rl.appendErrorsIfDuplicates(o,r,qoe.getDuplicateMetricUniqueNames)}validateUniqueDegenerateDimensions(r,i){let o=rl.groupBy(i,l=>[l]);rl.appendErrorsIfDuplicates(o,r,qoe.getDuplicateDimensionUniqueNames)}validateCommonRelationshipDimension(r,i){if(i.length<2)return;rl.findCommonElement(i)||r.addError(qoe.commonRelationshipDimension)}validateUniqueQueryNameOverrides(r,i){let o=rl.groupBy(i,l=>[l]);rl.appendErrorsIfDuplicates(o,r,qoe.getDuplicateQueryNameOverrides)}};var ZTe=class{validateObject(r,i){let o=r.data,l=Mo.create();return i.forEach(p=>{let _=p.data;o.unique_name!==_.unique_name&&_.object_type==="connection"&&o.as_connection===_.as_connection&&o.database===_.database&&o.schema===_.schema&&l.file(r).addWarning(`Connection "${o.unique_name}" is duplicated with file ${p.relativePath}`)}),l}};var qVe=Ak.getAllValues(Pk),BVe=Ak.getAllValues(Y6),n4r=n=>{let r=qVe.find(i=>n.startsWith(i));if(r)return r},i4r=n=>qVe.some(r=>r===n),s4r=n=>{let r=BVe.find(i=>n.startsWith(i));if(r)return r},a4r=n=>BVe.some(r=>r===n),o4r=n=>{let r=BVe.find(l=>n.startsWith(l));if(!r)return!1;let i=n.replace(r,"");return/^\(\d*,\d*\)$/gm.test(i)},c4r={allDataTypes:qVe,getColumnTypeFromYaml:n4r,hasColumnExactMatch:i4r,isColumnPrecisionType:a4r,isValidPrecisionFormat:o4r,getColumnTypeWithPrecisionFromYaml:s4r},wx=c4r;var l4r=new RegExp(`^(${Object.values(Y6).join("|")})\\(\\d+,\\s*0\\)$`);function nkt(n){return l4r.test(n)}var ikt=["long","int","bigint"],u4r=["timestamp","datetime","date"],skt=[...ikt,...u4r],mC={parentColNotExist:n=>`Parent column "${n}" does not exist`,parentColIsTheSame:n=>`Parent column "${n}" should not be the same column`,parentColNoParent:n=>`Parent column "${n}" should not have parent property set`,invalidDataType:(n,r)=>`Column "${n}" has invalid data_type: "${r}". Supported data types are ${wx.allDataTypes.join(",")}`,invalidPrecisionDataType:(n,r,i)=>`Column "${n}" has invalid data_type: "${r}". Precision is not well formed. It should be "${i}(x,y)"`,datasetReferencesSameTable:(n,r)=>`There is another dataset referencing the same table/view. Unique name "${n}", filepath: "${r}"`,incrementColumnNotExist:n=>`Referenced column "${n}" in incremental does not exist`,incrementColumnInvalidColumnType:n=>`Referenced column "${n}" type is invalid. Supported column types: ${skt.join(", ")}`,invalidGracePeriod:"Invalid incremental grace_period.",invalidDurationGracePeriod:"Invalid incremental grace_period. The duration should contain a non-negative integer value, followed by time unit. Time unit can be 's' (second), 'm' (minute), 'h' (hour), 'd' (day) or 'w' (week). Example: '100s', '15d', '2w'.",invalidIntegerGracePeriod:"Invalid incremental grace_period. Grace period must be a non-negative integer for integer-like columns.",duplicateColumnName:(n,r)=>`Duplicate column name "${n}". ${r} duplicate items found`,missingDatabaseInConnectionIfQDSDataset:n=>`Connection file with name "${n}" must have specified "database", because dataset use table.`,missingSchemaInConnectionIfQDSDataset:n=>`Connection file with name "${n}" must have specified "schema", because dataset use table.`},eCe=class{constructor(r){this.yamlCommonReferenceValidator=r}validateObject(r,i,o){let l=Mo.create(),p=r.data,_=p.connection_id;this.validateConnectionAndAddReferenceObjectId(_,r,i,o,l,!Zl.hasDatasetSqlProp(p)),p.alternate!==void 0&&Zl.isAlternateTable(p.alternate)&&this.validateConnectionAndAddReferenceObjectId(p.alternate.connection_id,r,i,o,l,!!p.alternate.table),p.columns.filter(Zl.isDerivedColumn).forEach(k=>{if(k.name===k.parent_column)return l.file(r).addError(mC.parentColIsTheSame(k.name));let j=p.columns.find(z=>k.parent_column===z.name);j||l.file(r).addError(mC.parentColNotExist(k.parent_column)),j&&Zl.isDerivedColumn(j)&&l.file(r).addError(mC.parentColNoParent(j.name))}),p.columns.forEach(k=>{this.validateColumn(r,k,l)});let T=rl.groupBy(p.columns.map(k=>k.name),k=>[k]);return rl.appendErrorsIfDuplicates(T,l.file(r),mC.duplicateColumnName),Array.from(i.values()).filter(k=>{let j=k.data;return j.object_type==="dataset"&&j.table===p.table&&j.connection_id===p.connection_id&&j.unique_name!==p.unique_name&&!Zl.hasDatasetSqlProp(j)}).forEach(k=>l.file(r).addWarning(mC.datasetReferencesSameTable(k.data.unique_name,k.relativePath))),p.incremental&&this.validateIncremental(p.incremental,p.columns,l.file(r)),l}validateIncremental(r,i,o){let l=i.find(p=>p.name===r.column);l||o.addError(mC.incrementColumnNotExist(r.column)),l?.data_type&&!skt.includes(l?.data_type)&&!nkt(l?.data_type)&&o.addError(mC.incrementColumnInvalidColumnType(r.column)),this.validateGracePeriod(r.grace_period,l?.data_type,o)}validateGracePeriod(r,i,o){let l=i&&(ikt.includes(i)||nkt(i));(l?G6.isValidNonNegativeInteger(r):G6.isValidDuration(r))||o.addError(l?mC.invalidIntegerGracePeriod:mC.invalidDurationGracePeriod)}validateConnectionAndAddReferenceObjectId(r,i,o,l,p,_){let b=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(r,o,i,"connection",p);b&&(l.add(r),this.validateDatabaseAndSchemaInReferencedConnection(i,b.data,p,_))}validateDatabaseAndSchemaInReferencedConnection(r,i,o,l){if(!l)return;let p=r.data,_=i;_&&!_.database&&o.file(r).addError(mC.missingDatabaseInConnectionIfQDSDataset(p.connection_id)),_&&!_.schema&&o.file(r).addError(mC.missingSchemaInConnectionIfQDSDataset(p.connection_id))}validateColumn(r,i,o){if(Zl.hasColumnDataTypeProp(i)){if(!wx.getColumnTypeFromYaml(i.data_type)){o.file(r).addError(mC.invalidDataType(i.name,i.data_type));return}let p=wx.getColumnTypeWithPrecisionFromYaml(i.data_type);if(p!==void 0){if(!wx.hasColumnExactMatch(i.data_type)&&!wx.isValidPrecisionFormat(i.data_type)){o.file(r).addError(mC.invalidPrecisionDataType(i.name,i.data_type,p));return}}else wx.hasColumnExactMatch(i.data_type)||o.file(r).addError(mC.invalidDataType(i.name,i.data_type))}}};var Bb;(function(n){n.Int="int",n.Decimal="decimal",n.Long="long",n.Double="double",n.Float="float",n.String="string",n.DateTime="datetime",n.Date="date",n.Boolean="boolean",n.BigInt="bigint",n.TinyInt="tinyint",n.Number="number",n.TimeStamp="timestamp",n.Numeric="numeric"})(Bb||(Bb={}));var akt;(function(n){n.Numeric="numeric",n.Number="number",n.Decimal="decimal"})(akt||(akt={}));var Qh;(function(n){n.GeneralNumber="general number",n.Standard="standard",n.Scientific="scientific",n.Fixed="fixed",n.Percent="percent",n.GeneralDate="general date",n.LongDate="long date",n.MediumDate="medium date",n.ShortDate="short date",n.LongTime="long time",n.MediumTime="medium time",n.ShortTime="short time",n.YesNo="yes/no",n.TrueFalse="true/false",n.OnOff="on/off"})(Qh||(Qh={}));var tD=[Qh.GeneralNumber,Qh.Standard,Qh.Scientific],tCe=tD.concat([Qh.Fixed,Qh.Percent]),$Ve=[Qh.GeneralDate,Qh.LongDate,Qh.MediumDate,Qh.ShortDate,Qh.LongTime,Qh.MediumTime,Qh.ShortTime],f4r=[Qh.YesNo,Qh.TrueFalse,Qh.OnOff],f7={[Bb.Int]:tD,[Bb.Long]:tD,[Bb.Float]:tCe,[Bb.Double]:tCe,[Bb.Decimal]:tCe,[Bb.DateTime]:$Ve,[Bb.Date]:$Ve,[Bb.Boolean]:f4r,[Bb.String]:[],[Bb.BigInt]:tD,[Bb.TinyInt]:tD,[Bb.Number]:tD,[Bb.TimeStamp]:$Ve,[Bb.Numeric]:tCe},jO=n=>Array.from(new Set(Object.values(n).flat()));var rCe=n=>{let r=n.filter(Ic.isRegularRelation);return rl.groupBy(r,i=>[i.from.dataset,i.to.dimension,i.to.level,i.role_play])};var Ah={getDimensionDegenerateError:(n,r)=>`The dimension '${r}' should ${n?"be degenerative":"not be degenerative"}.`,getCalcMeasureContainsANonExistingMeasure:(n,r)=>`Calculated metric "${n}" expression contains a non-existing metric: ${r}.`,getDuplicateRelationshipsMessage:(n,r)=>Ic.isSecurityRelation(n)?`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}] to row_security: ${n.to.row_security}`:`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}] to dimension: ${n.to.dimension} and level: ${n.to.level}`,getMultiRelationshipsToLevelMessage:(n,r)=>Ic.isSecurityRelation(n)?`There are ${r} relationships from ${n.from.dataset} to ${n.to.row_security} - row security. Please specify unique role-playing templates in the relationships.`:Ic.isRegularRelation(n)?`There are ${r} relationships from ${n.from.dataset} to ${n.to.dimension} - Level ${n.to.level}. Please specify unique role-playing templates in the relationships.`:`There are ${r} relationships from ${n.from.dataset} to - Level ${n.to.level}. Please specify unique role-playing templates in the relationships.`,getDuplicateRelationshipsUniqueNameMessage:(n,r)=>`There are ${r} relationships with the same unique_name: ${n.unique_name}.`,getDuplicateMetricUniqueNames:(n,r)=>`Metrics must NOT have duplicate items (${n.unique_name} appears ${r} times)`,getDuplicateAggregatesUniqueNames:(n,r)=>`Aggregates must NOT have duplicate items (${n.unique_name} appears ${r} times)`,overridesInfo:"query_name overrides detected in model",getOverrideNotReferencedInModel:n=>`Override "${n}" is not referenced in the metrics or dimensions`,getOverridesDuplicateOnQueryNames:n=>`${n.map(r=>`${r.object_type} with unique_name "${r.unique_name}"`).join(", ")} have the same query_name "${n[0]?.query_name}"`,getDatasetForPropertiesNotExist:n=>`Dataset for dataset_properties ${n} not exist.`,getDatasetPropertiesIncorrectType:n=>`Dataset properties reference ${n} is not dataset`,getDrillThroughAttributeNotFoundInModel:(n,r)=>`Drillthrough "${n}" references dimension "${r}" that does not exist in the model.`,getDrillThroughMetricNotFoundInModel:(n,r)=>`Drillthrough "${n}" references metric "${r}" that does not exist in the model.`,getPerspectiveMetricNotFoundInModel:(n,r)=>`Perspective "${n}" references metric "${r}" that does not exist in the model.`,getPerspectiveDimensionNotFoundInModel:(n,r)=>`Perspective "${n}" references dimension "${r}" that does not exist in the model.`,getPerspectiveHierarchyLevelNotFound:(n,r,i,o)=>`Perspective "${n}" references hierarchy "${r}" with level "${i}" that does not exist in dimension "${o}".`,getPerspectiveHierarchyNotFound:(n,r,i)=>`Perspective "${n}" references hierarchy "${r}" that does not exist in dimension ${i}.`,getPerspectiveSecondaryAttributeNotFound:(n,r,i)=>`Perspective "${n}" references secondary attribute "${r}" that does not exist in dimension "${i}".`,getMaximumDepthOfNestedDimensionExceeded:n=>`A dimension referenced in perspectives or drill-through cannot have more than the maximum allowed depth of nested dimensions. Max depth allowed: ${n}`,getM2MPropDetectedInRelation:n=>`Property "m2m" detected in a relationship with unique_name: "${n}". It is allowed only in embedded dimensional relationships.`},nCe={getDrillTroughExistingWarning:"Warning: drillthroughs are not yet supported and will be skipped.",getTargetConnectionWarning:(n,r)=>`target_connection is obsolete. Please remove it. Aggregate at index ${r}, agg name: ${n}`,levelsPropDetectedInPerspective:(n,r,i)=>`An obsolete property "levels" detected in perspectives[unique_name=${n}] -> dimensions[name=${r}] -> hierarchies[name${i}]`};var d4r=n=>Pa.hasProps(n,"column"),okt=n=>d4r(n)?n.column:n.name_column,_4r=n=>{let r="";return n.forEach((i,o)=>{let l=i.map(p=>p.name).join(", ");r+=`Column: "${l}" with data type: ${o}. `}),r},ckt=n=>n?`Hierarchy "${n.hierarchyName}" with Level "${n.levelName}" with ${n.attributeType}`:"Level",rp={notExistingCol:(n,r)=>`Non-existing column "${n}" in dataset "${r}"`,notApplicableFormatForColType:n=>`Inapplicable formatting for column data_type. ${ckt(n.hierarchy)} "${n.attribute.unique_name}" should not have format property set for column type "${n.colType}" with name "${okt(n.attribute)}"`,formatNotCompatibleWithColType:(n,r)=>`Incompatible formatting for related column data_type. ${ckt(n.hierarchy)} "${n.attribute.unique_name}" with format "${n.attribute.format}" is incompatible with "${n.colType}" for column "${okt(n.attribute)}". Possible formats: ${r[n.colType].join(", ")}`,duplicateSnowflakeRelationshipsMessage:(n,r)=>`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}] to level: ${n.to.level}`,duplicateEmbeddedRelationshipsMessage:(n,r)=>`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}], hierarchy: ${n.from.hierarchy} and level: ${n.from.level} to dimension: ${n.to.dimension} and level: ${n.to.level}`,formatNotCompatibleWithMetric:(n,r)=>`Incompatible format(${r}) for metric "${n}". Possible formats: ${tD.join(", ")}`,missingRelationshipHierarchy:n=>`Non-existing hierarchy named "${n}"`,invalidCalcMemberExpression:n=>`Invalid calculated member expression: ${n}`,duplicateCalcMemberNameInCalcGroup:n=>`There are calculated members with duplicated names in "${n}" calculation group`,timeUnitPropDetectedInLevel:(n,r)=>`Property "time_unit" detected in hierarchy: "${n}" with level: "${r}"`,customEmptyMemberSortNameMissing:(n,r)=>`Custom empty member should have sort_name property when sort_column is set. Affected ${r}: "${n}"`,timeUnitMissingInTimeDimension:n=>`Level "${n}" is part of a time dimension but property "time_unit" is missing`,sharedDegenerateLevelColumnsError:(n,r,i)=>`${n} for a level in a shared degenerate dimension should have the same data type. Affected level: ${r}. ${i}`,invalidLevelAttributeReference:(n,r)=>`hierarchy[${n.unique_name!==void 0?`unique_name="${n.unique_name}"`:n.label!=null?`label="${n.label}"`:`index=${n.index}`}], level "${r}" has no corresponding level_attribute definition`,inconsistentDuplicatedLevel:(n,r)=>`Level "${n}" is duplicated in the following hierarchies: ${r.map(i=>`"${i}"`).join(", ")}, but the levels below it differ. All levels below "${n}" must match across these hierarchies.`,invalidTimeUnitLevelOrder:n=>`hierarchy[${n.hierarchyName}], level "${n.levelName}" Time Units must be greater than or equal to the level below it (i.e. Hour -> Minute) in a time hierarchy`,duplicateDegenerateDimensionLevelAttributesMessage:(n,r,i)=>`Dataset "${n}" and key columns "${r.join(", ")}" combination is duplicated in level attributes: ${i.join(", ")}`,duplicateDegenerateDimensionLevelsMultipleDatasetsMessage:(n,r)=>`There are duplicated level attributes (${r.join(", ")}) using the same datasets (${n.join(", ")}) and the same key columns.`,sharedLevelAttributesNotPointingToSameDatasets:(n,r,i)=>`Level attributes should point to the same datasets. Dataset "${n}" is being used in ${r} out of ${i} level attributes.`,degenerateDimensionLevelAttributesTypeError:(n,r)=>`Level attributes in a degenerate dimension must be of the same type. The dimension has single dataset attributes: ${nh(n)} and multiple datasets attributes: ${nh(r)}`,secondaryAttributeInMultipleDatasetLAError:(n,r)=>`Secondary attributes are not allowed for level attributes with multiple datasets in degenerate dimensions. Affected level "${n}". Remove: "${r}"`,numberOfSortColumnsInMultipleDatasetsDegenerateError:n=>`Level "${n}" only has a sort column for some of its datasets. Either all datasets should have a sort column, or none should have one.`,multipleDatasetsInNormalDimensionNotAllowed:n=>`Only levels in a degenerate dimension can have multiple datasets. Property "shared_degenerate_columns" is not allowed for level "${n}".`,referredLevelNameIsEqualToParenLevelError:(n,r)=>`The referred level name "${n}" is equal to parent level name "${r}".`,referredLevelNameIsNotInTheSameHierarchyError:n=>`The referred level name "${n}" in parallel period is not in the same hierarchy.`,parallelPeriodShouldBeUseOnlyInTimeDimensionError:()=>"Parallel period should be use only in time dimension.",parallelPeriodKeyColumnIsNotExistInRelatedLevelDatasets:(n,r)=>`The parallel period key_column "${n}" does not exist in dataset "${r}"`,getM2MPropDetectedInRelation:n=>`Property "m2m" detected in a ${n} relationship. It is allowed only in embedded relationships.`,invalidReference:(n,r)=>`Invalid reference ${n.join(" -> ")}. ${r}`,scdOnlySimpleColumnsAreAllowed:(n,r)=>`Column "${r}" is not simple column. ${n.join(" -> ")}.`,scdInvalidDataType:(n,r,i)=>rp.invalidReference(n,`Column "${r.name}" has invalid data_type "${r.data_type}". Allowed types are: ${i.join(", ")}`),scdInvalidTemplateMissingPlaceholder:(n,r)=>`Invalid template. Missing "{0}" place holder. ${n.join(" -> ")}. Template: "${r}"`,scdInvalidTemplateMultiplePlaceholders:(n,r)=>`Invalid template. More than one place holders "{0}". ${n.join(" -> ")}. Template: "${r}"`,scdDuplicateColumns:(n,r)=>`Duplicate columns usage for ${r.join(", ")}. You cannot use same column. ${n.join(" -> ")}.`,scdGetMultipleLevelsWithScdOnOneHierarchy:(n,r,i)=>`Error in hierarchy "${n}" -> level "${r}". Multiple levels with slowly changing dimensions settings in one hierarchy is not supported. Other levels with SCD: ${i.join(", ")}`,scdColumnsDataTypesDoNotMatch:n=>`All slowly changing dimensions columns should have same data_type. Current: ${n.map(r=>`${r.column}:${r.data_type}`).join(", ")}`,rowSecurityScopeFactOnlyError:(n,r,i)=>`Security Dimension ${n}_attribute_${r} has scope \u201C${i}\u201D but is not connected to a fact dataset.`},iCe=class{constructor(r,i,o,l=f7){this.yamlCommonReferenceValidator=r,this.expressionValidator=i,this.formatMap=l,this.yamlErrorContextUtil=o}validateObject(r,i,o){let l=r.data,p=Mo.create(),_=[];return this.verifyDegenerateDimsLevelTypes(l,p.file(r)),l.level_attributes.forEach(b=>{this.validateCustomEmptyMember(b,p,r,"level"),this.validateTimeUnitProperty(b,l,p,r),this.verifyNormalDimensionsHaveASingleDataset(b,l,p.file(r)),this.verifyDimensionDatasetsAndColumns({levelAttribute:b,item:r,validatorOutput:p,elementsMap:i,referencedObjectIds:o}),this.verifyLevelAttributesForDegenerateDim(b,l,p.file(r)),ki.isLevelFromOneDataset(b)&&b.scd_properties&&(_.push(b.unique_name),this.validateSlowlyChangingDimensionProperties(r,b,i,p))}),p.append(this.yamlCommonReferenceValidator.validateRelationships(r,i,o)),l.relationships&&(this.validateUniqueRelationships(p.file(r),l.relationships.filter(ki.isEmbeddedRelation),rp.duplicateEmbeddedRelationshipsMessage),this.validateUniqueRelationships(p.file(r),l.relationships.filter(ki.isSnowflakeRelation),rp.duplicateSnowflakeRelationshipsMessage),this.validateRelationshipHierarchy(p.file(r),l.relationships.filter(ki.isEmbeddedRelation),l.hierarchies.map(b=>b.unique_name)),this.validateRelationshipM2MProp(p.file(r),l.relationships),this.validateSecurityRelationshipsWithRowSecurityScope(p.file(r),i,l.relationships.filter(ki.isSecurityRelation))),l.calculation_groups?.forEach(b=>{this.validateUniqueCalcMemberNameInCalcGroup(p.file(r),b.calculated_members.map(T=>T.unique_name),b.unique_name),b.calculated_members.forEach(T=>{let E=T.expression;E&&!this.expressionValidator.areParenthesesValid(E)&&p.file(r).addError(rp.invalidCalcMemberExpression(E))})}),l.hierarchies.forEach((b,T)=>{this.validateSlowlyChangingDimensionHierarchy(r,b,_,p),b.levels.forEach((E,k)=>{let j={hierarchyName:b.unique_name||b.label,levelName:E.unique_name};E.parallel_periods&&(this.validateParallelPeriodIsOnlyInTimeDimension(l,b.levels,p.file(r)),this.validateReferredLevelParallelPeriod(b,E,p.file(r)),this.validateParallelPeriodKeyColumnsExistsInTheRelatedLevelDatasets(l,E.parallel_periods,i,o,r,p));let z=l.level_attributes.find(X=>X.unique_name===E.unique_name);if(!z){let X=new qk().getLevelContext({hierarchyUniqueName:j.hierarchyName,validationType:"not_existing_level_reference",itemUniqueName:E.unique_name,message:"no corresponding level_attribute definition"});p.file(r).addErrorWithContext(rp.invalidLevelAttributeReference({...b,index:T},E.unique_name),X)}if(this.timeUnitLevelHasOrderError(l.level_attributes,z,b.levels[k-1])){let X=this.yamlErrorContextUtil.getLevelContext({hierarchyUniqueName:j.hierarchyName,validationType:"invalid_time_unit_order",itemUniqueName:j.levelName,message:"invalid time_unit level order"});p.file(r).addErrorWithContext(rp.invalidTimeUnitLevelOrder(j),X)}E.secondary_attributes?.forEach(X=>{this.validateDegenerateDimensionSecondaryAttribute(X,E,l,p.file(r)),this.validateCustomEmptyMember(X,p,r,"secondary-attribute");let ue=this.getYamlDataset(X.dataset,i,o,r,p),De={...j,attributeType:"secondary_attribute"};this.validateDatasetColumns(ue,X,r,p,De)}),E.aliases?.forEach(X=>{let ue=this.getYamlDataset(X.dataset,i,o,r,p),De={...j,attributeType:"level_alias"};this.validateDatasetColumns(ue,X,r,p,De)}),E.metrics?.forEach(X=>{let ue=this.getYamlDataset(X.dataset,i,o,r,p);if(!ue)return;let De=this.getDatasetColumn(ue,X.column,r,p);De&&Zl.hasColumnDataTypeProp(De)&&this.validateMetricFormatProperty(X,p.file(r))}),"time_unit"in E&&p.file(r).addError(rp.timeUnitPropDetectedInLevel(b.unique_name,E.unique_name))})}),this.validateInconsistentDuplicatedLevel(l.hierarchies,p.file(r)),this.validateUniqueMultipleRelationshipsToLevel(p.file(r),l),p}validateInconsistentDuplicatedLevel(r,i){let o=r.flatMap(({levels:p,unique_name:_})=>p.map(({unique_name:b},T)=>({levelName:b,hierarchyName:_,levelSubTree:p.slice(T).map(({unique_name:E})=>E)}))),l=rl.groupBy(o,({levelName:p})=>[p]);Array.from(l.values()).reverse().some(p=>{let _=p.map(({levelSubTree:E})=>E);if(fwt(_))return!1;let[{levelName:b}]=p,T=p.map(({hierarchyName:E})=>E);return i.addError(rp.inconsistentDuplicatedLevel(b,T)),!0})}validateUniqueMultipleRelationshipsToLevel(r,i){if(i.relationships){let o=rCe(i.relationships);rl.appendErrorsIfDuplicates(o,r,Ah.getMultiRelationshipsToLevelMessage)}}getParallelLevelDatasets(r,i,o,l,p,_){let b=new Set;return r.level_attributes.forEach(T=>{T.unique_name===i&&(ki.isLevelWithMultipleDatasets(T)?T.shared_degenerate_columns.forEach(E=>b.add(E.dataset)):b.add(T.dataset))}),Array.from(b).map(T=>this.getYamlDataset(T,o,l,p,_)).filter(T=>T!==void 0)}validateParallelPeriodKeyColumnsExistsInTheRelatedLevelDatasets(r,i,o,l,p,_){i.forEach(b=>{let T=this.getParallelLevelDatasets(r,b.level,o,l,p,_);b.key_columns.forEach(E=>{T.forEach(k=>{k.columns.some(j=>j.name===E)||_.file(p).addError(rp.parallelPeriodKeyColumnIsNotExistInRelatedLevelDatasets(E,k.unique_name))})})})}validateReferredLevelParallelPeriod(r,i,o){let l=us.ensure(i.parallel_periods,"Do not have parallel periods in level"),p=l.filter(b=>b.level===i.unique_name);p.length>0&&p.forEach(b=>{o.addError(rp.referredLevelNameIsEqualToParenLevelError(i.unique_name,b.level))});let _=l.filter(b=>!r.levels.some(T=>b.level===T.unique_name));_.length>0&&_.forEach(b=>{o.addError(rp.referredLevelNameIsNotInTheSameHierarchyError(b.level))})}validateParallelPeriodIsOnlyInTimeDimension(r,i,o){r.type!=="time"&&i.some(p=>p.parallel_periods!==void 0)&&o.addError(rp.parallelPeriodShouldBeUseOnlyInTimeDimensionError())}validateDegenerateDimensionSecondaryAttribute(r,i,o,l){let p=o.level_attributes.find(_=>_.unique_name===i.unique_name);p&&ki.isLevelWithMultipleDatasets(p)&&l.addError(rp.secondaryAttributeInMultipleDatasetLAError(i.unique_name,r.unique_name))}verifyDegenerateDimsLevelTypes(r,i){if(!r.is_degenerate)return;let o=r.level_attributes.filter(p=>ki.isLevelWithMultipleDatasets(p)),l=r.level_attributes.filter(p=>ki.isLevelFromOneDataset(p));if(o.length===r.level_attributes.length)this.verifySharedDegenerateDimsDatasetsUsage(r,i);else{if(l.length===r.level_attributes.length)return;i.addError(rp.degenerateDimensionLevelAttributesTypeError(l.map(p=>p.unique_name),o.map(p=>p.unique_name)))}}verifySharedDegenerateDimsDatasetsUsage(r,i){if(!r.is_degenerate)return;let o=r.level_attributes.length;this.groupSharedLevelAttributesByDataset(r).forEach((p,_)=>{p.length!==o&&i.addWarning(rp.sharedLevelAttributesNotPointingToSameDatasets(_,p.length,o))})}groupSharedLevelAttributesByDataset(r){let i=new Map;return r.is_degenerate&&r.level_attributes.forEach(o=>{ki.isLevelWithMultipleDatasets(o)&&o.shared_degenerate_columns.forEach(l=>{i.has(l.dataset)||i.set(l.dataset,[]);let p=i.get(l.dataset);p&&p.push(o.unique_name)})}),i}verifyNormalDimensionsHaveASingleDataset(r,i,o){!i.is_degenerate&&ki.isLevelWithMultipleDatasets(r)&&o.addError(rp.multipleDatasetsInNormalDimensionNotAllowed(r.unique_name))}verifyDimensionDatasetsAndColumns(r){let{levelAttribute:i,item:o,validatorOutput:l,elementsMap:p,referencedObjectIds:_}=r;if(ki.isLevelWithMultipleDatasets(i))this.verifyMultipleDatasetsColumns(r),i.shared_degenerate_columns.forEach(b=>{let T=this.getYamlDataset(b.dataset,p,_,o,l),E={dataset:b.dataset,name_column:b.name_column,key_columns:b.key_columns,sort_column:b.sort_column,is_unique_key:b.is_unique_key,unique_name:i.unique_name,label:i.label};this.validateDatasetColumns(T,E,o,l)});else{let b=this.getYamlDataset(i.dataset,p,_,o,l);this.validateDatasetColumns(b,i,o,l)}}getLevelAttributeColumnsByType(r){let{levelAttribute:i,item:o,validatorOutput:l,elementsMap:p,referencedObjectIds:_}=r,b=[],T=[],E=[];return ki.isLevelWithMultipleDatasets(i)&&i.shared_degenerate_columns.forEach(k=>{let j=this.getYamlDataset(k.dataset,p,_,o,l);if(!j)return;let z=this.getSharedDegenerateDimensionColumn(j,k.key_columns[0],r),X=this.getSharedDegenerateDimensionColumn(j,k.name_column,r),ue=k.sort_column?this.getSharedDegenerateDimensionColumn(j,k.sort_column,r):void 0;!z||!X||(b.push(z),T.push(X),ue&&E.push(ue))}),{groupedKeyColumns:b,groupedValueColumns:T,groupedSortColumns:E}}verifyMultipleDatasetsColumns(r){let{levelAttribute:i}=r;if(ki.isLevelWithMultipleDatasets(i)){let{groupedKeyColumns:o,groupedValueColumns:l,groupedSortColumns:p}=this.getLevelAttributeColumnsByType(r);this.validateSharedDegenerateDimensionColumn(o,"Key columns",r),this.validateSharedDegenerateDimensionColumn(l,"Value columns",r),this.validateSharedDegenerateDimensionColumn(p,"Sort columns",r),this.validateNumberOfSortColumnsColumn(o,p,i,r.item,r.validatorOutput)}}validateNumberOfSortColumnsColumn(r,i,o,l,p){i.length!==0&&i.length!==r.length&&p.file(l).addError(rp.numberOfSortColumnsInMultipleDatasetsDegenerateError(o.unique_name))}validateSharedDegenerateDimensionColumn(r,i,o){let{levelAttribute:l,item:p,validatorOutput:_}=o,b=rl.groupBy(r,T=>[T.data_type]);b.size>1&&_.file(p).addError(rp.sharedDegenerateLevelColumnsError(i,l.unique_name,_4r(b)))}getSharedDegenerateDimensionColumn(r,i,o){let{item:l,validatorOutput:p}=o,_=this.getDatasetColumn(r,i,l,p);if(_&&Zl.hasColumnDataTypeProp(_))return _}verifyLevelAttributesForDegenerateDim(r,i,o){if(!i.is_degenerate)return;let l=this.getLevelDataSources(r),p=i.level_attributes.filter(_=>this.areTwoLevelDataSourcesEqual(l,this.getLevelDataSources(_)));if(!(p.length<=1))if(l.size===1){let[[_,b]]=Array.from(l.entries());o.addError(rp.duplicateDegenerateDimensionLevelAttributesMessage(_,b,p.map(T=>T.unique_name)))}else{let _=Array.from(l.keys());o.addError(rp.duplicateDegenerateDimensionLevelsMultipleDatasetsMessage(_,p.map(b=>b.unique_name)))}}getLevelDataSources(r){let i=new Map;return ki.isLevelFromOneDataset(r)&&i.set(r.dataset,r.key_columns),ki.isLevelWithMultipleDatasets(r)&&r.shared_degenerate_columns.forEach(o=>{i.set(o.dataset,o.key_columns)}),i}areTwoLevelDataSourcesEqual(r,i){return r.size!==i.size?!1:Array.from(r.entries()).every(([o,l])=>{let p=i.get(o);if(!p||l.length!==p.length)return!1;let _=[...l].sort(),b=[...p].sort();return _.every((T,E)=>T===b[E])})}validateDatasetColumns(r,i,o,l,p){if(!r)return;i.key_columns?.forEach(b=>{this.getDatasetColumn(r,b,o,l)}),i.sort_column&&this.getDatasetColumn(r,i.sort_column,o,l);let _=this.getDatasetColumn(r,i.name_column,o,l);_&&Zl.hasColumnDataTypeProp(_)&&this.validateFormatProperty(i,_.data_type,o,l,p)}validateTimeUnitProperty(r,i,o,l){i.type==="time"&&!r.time_unit&&o.file(l).addErrorWithContext(rp.timeUnitMissingInTimeDimension(r.unique_name),this.yamlErrorContextUtil.getLevelAttributeContext({itemUniqueName:r.unique_name,message:"time_unit missing",validationType:"time_unit"}))}validateCustomEmptyMember(r,i,o,l){if(r.custom_empty_member&&ki.isLevelFromOneDataset(r)&&r.sort_column&&!r.custom_empty_member.sort_name){let p=l==="level"?this.yamlErrorContextUtil.getLevelAttributeContext:this.yamlErrorContextUtil.getSecondaryAttributeContext;i.file(o).addErrorWithContext(rp.customEmptyMemberSortNameMissing(r.unique_name,l),p({itemUniqueName:r.unique_name,message:"custom_empty_member missing sort key",validationType:"custom_empty_member"}))}}validateMetricFormatProperty(r,i){if(!r.format)return;let o=jO(this.formatMap).find(l=>l===r.format);o&&!tD.includes(o)&&i.addError(rp.formatNotCompatibleWithMetric(r.unique_name,r.format))}validateFormatProperty(r,i,o,l,p){if(!r.format)return;let _=wx.getColumnTypeFromYaml(i);if(!_)return;let b={attribute:r,colType:_,hierarchy:p};if(!this.formatMap[_].length){l.file(o).addError(rp.notApplicableFormatForColType(b));return}let T=jO(this.formatMap).find(E=>E===r.format);T&&!this.formatMap[_].includes(T)&&l.file(o).addError(rp.formatNotCompatibleWithColType(b,this.formatMap))}getYamlDataset(r,i,o,l,p){let _=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(r,i,l,"dataset",p);if(_)return o.add(r),_.data}getDatasetColumn(r,i,o,l,p){let _=r.columns.find(b=>b.name===i);if(!_){let b=rp.notExistingCol(i,r.unique_name),T=p?.contextItems?rp.invalidReference(p?.contextItems,b):b;p?.validationContext?l.file(o).addErrorWithContext(T,{...p.validationContext,message:T}):l.file(o).addError(T)}return _}validateUniqueRelationships(r,i,o){let l=rl.groupBy(i,p=>{let _=Object.values(p.from).concat(Object.values(p.to));return ki.isEmbeddedRelation(p)?_.concat(p.role_play?[p.role_play]:[]):_});rl.appendErrorsIfDuplicates(l,r,o)}validateRelationshipM2MProp(r,i){i.forEach(o=>{let l=ki.isSnowflakeRelation(o),p=l||ki.isSecurityRelation(o);if(Object.prototype.hasOwnProperty.call(o,"m2m")&&p){let _=l?"snowflake":"security";r.addError(rp.getM2MPropDetectedInRelation(_))}})}validateRelationshipHierarchy(r,i,o){i.forEach(l=>{o.includes(l.from.hierarchy)||r.addError(rp.missingRelationshipHierarchy(l.from.hierarchy))})}validateSecurityRelationshipsWithRowSecurityScope(r,i,o){o.forEach(l=>{if(ki.isEmbeddedRelation(l)&&ki.isSecurityRelation(l)){let p=i.get(l.to.row_security);if(!p)return;let{data:_}=p;_.scope==="fact_only"&&r.addError(rp.rowSecurityScopeFactOnlyError(l.to.row_security,_.filter_key_column,"fact_only"))}})}validateUniqueCalcMemberNameInCalcGroup(r,i,o){rl.checkIfDuplicateNameExists(i)&&r.addError(rp.duplicateCalcMemberNameInCalcGroup(o))}timeUnitLevelHasOrderError(r,i,o){if(!o||!i?.time_unit)return!1;let l=Object.values(iQ),p=l.indexOf(i.time_unit),_=r.find(T=>T.unique_name===o.unique_name),b=-1;return _?.time_unit&&(b=l.indexOf(_?.time_unit)),p<b&&_?.time_unit!=="undefined"}validateSlowlyChangingDimensionHierarchy(r,i,o,l){if(o.length<=1)return;let p=i.levels.filter(_=>o.includes(_.unique_name)).map(_=>_.unique_name);p.length>1&&p.forEach((_,b)=>{let T=p.filter((j,z)=>z!==b),E=rp.scdGetMultipleLevelsWithScdOnOneHierarchy(i.unique_name,_,T),k=qk.create().getLevelContext({validationType:"custom",hierarchyUniqueName:i.unique_name,itemUniqueName:_,message:E});l.file(r).addErrorWithContext(E,k)})}validateSlowlyChangingDimensionProperties(r,i,o,l){if(!i.scd_properties)return;let p=o.get(i.dataset);if(!p)return;let{data:_}=p;if(!_l.isDataset(_))return;let b=[`level_attributes[unique_name=${i.unique_name}]`,"scd_properties"],T=qk.create().getLevelAttributeContext({itemUniqueName:i.unique_name,validationType:"custom",message:"To be set later"}),E=[],k=this.getScdColumnType(r,{contextItems:[...b,"effective_start"],validationContext:T},i.scd_properties.effective_start,_,l);this.scdValidateTemplate(r,{contextItems:[...b,"effective_start"],validationContext:T},i.scd_properties.effective_start,l),E.push({scdKey:"effective_start",column:i.scd_properties.effective_start.column,data_type:k});let j=this.getScdColumnType(r,{contextItems:[...b,"effective_end"],validationContext:T},i.scd_properties.effective_end,_,l);if(this.scdValidateTemplate(r,{contextItems:[...b,"effective_end"],validationContext:T},i.scd_properties.effective_end,l),E.push({scdKey:"effective_end",column:i.scd_properties.effective_end.column,data_type:j}),i.scd_properties.created){let X=this.getScdColumnType(r,{contextItems:[...b,"created"],validationContext:T},i.scd_properties.created,_,l);this.scdValidateTemplate(r,{contextItems:[...b,"created"],validationContext:T},i.scd_properties.created,l),E.push({scdKey:"created",column:i.scd_properties.created.column,data_type:X})}this.scdValidateTemplate(r,{contextItems:[...b,"as_of_date"],validationContext:T},i.scd_properties.as_of_date,l),this.scdValidateTemplate(r,{contextItems:[...b,"is_latest"],validationContext:T},i.scd_properties.is_latest,l);let z=rl.groupBy(E,X=>[X.column]);if(Array.from(z.entries()).filter(([,X])=>X.length>1).forEach(([,X])=>{let ue=X.map(Je=>Je.scdKey),De=rp.scdDuplicateColumns(b,ue);l.file(r).addErrorWithContext(De,{...T,message:De})}),E.every(X=>X.data_type!==void 0)){let X=new Set;if(E.forEach(ue=>{X.add(ue.data_type)}),X.size>1){let ue=rp.scdColumnsDataTypesDoNotMatch(E);l.file(r).addErrorWithContext(ue,{...T,message:ue})}}}getScdColumnType(r,i,o,l,p){let _=[...i.contextItems,"column"],b=this.getDatasetColumn(l,o.column,r,p,{contextItems:_,validationContext:i.validationContext});if(b){if(!Zl.isSimpleColumn(b)){let T=rp.scdOnlySimpleColumnsAreAllowed(_,b.name);p.file(r).addErrorWithContext(T,{...i.validationContext,message:T});return}if(!$Q.includes(b.data_type)){let T=rp.scdInvalidDataType(_,b,$Q);p.file(r).addErrorWithContext(T,{...i.validationContext,message:T})}return b.data_type}}scdValidateTemplate(r,i,o,l){let p,_=[...i.contextItems,"display_name_template"],b=o.display_name_template.indexOf("{0}");b<0?p=rp.scdInvalidTemplateMissingPlaceholder(_,o.display_name_template):o.display_name_template.lastIndexOf("{0}")!==b&&(p=rp.scdInvalidTemplateMultiplePlaceholders(_,o.display_name_template)),p&&l.file(r).addErrorWithContext(p,{...i.validationContext,message:p})}};var m4r={formatNotCompatibleWithMeasureFormats:(n,r)=>`Invalid format value "${n}" you probably mean "${r}"!`},n$=class{static validate(r,i,o){let p=Ak.getAllValues(sQ,"string").find(_=>DQ(_,r));p&&p!==r&&o.file(i).addError(m4r.formatNotCompatibleWithMeasureFormats(r,p))}};var sCe=class{constructor(r){this.expressionValidator=r}validateObject(r){let i=r.data,o=Mo.create();return i.expression&&!this.expressionValidator.areParenthesesValid(i.expression)&&o.file(r).addError(`Invalid metric expression: ${i.expression}`),i.format&&n$.validate(i.format,r,o),o}};var i$="semi_additive ",gA={notExistingCol:(n,r)=>`Missing dataset column. Column "${n}" does not exist in "${r}" dataset`,notApplicableFormatForColType:(n,r)=>`Inapplicable formatting for column data_type. Measure "${n.unique_name}" should not have format property set for column type "${r}" with name "${n.column}"`,formatNotCompatibleWithColType:(n,r,i)=>`Incompatible formatting for related column data_type. Measure "${n.unique_name}" with format "${n.format}" is incompatible with "${r}" for column "${n.column}". ${i[r].length>0?"Possible formats: "+i[r].join(", "):""}`,calcMethodNotCompatibleWithColumnType:(n,r)=>`Measure "${n.unique_name}" with calculated_method "${n.calculation_method}", requires different column data_type than "${r}"`,semiAdditiveHasNoRelationshipsOrDegenerateDimensions:()=>`${i$} There should be at least one relationships or degenerate dimension in semi additive.`,semiAdditiveHasEmptyRelationship:()=>`${i$} Relationship in semi additive cannot be empty.`,semiAdditiveHasUnknownRelationship:(n,r)=>`${i$} Relationship "${n}" does not exist in any of the models containing the metric "${r}"`,semiAdditiveDegenerateDimensionHasUnknownLevel:(n,r)=>`${i$} Degenerate dimension ${n} references unknown level ${r}.`,modelHasNoValidAttributes:n=>`${i$} Model ${n} has no valid attributes for this measure.`,modelHasInvalidNestedRelationship:(n,r)=>`${i$} Relationship ${r.join(", ")} is invalid in model ${n}.`,semiAdditiveNestedRelationshipLengthExceeded:()=>`${i$} Semi-additive attributes are not supported in dimensions nested beyond two levels. You can reference semi-additive attributes in a dimension nested within another dimension (e.g., model -> dim 1 -> dim 2), but not in deeper levels (e.g., model -> dim 1 -> dim 2 -> dim 3)."`,validateSemiAdditiveAggregationType:(n,r)=>`Semi-additive metrics can only use Sum, Min or Max Aggregation types. Metric "${n}" has "${r}" Aggregation type.`},h4r=2,aCe=class{constructor(r,i=f7){this.yamlCommonReferenceValidator=r,this.formatMap=i}validateObject(r,i,o){let l=r.data,p=Mo.create();if(l.dataset){let _=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(l.dataset,i,r,"dataset",p);if(!_)return p;o.add(l.dataset);let T=_.data.columns.find(E=>E.name===l.column);if(!T)return p.file(r).addError(gA.notExistingCol(l.column,_.data.unique_name)),p;if(Zl.hasColumnDataTypeProp(T)){let E=wx.getColumnTypeFromYaml(T.data_type);if(!E)return p;let k=jO(this.formatMap).find(j=>j===l.format);k&&!tD.includes(k)&&!this.formatMap[E].find(j=>j===l.format)&&p.file(r).addError(gA.formatNotCompatibleWithColType(l,E,this.formatMap)),this.validateCalcMethod(p,r,E)}l.semi_additive&&(this.validateSemiAdditiveRelationships(p,r,i),this.validateSemiAdditiveByCalculationMethod(p,r))}return l.format&&n$.validate(l.format,r,p),p}validateSemiAdditiveRelationships(r,i,o){let l=i.data;if(l.semi_additive?.relationships===void 0&&l.semi_additive?.degenerate_dimensions===void 0){r.file(i).addError(gA.semiAdditiveHasNoRelationshipsOrDegenerateDimensions());return}if(l.semi_additive?.degenerate_dimensions===void 0&&l.semi_additive?.relationships?.length===0)return r.file(i).addError(gA.semiAdditiveHasEmptyRelationship());let p=[],_=[];o.forEach(b=>{if(b.data.object_type==="model"){let T=b.data;!!T.metrics.find(k=>k.unique_name===l.unique_name)&&p.push({unique_name:T.unique_name,degenerateDimensions:T.dimensions??[],relationships:T.relationships})}else if(b.data.object_type==="dimension"){let T=b.data;_.push(T)}}),l.semi_additive.relationships?.forEach(b=>{Array.isArray(b)?(b.length>h4r&&r.file(i).addError(gA.semiAdditiveNestedRelationshipLengthExceeded()),b.forEach(T=>{p.some(k=>k.relationships.map(j=>j.unique_name).includes(T))||_.some(k=>k.relationships?.find(j=>ki.isEmbeddedRelation(j)&&j.unique_name===T))||r.file(i).addWarning(gA.semiAdditiveHasUnknownRelationship(T,l.unique_name))}),p.forEach(T=>{b.every(k=>{let j=T.relationships.map(X=>X.unique_name).includes(k),z=_.some(X=>X.relationships?.find(ue=>ki.isEmbeddedRelation(ue)&&ue.unique_name===k));return j||z})||r.file(i).addWarning(gA.modelHasInvalidNestedRelationship(T.unique_name,b))})):p.some(E=>E.relationships.map(k=>k.unique_name).includes(b))||_.some(E=>E.relationships?.find(k=>ki.isEmbeddedRelation(k)&&k.unique_name===b))||r.file(i).addWarning(gA.semiAdditiveHasUnknownRelationship(b,l.unique_name))}),l.semi_additive.degenerate_dimensions&&l.semi_additive.degenerate_dimensions.forEach(b=>{if(p.every(E=>{let k=_.find(j=>j.is_degenerate&&j.unique_name===b.name&&E.degenerateDimensions.includes(b.name));return k?!k.level_attributes.find(j=>j.unique_name===b.level):!1}))return r.file(i).addError(gA.semiAdditiveDegenerateDimensionHasUnknownLevel(b.name,b.level)),!1}),p.forEach(b=>{let T=!1;l.semi_additive?.relationships?.forEach(E=>{T||(Array.isArray(E)?E.every(j=>!!(b.relationships.find(z=>z.unique_name===j)||_.find(z=>z.relationships?.find(X=>ki.isEmbeddedRelation(X)&&X.unique_name===j))))&&(T=!0):(b.relationships.find(j=>j.unique_name===E)||_.find(j=>j.relationships?.find(z=>ki.isEmbeddedRelation(z)&&z.unique_name===E)))&&(T=!0))}),l.semi_additive?.degenerate_dimensions?.forEach(E=>{T||b.degenerateDimensions.find(k=>E.name===k)&&(T=!0)}),T||r.file(i).addError(gA.modelHasNoValidAttributes(b.unique_name))})}validateSemiAdditiveByCalculationMethod(r,i){let o=i.data;sTe.includes(o.calculation_method)||r.file(i).addError(gA.validateSemiAdditiveAggregationType(o.unique_name,o.calculation_method))}validateCalcMethod(r,i,o){let l=i.data;aTe[o].includes(l.calculation_method)||r.file(i).addError(gA.calcMethodNotCompatibleWithColumnType(l,o))}};var JQ={referenceAggregateObjectNotExist:(n,r,i)=>`Incorrect aggregate reference. An aggregate with unique_name "${n}" references a ${i} "${r}" which is not referenced in the model`,wrongAttributeType:(n,r,i,o)=>`Incorrect aggregate attribute type. An aggregate with unique_name "${n}" references "${r}" as a ${i}, but it should be specified as a ${o}`,noCommonRelationFound:n=>{let r=n.metricDataset.path?` through dependency path: ${n.metricDataset?.path.join(" -> ")}`:"";return`Error in an aggregate with unique_name "${n.aggName}". There is no common relation between metric "${n.metric}" and dimension "${n.dimension}". The metric uses a dataset "${n.metricDataset.dataSet}"${r}, but the dimension has no relation to it in this model`}},Boe=class{constructor(r){this.yamlCommonReferenceValidator=r;this.getDimensionalAttributes=(r,i)=>r.filter(o=>this.isDimensionalAttribute(o,i));this.isDimensionalAttribute=(r,i)=>QL(r)&&r.dimension!==void 0&&i.get(r.dimension)?.data.object_type==="dimension"}validateAggregates(r,i,o){let l=i.data.aggregates;if(!l||l.length===0)return;let p=i.data.relationships.filter(Ic.isRegularRelation),_=this.getDatasetsForDimensions(p,o),b=i.data.dimensions&&i.data.dimensions.length>0?{..._,...this.getDatasetsForDegenerates(i.data.dimensions,o)}:_;this.validateUniqueAggregates(r.file(i),l);let T={};l.forEach((E,k)=>{let{attributes:j,metrics:z}=E;(j?.length??0)+(E.metrics?.length??0)<1&&r.file(i).addError(`Aggregate ${E.unique_name} should have at least one attribute or metric`);let ue=r.getFileOutputErrorCount(i);if(j&&this.validateAggregateAttributes(i,E,o,r),z){let De=j?j.filter($e=>YL($e)):[];this.yamlCommonReferenceValidator.validateMetricReferences(r,i,o,z),this.validateAggregateMetricsExistInModel(r,i,E);let Je=r.getFileOutputErrorCount(i);ue===Je&&z.forEach($e=>{this.getDatasetsForMetric($e,o,T).forEach(ht=>{De?.filter(cr=>!b[cr.dimension]?.includes(ht.dataSet)).forEach(cr=>{r.file(i).addError(JQ.noCommonRelationFound({aggName:E.unique_name,metric:$e,dimension:cr.dimension,metricDataset:ht}))})})})}Object.keys(E).includes("target_connection")&&r.file(i).addWarning(nCe.getTargetConnectionWarning(E.unique_name||E.label,k))})}validateAggregateAttributes(r,i,o,l){if(!i.attributes)return;let{referencedDimensionsInModel:p,referencedRowSecuritiesInModel:_}=this.getModelRelatedEntities(r,o),b=this.getDimensionalAttributes(i.attributes,o);this.yamlCommonReferenceValidator.validateAttributesReferences(l,r,o,b),this.validateAggregateDimensionReferencesNotMistyped(l,r,_,i),this.validateAggregateDimensionReferencesExist(l,r,p,i,_),this.validateAggregateRowSecurityReferencesNotMistyped(l,r,p,i),this.validateAggregateRowSecurityReferencesExist(l,r,_,i,p)}validateUniqueAggregates(r,i){let o=rl.groupBy(i,l=>[l.unique_name]);rl.appendErrorsIfDuplicates(o,r,Ah.getDuplicateAggregatesUniqueNames)}validateAggregateDimensionReferencesExist(r,i,o,l,p){this.getUniqueReferencedDimensions(l).filter(b=>!o.includes(b)).forEach(b=>{p.includes(b)||r.file(i).addError(JQ.referenceAggregateObjectNotExist(l.unique_name,b,"dimension"))})}validateAggregateDimensionReferencesNotMistyped(r,i,o,l){this.getUniqueReferencedDimensions(l).filter(_=>o.includes(_)).forEach(_=>{r.file(i).addError(JQ.wrongAttributeType(l.unique_name,_,"dimension","row_security"))})}getUniqueReferencedDimensions(r){let i=r.attributes?.filter(QL)||[];return[...new Set(i.map(o=>o.dimension))]}validateAggregateRowSecurityReferencesExist(r,i,o,l,p){this.getUniqueReferencedRowSecurities(l).filter(b=>!o.includes(b)).forEach(b=>{p.includes(b)||r.file(i).addError(JQ.referenceAggregateObjectNotExist(l.unique_name,b,"row_security"))})}validateAggregateRowSecurityReferencesNotMistyped(r,i,o,l){this.getUniqueReferencedRowSecurities(l).filter(_=>o.includes(_)).forEach(_=>{r.file(i).addError(JQ.wrongAttributeType(l.unique_name,_,"row_security","dimension"))})}getUniqueReferencedRowSecurities(r){let i=r.attributes?.filter(gQ)||[];return[...new Set(i.map(o=>o.row_security))]}validateAggregateMetricsExistInModel(r,i,o){o.metrics?.filter(l=>!i.data.metrics.some(p=>p.unique_name===l)).forEach(l=>{r.file(i).addError(JQ.referenceAggregateObjectNotExist(o.unique_name,l,"metric"))})}getModelRelatedEntities(r,i){let o=r.data.relationships.filter(Ic.isRegularRelation),l=r.data.relationships.filter(Ic.isSecurityRelation),p=o.flatMap(b=>this.resolveEmbeddedDimensions(b.to.dimension,i)).concat(r.data.dimensions??[]),_=l.flatMap(b=>this.resolveRowSecurityForAggregates(b.to.row_security,i));return{referencedDimensionsInModel:p,referencedRowSecuritiesInModel:_}}resolveRowSecurityForAggregates(r,i){let o=i.get(r);return!o||!_l.isRowSecurity(o.data)?[]:[o.data.unique_name]}resolveEmbeddedDimensions(r,i,o=new Set,l=1){us.ensure(l<=100,"Max recursion depth exceeded.");let p=i.get(r);if(!p||!_l.isDimension(p.data))return[];let _=p.data.unique_name;if(o.has(_))return[];o.add(_);let b=(p.data.relationships??[]).filter(ki.isEmbeddedRelation).flatMap(T=>this.resolveEmbeddedDimensions(T.to.dimension,i,o,l+1));return[_,...b]}getDatasetsForDimensions(r,i){return r.reduce((o,l)=>(this.resolveEmbeddedDimensions(l.to.dimension,i).forEach(p=>{let _=o[p]||[];_.includes(l.from.dataset)||_.push(l.from.dataset),o[p]=_}),o),{})}getDatasetsForDegenerates(r,i){return r.reduce((o,l)=>{let p=i.get(l);if(!p||!_l.isDimension(p.data))return o;let _=p.data.level_attributes.flatMap(b=>ki.isLevelFromOneDataset(b)?[b.dataset]:b.shared_degenerate_columns.map(T=>T.dataset));return o[l]=_,o},{})}getDatasetsForMetric(r,i,o,l=uA,p=1){if(us.ensure(p<=200,"Max recursion depth exceeded."),o[r])return o[r];let _=i.get(r);if(!_)return[];let b=_.data,T=[];return mQ.isCalcMetric(b)?l(b.expression).forEach(E=>{this.getDatasetsForMetric(E,i,o,l,p+1).forEach(k=>{T.some(j=>j.dataSet===k.dataSet)||T.push({dataSet:k.dataSet,path:[E,...k.path||[]]})})}):T.push({dataSet:b.dataset}),o[r]=T,T}};var lkt=50,oCe=class{constructor(r,i){this.yamlCommonReferenceValidator=r;this.yamlModelAggregateValidator=i}validateObject(r,i,o){let l=r.data,p=Mo.create(),_=[];l.relationships.forEach(T=>{Ic.isRegularRelation(T)&&_.push(T.to.dimension)}),this.validateMetrics(r,l.metrics,i,o,p),this.validateDimensions(p,r,i,o,!1,_),this.validateDimensions(p,r,i,o,!0,l.dimensions),p.append(this.yamlCommonReferenceValidator.validateRelationships(r,i,o)),this.yamlCommonReferenceValidator.validateRelationshipsReferences(p,r,i),this.validateRelationshipM2MProp(p.file(r),l.relationships),this.validateUniqueRelationships(p.file(r),l),this.validateUniqueMetrics(p.file(r),l),this.validateOverrides(p,r),this.validateDatasetsProperties(p,r,i);let b=r;return this.yamlModelAggregateValidator.validateAggregates(p,b,i),this.validateDrillThroughs(p,b,i),this.validatePerspectives(p,b,i),this.validateUniqueMultipleRelationshipsToLevel(p.file(r),l),p}validateUniqueMultipleRelationshipsToLevel(r,i){let o=rCe(i.relationships);rl.appendErrorsIfDuplicates(o,r,Ah.getMultiRelationshipsToLevelMessage)}validateDatasetsProperties(r,i,o){i.data.dataset_properties&&Object.keys(i.data.dataset_properties).forEach(l=>{let p=o.get(l);p||r.file(i).addError(Ah.getDatasetForPropertiesNotExist(l)),p&&p?.data.object_type!=="dataset"&&r.file(i).addError(Ah.getDatasetPropertiesIncorrectType(l))})}validateMetrics(r,i,o,l,p){i.forEach(_=>{let b=o.get(_.unique_name);if(!b){p.file(r).addError(ih.referenceObjectNotExist("metric",_.unique_name));return}if(b.data.object_type!=="metric"&&b.data.object_type!=="metric_calc"){p.file(r).addError(ih.incorrectReference("metric",_.unique_name,b.data.object_type));return}l.add(_.unique_name)})}validateDimensions(r,i,o,l,p,_){_?.forEach(b=>{let T=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(b,o,i,"dimension",r);if(!T)return;let E=T.data;E.is_degenerate||(E.is_degenerate=!1),E.is_degenerate!==p&&r.file(i).addError(Ah.getDimensionDegenerateError(p,b)),T&&l.add(b)})}getAllModelDimensions(r){return r.data.relationships.filter(Ic.hasDimensionProp).map(o=>o.to.dimension).concat(r.data.dimensions||[])}collectNestedDimensions(r){let{dimensionName:i,depth:o,result:l,elementsMap:p}=r;if(o>lkt)throw new Error(Ah.getMaximumDepthOfNestedDimensionExceeded(lkt));if(l.has(i))return;let _=p.get(i);if(_&&_.data.object_type==="dimension"){let b=_.data;if(l.set(i,b),b.relationships){for(let T of b.relationships)if(ki.isRegularRelation(T)&&ki.isEmbeddedRelation(T)){let E=T.to.dimension;this.collectNestedDimensions({dimensionName:E,depth:o+1,result:l,elementsMap:p})}}}}getAllModelDimensionsIncludingNestedDims(r,i){let o=new Map;return this.getAllModelDimensions(r).forEach(p=>{this.collectNestedDimensions({dimensionName:p,depth:1,result:o,elementsMap:i})}),o}validateDrillThroughAttributes(r){let{validatorOutput:i,file:o,elementsMap:l,dt:p,attributes:_}=r;if(_){this.yamlCommonReferenceValidator.validateAttributesReferences(i,o,l,_);let b=this.getAllModelDimensionsIncludingNestedDims(o,l);_.forEach(T=>{b.get(T.dimension)||i.file(o).addError(Ah.getDrillThroughAttributeNotFoundInModel(p.unique_name,T.dimension))})}}validateDrillThroughMetrics(r,i,o,l,p){p&&i.data.metrics&&(this.yamlCommonReferenceValidator.validateMetricReferences(r,i,o,p),p.forEach(_=>{i.data.metrics.find(T=>T.unique_name===_)||r.file(i).addError(Ah.getDrillThroughMetricNotFoundInModel(l.unique_name,_))}))}validateDrillThroughs(r,i,o){let{drillthroughs:l}=i.data;l&&l.forEach(p=>{let{attributes:_,metrics:b}=p;this.validateDrillThroughAttributes({validatorOutput:r,file:i,elementsMap:o,dt:p,attributes:_}),this.validateDrillThroughMetrics(r,i,o,p,b)})}validatePerspectivesDimensions(r,i,o,l,p){if(!p)return;this.yamlCommonReferenceValidator.validatePerspectiveDimensionReferences(r,i,o,p);let _=this.getAllModelDimensionsIncludingNestedDims(i,o);p.forEach(b=>{let T=_.get(b.name);if(!T){r.file(i).addError(Ah.getPerspectiveDimensionNotFoundInModel(l.unique_name,b.name));return}this.validatePerspectiveHierarchies(r,i,b,l,T)})}validatePerspectiveHierarchies(r,i,o,l,p){o.hierarchies&&o.hierarchies.forEach(_=>{if(!p.hierarchies?.find(T=>T.unique_name===_.name)){r.file(i).addError(Ah.getPerspectiveHierarchyNotFound(l.unique_name,_.name,o.name));return}if(_.level&&(p.level_attributes?.find(E=>E.unique_name===_.level)||r.file(i).addError(Ah.getPerspectiveHierarchyLevelNotFound(l.unique_name,_.name,_.level,o.name))),_.levels){let T=nCe.levelsPropDetectedInPerspective(l.unique_name,o.name,_.name);r.file(i).addWarning(T,{type:"PerspectiveLevelFix",context:{model:i.data.unique_name,perspective:l.unique_name,dimension:o.name,hierarchy:_.name}})}_.levels&&_.levels.forEach(T=>{p.level_attributes?.find(k=>k.unique_name===T)||r.file(i).addError(Ah.getPerspectiveHierarchyLevelNotFound(l.unique_name,_.name,T,o.name))})}),o.secondary_attributes&&o.secondary_attributes.forEach(_=>{p.hierarchies.flatMap(E=>E.levels).flatMap(E=>E.secondary_attributes||[])?.find(E=>E.unique_name===_)||r.file(i).addError(Ah.getPerspectiveSecondaryAttributeNotFound(l.unique_name,_,o.name))})}validatePerspectiveMetrics(r,i,o,l,p){p&&(this.yamlCommonReferenceValidator.validateMetricReferences(r,i,o,p),p.forEach(_=>{i.data.metrics?.find(T=>T.unique_name===_)||r.file(i).addError(Ah.getPerspectiveMetricNotFoundInModel(l.unique_name,_))}))}validatePerspectives(r,i,o){let{perspectives:l}=i.data;l&&l.forEach(p=>{let{dimensions:_,metrics:b}=p;this.validatePerspectivesDimensions(r,i,o,p,_),this.validatePerspectiveMetrics(r,i,o,p,b)})}validateUniqueRelationships(r,i){let o=rl.groupBy(i.relationships,p=>Object.values(p.from).concat(Object.values(p.to)));rl.appendErrorsIfDuplicates(o,r,Ah.getDuplicateRelationshipsMessage);let l=rl.groupBy(i.relationships,p=>[p.unique_name]);rl.appendErrorsIfDuplicates(l,r,Ah.getDuplicateRelationshipsUniqueNameMessage)}validateRelationshipM2MProp(r,i){i.forEach(o=>{Object.prototype.hasOwnProperty.call(o,"m2m")&&r.addError(Ah.getM2MPropDetectedInRelation(o.unique_name))})}validateUniqueMetrics(r,i){let o=rl.groupBy(i.metrics,l=>[l.unique_name]);rl.appendErrorsIfDuplicates(o,r,Ah.getDuplicateMetricUniqueNames)}validateOverrides(r,i){let o=i.data;if(!o.overrides)return;let l=o.overrides;r.file(i).addInfo(Ah.overridesInfo);let p=o.metrics.map(T=>T.unique_name).concat(o.dimensions||[]);Object.keys(l).filter(T=>!p.includes(T)).forEach(T=>{r.file(i).addError(Ah.getOverrideNotReferencedInModel(T))});let _=o.metrics.map(T=>this.getOverrideWithObjectType(T.unique_name,l,"metric")).concat(o.dimensions?.map(T=>this.getOverrideWithObjectType(T,l,"dimension"))||[]),b=rl.groupBy(_,T=>[T.query_name.toLowerCase()]);Array.from(b.values()).filter(T=>T.length>1).forEach(T=>{r.file(i).addError(Ah.getOverridesDuplicateOnQueryNames(T))})}getOverrideWithObjectType(r,i,o){return Object.keys(i).includes(r)?{query_name:i[r].query_name,unique_name:r,object_type:o}:{query_name:r,unique_name:r,object_type:o}}};var ukt={missingIdsColumn:(n,r)=>`Missing ids_column. Column "${n}" does not exist in "${r}" dataset`,missingFilterKeyColumn:(n,r)=>`Missing filter_key_column. Column "${n}" does not exist in "${r}" dataset`,notExistingDataset:n=>`Dataset "${n}" does not exist`},cCe=class{constructor(r){this.yamlCommonReferenceValidator=r}validateObject(r,i,o){let l=r.data,p=Mo.create();if(hQ.hasDatasetProp(l)){let _=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(l.dataset,i,r,"dataset",p);if(!_)return p;o.add(l.dataset);let b=_.data,T=b.columns.find(k=>k.name===l.ids_column),E=b.columns.find(k=>k.name===l.filter_key_column);if(T||p.file(r).addError(ukt.missingIdsColumn(l.ids_column,_.data.unique_name)),!E)return p.file(r).addError(ukt.missingFilterKeyColumn(l.filter_key_column,_.data.unique_name)),p}return p}};var p7=new joe,fkt=new Moe,dkt=new Boe(p7),pkt=new oCe(p7,dkt),g4r=new qk,y4r={dataset:new eCe(p7),dimension:new iCe(p7,fkt,g4r),metric:new aCe(p7),metric_calc:new sCe(fkt),model:pkt,model_settings:new Loe,global_settings:new Loe,connection:new ZTe,row_security:new cCe(p7),catalog:new KTe(pkt,p7),composite_model:new XTe(p7,dkt)},lCe=class n{static create(){return new n}getObjectValidator(r){return y4r[r]}validate(r){let i=Mo.create(),o=new Set,l=new Map;return r.forEach(_=>l.set(_.data.unique_name,_)),r.forEach(_=>{let b=this.getObjectValidator(_.data.object_type);i.append(b.validateObject(_,l,o))}),r.filter(_=>_.data.object_type!=="model"&&_.data.object_type!=="composite_model"&&_.data.object_type!=="catalog"&&_.data.object_type!=="model_settings"&&_.data.object_type!=="global_settings").filter(_=>!o.has(_.data.unique_name)).forEach(_=>{i.file(_).addWarning("File not in use. File has no references to it.")}),i}};var mkt=(r=>(r.MetricalAttribute="metrical_attribute",r))(mkt||{});var Dvn={...dl,...mkt},$oe={globalScopeError:(n,r,i,o)=>`The "${i}" name "${n}" is not unique. The file "${r}" contains "${o}" with the same name`,fileScopeError:(n,r,i)=>`Duplicate ${n} and ${r} unique names: ${i}`,duplicatePermissionUniqueName:n=>{let r=n.map(i=>i.type==="perspective"?`a perspective unique_name in model ${i.modelFile.data.unique_name}`:`a file unique_name in model ${i.modelFile.data.unique_name}`);return`Unique_name "${n[0].unique_name}" is duplicated. It appears as: ${nh(r)};`},dimAttributesDuplicateUniqueName:n=>`Duplicate unique_names "${n.unique_name}". Hierarchy[${n.hierarchy}] -> ${n.level?`Level[${n.level}] -> ${n.objectType}`:`Level[${n.unique_name}]`}`},_kt=["metric_calc","metric","metrical_attribute"];var Joe={level:"Duplicate level unique name within the same hierarchy",levelAttribute:"Duplicate level_attribute unique names",duplicateUniqueName:"Duplicate unique names"},v4r=(n,r)=>{let i=_kt.includes(n.type),o=_kt.includes(r.type);return i&&o||!i&&!o},uCe=class n{constructor(r){this.hasDuplicatePerspectiveUniqueNames=r=>r.some(i=>i.type==="perspective");this.hasDuplicateUniqueNames=r=>Array.from(r.values()).some(i=>i.length>1);this.getLevelContext=(r,i)=>this.yamlErrorContextUtil.getLevelContext({itemUniqueName:r,message:Joe.level,validationType:"unique_name",hierarchyUniqueName:i||""});this.getLevelAttributeContext=r=>this.yamlErrorContextUtil.getLevelAttributeContext({itemUniqueName:r,message:Joe.levelAttribute,validationType:"unique_name"});this.getSecondaryAttributeContext=r=>this.yamlErrorContextUtil.getSecondaryAttributeContext({itemUniqueName:r,message:Joe.duplicateUniqueName,validationType:"unique_name"});this.yamlErrorContextUtil=r}static create(r){return new n(r)}validate(r){let i=new Array;this.addFiles(r,i),this.addMetricalAttributes(r,i);let o=Mo.create();return i.forEach((l,p)=>{i.forEach((_,b)=>{b>p&&DQ(l.uniqueName,_.uniqueName)&&v4r(l,_)&&this.addErrorsInDuplicatedFiles(_.uniqueName,l.file,l.type,_.file,_.type,o)})}),r.forEach(l=>{l.data.object_type==="dimension"&&this.validateDimension(l,o)}),this.validateModelPerspectiveUniqueNames(r,o),o}groupModelsAndPerspectivesByUniqueName(r,i){let o=r.flatMap(l=>{let p=XL(l,i),_=p.data.perspectives?.map(b=>({unique_name:b.unique_name,type:"perspective",modelFile:p}))||[];return[{unique_name:p.data.unique_name,type:"model",modelFile:p},..._]});return rl.groupBy(o,l=>[l.unique_name])}validateModelPerspectiveUniqueNames(r,i,o=KL){let l=o(r),p=this.groupModelsAndPerspectivesByUniqueName(l,r);this.hasDuplicateUniqueNames(p)&&this.addErrorsForDuplicateModelAndPerspectiveUniqueNames(p,i)}addErrorsForDuplicateModelAndPerspectiveUniqueNames(r,i){Array.from(r.values()).forEach(o=>{o.length>1&&this.hasDuplicatePerspectiveUniqueNames(o)&&this.getUniqueFilesWithDuplicateUniqueNames(o).forEach(p=>{i.file(p.modelFile).addError($oe.duplicatePermissionUniqueName(o))})})}getUniqueFilesWithDuplicateUniqueNames(r){return r.filter((i,o,l)=>o===l.findIndex(p=>p.modelFile.data.unique_name===i.modelFile.data.unique_name))}addMetricalAttributes(r,i){r.filter(o=>o.data.object_type==="dimension").forEach(o=>{o.data.hierarchies.forEach(p=>{p.levels.forEach(_=>{_.metrics&&_.metrics.forEach(b=>{i.push({file:o,uniqueName:b.unique_name,type:"metrical_attribute",path:o.relativePath})})})})})}addFiles(r,i){r.forEach(o=>{i.push({file:o,uniqueName:o.data.unique_name,type:o.data.object_type,path:o.relativePath})})}addErrorsInDuplicatedFiles(r,i,o,l,p,_){if(i.relativePath===l.relativePath){_.file(i).addError($oe.fileScopeError(o,p,r));return}_.file(i).addError($oe.globalScopeError(r,l.relativePath,o,p)),_.file(l).addError($oe.globalScopeError(r,i.relativePath,p,o))}validateDimension(r,i){let o=r.data;this.validateUniqueNames(o.level_attributes.map(l=>l.unique_name),"level_attribute",i.file(r),{getContext:this.getLevelAttributeContext}),this.validateUniqueNames(o.hierarchies.map(l=>l.unique_name),"hierarchy",i.file(r)),o.hierarchies.forEach(l=>{let p=l.levels.map(_=>_.unique_name);this.validateUniqueNames(p,"level",i.file(r),{getContext:this.getLevelContext,hierarchyUniqueName:l.unique_name})}),this.validateDimensionalAttributes(r,i)}validateUniqueNames(r,i,o,l){let p=this.groupUniqueNames(r);l?rl.appendErrorsWithContextIfDuplicates(p,o,this.getErrorMessage(i,l?.hierarchyUniqueName),l):rl.appendErrorsIfDuplicates(p,o,this.getErrorMessage(i))}getErrorMessage(r,i){return(l,p)=>i?`Duplicate ${r} unique_names "${l}" within hierarchy "${i}". ${p} duplicate items found.`:`Duplicate ${r} unique_names "${l}". ${p} duplicate items found.`}groupUniqueNames(r){return rl.groupBy(r,i=>[i])}validateDimensionalAttributes(r,i){let o=rl.groupBy(this.getAllDimensionalAttributes(r.data),l=>[l.unique_name]);rl.processDuplicates(o,l=>{l.forEach(p=>{i.file(r).addErrorWithContext($oe.dimAttributesDuplicateUniqueName(p),p.context)})})}getAllDimensionalAttributes(r){let i=r.hierarchies.flatMap(l=>l.levels.map(p=>({...p,hierarchy:l.unique_name}))),o=i.flatMap(l=>{let p=l.secondary_attributes?.map(b=>({unique_name:b.unique_name,hierarchy:l.hierarchy,objectType:"secondary_attribute",level:l.unique_name,context:this.getSecondaryAttributeContext(b.unique_name)}))||[],_=l.aliases?.map(b=>({unique_name:b.unique_name,hierarchy:l.hierarchy,objectType:"level_alias",level:l.unique_name,context:this.yamlErrorContextUtil.getLevelAliasContext({itemUniqueName:b.unique_name,message:Joe.duplicateUniqueName,validationType:"unique_name"})}))||[];return p.concat(_)});return[...this.getUniqueLevelsInDimension(i),...o]}getUniqueLevelsInDimension(r){let i=rl.groupBy(r,o=>[o.unique_name]);return Array.from(i.values()).flatMap(o=>o[0]).map(o=>({unique_name:o.unique_name,hierarchy:o.hierarchy,objectType:"level",context:this.yamlErrorContextUtil.getLevelContext({itemUniqueName:o.unique_name,message:Joe.duplicateUniqueName,validationType:"unique_name",hierarchyUniqueName:o.hierarchy})}))}};var fCe={$id:"https://www.atscale.com/ml/catalog.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"catalog",type:"object",required:["object_type","unique_name","label","version","aggressive_agg_promotion","build_speculative_aggs"],properties:{object_type:{const:"catalog"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},version:{type:"number",minimum:1},hidden_models:{type:"array",items:{type:"string",minLength:1}},aggressive_agg_promotion:{type:"boolean"},build_speculative_aggs:{type:"boolean"},description:{type:"string",minLength:1},dataset_properties:{type:"object",additionalProperties:{type:"object",properties:{allow_aggregates:{type:"boolean"},allow_local_aggs:{type:"boolean"},allow_peer_aggs:{type:"boolean"},allow_preferred_aggs:{type:"boolean"}}}},aggregate_store:{type:"object",required:["as_connection"],properties:{as_connection:{type:"string"},row_count_limit:{type:"integer",minimum:1,maximum:2147483648},total_row_count_limit:{type:"integer",minimum:1,maximum:2147483648}},additionalProperties:!1}}};var pCe={$id:"https://www.atscale.com/ml/connection.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Connection",type:"object",required:["object_type","unique_name","label","as_connection"],properties:{object_type:{const:"connection"},unique_name:{type:"string",minLength:1,maxLength:128},label:{type:"string",minLength:1,maxLength:128},database:{type:"string",minLength:1},schema:{type:"string",minLength:1},as_connection:{type:"string",minLength:1}}};var dCe={$id:"https://www.atscale.com/ml/dataset.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Dataset",type:"object",required:["object_type","unique_name","label","connection_id","columns"],oneOf:[{required:["sql"],errorMessage:"Missing sql prop - please add (sql) OR table property"},{required:["table"],errorMessage:"Missing table prop - please add (sql) OR table property"}],properties:{object_type:{const:"dataset"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},description:{type:"string",minLength:1},connection_id:{type:"string",minLength:1,maxLength:128},columns:{type:"array",contains:{type:"object"},items:{oneOf:[{required:["data_type"],errorMessage:"oneOf: if on a column the data_type is set then the map property should not be set",not:{required:["map"]}},{required:["map"],errorMessage:"oneOf: if on a column the map property is set then neither data_type nor parent_column should exists",not:{anyOf:[{required:["data_type"]},{required:["parent_column"]}]}}],type:"object",required:["name"],properties:{name:{type:"string",minLength:1},data_type:{type:"string",minLength:3,errorMessage:"invalid column data_type must be one of 'string', ' int', ' long', ' bigint', 'tinyint', 'float', 'double', 'decimal', 'decimal(x,y)', 'number', 'number(x,y)', 'numeric(x,y)', 'boolean', 'date', 'datetime', 'timestamp'"},sql:{type:"string",minLength:1},dialects:{type:"array",items:{type:"object",required:["dialect","sql"],properties:{dialect:{type:"string",minLength:1,enum:["Snowflake","BigQuery","Iris","Postgresql","DatabricksSQL"],errorMessage:"must have a value: 'Snowflake', 'BigQuery', 'Iris', 'Postgresql' or 'DatabricksSQL'"},sql:{type:"string",minLength:1}}}},map:{type:"object",required:["field_terminator","key_terminator","key_type","value_type"],properties:{field_terminator:{type:"string",minLength:1},key_terminator:{type:"string",minLength:1},key_type:{type:"string",minLength:1},value_type:{type:"string",minLength:1},is_prefixed:{type:"boolean"}}},parent_column:{type:"string",minLength:1}}}},table:{type:"string",minLength:1},sql:{type:"string",minLength:1},dialects:{type:"array",items:{type:"object",required:["dialect","sql"],properties:{dialect:{type:"string",minLength:1,enum:["Snowflake","BigQuery","Iris","Postgresql","DatabricksSQL"],errorMessage:"must have a value: 'Snowflake', 'BigQuery', 'Iris', 'Postgresql' or 'DatabricksSQL'"},sql:{type:"string",minLength:1}}}},immutable:{type:"boolean"},alternate:{oneOf:[{required:["sql"],errorMessage:"use (sql) OR (table + connection_id) properties",not:{anyOf:[{required:["table"]},{required:["connection_id"]}]}},{required:["table","connection_id"],errorMessage:"use (sql) OR (table + connection_id) properties",not:{required:["sql"]}}],type:"object",required:["type"],properties:{type:{type:"string",minLength:1},sql:{type:"string",minLength:1},connection_id:{type:"string",minLength:1,maxLength:128},table:{type:"string",minLength:1}}},incremental:{type:"object",required:["column","grace_period"],properties:{column:{type:"string",minLength:1,maxLength:128},grace_period:{type:"string",description:"A duration string (e.g. '100s', '15d', '2w') or a non-negative integer for integer-like columns.",minLength:2,maxLength:11,errorMessage:{minLength:"must be at least 2 characters long.",maxLength:"must be at most 11 characters long."},oneOf:[{pattern:"^\\d{1,10}[smhdw]$",errorMessage:"Invalid value. Should be in format: decimal + time unit. Example: '100s', '15d', '2w'."},{pattern:"^\\d+$",errorMessage:"Invalid value. Grace period must be a non-negative integer for integer-like columns."}]}}}},errorMessage:{oneOf:"Cannot have both sql and table props - please add only one of them"}};var _Ce={$id:"https://www.atscale.com/ml/dimension.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Dimension",type:"object",required:["label","hierarchies","level_attributes","unique_name","object_type"],properties:{label:{type:"string",minLength:1,maxLength:63},description:{type:"string",minLength:1},type:{enum:["time","standard"],errorMessage:"must have a value: 'time' or 'standard'"},hierarchies:{type:"array",items:{type:"object",required:["label","unique_name","levels"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},levels:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},secondary_attributes:{type:"array",items:{type:"object",required:["unique_name","label","dataset","name_column","key_columns"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},dataset:{type:"string",minLength:1,maxLength:128},name_column:{type:"string",minLength:1},key_columns:{type:"array"},sort_column:{type:"string",minLength:1},description:{type:"string",minLength:1},is_hidden:{type:"boolean"},folder:{type:"string",minLength:1,maxLength:128},contains_unique_names:{type:"boolean"},allowed_calcs_for_dma:{type:"array",items:{type:"string",minLength:1}},exclude_from_dim_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},custom_empty_member:{type:"object",required:["key","name"],properties:{key:{type:"array"},name:{type:"string",minLength:1,maxLength:128},sort_name:{type:"string",minLength:1}}},is_excel_pivot_table_property:{type:"boolean"},is_user_defined_property:{type:"boolean"}}}},aliases:{type:"array",items:{type:"object",required:["unique_name","label","dataset","name_column"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},dataset:{type:"string",minLength:1,maxLength:128},name_column:{type:"string",minLength:1,maxLength:128},sort_column:{type:"string",minLength:1},description:{type:"string",minLength:1},is_hidden:{type:"boolean"},folder:{type:"string",minLength:1},format:{type:"string",minLength:1},exclude_from_dim_agg:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},custom_empty_member:{type:"object",required:["name"],properties:{key:{type:"array",items:{type:"string",minLength:1}},name:{type:"string",minLength:1,maxLength:128},sort_name:{minLength:1,maxLength:128}}},is_excel_pivot_table_property:{type:"boolean"},is_user_defined_property:{type:"boolean"}}}},metrics:{type:"array",items:{type:"object",required:["unique_name","label","dataset","column","calculation_method"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:128},dataset:{type:"string",minLength:1,maxLength:128},column:{type:"string",minLength:1,maxLength:128},calculation_method:{type:"string",enum:["sum","minimum","maximum","count distinct","sum distinct","estimated count distinct","count non-null"],errorMessage:"Type must be: sum, minimum, maximum, count distinct, sum distinct, estimated count distinct, count non-null"},description:{type:"string",minLength:1},is_hidden:{type:"boolean"},folder:{type:"string",minLength:1},format:{type:"string",minLength:1},exclude_from_dim_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},custom_empty_member:{type:"object",required:["key","name","sort_name"],properties:{key:{type:"array"},name:{type:"string",minLength:1},sort_name:{type:"string",minLength:1}}},unrelated_dimensions_handling:{enum:["error","repeat","empty"],errorMessage:"Type must be: 'error', 'repeat', 'empty'"}}}},parallel_periods:{type:"array",items:{type:"object",required:["level","key_columns"],properties:{level:{type:"string",minLength:1},key_columns:{type:"array",items:{type:"string",minLength:1},minItems:1}}},minLength:1},is_hidden:{type:"boolean"}}}},description:{type:"string",minLength:1},folder:{type:"string",minLength:1},filter_empty:{type:"string",enum:["yes","no","always"],errorMessage:"must have a value: 'yes', 'no' or 'always'"},default_member:{type:"object",properties:{expression:{type:"string",minLength:1},apply_only_when_in_query:{type:"boolean"}},required:["expression"]}}}},level_attributes:{type:"array",items:{type:"object",required:["label","unique_name"],anyOf:[{required:["shared_degenerate_columns"],not:{anyOf:[{required:["dataset"]},{required:["name_column"]},{required:["key_columns"]}]},errorMessage:"Invalid configuration: Please provide either 'dataset', 'name_column', and 'key_columns' for a single dataset or 'shared_degenerate_columns' for multiple datasets, but not both or neither."},{required:["dataset","name_column","key_columns"],not:{required:["shared_degenerate_columns"]},errorMessage:{required:"Missing required properties for single-dataset syntax. The properties 'dataset', 'name_column', and 'key_columns' are required.",not:"Invalid configuration: Please provide either 'dataset', 'name_column', and 'key_columns' for a single dataset or 'shared_degenerate_columns' for multiple datasets, but not both or neither."}}],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},dataset:{type:"string",minLength:1,maxLength:128},description:{type:"string",minLength:1},contains_unique_names:{type:"boolean"},name_column:{type:"string",minLength:1},key_columns:{type:"array",items:{type:"string",minLength:1}},sort_column:{type:"string",minLength:1},constraint_translation_rank:{type:"integer",minimum:-2147483648,maximum:2147483648},is_unique_key:{type:"boolean"},shared_degenerate_columns:{type:"array",minItems:1,maxItems:128,items:{type:"object",required:["dataset","name_column","key_columns"],properties:{dataset:{type:"string",minLength:1,maxLength:128},name_column:{type:"string",minLength:1},key_columns:{type:"array",minItems:1,maxItems:1,items:{type:"string",minLength:1,maxLength:128}},sort_column:{type:"string",minLength:1,maxLength:128},is_unique_key:{type:"boolean"}}}},is_hidden:{type:"boolean"},allowed_calcs_for_dma:{type:"array",items:{type:"string",minLength:1}},exclude_from_dim_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},custom_empty_member:{type:"object",required:["key","name"],properties:{key:{type:"array"},name:{type:"string",minLength:1,maxLength:128}}},time_unit:{type:"string",enum:["year","halfyear","trimester","quarter","month","week","day","hour","minute","second","undefined"]},scd_properties:{type:"object",description:"Defines the level as Slowly changing dimension.",$comment:"Introduced in SML version 1.6",required:["effective_interval_type","effective_start","effective_end","as_of_date","is_latest","join_on_fact_effective_key"],properties:{effective_interval_type:{type:"string",description:"It defines the interval handling of the effective start and effective end columns. It should have one of the standard values: 'right_open_interval' or 'left_open_interval' or 'closed'",enum:["right_open_interval","left_open_interval","closed"],errorMessage:"must have a value: 'right_open_interval' or 'left_open_interval' or 'closed'"},effective_start:{type:"object",description:"Defines the effective start setup of the Slowly changing dimension level",required:["column","display_name_template"],properties:{column:{type:"string",description:"This defines the effective start column for the Slowly changing dimension.",minLength:1},display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} effective-start'. It can be combined with role-playing relationships",minLength:1,examples:["{0} effective-start","{0} effective start"]},has_null_values:{type:"boolean",description:"Determines whether the effective start column has null values. Defaults to true",default:!0},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to false",default:!1}}},effective_end:{type:"object",description:"Defines the effective end setup of the Slowly changing dimension level",required:["column","display_name_template"],properties:{column:{type:"string",description:"This defines the effective end column for the Slowly changing dimension.",minLength:1},display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} effective-end'. It can be combined with role-playing relationships",minLength:1,examples:["{0} effective-end","{0} effective end"]},has_null_values:{type:"boolean",description:"Determines whether the effective end column has null values. Defaults to true",default:!0},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to false",default:!1}}},created:{type:"object",description:"Defines the 'created at' setup of the Slowly changing dimension level",required:["column","display_name_template"],properties:{column:{type:"string",description:"This defines the 'crated at' column for the Slowly changing dimension.",minLength:1},display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} Created'. It can be combined with role-playing relationships",minLength:1,examples:["{0} Created"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to false",default:!1}}},as_of_date:{type:"object",description:"Defines the 'as of date' attribute for the BI tool to consume",required:["display_name_template"],properties:{display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} As-Of-Date'. It can be combined with role-playing relationships",minLength:1,examples:["{0} As-Of-Date"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to true",default:!0}}},is_latest:{type:"object",description:"Defines the 'is latest' attribute for the BI tool to consume",required:["display_name_template"],properties:{display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} Is Latest'. It can be combined with role-playing relationships",minLength:1,examples:["{0} Is Latest"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to true",default:!0}}},join_on_fact_effective_key:{type:"object",description:"Defines the 'is join on fact effective' attribute for the BI tool to consume",required:["display_name_template"],properties:{display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} Join-On-Fact-Effective-Key'. It can be combined with role-playing relationships",minLength:1,examples:["{0} Join-On-Fact-Effective-Key"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to true",default:!0}}}}}}}},relationships:{type:"array",items:{type:"object",required:["from","to","type"],properties:{unique_name:{type:"string",minLength:1,maxLength:512},from:{type:"object",required:["dataset","join_columns"],properties:{dataset:{type:"string",minLength:1,maxLength:128},join_columns:{type:"array",items:{type:"string",minLength:1,maxLength:128}},hierarchy:{type:"string",items:{type:"string",minLength:1}},level:{type:"string",items:{type:"string",minLength:1,maxLength:128}}}},to:{type:"object",required:[],oneOf:[{required:["level"],errorMessage:"Missing level prop - please add row_security OR level property"},{required:["row_security"],errorMessage:"Missing row_security prop - please add row_security OR level property"}],properties:{dimension:{type:"string",minLength:1,maxLength:128},level:{type:"string",minLength:1,maxLength:128},row_security:{type:"string",minLength:1,maxLength:128}}},type:{type:"string",enum:["embedded","snowflake"],errorMessage:"must have a value: 'embedded' or 'snowflake'"},role_play:{type:"string",pattern:".*\\{0\\}.*",errorMessage:"template field must be a string that always contains {0} placeholder. The placeholder indicates where the role-played dimension's name should go."},m2m:{type:"boolean"}}}},calculation_groups:{type:"array",items:{type:"object",required:["unique_name","label","calculated_members"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},label:{type:"string",minLength:1,maxLength:128},is_hidden:{type:"boolean"},calculated_members:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},description:{type:"string",minLength:1},expression:{type:"string",minLength:1},is_hidden:{type:"boolean"},format:{type:"string",minLength:1},template:{type:"string",enum:["Current","Previous","Current vs Previous","Current vs Previous Pct","Next","Current vs Next","Current vs Next Pct","Pct of Total","Pct of Parent","Last Year","Current vs Last Year","Current vs Last Year Pct","Year to Date","Quarter to Date","Month to Date","Month Moving Average 3 Month","Moving Average 30 Period","Moving Average 5 Period","Moving Std Dev 30 Period","Moving Std Dev 5 Period"]},use_input_metric_format:{type:"boolean"}},anyOf:[{required:["expression"],not:{required:["template"]},errorMessage:"Invalid configuration: Please provide either 'expression' or 'template', but not both or neither."},{required:["template"],not:{required:["expression"]},errorMessage:{required:"Missing required properties. Please provide either 'expression' or 'template', but not both or neither.",not:"Invalid configuration: Please provide either 'expression' or 'template', but not both or neither."}}]}},description:{type:"string",minLength:1},folder:{type:"string",minLength:1,maxLength:128},precedence:{type:"number"}}}},unique_name:{type:"string",minLength:1,maxLength:128},object_type:{const:"dimension"},is_degenerate:{type:"boolean"}}};var mCe={$id:"https://www.atscale.com/ml/measure.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Measure",type:"object",required:["unique_name","object_type","label","dataset","column","calculation_method"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},object_type:{const:"metric"},label:{type:"string",minLength:1,maxLength:128},dataset:{type:"string",minLength:1,maxLength:128},column:{type:"string",minLength:1,maxLength:128},calculation_method:{type:"string",enum:["sum","average","minimum","maximum","count distinct","sum distinct","estimated count distinct","count non-null","stddev_samp","stddev_pop","var_samp","var_pop","percentile"],errorMessage:"Type must be: sum, average, minimum, maximum, count distinct, sum distinct, estimated count distinct, count non-null, stddev_samp, stddev_pop, var_samp, var_pop or percentile"},description:{type:"string",minLength:1},format:{type:"string",minLength:1},unrelated_dimensions_handling:{enum:["error","repeat","empty"],errorMessage:"Type must be: 'error', 'repeat', 'empty'"},semi_additive:{type:"object",required:["position"],anyOf:[{required:["relationships"],errorMessage:"There should be at least one attribute in the semi-additive. Please define either 'relationships' or 'degenerate_dimensions'."},{required:["degenerate_dimensions"],errorMessage:"There should be at least one attribute in the semi-additive. Please define either 'relationships' or 'degenerate_dimensions'."}],properties:{position:{type:"string",enum:["first","last","first_child","last_child"],errorMessage:"Supported values: 'first', 'last', 'first_child' and 'last_child'"},relationships:{type:"array",items:{type:["array","string"],items:{minLength:1,type:"string"}}},degenerate_dimensions:{type:"array",items:{type:"object",properties:{name:{type:"string",minLength:1,maxLength:128},level:{type:"string",minLength:1,maxLength:128}}}}}},compression:{type:"number",minimum:1,maximum:5e4},named_quantiles:{type:"string",enum:["median","quartiles","deciles"],errorMessage:"must be equal to one of the allowed values: median, quartiles or deciles"},custom_quantiles:{type:"array",minItems:1,items:{type:"number",minimum:0,maximum:1}},is_hidden:{type:"boolean"}},allOf:[{if:{required:["calculation_method"],properties:{calculation_method:{const:"percentile"}}},then:{required:["compression"],oneOf:[{required:["named_quantiles"]},{required:["custom_quantiles"]}]},errorMessage:"For calculation_method percentile, compression (number) and either named_quantiles (median, quartiles, deciles) or custom_quantiles (array of numbers) must be provided"}]};var hCe={$id:"https://www.atscale.com/ml/measureCalc.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"MeasureCalc",type:"object",required:["object_type","unique_name","label","expression"],properties:{object_type:{const:"metric_calc"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},expression:{type:"string",minLength:1},description:{type:"string",minLength:1},format:{type:"string",minLength:1},is_hidden:{type:"boolean"},mdx_aggregate_function:{type:"string",enum:["SUM","MAX","MIN","COUNT","AVG"],errorMessage:"must have a value: 'SUM', 'MAX', 'MIN', 'COUNT' or 'AVG'"}}};var gCe={$id:"https://www.atscale.com/ml/model.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Model",type:"object",required:["object_type","unique_name","label","relationships","metrics"],properties:{object_type:{const:"model"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},include_default_drillthrough:{type:"boolean"},relationships:{type:"array",items:{type:"object",required:["unique_name","from","to"],properties:{unique_name:{type:"string",minLength:1,maxLength:512},from:{type:"object",required:["dataset","join_columns"],properties:{dataset:{type:"string",minLength:1,maxLength:128},join_columns:{type:"array",items:{type:"string",minLength:1,maxLength:128}},scd_column:{type:"string",minLength:1,maxLength:128,description:"The date column on the fact table which is used to evaluate the values of the Slowly changing dimension",$comment:"Introduced in SML version 1.6"}}},to:{type:"object",required:[],oneOf:[{required:["dimension","level"],errorMessage:"Missing level prop - please add row_security OR level property"},{required:["row_security"],errorMessage:"Missing row_security prop - please add row_security OR level property"}],properties:{dimension:{type:"string",minLength:1,maxLength:128},level:{type:"string",minLength:1,maxLength:128},row_security:{type:"string",minLength:1,maxLength:128}}},role_play:{type:"string",pattern:".*\\{0\\}.*",errorMessage:"template field must be a string that always contains {0} placeholder. The placeholder indicates where the role-played dimension's name should go."},constraint_translation:{type:"object",required:["level","from_columns"],properties:{level:{type:"string",minLength:1,maxLength:63},from_columns:{type:"array",items:{type:"string",minLength:1,maxLength:128},minItems:1,errorMessage:": a constraint_translation should have at least one join_column defined"}}}}}},dimensions:{type:"array",items:{type:"string",minLength:1,maxLength:128},uniqueItems:!0},metrics:{type:"array",minItems:1,errorMessage:": a model should have at least one metric defined",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},folder:{type:"string",minLength:1}}}},partitions:{type:"array",items:{type:"object",required:["unique_name","dimension","attribute","type"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},dimension:{type:"string",minLength:1,maxLength:128},attribute:{type:"string",minLength:1,maxLength:128},type:{type:"string",enum:["key","name","name+key"],errorMessage:"must be 'key', 'name' or 'name+key'",minLength:1}}}},description:{type:"string",minLength:1},perspectives:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},dimensions:{type:"array",items:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1,maxLength:128},hierarchies:{type:"array",items:{type:"object",required:["name"],not:{required:["level","levels"]},errorMessage:{not:"Properties 'level' and 'levels' are mutually exclusive and cannot be used together in a hierarchy item."},properties:{name:{type:"string",minLength:1,maxLength:128},levels:{type:"array",items:{type:"string",minLength:1,maxLength:128},minItems:1,maxItems:1},level:{type:"string",minLength:1,maxLength:128}}}},secondary_attributes:{type:"array",items:{type:"string",minLength:1,maxLength:128}}}}},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}}}}},drillthroughs:{type:"array",items:{type:"object",required:["metrics","unique_name"],properties:{notes:{type:"string",minLength:1},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}},attributes:{type:"array",items:{type:"object",required:["name","dimension"],properties:{name:{type:"string",minLength:1},dimension:{type:"string",minLength:1},relationships_path:{type:"array",items:{type:"string",minLength:1}}}}},unique_name:{type:"string",minLength:1,maxLength:128}}}},aggregates:{type:"array",items:{type:"object",required:["label","unique_name"],properties:{attributes:{type:"array",items:{type:"object",required:[],oneOf:[{required:["dimension","name"],errorMessage:"Missing name prop - please add row_security OR name property"},{required:["row_security"],errorMessage:"Missing row_security prop - please add row_security OR name property"}],properties:{name:{type:"string",minLength:1,maxLength:128},dimension:{type:"string",minLength:1,maxLength:128},row_security:{type:"string",minLength:1,maxLength:128},partition:{type:"string",minLength:1,maxLength:128},distribution:{type:"string",minLength:1},relationships_path:{type:"array",items:{type:"string",minLength:1}}}}},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}},label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:128},caching:{type:"string",enum:["engine-memory"],errorMessage:"must be 'engine-memory'",minLength:1}}}},overrides:{type:"object",additionalProperties:{type:"object",required:["query_name"],properties:{query_name:{type:"string",minLength:1,maxLength:128}}}},dataset_properties:{type:"object",additionalProperties:{type:"object",properties:{allow_aggregates:{type:"boolean"},allow_local_aggs:{type:"boolean"},allow_peer_aggs:{type:"boolean"},allow_preferred_aggs:{type:"boolean"},create_hinted_aggregate:{type:"boolean"}}}}}};var yCe={$id:"https://www.atscale.com/ml/rowSecurity.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"RowSecurity",type:"object",required:["unique_name","object_type","label","dataset","scope","ids_column","id_type","filter_key_column"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},object_type:{const:"row_security"},label:{type:"string",minLength:1,maxLength:128},description:{type:"string"},dataset:{type:"string",minLength:1,maxLength:128},scope:{type:"string",enum:["fact","related","all","fact_only"],errorMessage:"must have a value: 'fact', 'fact_only', 'related' or 'all'"},ids_column:{type:"string",minLength:1},id_type:{type:"string",enum:["user","group"],errorMessage:"must have a value: 'user' or 'group'"},filter_key_column:{type:"string",minLength:1},use_filter_key:{type:"boolean"},secure_totals:{type:"boolean"}}};var UQ=class{validateAML(r){return{isValid:!0,errors:[]}}};var Uoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var vCe={$id:"https://www.atscale.com/ml/compositeModel.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"CompositeModel",type:"object",required:["object_type","unique_name","label","models"],properties:{object_type:{const:"composite_model"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},models:{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:128},uniqueItems:!0},metrics:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},folder:{type:"string",minLength:1}}}},description:{type:"string",minLength:1},aggregates:{type:"array",items:{type:"object",required:["label","unique_name"],properties:{attributes:{type:"array",items:{type:"object",required:["name","dimension"],properties:{name:{type:"string",minLength:1,maxLength:128},dimension:{type:"string",minLength:1,maxLength:128},partition:{type:"string",minLength:1,maxLength:128},distribution:{type:"string",minLength:1},relationships_path:{type:"array",items:{type:"string",minLength:1}}}}},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}},label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:128},caching:{type:"string",enum:["engine-memory"],errorMessage:"must be 'engine-memory'",minLength:1}}}}}};var Woe=class extends Xy{constructor(i){super(i,vCe);this.schemaValidator=i}};var Voe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var WQ=class extends Xy{};var I4r=(n,r)=>{let i={foundKey:"dimension",object:"undefined unique name"},o=Object.values(dl).reduce((p,_)=>Object.keys(r.from).includes(_)?[...p,_]:Object.keys(r.to).includes(_)?[...p,_]:p,[]),l="";for(let p of o){let _=Pa.hasProps(r.from,p),b=Pa.hasProps(r.to,p);_&&L1.safeParse(r.from[p]).success&&(l=r.from[p],i={foundKey:p,object:l}),b&&L1.safeParse(r.to[p]).success&&(l=r.to[p],i={foundKey:p,object:l})}return o.forEach(p=>{let _=Pa.hasProps(r.from,p),b=L1.safeParse(r.from[p]).success;_&&b&&(l=r.from[p],i={foundKey:p,object:l});let T=Pa.hasProps(r.to,p),E=L1.safeParse(r.to[p]).success;T&&E&&(l=r.to[p],i={foundKey:p,object:l})}),_l.isModel(n.data)?UB.getRelationshipInModelError({object:Array.isArray(i.object)?i.object[0]:i.object,orphanType:i.foundKey}):CUe.getRelationshipInDimensionError({object:Array.isArray(i.object)?i.object[0]:i.object,orphanType:i.foundKey})},bCe=({result:n,orphanRelationships:r=[],file:i})=>{let o=aC.deep(n),l=r.map(_=>I4r(i,_)),p=[...o.errors,...l];return{errors:p,isValid:p.length===0}};var zoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}validateAML(i){let{data:o,...l}=aC.deep(i);if(!Array.isArray(o.relationships))return super.validateAML(i);let p=[],_=[];return o.relationships.forEach(b=>{ki.isOrphanRelation(b)?p.push(b):_.push(b)}),bCe({result:super.validateAML({...l,data:{...o,relationships:_}}),orphanRelationships:p,file:i})}};var Goe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var k4r={legacySchemaNotAllowed:()=>"semi_additive Unsupported properties in definition. ('dimension', 'hierarchy', and 'level' are not allowed.)"},Hoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}validateAML(i){let o=super.validateAML(i);if(i.data.semi_additive&&("dimension"in i.data.semi_additive||"hierarchy"in i.data.semi_additive||"level"in i.data.semi_additive)){let l="There should be at least one attribute in the semi-additive. Please define either 'relationships' or 'degenerate_dimensions'.";o.errors=[...o.errors.filter(p=>p.indexOf(l)===-1),k4r.legacySchemaNotAllowed()]}return o}};var Qoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}validateAML(i){let{data:o,...l}=aC.deep(i);if(!Array.isArray(o.relationships))return super.validateAML(i);let p=[],_=[];return o.relationships.forEach(b=>{Ic.isOrphanRelation(b)?p.push(b):_.push(b)}),bCe({result:super.validateAML({...l,data:{...o,relationships:_}}),orphanRelationships:p,file:i})}};var P4r={model:new Qoe(new _C({allErrors:!0}),gCe),dimension:new zoe(new _C({allErrors:!0}),_Ce),row_security:new WQ(new _C({allErrors:!0}),yCe),dataset:new WQ(new _C({allErrors:!0}),dCe),metric:new Hoe(new _C({allErrors:!0}),mCe),metric_calc:new Goe(new _C({allErrors:!0}),hCe),connection:new Voe(new _C({allErrors:!0}),pCe),catalog:new Uoe(new _C({allErrors:!0}),fCe),composite_model:new Woe(new _C({allErrors:!0})),model_settings:new UQ,global_settings:new UQ},Yoe=class n{constructor(r=P4r){this.objectValidatorMappings=r}static create(){return new n}getValidator(r){return this.objectValidatorMappings[r]}validate(r){let i=Mo.create();return r.forEach(o=>{let l=this.getValidator(o.data.object_type).validateAML(o);l.isValid||l.errors.forEach(p=>i.file(o).addError(p))}),i}};var Koe=class{constructor(r={}){let i={yamlObjectTypeExtractor:new EB,objectValidator:new Jxe,repoParser:new UL,yamlErrorContextUtil:new qk,yamlDegenerateDimensionUtil:new JB};this.dependencies=Object.assign(i,r)}validateRepo(r,i){let o=new Mo,l=this.dependencies.repoParser.parseFolderStructure(r,o),p=this.dependencies.repoParser.extractYamlFiles(l,o);return p=this.dependencies.repoParser.getYamlFilesWithValidObjectType(p,o),o.append(this.validateYamlFiles(p,l,i)),{filesOutput:o.filesOutput,globalOutput:o.globalOutput}}validateYamlFiles(r,i,o=!1){let l=this.dependencies.objectValidator.addValidator(pTe.create(o));return o||l.addValidator(_Te.create()).addRequiredValidator(Yoe.create()).addRequiredValidator(YTe.create()).addRequiredValidator(uCe.create(this.dependencies.yamlErrorContextUtil)).addValidator(Xxe.create()).addValidator(nTe.create()).addValidator(lCe.create()).addValidator(Kxe.create()).addValidator(uTe.create(this.dependencies.yamlDegenerateDimensionUtil)).addValidator(tTe.create(this.dependencies.yamlDegenerateDimensionUtil)).addValidator(dTe.create()),l.validate(r,i)}getYamlFilesWithValidObjectType(r,i){let o=[];return r.forEach(l=>{this.dependencies.yamlObjectTypeExtractor.getType(l,i)&&o.push(l)}),o}};var s$=class extends Error{constructor(r,i){super(r),this.output=i}};var n3=(n,r)=>r(n.data),N4r={isConnectionFile(n){return n3(n,uC.isConnection)},isDatasetFile(n){return n3(n,uC.isDataset)},isDimensionFile(n){return n3(n,uC.isDimension)},isMeasureFile(n){return n3(n,uC.isMetric)},isModelFile(n){return n3(n,uC.isModel)},isCompositeModelFile(n){return n3(n,uC.isCompositeModel)},isMeasureCalcFile(n){return n3(n,uC.isMetricCalc)},isCatalogFile(n){return n3(n,uC.isCatalog)},isGlobalSettingsFile(n){return n3(n,uC.isGlobalSettings)}},WVe=N4r;var Xoe=class n extends Error{static getErrorMessage(r,i,o,l){return`Uuid ${r} detected. Uuid: ${i}.
671
+ loggerName`})}},Ckr=new gUe("LogsDB");var qEt;(function(n){n.GsheetApiFetch="GsheetApiFetch",n.GsheetApiWrite="GsheetApiWrite",n.EngineQuery="EngineQuery",n.PrepareData="PrepareData"})(qEt||(qEt={}));function yUe(n){return n=n.replace(/^(https:\/\/|git@)/,""),n=n.replace(":","/"),n.replace(/\.git$/,"").toLowerCase()}var Rxe=class{constructor(r,i={}){this.data=r,this.cloneOptions=i}get clonedData(){return rQ.deep(this.data,this.cloneOptions)}with(r){let i=Object.assign(this.clonedData,r),o=Object.getPrototypeOf(this).constructor;return new o(i,this.cloneOptions)}mutate(r){let i=r(this.clonedData);return this.with(i)}build(){return this.clonedData}};var Q6=class n extends Rxe{static from(r,i={}){return new n(r,i)}static fromPartial(r,i={}){return new n(r,i)}};var Mxe;(function(n){n.Root="R",n.PackagesRoot="PR",n.Package="P"})(Mxe||(Mxe={}));var Gae="package.yml";var Lxe=class{constructor(r,i={}){this.data=r;this.cloneOptions=i}get clonedData(){return rQ.deep(this.data,this.cloneOptions)}with(r){let i=Object.assign(this.clonedData,r),o=Object.getPrototypeOf(this).constructor;return new o(i,this.cloneOptions)}mutate(r){let i=r(this.clonedData);return this.with(i)}build(){return this.clonedData}};var jxe=class n extends Lxe{static from(r,i={}){return new n(r,i)}static fromPartial(r,i={}){return new n(r,i)}};var nQ=class n extends jxe{static create(){let r={url:"http://shared-repo.git",name:"shared",branch:"develop",version:"1"};return new n(r)}with(r){return super.with(r)}version(r){return this.with({version:r})}name(r){return this.with({name:r})}withTestIdentifier(r){return this.with({branch:`branch-${r}`,name:r,url:`url-${r}`,version:`commit-${r}`})}static newCommit(r,i){return{name:r,commit:i}}};var wkr={added:[],modified:[],deleted:[]},qxe=class n extends Q6{static create(){return new n(wkr)}getPackages(...r){return r.map(i=>nQ.create().withTestIdentifier(i).build())}with(r){return super.with(r)}withModified(...r){return this.with({modified:this.getPackages(...r)})}withDeleted(...r){return this.with({deleted:this.getPackages(...r)})}withAdded(...r){return this.with({added:this.getPackages(...r)})}};var Bxe=class{constructor(r,i){this.fileService=r;this.logger=i}parsePackageConfig(r,i=!1){let o={packages:[],version:1};try{let l=CB.create().parseRawContent(r,"yml");if(typeof l!="object")throw Error("Invalid package format.");return l}catch(l){let p=`Error parsing packages config file. Original error: ${qd.getErrorMessage(l)}`;if(this.logger.error(p),i)throw Error(p);return o}}async getPackages(r){let i=[],o=Ro.getPath(r,cC);if(await this.fileService.doesFileExist(o))try{let p=await this.fileService.readFile(o);return this.parsePackageConfig(p).packages}catch(p){return this.logger.error(`Error reading packages config file. Original error: ${qd.getErrorMessage(p)}`),i}return i}getPackagesDiff(r,i){let o=qxe.create().build();return i.forEach(l=>{r.find(_=>_.name===l.name)||o.added.push(l)}),r.forEach(l=>{let p=i.find(_=>_.name===l.name);p?this.arePackagesEqual(l,p)||o.modified.push(p):o.deleted.push(l)}),o}arePackagesEqual(r,i){return r.url===i.url&&r.branch===i.branch&&r.name===i.name&&r.version===i.version}getPackageRepoPath(r,i){return`/${r.replace(new RegExp("/","g"),"").trim()}${i}_package`}parseVersion(r){return us.ensure(r.startsWith("commit:"),"invalid package version. Supported values: 'commit:sha'"),{commitId:r.replace("commit:","").trim()}}getNewCommitVersion(r){return`commit:${r}`}};var vUe=class{constructor(r){this.validator=r}add(r,i){this.validator.addGlobalOutput(r,i)}addError(r){this.add("error",r)}addWarning(r){this.add("warning",r)}addInfo(r){this.add("info",r)}},bUe=class{constructor(r,i){this.validator=r;this.file=i}get relativePath(){return typeof this.file=="string"?this.file:this.file.relativePath}add(r,i,o){this.validator.addFileOutput(this.relativePath,r,i,o)}addRaw(r){this.validator.addFileOutputRaw(this.relativePath,r)}addError(r,i){this.add("error",r,{fixAction:i})}addErrorWithContext(r,i){this.add("error",r,{context:i})}addWarning(r,i){this.add("warning",r,{fixAction:i})}addWarningWithContext(r,i){this.add("warning",r,{context:i})}addInfo(r){this.add("info",r)}},Mo=class n{constructor(r,i){this.hasGlobalMessage=r=>this.globalOutput.some(o=>o.message===r);this.hasFileWarningMessage=r=>this.filesOutput.some(o=>o.compilationOutput.some(l=>l.message===r&&l.severity==="warning"));this.hasFileErrorMessage=r=>this.filesOutput.some(o=>o.compilationOutput.some(l=>l.message===r&&l.severity==="error"));this.hasFileInfoMessage=r=>this.filesOutput.some(i=>i.compilationOutput.some(o=>o.message===r&&o.severity==="info"));this.globalOutput=r?.globalOutput||[],this.filesOutput=r?.filesOutput||[],this.validationSource=i}static create(r,i){return new n(r,i)}static createForEngine(){return new n(void 0,"engine")}addFileOutput(r,i,o,l){this.addFileOutputRaw(r,{severity:i,message:o,context:l?.context,fixAction:l?.fixAction,validationSource:this.validationSource})}addFileOutputRaw(r,i){let o=this.filesOutput.find(l=>l.relativePath===r);if(!o)this.filesOutput.push({relativePath:r,compilationOutput:[i]});else{if(o.compilationOutput.some(({message:p,severity:_})=>p===i.message&&_===i.severity))return;o.compilationOutput.push(i)}}addGlobalOutput(r,i){this.globalOutput.push({severity:r,message:i,validationSource:this.validationSource})}global(){return new vUe(this)}file(r){return new bUe(this,r)}getFileOutput(r,i){let o=typeof r=="string"?r:r.relativePath,l=this.filesOutput.find(p=>p.relativePath===o)?.compilationOutput||[];return i?l.filter(p=>p.severity===i):l}getFilesWithErrors(){return this.filesOutput.filter(r=>r.compilationOutput.some(i=>i.severity==="error"))}append(r){r.globalOutput.length>0&&this.globalOutput.push(...r.globalOutput),r.filesOutput.forEach(i=>{i.compilationOutput.forEach(o=>{this.file(i).addRaw(o)})})}get hasErrors(){return this.globalOutput.some(r=>r.severity==="error")||this.filesOutput.flatMap(r=>r.compilationOutput).some(r=>r.severity==="error")}get hasWarnings(){return this.globalOutput.some(r=>r.severity==="warning")||this.filesOutput.flatMap(r=>r.compilationOutput).some(r=>r.severity==="warning")}get hasInfos(){return this.globalOutput.some(r=>r.severity==="info")||this.filesOutput.flatMap(r=>r.compilationOutput).some(r=>r.severity==="info")}getFileOutputErrorCount(r){return this.getFileOutput(r,"error").length}get output(){return{filesOutput:this.filesOutput,globalOutput:this.globalOutput}}};var BEt="packages",$xe=class{constructor(r){this.getRepoNameFromFolderPath=r=>r.replace(/^\/|\/$/g,"");this.fileService=r.fileService,this.logger=r.logger,this.compilerSettings=r.compilerSettings||{amlFileExtensions:["yaml","yml"]},this.repoParser=r.repoParser||new UL,this.packageParser=r.packageParser||new Bxe(this.fileService,this.logger)}async parseFolder(r,i=Mo.create()){let o=await this.parseFolderRec(r,"",i,"R",ML,{}),l=await this.packageParser.getPackages(r);l.length>0&&await this.parsePackageFolders(o,i,l,r);let p=this.repoParser.parseFolderStructure(o,i);return p.origin="R",p}getPackagesRootFolder(){return{files:[],folders:[],origin:"PR",path:Ro.getFolderPath("",BEt),packageName:ML}}async parsePackageFolders(r,i,o,l){let p=this.getPackagesRootFolder();for(let _=0;_<o.length;_++){let b=o[_],T=Ro.getFolderPath(Ro.getFolderPath("",BEt),b.name),E={files:[],folders:[],origin:"P",path:T,packageName:b.name},k=this.packageParser.getPackageRepoPath(l,b.name),j=await this.fileService.isFolderExist(k);if(p.folders.push(E),j){let z={},X=await this.parseFolderRec(this.packageParser.getPackageRepoPath(this.getRepoNameFromFolderPath(l),b.name),"",i,"P",b.name,z,b.url);this.addPackageFiles(E,X,T)}}o.length>0&&r.folders.push(p)}addPackageFiles(r,i,o){i.files.forEach(l=>r.files.push({...l,relativePath:Ro.join(o,l.relativePath)})),i.folders.forEach(l=>{r.folders.push({...l,files:[],folders:[],path:Ro.join(o,l.path)})}),r.folders.forEach((l,p)=>{this.addPackageFiles(l,i.folders[p],o)})}async parseFolderRec(r,i,o,l,p,_,b){let T=Ro.getPath(r,i),E=await this.fileService.getFolders(T),k=await this.fileService.getFiles(T),j=await Promise.all(E.map(X=>this.parseFolderRec(r,Ro.getFolderPath(i,X),o,l,p,_,b)));return{files:await Promise.all(k.map(X=>{let ue=Ro.join(i,X);return this.parseFile(r,ue,o,l,p,_,b)})),folders:j,path:i,origin:l,packageName:p}}async parseFile(r,i,o,l,p,_,b){let T=Ro.getPath(r,i),E=Ro.getExtensionFromPath(i),k=E!==void 0&&this.compilerSettings.amlFileExtensions.includes(E),j=E!==void 0&&CO.includes(E),z=E!==void 0&&E===RL;if(!k&&!j&&!z){let De={compilationOutput:[],relativePath:i,type:rh.Unknown,origin:l,packageName:p};return o.file(De).addInfo("File is not recognized as atscale file and will be skipped"),De}let X;j?X=rh.Text:z?X=rh.Environment:X=rh.Unknown;let ue=await this.fileService.readFile(T);return{compilationOutput:[],type:X,rawContent:ue,relativePath:i,origin:l,packageName:p,packageUrl:b?this.getNormalizedGitUrl(_,b):void 0}}getNormalizedGitUrl(r,i){return r[i]||(r[i]=Cxe(i)),r[i]}};var $Et=n=>Pa.hasProps(n,"isFolderValidator");var Jxe=class{constructor(){this.validators=[]}addValidator(r){return this.validators.push({validator:r,canProceedOnError:!0}),this}addRequiredValidator(r){return this.validators.push({validator:r,canProceedOnError:!1}),this}addValidatorIfNoErrorsSoFar(r,i=!1){return this.validators.push({validator:r,canProceedOnError:i,requireNoErrors:!0}),this}validate(r,i){let o=Mo.create();for(let l=0;l<this.validators.length;l++){let p=this.validators[l];if(p.requireNoErrors&&o.hasErrors)break;let _;try{$Et(p.validator)?_=p.validator.validateFolderStructure(i):_=p.validator.validate(r)}catch(b){let T=qd.getErrorMessage(b);_=Mo.create(),_.addGlobalOutput("error",T)}if(o.append(_),!p.canProceedOnError&&_.hasErrors)break}return o}};var Pk=(ue=>(ue.Int="int",ue.Decimal="decimal",ue.Long="long",ue.Double="double",ue.Float="float",ue.String="string",ue.DateTime="datetime",ue.Date="date",ue.Boolean="boolean",ue.BigInt="bigint",ue.TinyInt="tinyint",ue.Number="number",ue.TimeStamp="timestamp",ue.Numeric="numeric",ue))(Pk||{}),Y6=(o=>(o.Numeric="numeric",o.Number="number",o.Decimal="decimal",o))(Y6||{});var iQ=(j=>(j.Year="year",j.HalfYear="halfyear",j.Trimester="trimester",j.Quarter="quarter",j.Month="month",j.Week="week",j.Day="day",j.Hour="hour",j.Minute="minute",j.Second="second",j.Undefined="undefined",j))(iQ||{});var sQ=(De=>(De.GeneralNumber="general number",De.Standard="standard",De.Scientific="scientific",De.Fixed="fixed",De.Percent="percent",De.GeneralDate="general date",De.LongDate="long date",De.MediumDate="medium date",De.ShortDate="short date",De.LongTime="long time",De.MediumTime="medium time",De.ShortTime="short time",De.YesNo="yes/no",De.TrueFalse="true/false",De.OnOff="on/off",De))(sQ||{});var Ikr=["version","unique_name","object_type","label","packages"],Gfn=[...Ikr,"name","description","url","branch"];var IO=(n,r)=>n.object_type===r,_l={isConnection(n){return IO(n,"connection")},isDataset(n){return IO(n,"dataset")},isDimension(n){return IO(n,"dimension")},isRowSecurity(n){return IO(n,"row_security")},isMetric(n){return IO(n,"metric")},isModel(n){return IO(n,"model")},isCompositeModel(n){return IO(n,"composite_model")},isMetricCalc(n){return IO(n,"metric_calc")},isCatalog(n){return IO(n,"catalog")},isGlobalSettings(n){return IO(n,"global_settings")}};var Zl=class n{static isSimpleColumn(r){return Pa.hasProps(r,"data_type")&&Pa.hasNoProps(r,"parent_column")}static isCalculatedColumn(r){return n.isSimpleColumn(r)&&(Pa.hasProps(r,"sql")||Pa.hasProps(r,"dialects"))}static isDerivedColumn(r){return Pa.hasProps(r,"data_type","parent_column")}static isMapColumn(r){return Pa.hasProps(r,"map")}static hasColumnDataTypeProp(r){return this.isSimpleColumn(r)||this.isDerivedColumn(r)}static hasDatasetSqlProp(r){return Pa.hasProps(r,"sql")}static isAlternateSql(r){return Pa.hasProps(r,"sql")&&Pa.hasNoProps(r,"connection_id")&&Pa.hasNoProps(r,"table")}static isAlternateTable(r){return Pa.hasProps(r,"connection_id")&&Pa.hasProps(r,"table")&&Pa.hasNoProps(r,"sql")}};var Bd;(function(n){n.assertEqual=l=>l;function r(l){}n.assertIs=r;function i(l){throw new Error}n.assertNever=i,n.arrayToEnum=l=>{let p={};for(let _ of l)p[_]=_;return p},n.getValidEnumValues=l=>{let p=n.objectKeys(l).filter(b=>typeof l[l[b]]!="number"),_={};for(let b of p)_[b]=l[b];return n.objectValues(_)},n.objectValues=l=>n.objectKeys(l).map(function(p){return l[p]}),n.objectKeys=typeof Object.keys=="function"?l=>Object.keys(l):l=>{let p=[];for(let _ in l)Object.prototype.hasOwnProperty.call(l,_)&&p.push(_);return p},n.find=(l,p)=>{for(let _ of l)if(p(_))return _},n.isInteger=typeof Number.isInteger=="function"?l=>Number.isInteger(l):l=>typeof l=="number"&&isFinite(l)&&Math.floor(l)===l;function o(l,p=" | "){return l.map(_=>typeof _=="string"?`'${_}'`:_).join(p)}n.joinValues=o,n.jsonStringifyReplacer=(l,p)=>typeof p=="bigint"?p.toString():p})(Bd||(Bd={}));var SUe;(function(n){n.mergeShapes=(r,i)=>({...r,...i})})(SUe||(SUe={}));var Vo=Bd.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),VL=n=>{switch(typeof n){case"undefined":return Vo.undefined;case"string":return Vo.string;case"number":return isNaN(n)?Vo.nan:Vo.number;case"boolean":return Vo.boolean;case"function":return Vo.function;case"bigint":return Vo.bigint;case"symbol":return Vo.symbol;case"object":return Array.isArray(n)?Vo.array:n===null?Vo.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Vo.promise:typeof Map<"u"&&n instanceof Map?Vo.map:typeof Set<"u"&&n instanceof Set?Vo.set:typeof Date<"u"&&n instanceof Date?Vo.date:Vo.object;default:return Vo.unknown}},Ra=Bd.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),kkr=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Z2=class extends Error{constructor(r){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=r}get errors(){return this.issues}format(r){let i=r||function(p){return p.message},o={_errors:[]},l=p=>{for(let _ of p.issues)if(_.code==="invalid_union")_.unionErrors.map(l);else if(_.code==="invalid_return_type")l(_.returnTypeError);else if(_.code==="invalid_arguments")l(_.argumentsError);else if(_.path.length===0)o._errors.push(i(_));else{let b=o,T=0;for(;T<_.path.length;){let E=_.path[T];T===_.path.length-1?(b[E]=b[E]||{_errors:[]},b[E]._errors.push(i(_))):b[E]=b[E]||{_errors:[]},b=b[E],T++}}};return l(this),o}toString(){return this.message}get message(){return JSON.stringify(this.issues,Bd.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(r=i=>i.message){let i={},o=[];for(let l of this.issues)l.path.length>0?(i[l.path[0]]=i[l.path[0]]||[],i[l.path[0]].push(r(l))):o.push(r(l));return{formErrors:o,fieldErrors:i}}get formErrors(){return this.flatten()}};Z2.create=n=>new Z2(n);var Hae=(n,r)=>{let i;switch(n.code){case Ra.invalid_type:n.received===Vo.undefined?i="Required":i=`Expected ${n.expected}, received ${n.received}`;break;case Ra.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,Bd.jsonStringifyReplacer)}`;break;case Ra.unrecognized_keys:i=`Unrecognized key(s) in object: ${Bd.joinValues(n.keys,", ")}`;break;case Ra.invalid_union:i="Invalid input";break;case Ra.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${Bd.joinValues(n.options)}`;break;case Ra.invalid_enum_value:i=`Invalid enum value. Expected ${Bd.joinValues(n.options)}, received '${n.received}'`;break;case Ra.invalid_arguments:i="Invalid function arguments";break;case Ra.invalid_return_type:i="Invalid function return type";break;case Ra.invalid_date:i="Invalid date";break;case Ra.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(i=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?i=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?i=`Invalid input: must end with "${n.validation.endsWith}"`:Bd.assertNever(n.validation):n.validation!=="regex"?i=`Invalid ${n.validation}`:i="Invalid";break;case Ra.too_small:n.type==="array"?i=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?i=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?i=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:i="Invalid input";break;case Ra.too_big:n.type==="array"?i=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?i=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?i=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?i=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?i=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:i="Invalid input";break;case Ra.custom:i="Invalid input";break;case Ra.invalid_intersection_types:i="Intersection results could not be merged";break;case Ra.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case Ra.not_finite:i="Number must be finite";break;default:i=r.defaultError,Bd.assertNever(n)}return{message:i}},WEt=Hae;function Pkr(n){WEt=n}function Wxe(){return WEt}var Vxe=n=>{let{data:r,path:i,errorMaps:o,issueData:l}=n,p=[...i,...l.path||[]],_={...l,path:p},b="",T=o.filter(E=>!!E).slice().reverse();for(let E of T)b=E(_,{data:r,defaultError:b}).message;return{...l,path:p,message:l.message||b}},Nkr=[];function ic(n,r){let i=Vxe({issueData:r,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Wxe(),Hae].filter(o=>!!o)});n.common.issues.push(i)}var XS=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,i){let o=[];for(let l of i){if(l.status==="aborted")return Lu;l.status==="dirty"&&r.dirty(),o.push(l.value)}return{status:r.value,value:o}}static async mergeObjectAsync(r,i){let o=[];for(let l of i)o.push({key:await l.key,value:await l.value});return n.mergeObjectSync(r,o)}static mergeObjectSync(r,i){let o={};for(let l of i){let{key:p,value:_}=l;if(p.status==="aborted"||_.status==="aborted")return Lu;p.status==="dirty"&&r.dirty(),_.status==="dirty"&&r.dirty(),p.value!=="__proto__"&&(typeof _.value<"u"||l.alwaysSet)&&(o[p.value]=_.value)}return{status:r.value,value:o}}},Lu=Object.freeze({status:"aborted"}),VEt=n=>({status:"dirty",value:n}),xx=n=>({status:"valid",value:n}),DUe=n=>n.status==="aborted",xUe=n=>n.status==="dirty",Qae=n=>n.status==="valid",zxe=n=>typeof Promise<"u"&&n instanceof Promise,Sl;(function(n){n.errToObj=r=>typeof r=="string"?{message:r}:r||{},n.toString=r=>typeof r=="string"?r:r?.message})(Sl||(Sl={}));var fA=class{constructor(r,i,o,l){this._cachedPath=[],this.parent=r,this.data=i,this._path=o,this._key=l}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},JEt=(n,r)=>{if(Qae(r))return{success:!0,data:r.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let i=new Z2(n.common.issues);return this._error=i,this._error}}};function tf(n){if(!n)return{};let{errorMap:r,invalid_type_error:i,required_error:o,description:l}=n;if(r&&(i||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return r?{errorMap:r,description:l}:{errorMap:(_,b)=>_.code!=="invalid_type"?{message:b.defaultError}:typeof b.data>"u"?{message:o??b.defaultError}:{message:i??b.defaultError},description:l}}var rf=class{constructor(r){this.spa=this.safeParseAsync,this._def=r,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(r){return VL(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:VL(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new XS,ctx:{common:r.parent.common,data:r.data,parsedType:VL(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){let i=this._parse(r);if(zxe(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(r){let i=this._parse(r);return Promise.resolve(i)}parse(r,i){let o=this.safeParse(r,i);if(o.success)return o.data;throw o.error}safeParse(r,i){var o;let l={common:{issues:[],async:(o=i?.async)!==null&&o!==void 0?o:!1,contextualErrorMap:i?.errorMap},path:i?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:VL(r)},p=this._parseSync({data:r,path:l.path,parent:l});return JEt(l,p)}async parseAsync(r,i){let o=await this.safeParseAsync(r,i);if(o.success)return o.data;throw o.error}async safeParseAsync(r,i){let o={common:{issues:[],contextualErrorMap:i?.errorMap,async:!0},path:i?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:VL(r)},l=this._parse({data:r,path:o.path,parent:o}),p=await(zxe(l)?l:Promise.resolve(l));return JEt(o,p)}refine(r,i){let o=l=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(l):i;return this._refinement((l,p)=>{let _=r(l),b=()=>p.addIssue({code:Ra.custom,...o(l)});return typeof Promise<"u"&&_ instanceof Promise?_.then(T=>T?!0:(b(),!1)):_?!0:(b(),!1)})}refinement(r,i){return this._refinement((o,l)=>r(o)?!0:(l.addIssue(typeof i=="function"?i(o,l):i),!1))}_refinement(r){return new eE({schema:this,typeName:eu.ZodEffects,effect:{type:"refinement",refinement:r}})}superRefine(r){return this._refinement(r)}optional(){return Nk.create(this,this._def)}nullable(){return Z6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return X6.create(this,this._def)}promise(){return HL.create(this,this._def)}or(r){return FB.create([this,r],this._def)}and(r){return RB.create(this,r,this._def)}transform(r){return new eE({...tf(this._def),schema:this,typeName:eu.ZodEffects,effect:{type:"transform",transform:r}})}default(r){let i=typeof r=="function"?r:()=>r;return new BB({...tf(this._def),innerType:this,defaultValue:i,typeName:eu.ZodDefault})}brand(){return new Yxe({typeName:eu.ZodBranded,type:this,...tf(this._def)})}catch(r){let i=typeof r=="function"?r:()=>r;return new fQ({...tf(this._def),innerType:this,catchValue:i,typeName:eu.ZodCatch})}describe(r){let i=this.constructor;return new i({...this._def,description:r})}pipe(r){return Yae.create(this,r)}readonly(){return dQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Okr=/^c[^\s-]{8,}$/i,Fkr=/^[a-z][a-z0-9]*$/,Rkr=/[0-9A-HJKMNP-TV-Z]{26}/,Mkr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Lkr=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jkr=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,qkr=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Bkr=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,$kr=n=>n.precision?n.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${n.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${n.precision}}Z$`):n.precision===0?n.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):n.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function Jkr(n,r){return!!((r==="v4"||!r)&&qkr.test(n)||(r==="v6"||!r)&&Bkr.test(n))}var zL=class n extends rf{constructor(){super(...arguments),this._regex=(r,i,o)=>this.refinement(l=>r.test(l),{validation:i,code:Ra.invalid_string,...Sl.errToObj(o)}),this.nonempty=r=>this.min(1,Sl.errToObj(r)),this.trim=()=>new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==Vo.string){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.string,received:p.parsedType}),Lu}let o=new XS,l;for(let p of this._def.checks)if(p.kind==="min")r.data.length<p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty());else if(p.kind==="max")r.data.length>p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty());else if(p.kind==="length"){let _=r.data.length>p.value,b=r.data.length<p.value;(_||b)&&(l=this._getOrReturnCtx(r,l),_?ic(l,{code:Ra.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message}):b&&ic(l,{code:Ra.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message}),o.dirty())}else if(p.kind==="email")Lkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"email",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="emoji")jkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"emoji",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="uuid")Mkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"uuid",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="cuid")Okr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"cuid",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="cuid2")Fkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"cuid2",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="ulid")Rkr.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"ulid",code:Ra.invalid_string,message:p.message}),o.dirty());else if(p.kind==="url")try{new URL(r.data)}catch{l=this._getOrReturnCtx(r,l),ic(l,{validation:"url",code:Ra.invalid_string,message:p.message}),o.dirty()}else p.kind==="regex"?(p.regex.lastIndex=0,p.regex.test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"regex",code:Ra.invalid_string,message:p.message}),o.dirty())):p.kind==="trim"?r.data=r.data.trim():p.kind==="includes"?r.data.includes(p.value,p.position)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:{includes:p.value,position:p.position},message:p.message}),o.dirty()):p.kind==="toLowerCase"?r.data=r.data.toLowerCase():p.kind==="toUpperCase"?r.data=r.data.toUpperCase():p.kind==="startsWith"?r.data.startsWith(p.value)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:{startsWith:p.value},message:p.message}),o.dirty()):p.kind==="endsWith"?r.data.endsWith(p.value)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:{endsWith:p.value},message:p.message}),o.dirty()):p.kind==="datetime"?$kr(p).test(r.data)||(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.invalid_string,validation:"datetime",message:p.message}),o.dirty()):p.kind==="ip"?Jkr(r.data,p.version)||(l=this._getOrReturnCtx(r,l),ic(l,{validation:"ip",code:Ra.invalid_string,message:p.message}),o.dirty()):Bd.assertNever(p);return{status:o.value,value:r.data}}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...Sl.errToObj(r)})}url(r){return this._addCheck({kind:"url",...Sl.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...Sl.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...Sl.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...Sl.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...Sl.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...Sl.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...Sl.errToObj(r)})}datetime(r){var i;return typeof r=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:r}):this._addCheck({kind:"datetime",precision:typeof r?.precision>"u"?null:r?.precision,offset:(i=r?.offset)!==null&&i!==void 0?i:!1,...Sl.errToObj(r?.message)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...Sl.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i?.position,...Sl.errToObj(i?.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...Sl.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...Sl.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...Sl.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...Sl.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...Sl.errToObj(i)})}get isDatetime(){return!!this._def.checks.find(r=>r.kind==="datetime")}get isEmail(){return!!this._def.checks.find(r=>r.kind==="email")}get isURL(){return!!this._def.checks.find(r=>r.kind==="url")}get isEmoji(){return!!this._def.checks.find(r=>r.kind==="emoji")}get isUUID(){return!!this._def.checks.find(r=>r.kind==="uuid")}get isCUID(){return!!this._def.checks.find(r=>r.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(r=>r.kind==="cuid2")}get isULID(){return!!this._def.checks.find(r=>r.kind==="ulid")}get isIP(){return!!this._def.checks.find(r=>r.kind==="ip")}get minLength(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxLength(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}};zL.create=n=>{var r;return new zL({checks:[],typeName:eu.ZodString,coerce:(r=n?.coerce)!==null&&r!==void 0?r:!1,...tf(n)})};function Ukr(n,r){let i=(n.toString().split(".")[1]||"").length,o=(r.toString().split(".")[1]||"").length,l=i>o?i:o,p=parseInt(n.toFixed(l).replace(".","")),_=parseInt(r.toFixed(l).replace(".",""));return p%_/Math.pow(10,l)}var AB=class n extends rf{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==Vo.number){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.number,received:p.parsedType}),Lu}let o,l=new XS;for(let p of this._def.checks)p.kind==="int"?Bd.isInteger(r.data)||(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.invalid_type,expected:"integer",received:"float",message:p.message}),l.dirty()):p.kind==="min"?(p.inclusive?r.data<p.value:r.data<=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_small,minimum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),l.dirty()):p.kind==="max"?(p.inclusive?r.data>p.value:r.data>=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_big,maximum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),l.dirty()):p.kind==="multipleOf"?Ukr(r.data,p.value)!==0&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.not_multiple_of,multipleOf:p.value,message:p.message}),l.dirty()):p.kind==="finite"?Number.isFinite(r.data)||(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.not_finite,message:p.message}),l.dirty()):Bd.assertNever(p);return{status:l.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,Sl.toString(i))}gt(r,i){return this.setLimit("min",r,!1,Sl.toString(i))}lte(r,i){return this.setLimit("max",r,!0,Sl.toString(i))}lt(r,i){return this.setLimit("max",r,!1,Sl.toString(i))}setLimit(r,i,o,l){return new n({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:o,message:Sl.toString(l)}]})}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:Sl.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Sl.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Sl.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Sl.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Sl.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:Sl.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:Sl.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Sl.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Sl.toString(r)})}get minValue(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}get isInt(){return!!this._def.checks.find(r=>r.kind==="int"||r.kind==="multipleOf"&&Bd.isInteger(r.value))}get isFinite(){let r=null,i=null;for(let o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(i===null||o.value>i)&&(i=o.value):o.kind==="max"&&(r===null||o.value<r)&&(r=o.value)}return Number.isFinite(i)&&Number.isFinite(r)}};AB.create=n=>new AB({checks:[],typeName:eu.ZodNumber,coerce:n?.coerce||!1,...tf(n)});var IB=class n extends rf{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce&&(r.data=BigInt(r.data)),this._getType(r)!==Vo.bigint){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.bigint,received:p.parsedType}),Lu}let o,l=new XS;for(let p of this._def.checks)p.kind==="min"?(p.inclusive?r.data<p.value:r.data<=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_small,type:"bigint",minimum:p.value,inclusive:p.inclusive,message:p.message}),l.dirty()):p.kind==="max"?(p.inclusive?r.data>p.value:r.data>=p.value)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.too_big,type:"bigint",maximum:p.value,inclusive:p.inclusive,message:p.message}),l.dirty()):p.kind==="multipleOf"?r.data%p.value!==BigInt(0)&&(o=this._getOrReturnCtx(r,o),ic(o,{code:Ra.not_multiple_of,multipleOf:p.value,message:p.message}),l.dirty()):Bd.assertNever(p);return{status:l.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,Sl.toString(i))}gt(r,i){return this.setLimit("min",r,!1,Sl.toString(i))}lte(r,i){return this.setLimit("max",r,!0,Sl.toString(i))}lt(r,i){return this.setLimit("max",r,!1,Sl.toString(i))}setLimit(r,i,o,l){return new n({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:o,message:Sl.toString(l)}]})}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Sl.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Sl.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Sl.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Sl.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:Sl.toString(i)})}get minValue(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}};IB.create=n=>{var r;return new IB({checks:[],typeName:eu.ZodBigInt,coerce:(r=n?.coerce)!==null&&r!==void 0?r:!1,...tf(n)})};var kB=class extends rf{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==Vo.boolean){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.boolean,received:o.parsedType}),Lu}return xx(r.data)}};kB.create=n=>new kB({typeName:eu.ZodBoolean,coerce:n?.coerce||!1,...tf(n)});var PB=class n extends rf{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==Vo.date){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_type,expected:Vo.date,received:p.parsedType}),Lu}if(isNaN(r.data.getTime())){let p=this._getOrReturnCtx(r);return ic(p,{code:Ra.invalid_date}),Lu}let o=new XS,l;for(let p of this._def.checks)p.kind==="min"?r.data.getTime()<p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_small,message:p.message,inclusive:!0,exact:!1,minimum:p.value,type:"date"}),o.dirty()):p.kind==="max"?r.data.getTime()>p.value&&(l=this._getOrReturnCtx(r,l),ic(l,{code:Ra.too_big,message:p.message,inclusive:!0,exact:!1,maximum:p.value,type:"date"}),o.dirty()):Bd.assertNever(p);return{status:o.value,value:new Date(r.data.getTime())}}_addCheck(r){return new n({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:Sl.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:Sl.toString(i)})}get minDate(){let r=null;for(let i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r!=null?new Date(r):null}get maxDate(){let r=null;for(let i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r!=null?new Date(r):null}};PB.create=n=>new PB({checks:[],coerce:n?.coerce||!1,typeName:eu.ZodDate,...tf(n)});var oQ=class extends rf{_parse(r){if(this._getType(r)!==Vo.symbol){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.symbol,received:o.parsedType}),Lu}return xx(r.data)}};oQ.create=n=>new oQ({typeName:eu.ZodSymbol,...tf(n)});var NB=class extends rf{_parse(r){if(this._getType(r)!==Vo.undefined){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.undefined,received:o.parsedType}),Lu}return xx(r.data)}};NB.create=n=>new NB({typeName:eu.ZodUndefined,...tf(n)});var OB=class extends rf{_parse(r){if(this._getType(r)!==Vo.null){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.null,received:o.parsedType}),Lu}return xx(r.data)}};OB.create=n=>new OB({typeName:eu.ZodNull,...tf(n)});var GL=class extends rf{constructor(){super(...arguments),this._any=!0}_parse(r){return xx(r.data)}};GL.create=n=>new GL({typeName:eu.ZodAny,...tf(n)});var K6=class extends rf{constructor(){super(...arguments),this._unknown=!0}_parse(r){return xx(r.data)}};K6.create=n=>new K6({typeName:eu.ZodUnknown,...tf(n)});var Ok=class extends rf{_parse(r){let i=this._getOrReturnCtx(r);return ic(i,{code:Ra.invalid_type,expected:Vo.never,received:i.parsedType}),Lu}};Ok.create=n=>new Ok({typeName:eu.ZodNever,...tf(n)});var cQ=class extends rf{_parse(r){if(this._getType(r)!==Vo.undefined){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.void,received:o.parsedType}),Lu}return xx(r.data)}};cQ.create=n=>new cQ({typeName:eu.ZodVoid,...tf(n)});var X6=class n extends rf{_parse(r){let{ctx:i,status:o}=this._processInputParams(r),l=this._def;if(i.parsedType!==Vo.array)return ic(i,{code:Ra.invalid_type,expected:Vo.array,received:i.parsedType}),Lu;if(l.exactLength!==null){let _=i.data.length>l.exactLength.value,b=i.data.length<l.exactLength.value;(_||b)&&(ic(i,{code:_?Ra.too_big:Ra.too_small,minimum:b?l.exactLength.value:void 0,maximum:_?l.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:l.exactLength.message}),o.dirty())}if(l.minLength!==null&&i.data.length<l.minLength.value&&(ic(i,{code:Ra.too_small,minimum:l.minLength.value,type:"array",inclusive:!0,exact:!1,message:l.minLength.message}),o.dirty()),l.maxLength!==null&&i.data.length>l.maxLength.value&&(ic(i,{code:Ra.too_big,maximum:l.maxLength.value,type:"array",inclusive:!0,exact:!1,message:l.maxLength.message}),o.dirty()),i.common.async)return Promise.all([...i.data].map((_,b)=>l.type._parseAsync(new fA(i,_,i.path,b)))).then(_=>XS.mergeArray(o,_));let p=[...i.data].map((_,b)=>l.type._parseSync(new fA(i,_,i.path,b)));return XS.mergeArray(o,p)}get element(){return this._def.type}min(r,i){return new n({...this._def,minLength:{value:r,message:Sl.toString(i)}})}max(r,i){return new n({...this._def,maxLength:{value:r,message:Sl.toString(i)}})}length(r,i){return new n({...this._def,exactLength:{value:r,message:Sl.toString(i)}})}nonempty(r){return this.min(1,r)}};X6.create=(n,r)=>new X6({type:n,minLength:null,maxLength:null,exactLength:null,typeName:eu.ZodArray,...tf(r)});function aQ(n){if(n instanceof lC){let r={};for(let i in n.shape){let o=n.shape[i];r[i]=Nk.create(aQ(o))}return new lC({...n._def,shape:()=>r})}else return n instanceof X6?new X6({...n._def,type:aQ(n.element)}):n instanceof Nk?Nk.create(aQ(n.unwrap())):n instanceof Z6?Z6.create(aQ(n.unwrap())):n instanceof kO?kO.create(n.items.map(r=>aQ(r))):n}var lC=class n extends rf{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let r=this._def.shape(),i=Bd.objectKeys(r);return this._cached={shape:r,keys:i}}_parse(r){if(this._getType(r)!==Vo.object){let E=this._getOrReturnCtx(r);return ic(E,{code:Ra.invalid_type,expected:Vo.object,received:E.parsedType}),Lu}let{status:o,ctx:l}=this._processInputParams(r),{shape:p,keys:_}=this._getCached(),b=[];if(!(this._def.catchall instanceof Ok&&this._def.unknownKeys==="strip"))for(let E in l.data)_.includes(E)||b.push(E);let T=[];for(let E of _){let k=p[E],j=l.data[E];T.push({key:{status:"valid",value:E},value:k._parse(new fA(l,j,l.path,E)),alwaysSet:E in l.data})}if(this._def.catchall instanceof Ok){let E=this._def.unknownKeys;if(E==="passthrough")for(let k of b)T.push({key:{status:"valid",value:k},value:{status:"valid",value:l.data[k]}});else if(E==="strict")b.length>0&&(ic(l,{code:Ra.unrecognized_keys,keys:b}),o.dirty());else if(E!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let E=this._def.catchall;for(let k of b){let j=l.data[k];T.push({key:{status:"valid",value:k},value:E._parse(new fA(l,j,l.path,k)),alwaysSet:k in l.data})}}return l.common.async?Promise.resolve().then(async()=>{let E=[];for(let k of T){let j=await k.key;E.push({key:j,value:await k.value,alwaysSet:k.alwaysSet})}return E}).then(E=>XS.mergeObjectSync(o,E)):XS.mergeObjectSync(o,T)}get shape(){return this._def.shape()}strict(r){return Sl.errToObj,new n({...this._def,unknownKeys:"strict",...r!==void 0?{errorMap:(i,o)=>{var l,p,_,b;let T=(_=(p=(l=this._def).errorMap)===null||p===void 0?void 0:p.call(l,i,o).message)!==null&&_!==void 0?_:o.defaultError;return i.code==="unrecognized_keys"?{message:(b=Sl.errToObj(r).message)!==null&&b!==void 0?b:T}:{message:T}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(r){return new n({...this._def,shape:()=>({...this._def.shape(),...r})})}merge(r){return new n({unknownKeys:r._def.unknownKeys,catchall:r._def.catchall,shape:()=>({...this._def.shape(),...r._def.shape()}),typeName:eu.ZodObject})}setKey(r,i){return this.augment({[r]:i})}catchall(r){return new n({...this._def,catchall:r})}pick(r){let i={};return Bd.objectKeys(r).forEach(o=>{r[o]&&this.shape[o]&&(i[o]=this.shape[o])}),new n({...this._def,shape:()=>i})}omit(r){let i={};return Bd.objectKeys(this.shape).forEach(o=>{r[o]||(i[o]=this.shape[o])}),new n({...this._def,shape:()=>i})}deepPartial(){return aQ(this)}partial(r){let i={};return Bd.objectKeys(this.shape).forEach(o=>{let l=this.shape[o];r&&!r[o]?i[o]=l:i[o]=l.optional()}),new n({...this._def,shape:()=>i})}required(r){let i={};return Bd.objectKeys(this.shape).forEach(o=>{if(r&&!r[o])i[o]=this.shape[o];else{let p=this.shape[o];for(;p instanceof Nk;)p=p._def.innerType;i[o]=p}}),new n({...this._def,shape:()=>i})}keyof(){return zEt(Bd.objectKeys(this.shape))}};lC.create=(n,r)=>new lC({shape:()=>n,unknownKeys:"strip",catchall:Ok.create(),typeName:eu.ZodObject,...tf(r)});lC.strictCreate=(n,r)=>new lC({shape:()=>n,unknownKeys:"strict",catchall:Ok.create(),typeName:eu.ZodObject,...tf(r)});lC.lazycreate=(n,r)=>new lC({shape:n,unknownKeys:"strip",catchall:Ok.create(),typeName:eu.ZodObject,...tf(r)});var FB=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o=this._def.options;function l(p){for(let b of p)if(b.result.status==="valid")return b.result;for(let b of p)if(b.result.status==="dirty")return i.common.issues.push(...b.ctx.common.issues),b.result;let _=p.map(b=>new Z2(b.ctx.common.issues));return ic(i,{code:Ra.invalid_union,unionErrors:_}),Lu}if(i.common.async)return Promise.all(o.map(async p=>{let _={...i,common:{...i.common,issues:[]},parent:null};return{result:await p._parseAsync({data:i.data,path:i.path,parent:_}),ctx:_}})).then(l);{let p,_=[];for(let T of o){let E={...i,common:{...i.common,issues:[]},parent:null},k=T._parseSync({data:i.data,path:i.path,parent:E});if(k.status==="valid")return k;k.status==="dirty"&&!p&&(p={result:k,ctx:E}),E.common.issues.length&&_.push(E.common.issues)}if(p)return i.common.issues.push(...p.ctx.common.issues),p.result;let b=_.map(T=>new Z2(T));return ic(i,{code:Ra.invalid_union,unionErrors:b}),Lu}}get options(){return this._def.options}};FB.create=(n,r)=>new FB({options:n,typeName:eu.ZodUnion,...tf(r)});var Uxe=n=>n instanceof MB?Uxe(n.schema):n instanceof eE?Uxe(n.innerType()):n instanceof LB?[n.value]:n instanceof jB?n.options:n instanceof qB?Object.keys(n.enum):n instanceof BB?Uxe(n._def.innerType):n instanceof NB?[void 0]:n instanceof OB?[null]:null,Gxe=class n extends rf{_parse(r){let{ctx:i}=this._processInputParams(r);if(i.parsedType!==Vo.object)return ic(i,{code:Ra.invalid_type,expected:Vo.object,received:i.parsedType}),Lu;let o=this.discriminator,l=i.data[o],p=this.optionsMap.get(l);return p?i.common.async?p._parseAsync({data:i.data,path:i.path,parent:i}):p._parseSync({data:i.data,path:i.path,parent:i}):(ic(i,{code:Ra.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),Lu)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(r,i,o){let l=new Map;for(let p of i){let _=Uxe(p.shape[r]);if(!_)throw new Error(`A discriminator value for key \`${r}\` could not be extracted from all schema options`);for(let b of _){if(l.has(b))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(b)}`);l.set(b,p)}}return new n({typeName:eu.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:l,...tf(o)})}};function TUe(n,r){let i=VL(n),o=VL(r);if(n===r)return{valid:!0,data:n};if(i===Vo.object&&o===Vo.object){let l=Bd.objectKeys(r),p=Bd.objectKeys(n).filter(b=>l.indexOf(b)!==-1),_={...n,...r};for(let b of p){let T=TUe(n[b],r[b]);if(!T.valid)return{valid:!1};_[b]=T.data}return{valid:!0,data:_}}else if(i===Vo.array&&o===Vo.array){if(n.length!==r.length)return{valid:!1};let l=[];for(let p=0;p<n.length;p++){let _=n[p],b=r[p],T=TUe(_,b);if(!T.valid)return{valid:!1};l.push(T.data)}return{valid:!0,data:l}}else return i===Vo.date&&o===Vo.date&&+n==+r?{valid:!0,data:n}:{valid:!1}}var RB=class extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r),l=(p,_)=>{if(DUe(p)||DUe(_))return Lu;let b=TUe(p.value,_.value);return b.valid?((xUe(p)||xUe(_))&&i.dirty(),{status:i.value,value:b.data}):(ic(o,{code:Ra.invalid_intersection_types}),Lu)};return o.common.async?Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([p,_])=>l(p,_)):l(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}};RB.create=(n,r,i)=>new RB({left:n,right:r,typeName:eu.ZodIntersection,...tf(i)});var kO=class n extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.array)return ic(o,{code:Ra.invalid_type,expected:Vo.array,received:o.parsedType}),Lu;if(o.data.length<this._def.items.length)return ic(o,{code:Ra.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Lu;!this._def.rest&&o.data.length>this._def.items.length&&(ic(o,{code:Ra.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());let p=[...o.data].map((_,b)=>{let T=this._def.items[b]||this._def.rest;return T?T._parse(new fA(o,_,o.path,b)):null}).filter(_=>!!_);return o.common.async?Promise.all(p).then(_=>XS.mergeArray(i,_)):XS.mergeArray(i,p)}get items(){return this._def.items}rest(r){return new n({...this._def,rest:r})}};kO.create=(n,r)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new kO({items:n,typeName:eu.ZodTuple,rest:null,...tf(r)})};var Hxe=class n extends rf{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.object)return ic(o,{code:Ra.invalid_type,expected:Vo.object,received:o.parsedType}),Lu;let l=[],p=this._def.keyType,_=this._def.valueType;for(let b in o.data)l.push({key:p._parse(new fA(o,b,o.path,b)),value:_._parse(new fA(o,o.data[b],o.path,b))});return o.common.async?XS.mergeObjectAsync(i,l):XS.mergeObjectSync(i,l)}get element(){return this._def.valueType}static create(r,i,o){return i instanceof rf?new n({keyType:r,valueType:i,typeName:eu.ZodRecord,...tf(o)}):new n({keyType:zL.create(),valueType:r,typeName:eu.ZodRecord,...tf(i)})}},lQ=class extends rf{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.map)return ic(o,{code:Ra.invalid_type,expected:Vo.map,received:o.parsedType}),Lu;let l=this._def.keyType,p=this._def.valueType,_=[...o.data.entries()].map(([b,T],E)=>({key:l._parse(new fA(o,b,o.path,[E,"key"])),value:p._parse(new fA(o,T,o.path,[E,"value"]))}));if(o.common.async){let b=new Map;return Promise.resolve().then(async()=>{for(let T of _){let E=await T.key,k=await T.value;if(E.status==="aborted"||k.status==="aborted")return Lu;(E.status==="dirty"||k.status==="dirty")&&i.dirty(),b.set(E.value,k.value)}return{status:i.value,value:b}})}else{let b=new Map;for(let T of _){let E=T.key,k=T.value;if(E.status==="aborted"||k.status==="aborted")return Lu;(E.status==="dirty"||k.status==="dirty")&&i.dirty(),b.set(E.value,k.value)}return{status:i.value,value:b}}}};lQ.create=(n,r,i)=>new lQ({valueType:r,keyType:n,typeName:eu.ZodMap,...tf(i)});var uQ=class n extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.parsedType!==Vo.set)return ic(o,{code:Ra.invalid_type,expected:Vo.set,received:o.parsedType}),Lu;let l=this._def;l.minSize!==null&&o.data.size<l.minSize.value&&(ic(o,{code:Ra.too_small,minimum:l.minSize.value,type:"set",inclusive:!0,exact:!1,message:l.minSize.message}),i.dirty()),l.maxSize!==null&&o.data.size>l.maxSize.value&&(ic(o,{code:Ra.too_big,maximum:l.maxSize.value,type:"set",inclusive:!0,exact:!1,message:l.maxSize.message}),i.dirty());let p=this._def.valueType;function _(T){let E=new Set;for(let k of T){if(k.status==="aborted")return Lu;k.status==="dirty"&&i.dirty(),E.add(k.value)}return{status:i.value,value:E}}let b=[...o.data.values()].map((T,E)=>p._parse(new fA(o,T,o.path,E)));return o.common.async?Promise.all(b).then(T=>_(T)):_(b)}min(r,i){return new n({...this._def,minSize:{value:r,message:Sl.toString(i)}})}max(r,i){return new n({...this._def,maxSize:{value:r,message:Sl.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}};uQ.create=(n,r)=>new uQ({valueType:n,minSize:null,maxSize:null,typeName:eu.ZodSet,...tf(r)});var Qxe=class n extends rf{constructor(){super(...arguments),this.validate=this.implement}_parse(r){let{ctx:i}=this._processInputParams(r);if(i.parsedType!==Vo.function)return ic(i,{code:Ra.invalid_type,expected:Vo.function,received:i.parsedType}),Lu;function o(b,T){return Vxe({data:b,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Wxe(),Hae].filter(E=>!!E),issueData:{code:Ra.invalid_arguments,argumentsError:T}})}function l(b,T){return Vxe({data:b,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Wxe(),Hae].filter(E=>!!E),issueData:{code:Ra.invalid_return_type,returnTypeError:T}})}let p={errorMap:i.common.contextualErrorMap},_=i.data;if(this._def.returns instanceof HL){let b=this;return xx(async function(...T){let E=new Z2([]),k=await b._def.args.parseAsync(T,p).catch(X=>{throw E.addIssue(o(T,X)),E}),j=await Reflect.apply(_,this,k);return await b._def.returns._def.type.parseAsync(j,p).catch(X=>{throw E.addIssue(l(j,X)),E})})}else{let b=this;return xx(function(...T){let E=b._def.args.safeParse(T,p);if(!E.success)throw new Z2([o(T,E.error)]);let k=Reflect.apply(_,this,E.data),j=b._def.returns.safeParse(k,p);if(!j.success)throw new Z2([l(k,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new n({...this._def,args:kO.create(r).rest(K6.create())})}returns(r){return new n({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,o){return new n({args:r||kO.create([]).rest(K6.create()),returns:i||K6.create(),typeName:eu.ZodFunction,...tf(o)})}},MB=class extends rf{get schema(){return this._def.getter()}_parse(r){let{ctx:i}=this._processInputParams(r);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}};MB.create=(n,r)=>new MB({getter:n,typeName:eu.ZodLazy,...tf(r)});var LB=class extends rf{_parse(r){if(r.data!==this._def.value){let i=this._getOrReturnCtx(r);return ic(i,{received:i.data,code:Ra.invalid_literal,expected:this._def.value}),Lu}return{status:"valid",value:r.data}}get value(){return this._def.value}};LB.create=(n,r)=>new LB({value:n,typeName:eu.ZodLiteral,...tf(r)});function zEt(n,r){return new jB({values:n,typeName:eu.ZodEnum,...tf(r)})}var jB=class n extends rf{_parse(r){if(typeof r.data!="string"){let i=this._getOrReturnCtx(r),o=this._def.values;return ic(i,{expected:Bd.joinValues(o),received:i.parsedType,code:Ra.invalid_type}),Lu}if(this._def.values.indexOf(r.data)===-1){let i=this._getOrReturnCtx(r),o=this._def.values;return ic(i,{received:i.data,code:Ra.invalid_enum_value,options:o}),Lu}return xx(r.data)}get options(){return this._def.values}get enum(){let r={};for(let i of this._def.values)r[i]=i;return r}get Values(){let r={};for(let i of this._def.values)r[i]=i;return r}get Enum(){let r={};for(let i of this._def.values)r[i]=i;return r}extract(r){return n.create(r)}exclude(r){return n.create(this.options.filter(i=>!r.includes(i)))}};jB.create=zEt;var qB=class extends rf{_parse(r){let i=Bd.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(r);if(o.parsedType!==Vo.string&&o.parsedType!==Vo.number){let l=Bd.objectValues(i);return ic(o,{expected:Bd.joinValues(l),received:o.parsedType,code:Ra.invalid_type}),Lu}if(i.indexOf(r.data)===-1){let l=Bd.objectValues(i);return ic(o,{received:o.data,code:Ra.invalid_enum_value,options:l}),Lu}return xx(r.data)}get enum(){return this._def.values}};qB.create=(n,r)=>new qB({values:n,typeName:eu.ZodNativeEnum,...tf(r)});var HL=class extends rf{unwrap(){return this._def.type}_parse(r){let{ctx:i}=this._processInputParams(r);if(i.parsedType!==Vo.promise&&i.common.async===!1)return ic(i,{code:Ra.invalid_type,expected:Vo.promise,received:i.parsedType}),Lu;let o=i.parsedType===Vo.promise?i.data:Promise.resolve(i.data);return xx(o.then(l=>this._def.type.parseAsync(l,{path:i.path,errorMap:i.common.contextualErrorMap})))}};HL.create=(n,r)=>new HL({type:n,typeName:eu.ZodPromise,...tf(r)});var eE=class extends rf{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===eu.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(r){let{status:i,ctx:o}=this._processInputParams(r),l=this._def.effect||null,p={addIssue:_=>{ic(o,_),_.fatal?i.abort():i.dirty()},get path(){return o.path}};if(p.addIssue=p.addIssue.bind(p),l.type==="preprocess"){let _=l.transform(o.data,p);return o.common.issues.length?{status:"dirty",value:o.data}:o.common.async?Promise.resolve(_).then(b=>this._def.schema._parseAsync({data:b,path:o.path,parent:o})):this._def.schema._parseSync({data:_,path:o.path,parent:o})}if(l.type==="refinement"){let _=b=>{let T=l.refinement(b,p);if(o.common.async)return Promise.resolve(T);if(T instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return b};if(o.common.async===!1){let b=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});return b.status==="aborted"?Lu:(b.status==="dirty"&&i.dirty(),_(b.value),{status:i.value,value:b.value})}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(b=>b.status==="aborted"?Lu:(b.status==="dirty"&&i.dirty(),_(b.value).then(()=>({status:i.value,value:b.value}))))}if(l.type==="transform")if(o.common.async===!1){let _=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!Qae(_))return _;let b=l.transform(_.value,p);if(b instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:b}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(_=>Qae(_)?Promise.resolve(l.transform(_.value,p)).then(b=>({status:i.value,value:b})):_);Bd.assertNever(l)}};eE.create=(n,r,i)=>new eE({schema:n,typeName:eu.ZodEffects,effect:r,...tf(i)});eE.createWithPreprocess=(n,r,i)=>new eE({schema:r,effect:{type:"preprocess",transform:n},typeName:eu.ZodEffects,...tf(i)});var Nk=class extends rf{_parse(r){return this._getType(r)===Vo.undefined?xx(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}};Nk.create=(n,r)=>new Nk({innerType:n,typeName:eu.ZodOptional,...tf(r)});var Z6=class extends rf{_parse(r){return this._getType(r)===Vo.null?xx(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}};Z6.create=(n,r)=>new Z6({innerType:n,typeName:eu.ZodNullable,...tf(r)});var BB=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o=i.data;return i.parsedType===Vo.undefined&&(o=this._def.defaultValue()),this._def.innerType._parse({data:o,path:i.path,parent:i})}removeDefault(){return this._def.innerType}};BB.create=(n,r)=>new BB({innerType:n,typeName:eu.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...tf(r)});var fQ=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o={...i,common:{...i.common,issues:[]}},l=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return zxe(l)?l.then(p=>({status:"valid",value:p.status==="valid"?p.value:this._def.catchValue({get error(){return new Z2(o.common.issues)},input:o.data})})):{status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new Z2(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};fQ.create=(n,r)=>new fQ({innerType:n,typeName:eu.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...tf(r)});var pQ=class extends rf{_parse(r){if(this._getType(r)!==Vo.nan){let o=this._getOrReturnCtx(r);return ic(o,{code:Ra.invalid_type,expected:Vo.nan,received:o.parsedType}),Lu}return{status:"valid",value:r.data}}};pQ.create=n=>new pQ({typeName:eu.ZodNaN,...tf(n)});var Wkr=Symbol("zod_brand"),Yxe=class extends rf{_parse(r){let{ctx:i}=this._processInputParams(r),o=i.data;return this._def.type._parse({data:o,path:i.path,parent:i})}unwrap(){return this._def.type}},Yae=class n extends rf{_parse(r){let{status:i,ctx:o}=this._processInputParams(r);if(o.common.async)return(async()=>{let p=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return p.status==="aborted"?Lu:p.status==="dirty"?(i.dirty(),VEt(p.value)):this._def.out._parseAsync({data:p.value,path:o.path,parent:o})})();{let l=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return l.status==="aborted"?Lu:l.status==="dirty"?(i.dirty(),{status:"dirty",value:l.value}):this._def.out._parseSync({data:l.value,path:o.path,parent:o})}}static create(r,i){return new n({in:r,out:i,typeName:eu.ZodPipeline})}},dQ=class extends rf{_parse(r){let i=this._def.innerType._parse(r);return Qae(i)&&(i.value=Object.freeze(i.value)),i}};dQ.create=(n,r)=>new dQ({innerType:n,typeName:eu.ZodReadonly,...tf(r)});var GEt=(n,r={},i)=>n?GL.create().superRefine((o,l)=>{var p,_;if(!n(o)){let b=typeof r=="function"?r(o):typeof r=="string"?{message:r}:r,T=(_=(p=b.fatal)!==null&&p!==void 0?p:i)!==null&&_!==void 0?_:!0,E=typeof b=="string"?{message:b}:b;l.addIssue({code:"custom",...E,fatal:T})}}):GL.create(),Vkr={object:lC.lazycreate},eu;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(eu||(eu={}));var zkr=(n,r={message:`Input not instance of ${n.name}`})=>GEt(i=>i instanceof n,r),HEt=zL.create,QEt=AB.create,Gkr=pQ.create,Hkr=IB.create,YEt=kB.create,Qkr=PB.create,Ykr=oQ.create,Kkr=NB.create,Xkr=OB.create,Zkr=GL.create,ePr=K6.create,tPr=Ok.create,rPr=cQ.create,nPr=X6.create,iPr=lC.create,sPr=lC.strictCreate,aPr=FB.create,oPr=Gxe.create,cPr=RB.create,lPr=kO.create,uPr=Hxe.create,fPr=lQ.create,pPr=uQ.create,dPr=Qxe.create,_Pr=MB.create,mPr=LB.create,hPr=jB.create,gPr=qB.create,yPr=HL.create,UEt=eE.create,vPr=Nk.create,bPr=Z6.create,SPr=eE.createWithPreprocess,DPr=Yae.create,xPr=()=>HEt().optional(),TPr=()=>QEt().optional(),CPr=()=>YEt().optional(),EPr={string:(n=>zL.create({...n,coerce:!0})),number:(n=>AB.create({...n,coerce:!0})),boolean:(n=>kB.create({...n,coerce:!0})),bigint:(n=>IB.create({...n,coerce:!0})),date:(n=>PB.create({...n,coerce:!0}))},wPr=Lu,Cl=Object.freeze({__proto__:null,defaultErrorMap:Hae,setErrorMap:Pkr,getErrorMap:Wxe,makeIssue:Vxe,EMPTY_PATH:Nkr,addIssueToContext:ic,ParseStatus:XS,INVALID:Lu,DIRTY:VEt,OK:xx,isAborted:DUe,isDirty:xUe,isValid:Qae,isAsync:zxe,get util(){return Bd},get objectUtil(){return SUe},ZodParsedType:Vo,getParsedType:VL,ZodType:rf,ZodString:zL,ZodNumber:AB,ZodBigInt:IB,ZodBoolean:kB,ZodDate:PB,ZodSymbol:oQ,ZodUndefined:NB,ZodNull:OB,ZodAny:GL,ZodUnknown:K6,ZodNever:Ok,ZodVoid:cQ,ZodArray:X6,ZodObject:lC,ZodUnion:FB,ZodDiscriminatedUnion:Gxe,ZodIntersection:RB,ZodTuple:kO,ZodRecord:Hxe,ZodMap:lQ,ZodSet:uQ,ZodFunction:Qxe,ZodLazy:MB,ZodLiteral:LB,ZodEnum:jB,ZodNativeEnum:qB,ZodPromise:HL,ZodEffects:eE,ZodTransformer:eE,ZodOptional:Nk,ZodNullable:Z6,ZodDefault:BB,ZodCatch:fQ,ZodNaN:pQ,BRAND:Wkr,ZodBranded:Yxe,ZodPipeline:Yae,ZodReadonly:dQ,custom:GEt,Schema:rf,ZodSchema:rf,late:Vkr,get ZodFirstPartyTypeKind(){return eu},coerce:EPr,any:Zkr,array:nPr,bigint:Hkr,boolean:YEt,date:Qkr,discriminatedUnion:oPr,effect:UEt,enum:hPr,function:dPr,instanceof:zkr,intersection:cPr,lazy:_Pr,literal:mPr,map:fPr,nan:Gkr,nativeEnum:gPr,never:tPr,null:Xkr,nullable:bPr,number:QEt,object:iPr,oboolean:CPr,onumber:TPr,optional:vPr,ostring:xPr,pipeline:DPr,preprocess:SPr,promise:yPr,record:uPr,set:pPr,strictObject:sPr,string:HEt,symbol:Ykr,transformer:UEt,tuple:lPr,undefined:Kkr,union:aPr,unknown:ePr,void:rPr,NEVER:wPr,ZodIssueCode:Ra,quotelessJson:kkr,ZodError:Z2});var L1=Cl.string().min(1),tE=Cl.string().max(0),_Q=Cl.object({unique_name:Cl.string()}),APr=_Q.extend({from:Cl.object({dataset:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({dimension:L1,level:Cl.string()})}),IPr=_Q.extend({from:Cl.object({dataset:L1,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({dimension:tE,level:tE})}),kPr=_Q.extend({from:Cl.object({dataset:L1,join_columns:Cl.array(Cl.string())}),to:Cl.object({row_security:tE})}),PPr=_Q.extend({from:Cl.object({dataset:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({row_security:L1})}),KEt=_Q.extend({from:Cl.object({dataset:L1,hierarchy:Cl.string(),level:Cl.string(),join_columns:Cl.array(Cl.string())}),to:Cl.object({row_security:tE})}),XEt=_Q.extend({from:Cl.object({dataset:tE,hierarchy:tE,level:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({row_security:L1})}),NPr=Cl.object({from:Cl.object({dataset:tE,join_columns:Cl.array(Cl.string()).length(0)}),to:Cl.object({level:L1})}),OPr=Cl.object({from:Cl.object({dataset:L1,join_columns:Cl.array(Cl.string())}),to:Cl.object({level:tE})}),FPr=XEt.extend({to:Cl.object({level:Cl.string(),dimension:Cl.string()})}),RPr=KEt.extend({to:Cl.object({level:tE,dimension:tE})}),ZEt=APr.or(IPr),ewt=PPr.or(kPr),twt=NPr.or(OPr),rwt=FPr.or(RPr),nwt=XEt.or(KEt);var ki=class{static isOrphanRelation(r){return twt.safeParse(r).success||rwt.safeParse(r).success||nwt.safeParse(r).success}static isSnowflakeRelation(r){return r.type==="snowflake"}static isEmbeddedRelation(r){return r.type==="embedded"}static isSecurityRelation(r){return Pa.hasProps(r.to,"row_security")&&Pa.hasNoProps(r.to,"level")}static isLevelWithMultipleDatasets(r){return Pa.hasProps(r,"shared_degenerate_columns")}static isLevelFromOneDataset(r){return!Pa.hasProps(r,"shared_degenerate_columns")}static isRegularRelation(r){return Pa.hasProps(r.to,"level")&&Pa.hasNoProps(r.to,"row_security")}static hasHierarchyProp(r){return Pa.hasProps(r.from,"hierarchy")&&Pa.hasNoProps(r.to,"row_security")}static isModelRegularRelationship(r){return Pa.hasProps(r.to,"dimension","level")&&Pa.hasNoProps(r.from,"hierarchy")}};var mQ=class{static isCalcMetric=r=>Pa.hasProps(r,"expression")&&Pa.hasNoProps(r,"dataset","column");static isRegularMetric=r=>Pa.hasProps(r,"dataset","column")&&Pa.hasNoProps(r,"expression")};var Ic=class{static isSecurityRelation=r=>Pa.hasProps(r.to,"row_security")&&Pa.hasNoProps(r.to,"level");static isRegularRelation=r=>Pa.hasProps(r.to,"level")&&Pa.hasNoProps(r.to,"row_security");static hasDimensionProp=r=>Pa.hasProps(r.to,"dimension")&&Pa.hasNoProps(r.to,"row_security");static hasNoHierarchyProp=r=>Pa.hasNoProps(r.from,"hierarchy");static isOrphanRelation=r=>ZEt.safeParse(r).success||ewt.safeParse(r).success};var hQ=class{static hasDatasetProp(r){return Pa.hasProps(r,"dataset")}};function QL(n){return"dimension"in n}function gQ(n){return"row_security"in n}function YL(n){return"dimension"in n&&"name"in n}var vQ=n=>["count distinct","sum distinct","estimated count distinct","count non-null"].includes(n);var iwt;(function(n){n.Yes="yes",n.No="no",n.Always="always"})(iwt||(iwt={}));var swt;(function(n){n.Time="time",n.Standard="standard"})(swt||(swt={}));var awt;(function(n){n.Year="year",n.HalfYear="halfyear",n.Trimester="trimester",n.Quarter="quarter",n.Month="month",n.Week="week",n.Day="day",n.Hour="hour",n.Minute="minute",n.Second="second",n.Undefined="undefined"})(awt||(awt={}));var Xae;(function(n){n.Embedded="embedded",n.Snowflake="snowflake"})(Xae||(Xae={}));var owt;(function(n){n.RightOpenInterval="right_open_interval",n.LeftOpenInterval="left_open_interval",n.Closed="closed"})(owt||(owt={}));var cwt=50,pA=class{constructor(){this.filterRelationships=r=>r?.filter(i=>{if(i.type===Xae.Snowflake)return i.from.dataset.length>0;if(ki.isRegularRelation(i))return i.from.dataset.length>0&&i.to.dimension.length>0;if(ki.isSecurityRelation(i))return i.from.dataset.length>0&&i.to.row_security})||[]}sortYamlModels(r){let i={connections:new Map,datasets:new Map,dimensions:new Map,measures:new Map,models:new Map,calculations:new Map,rowSecurity:new Map,compositeModels:new Map};return r.forEach(o=>{this.setYamlFileToRepoObjects(i,o)}),i}getModelDimensions(r,i){let o=this.getMapElementsByList(this.getUnique(r),i);return o.forEach(l=>{this.addEmbeddedDimensions(i,l,o)}),o}getModelRowSecurityList(r,i){return this.getMapElementsByList(this.getUnique(r),i)}getCatalogUsedDimensions(r){let i=[],o=this.sortYamlModels(this.getYamlFilesWithoutDetachedRelationships(r));o.models.forEach(p=>{let _=this.getModelDimensions(p.relationships.filter(Ic.isRegularRelation).map(b=>b.to.dimension).concat(p.dimensions||[]),o.dimensions);i.push(..._)});let l=this.getUnique(i.map(p=>p.unique_name));return r.filter(({data:{unique_name:p}})=>l.includes(p))}addEmbeddedDimensions(r,i,o,l=[],p=0){if(p>cwt)throw new V6(`Max recursive depth exceeded. Dimension Path: ${l.join(" -> ")}`);if(l.includes(i.unique_name))return;let _=[];if(i.relationships?.forEach(b=>{b.type===Xae.Embedded&&ki.isRegularRelation(b)&&_.push(b.to.dimension)}),_.length){let b=this.getMapElementsByList(_,r);b.forEach(T=>this.addEmbeddedDimensions(r,T,o,[...l,i.unique_name],p++)),b.forEach(T=>{o.some(k=>k.unique_name===T.unique_name)||o.push(T)})}}getMapElementsByList(r,i,o){let l=[];return r.reduce((p,_)=>{let b=i.get(_);return o||zae.exists(b,`Yaml Item "${_}" do not exist.`),b&&p.push(b),p},l)}getMetricsByList(r,i,o){let l=[];return r.reduce((p,_)=>{let b=i.get(_.unique_name);return o||zae.exists(b,`Yaml Item "${_.unique_name}" do not exist.`),b&&p.push(b),p},l)}getModelDatasets(r,i,o,l){let p=i.reduce((k,j)=>[...k,...j.level_attributes],[]),_=p.filter(ki.isLevelFromOneDataset).map(({dataset:k})=>k),b=p.filter(ki.isLevelWithMultipleDatasets).flatMap(({shared_degenerate_columns:k})=>k).map(({dataset:k})=>k),T=[..._,...b,...o.map(k=>k.from.dataset),...l.map(k=>k.dataset)],E=this.getUnique(T);return this.getMapElementsByList(E,r)}getAllDatasets(r){return Array.from(r.values())}getYamlFilesWithoutDetachedRelationships(r){return r.map(i=>{let o=i.data;return!o.relationships||o.relationships.length===0?i:{...i,data:{...o,relationships:this.filterRelationships(o.relationships)}}})}getAllDataWarehouseConnectionsUsedInRepo(r){let i=new Map;return Array.from(r.models.values()).forEach(o=>{if(o.unique_name){let l=this.getAllConnectionUniqueNamesUsedInModel(o,r).map(p=>r.connections.get(p)).filter(this.filterUndefined).map(p=>p.as_connection);i.set(o.unique_name,this.getUnique(l))}}),i}getAllEmbeddedRelationshipsFromProject(r){return r.dimensions?.reduce((i,o)=>(o.embeddedRelationshipsMetadata&&i.push(...o.embeddedRelationshipsMetadata),i),[])??[]}getModelDatasetsUniqueNamesUsedInAnyChildObject(r,i){let o=r.relationships.map(T=>T.from.dataset),l=[],p=[];r.relationships.forEach(T=>{Ic.isRegularRelation(T)&&l.push(T.to.dimension),Ic.isSecurityRelation(T)&&p.push(T.to.row_security)});let _=l.map(T=>i.dimensions.get(T)).filter(T=>T!==void 0).flatMap(T=>this.getDimensionDatasetUniqueNamesInAnyChildObject(T,i)),b=p.map(T=>i.rowSecurity.get(T)).filter(T=>T!==void 0).flatMap(T=>T?.dataset);return this.getUnique([...o,..._,...b])}setYamlFileToRepoObjects(r,i){let o=i.data.unique_name;switch(zae.ensure(!r.models.has(o),`${i.data.object_type} with uniqueName ${o} already exists`),i.data.object_type){case Hh.Connection:r.connections.set(o,i.data);break;case Hh.Dataset:r.datasets.set(o,i.data);break;case Hh.Dimension:r.dimensions.set(o,i.data);break;case Hh.RowSecurity:r.rowSecurity.set(o,i.data);break;case Hh.Metric:r.measures.set(o,i.data);break;case Hh.MetricCalc:r.calculations.set(o,i.data);break;case Hh.Model:r.models.set(o,i.data);break;case Hh.CompositeModel:r.compositeModels.set(o,i.data);break}}getDimensionDatasetUniqueNamesInAnyChildObject(r,i,o=[],l=1){if(o.some(z=>z.unique_name===r.unique_name))return[];if(l>cwt)return[];let p=this.filterUndefinedArray(r.relationships?.map(z=>z.from.dataset)),_=[],b=[],T=[];(r.relationships||[]).forEach(z=>{_.push(z.from.dataset),ki.isRegularRelation(z)&&ki.isEmbeddedRelation(z)&&b.push(z.to.dimension),ki.isSecurityRelation(z)&&T.push(z.to.row_security)});let E=b.map(z=>i.dimensions.get(z)).filter(this.filterUndefined).flatMap(z=>this.getDimensionDatasetUniqueNamesInAnyChildObject(z,i,[...o,r],l++)),k=T.map(z=>i.rowSecurity.get(z)).filter(this.filterUndefined).flatMap(z=>z.dataset),j=r.hierarchies.flatMap(z=>z.levels.flatMap(X=>{let ue=r.level_attributes.find(ht=>ht.unique_name===X.unique_name),De=ue?ki.isLevelWithMultipleDatasets(ue)?ue.shared_degenerate_columns.map(({dataset:ht})=>ht):[ue.dataset]:[],Je=this.filterUndefinedArray(X.aliases?.map(ht=>ht.dataset)),$e=this.filterUndefinedArray(X.secondary_attributes?.map(ht=>ht.dataset)),Ke=this.filterUndefinedArray(X.metrics?.map(ht=>ht.dataset));return this.filterUndefinedArray([...De,...Je,...$e,...Ke,...k])}));return this.getUnique([...p,...j,..._,...E])}getAllConnectionUniqueNamesUsedInModel(r,i){return this.getUnique(this.getModelDatasetsUniqueNamesUsedInAnyChildObject(r,i).map(o=>i.datasets.get(o)).filter(this.filterUndefined).map(o=>o.connection_id))}filterUndefinedArray(r){return r===void 0?[]:r.filter(this.filterUndefined)}filterUndefined(r){return r!==void 0}getUnique(r){return Array.from(new Set(r))}};var rl=class{static groupBy(r,i){return r.reduce((o,l)=>{let p=JSON.stringify(i(l)),_=o.get(p)||[];return _.push(l),o.set(p,_),o},new Map)}static appendErrorsIfDuplicates(r,i,o){this.processDuplicates(r,l=>{let p=o(l[0],l.length);i.addError(p)})}static appendErrorsWithContextIfDuplicates(r,i,o,l){let{getContext:p,hierarchyUniqueName:_}=l;this.processDuplicates(r,b=>{let T=o(b[0],b.length),E=p(b[0],_);i.addErrorWithContext(T,E)})}static processDuplicates(r,i){Array.from(r.values()).filter(o=>o.length>1).forEach(i)}static checkIfDuplicateNameExists(r){return new Set(r).size!==r.length}static findCommonElement(r){if(r.length<2)return null;let i=[...r],o=i.splice(0,1)[0];for(let l of o)if(i.every(p=>p.has(l)))return l;return null}};var lwt={duplicateCalcGroupNameInDimension:()=>"There are Calculation Groups with duplicated names",duplicateCalcGroupNamesInDimensions:(n,r)=>`Calculation Group${n.length>1?"s":""} ${n.join(", ")} also occur in dimension: ${r}`},Kxe=class n{constructor(r){this.yamlQueries=r}static create(r=new pA){return new n(r)}validate(r){let i=Mo.create(),o=this.yamlQueries.getCatalogUsedDimensions(r),l=this.getMapCalcGroup(o);return this.validateCalcGroupNames(l,o,i),i}getMapCalcGroup(r){return r.reduce((i,o)=>{let l=o.data,p=l.unique_name,_=l.calculation_groups?.map(T=>T.unique_name)||[],b=[...i.get(p)||[],..._];return i.set(p,b),i},new Map)}validateCalcGroupNames(r,i,o){r.forEach((l,p)=>{let _=us.ensure(i.find(b=>b.data.unique_name===p),"Dimension file not exist");rl.checkIfDuplicateNameExists(l)&&o.file(_).addError(lwt.duplicateCalcGroupNameInDimension()),r.forEach((b,T)=>{if(p!==T){let E=b.filter(k=>l.includes(k));E.length>0&&o.file(_).addError(lwt.duplicateCalcGroupNamesInDimensions(E,T))}})})}};var MPr={getMultiDwError:(n,r)=>`Multi data-warehouse connections are used in model "${n}". Only one datawarehouse should be used per model. Data-warehouse connection ids: ${r.join(",")}`},Xxe=class n{constructor(r){this.yamlQueries=r}static create(r=new pA){return new n(r)}validate(r){let i=this.yamlQueries.sortYamlModels(r),o=this.yamlQueries.getAllDataWarehouseConnectionsUsedInRepo(i),l=Mo.create();return o.forEach((p,_)=>{p.length>1&&l.global().addError(MPr.getMultiDwError(_,p))}),l}};var PO=(n,r)=>n.object_type===r,uC={isConnection(n){return PO(n,Hh.Connection)},isDataset(n){return PO(n,Hh.Dataset)},isDimension(n){return PO(n,Hh.Dimension)},isRowSecurity(n){return PO(n,Hh.RowSecurity)},isMetric(n){return PO(n,Hh.Metric)},isModel(n){return PO(n,Hh.Model)},isCompositeModel(n){return PO(n,Hh.CompositeModel)},isMetricCalc(n){return PO(n,Hh.MetricCalc)},isCatalog(n){return PO(n,Hh.Catalog)},isGlobalSettings(n){return PO(n,Hh.GlobalSettings)}};var KL=n=>n.filter(r=>uC.isModel(r.data)||uC.isCompositeModel(r.data)),NO=n=>n.filter(r=>uC.isDimension(r.data)),Zxe=n=>n.reduce((r,i)=>(r.set(i.data.unique_name,i),r),new Map);var eTe=class{getDependencyCycleError(r){return`Dependency cycle detected ${r.join(" -> ")}`}checkDependencyCycles(r,i){try{let o=new Set;r.forEach(l=>{this.traverseDimensions(l,r,i,o)})}catch(o){let l=qd.getErrorMessage(o);i.addGlobalOutput("warning",`Dimension cycle dependency check failed. ${l}`)}}traverseDimensions(r,i,o,l,p=[]){let _=p.indexOf(r.data.unique_name),b=[...p,r.data.unique_name];if(_>=0){o.file(r).addWarning(this.getDependencyCycleError(b.slice(_)));return}l.has(r.data.unique_name)||(l.add(r.data.unique_name),r.data.relationships&&(r.data.relationships||[]).forEach(T=>{if(ki.isRegularRelation(T)&&ki.isEmbeddedRelation(T)){let E=i.find(k=>k.data.unique_name===T.to.dimension);if(!E)return;this.traverseDimensions(E,i,o,l,b)}}))}};var CUe={getDuplicateDegenerateDimensionsWarning(n,r){return`The "${n}" combination is used in multiple degenerate dimensions: ${nh(r)}.`},getRelationshipInDimensionError:({object:n,orphanType:r})=>`There is an unrelated ${r} in the dimension - "${n||"unknown"}".`},tTe=class n{constructor(r,i=new eTe){this.yamlDegenerateDimensionUtil=r;this.dimensionCircularReferenceValidator=i}static create(r){return new n(r)}validate(r){let i=Mo.create();return this.verifyDimensionFiles(r,i),i}verifyDimensionFiles(r,i,o=NO){let l=o(r);this.verifyDegenerateDimensions(l,i),this.dimensionCircularReferenceValidator.checkDependencyCycles(l,i)}verifyDegenerateDimensions(r,i){this.yamlDegenerateDimensionUtil.getDuplicatedDegenerateDimensions(r).forEach((l,p)=>{l.length>1&&l.forEach(_=>i.file(_).addWarning(CUe.getDuplicateDegenerateDimensionsWarning(p,l.map(b=>b.data.unique_name))))})}};var bQ={missing:"Missing file with name catalog, in the root folder",moreThanOne:"There are more than one files from type catalog in the root folder",notInRoot:"file is not located in the root folder",objectTypeMissing:"object_type is missing",notCorrectObjType:"the file name suggests its object_type to be catalog",notCorrectFileName:"the file object_type suggests its name to be catalog"},uwt={atscaleFileDeprecated:"atscale.yml is deprecated, please rename the file to catalog.yml"},rTe={deprecated:["atscale.yaml","atscale.yml"],unique:["catalog.yaml","catalog.yml"],get all(){return[...this.unique,...this.deprecated]}},nTe=class n{constructor(){this.isFolderValidator=!0}static create(){return new n}validateFolderStructure(r){let i=Mo.create();return this.verifyCatalogFile(r,i),i}validateFileObjectType(r,i){!r.data||Pa.hasNoProps(r.data,"object_type")?i.file(r).addError(bQ.objectTypeMissing):_l.isCatalog(r.data)||i.file(r).addError(bQ.notCorrectObjType)}getCountFromRoot(r,i,o){let l=0;return r.forEach(p=>{let _=Ro.getFileNameFromPath(p.relativePath);i.includes(_)&&(this.validateFileObjectType(p,o),l++)}),l}checkSubFoldersForCatalogFiles(r,i){if(!Ro.isFileOnRootLevel(r.relativePath)&&r.origin==="R"){let o=Ro.getFileNameFromPath(r.relativePath);rTe.all.includes(o)&&i.file(r).addError(bQ.notInRoot)}}validateFileNamesByObjectType(r,i){if(r.data?.object_type==="catalog"){let o=Ro.getFileNameFromPath(r.relativePath);rTe.all.includes(o)||i.file(r).addError(bQ.notCorrectFileName)}}isNoCatalogFiles(r,i){return r===0&&i===0}isTooManyCatalogFiles(r,i){return r>1||i>1||r===1&&i===1}isOnlyDeprecatedCatalogFile(r,i){return r===0&&i===1}handleTooManyCatalogFiles(r){r.addGlobalOutput("error",bQ.moreThanOne),r.addGlobalOutput("warning",uwt.atscaleFileDeprecated)}handleDeprecatedCatalogFile(r,i){i.addGlobalOutput("warning",uwt.atscaleFileDeprecated),this.processFiles(r,i)}processFiles(r,i){Ik.traverse(r,o=>{this.checkSubFoldersForCatalogFiles(o,i),this.validateFileNamesByObjectType(o,i)})}async verifyCatalogFile(r,i){let o=this.getCountFromRoot(r.files,rTe.unique,i),l=this.getCountFromRoot(r.files,rTe.deprecated,i);this.isNoCatalogFiles(o,l)?i.addGlobalOutput("error",bQ.missing):this.isTooManyCatalogFiles(o,l)?this.handleTooManyCatalogFiles(i):this.isOnlyDeprecatedCatalogFile(o,l)?this.handleDeprecatedCatalogFile(r,i):this.processFiles(r,i)}};var iTe=_u(eoe()),DQ=(n,r)=>n?.toLocaleLowerCase()===r?.toLocaleLowerCase(),fwt=n=>(0,iTe.uniqWith)(n,iTe.isEqual).length===1;function pwt(n){return n.map(r=>XL(r,n))}function XL(n,r){return _l.isCompositeModel(n.data)?{...n,data:LPr(n,r)}:n}function LPr(n,r){let i={relationships:[],metrics:n.data.metrics??[],object_type:"model",label:n.data.label,unique_name:n.data.unique_name,dimensions:[]};return n.data.models.forEach(o=>{let l=r.find(_=>_.data.unique_name===o);if(!l)throw new Error(`No object found with unique name ${o}`);let p=l.data;i.metrics=i.metrics.concat(p.metrics),i.dimensions=i.dimensions?.concat(p.dimensions??[]),i.relationships=i.relationships.concat(p.relationships),i.overrides=jPr(i,p)}),n.data.aggregates&&(i.aggregates=(i.aggregates??[]).concat(n.data.aggregates)),i.dimensions?.length||(i.dimensions=void 0),(!i.overrides||!Object.values(i.overrides).length)&&(i.overrides=void 0),i}function jPr(n,r){return{...n.overrides,...r.overrides}}var oTe=_u(eoe());var Vdn={error:"Display an error message and return nothing",repeat:"Include repeated values in query results",empty:"Include empty cells in query results"},OO=["sum","average","minimum","maximum","count distinct","sum distinct","estimated count distinct","count non-null","stddev_samp","stddev_pop","var_samp","var_pop","percentile"],sTe=["sum","minimum","maximum"],toe=OO.filter(n=>n!=="percentile"),zdn="sum",aTe={int:OO,long:OO,float:OO,double:OO,decimal:OO,bigint:OO,tinyint:OO,number:OO,numeric:OO,datetime:toe,date:toe,boolean:toe,string:toe,timestamp:toe};var BPr={median:[.5],quartiles:[.25,.5,.75,1],deciles:[.1,.2,.3,.4,.5,.6,.7,.8,.9,1]},xQ=n=>n.custom_quantiles??(n.named_quantiles&&BPr[n.named_quantiles]),TQ=(n,r)=>{let i=`${n} PCTL`;if(r==1)return`${i}100`;let o=String(Math.round(r*100));return o=o.toString().padStart(2,"0"),`${i}-${o}`},CQ=(n,r)=>`${n}_instance_${r}`;var $B=class{static isLevelHidden(r,i){return r.is_hidden??i.is_hidden??void 0}};var EUe=class n{getRelationshipsPaths(){}static create(){return new n}resolve(r){return r}addRolePlay(r){return roe.for(r)}},wUe=class n{constructor(r){this.model=r}static for(r){return new n(r)}getRelationshipsPaths(){}resolve(r){return(this.model.overrides||{})[r]?.query_name||r}addRolePlay(r){return roe.for(r)}},roe=class n{constructor(r){this.rolePlays=r}static for(r){return new n([r])}getRelationshipsPaths(){return this.rolePlays.map(r=>r.relationshipUniqueName)}resolve(r){return[...this.rolePlays].reverse().map(i=>i.rolePlay).reduce((i,o)=>o.replace("{0}",i),r)}addRolePlay(r){return new n([...this.rolePlays,r])}},AUe=class n{static create(){return new n}resolveMetric(r){return`[Measures].[${r}]`}resolveDimension(r){return`[${r}]`}resolveHierarchy(r,i){return`${this.resolveDimension(r)}.[${i}]`}resolveLevel(r,i,o){return`${this.resolveHierarchy(r,i)}.[${o}]`}resolveSecondaryAttribute(r,i){return`${this.resolveDimension(r)}.[${i}].[${i}]`}resolveLevelAlias(r,i){return`${this.resolveDimension(r)}.[${i}].[${i}]`}resolveCalculationGroup(r,i){return`${this.resolveDimension(r)}.[${i}]`}resolveCalculationMember(r,i,o){return`${this.resolveDimension(r)}.[${i}].[${o}]`}},cTe=class{constructor(){this.fullQueryNameResolver=AUe.create()}buildQueryableItemsForCompositeModel(r,i,o){let l=this.getModelMeasures(r,o),p=i.map(b=>this.buildQueryableItems(b,o)),_=r.data;return{metrics:l,dimensions:(0,oTe.default)(p).flatMap("dimensions").uniqBy("fullQueryName").value(),childModelsMetrics:(0,oTe.default)(p).flatMap("metrics").uniqBy("fullQueryName").value(),aggregates:_.aggregates||[],rowSecurities:(0,oTe.default)(p).flatMap("rowSecurities").uniqBy("fullQueryName").value()}}buildQueryableItems(r,i){let o={dimensions:[],metrics:[],aggregates:[],rowSecurities:[]},l=r.data;return o.metrics=this.getModelMeasures(r,i),l.dimensions?.forEach(p=>{this.populateDegenDimension(r,p,o,i)}),l.relationships?.filter(Ic.isRegularRelation).map(p=>({modelDimUniqueName:p.to.dimension,level:p.to.level,rolePlay:p.role_play,relationshipName:p.unique_name})).forEach(({modelDimUniqueName:p,level:_,rolePlay:b,relationshipName:T})=>{this.populateModelRelationDimension(r,p,_,b?{rolePlay:b,relationshipUniqueName:T}:void 0,o,i)}),l.relationships?.filter(Ic.isSecurityRelation).forEach(p=>{this.populateRowSecurity(r,p.to.row_security,o,i)}),o.aggregates=l.aggregates||[],o}getItem(r,i){return i.get(r)}getQueryName(r,i){return _l.isCompositeModel(r)?i:(r.overrides||{})[i]?.query_name||i}getModelMeasures(r,i){return r.data.metrics?r.data.metrics.map(o=>{let l=this.getItem(o.unique_name,i);if(!l||!["metric_calc","metric"].includes(l.data.object_type))return;let p=this.getQueryName(r.data,o.unique_name),_=l.data.object_type==="metric_calc"?"MetricCalc":"Metric",b=l.data;return _l.isMetric(b)&&b.calculation_method==="percentile"?xQ(b)?.map(E=>{let k=CQ(p,E);return{queryName:k,fullQueryName:this.fullQueryNameResolver.resolveMetric(k),uniqueName:o.unique_name,label:TQ(l.data.label,E),description:l.data.description,file:l,fileChain:[],type:_,folder:o.folder}})??[]:{queryName:p,fullQueryName:this.fullQueryNameResolver.resolveMetric(p),uniqueName:o.unique_name,label:l.data.label,description:l.data.description,file:l,fileChain:[],type:_,folder:o.folder}}).flat().filter(wO):[]}populateDegenDimension(r,i,o,l){this.populateDimension(r,i,void 0,o,l,wUe.for(r.data))}populateModelRelationDimension(r,i,o,l,p,_){let b=l?roe.for(l):EUe.create();this.populateDimension(r,i,o,p,_,b)}populateRowSecurity(r,i,o,l){let p=this.getItem(i,l);if(!p||p.data.object_type!=="row_security"||o.rowSecurities.some(T=>T.uniqueName===i))return;let _=i,b={uniqueName:i,queryName:_,fullQueryName:_,label:p.data.label||i,description:p.data.description,file:p,fileChain:[p]};o.rowSecurities.push(b)}populateDimension(r,i,o,l,p,_,b=[]){let T=this.getItem(i,p);if(!T||T.data.object_type!=="dimension")return;let E=_.resolve(i),k=T.data.hierarchies.filter(De=>o===void 0?!0:De.levels.find(Je=>Je.unique_name===o)).map(De=>{let Je=_.resolve(De.unique_name);return{queryName:Je,fullQueryName:this.fullQueryNameResolver.resolveHierarchy(E,Je),uniqueName:De.unique_name,label:_.resolve(De.label),description:De.description,folder:De.folder,levels:De.levels.map($e=>{$e.metrics?.forEach(cr=>{let Mr=this.fullQueryNameResolver.resolveMetric(cr.unique_name);l.metrics.filter(this.isModelQueryableDimensionMetric).some(ar=>ar.uniqueName===cr.unique_name&&ar.dimension===T.data.unique_name&&ar.level===$e.unique_name)||l.metrics.push({file:{data:{calculation_method:cr.calculation_method}},fileChain:[...b],queryName:cr.unique_name,fullQueryName:Mr,label:_.resolve(cr.label),type:"DimensionalMetric",uniqueName:cr.unique_name,description:cr.description,folder:cr.folder,dimension:T.data.unique_name,level:$e.unique_name})});let Ke=T.data.level_attributes.find(qL($e.unique_name)),ht=_.resolve($e.unique_name);return{queryName:ht,fullQueryName:this.fullQueryNameResolver.resolveLevel(E,Je,ht),uniqueName:$e.unique_name,label:Ke?.label?_.resolve(Ke.label):"",description:Ke?.description,isHidden:Ke&&$B.isLevelHidden($e,Ke),relationshipsPath:_.getRelationshipsPaths(),secondaryAttributes:($e.secondary_attributes||[]).map(cr=>{let Mr=_.resolve(cr.unique_name);return{queryName:Mr,fullQueryName:this.fullQueryNameResolver.resolveSecondaryAttribute(E,Mr),uniqueName:cr.unique_name,label:_.resolve(cr.label),description:cr.description,folder:cr.folder,isHidden:cr.is_hidden,relationshipsPath:_.getRelationshipsPaths()}}),aliases:($e.aliases||[]).map(cr=>{let Mr=_.resolve(cr.unique_name);return{queryName:Mr,fullQueryName:this.fullQueryNameResolver.resolveLevelAlias(E,Mr),uniqueName:cr.unique_name,label:_.resolve(cr.label),description:cr.description,folder:cr.folder,isHidden:cr.is_hidden,relationshipsPath:_.getRelationshipsPaths()}})}})}}),j=this.populateCalculationGroups(T.data.calculation_groups,i),z=this.fullQueryNameResolver.resolveDimension(E),X=l.dimensions.find(De=>De.fullQueryName===z);if(X){k.forEach(De=>{X.hierarchies.some($e=>$e.fullQueryName===De.fullQueryName)||X.hierarchies.push(De)});return}let ue={queryName:E,fullQueryName:z,uniqueName:i,label:_.resolve(T.data.label),description:T.data.description,hierarchies:k,file:T,fileChain:[...b],calculationGroups:j};l.dimensions.push(ue),T.data.relationships?.forEach(De=>{if(ki.isSecurityRelation(De)||!ki.isEmbeddedRelation(De))return;let Je=De.role_play?_.addRolePlay({rolePlay:De.role_play,relationshipUniqueName:De.unique_name}):_;this.populateDimension(r,De.to.dimension,De.to.level,l,p,Je,[...b,T])})}populateCalculationGroups(r,i){return r?r.map(o=>{let l=o.calculated_members.map(p=>({uniqueName:p.unique_name,queryName:p.unique_name,fullQueryName:this.fullQueryNameResolver.resolveCalculationMember(i,o.unique_name,p.unique_name),label:p.unique_name,description:p.description}));return{uniqueName:o.unique_name,queryName:o.unique_name,fullQueryName:this.fullQueryNameResolver.resolveCalculationGroup(i,o.unique_name),label:o.label,folder:o.folder,calculationMembers:l}}):[]}isModelQueryableDimensionMetric(r){return r.type==="DimensionalMetric"}};var $Pr=(n,r)=>`dataset: "${n}" and key_columns: ${nh(r)}`,JB=class{constructor(){this.getDuplicatedDegenerateDimensions=r=>{let i=this.groupByDatasetAndKeyColumn(r);return this.getDuplicatedDimensions(i)}}groupByDatasetAndKeyColumn(r){let i=new Map;return r.filter(o=>o.data.is_degenerate).forEach(o=>{o.data.level_attributes.forEach(l=>{if(ki.isLevelFromOneDataset(l)){let p=$Pr(l.dataset,l.key_columns);i.has(p)||i.set(p,[]);let _=i.get(p);_&&_.push(o)}})}),i}getDuplicatedDimensions(r){return new Map([...r].filter(([i,o])=>o.length>1))}};var kUe={getCalcMeasureCycleReferenceError:n=>`Cycle calculated measure reference detected. Reference path: ${n.map(r=>r.data.unique_name).join("->")}`,getMeasureIsNotFoundByUniqueName:n=>`Cannot check cycle reference for measure with unique_name: ${n}. It was not found in the resolved queryable items`,getMeasureIsNotFoundByQueryName:n=>`Cannot check cycle reference for measure with model context resolved queryName: ${n}. It was not found in the resolved queryable items`},lTe=class n{static create(){return new n}validate(r,i,o){let l=[];i.data.metrics.forEach(p=>{let _=r.find(T=>T.uniqueName===p.unique_name);if(!_){o.file(i).addWarning(kUe.getMeasureIsNotFoundByUniqueName(p.unique_name));return}if(_.type!=="MetricCalc")return;let b=this.getLongestCycleDependency(_,r,o.file(i),l);b&&l.push(b)}),l.forEach(p=>o.file(i).addError(kUe.getCalcMeasureCycleReferenceError(p)))}getLongestCycleDependency(r,i,o,l,p=[],_=0){if(us.ensure(_<50,"YamlModelCalcMeasuresCycleRefValidator max depth exceeded"),l.flatMap(E=>E).some(E=>E.data.unique_name===r.uniqueName))return;let b=[...p,r.file];if(p.find(E=>E.data.unique_name===r.uniqueName))return b;let T=r.file.data.expression;if(T){let E=uA(T),k=[];return E.forEach(j=>{let z=i.find(ue=>ue.queryName.toLowerCase()===j.toLowerCase());if(!z){o.addWarning(kUe.getMeasureIsNotFoundByQueryName(j));return}if(z.type!=="MetricCalc")return;let X=this.getLongestCycleDependency(z,i,o,l,b,_+1);X&&k.length<X.length&&(k=X)}),k.length>0?k:void 0}}};var UB={missingModels:"Missing Model files in folder structure",getDuplicateMetricError(n,r){return`Duplicate query name detected in context of a model "${n.unique_name}". Query name: "${r[0]?.queryName}".`},getCalcMeasureContainsANonExistingMeasure:(n,r)=>`Calculated metric "${n}" expression contains a non-existing metric: "${r}".`,getDuplicatedDegeneratedDimensionsInModelError:(n,r)=>`Degenerate dimensions: ${nh(n)} are referred in the model, however, they have duplicated "${r}" combination. Please remove duplicates.`,getDuplicatedDegeneratedDimensionsInMultipleModelsError:(n,r,i)=>`Degenerate dimensions: ${nh(n)} are referred in models: ${nh(r)}, however, they have duplicated ${i} combination. Please remove duplicates.`,getRelationshipInModelError:({object:n,orphanType:r})=>`There is an unrelated ${r} in the model - "${n||"unknown"}".`},uTe=class n{constructor(r,i,o){this.yamlDegenerateDimensionUtil=r;this.yamlModelQueryNameResolver=i;this.yamlModelCalcMeasuresCycleRefValidator=o}static create(r=new JB,i=new cTe,o=lTe.create()){return new n(r,i,o)}validate(r){let i=Mo.create();return this.verifyModelFiles(r,i),i}async verifyModelFiles(r,i,o=KL,l=Zxe){if(!r.find(b=>_l.isModel(b.data))){i.addGlobalOutput("error",UB.missingModels);return}let p=l(r),_=o(r);_.forEach(b=>{let T=XL(b,r),{metrics:E}=this.yamlModelQueryNameResolver.buildQueryableItems(T,p);this.verifyAllQueryNameMetricsDuplicates(E,T,i),this.verifyModelCalculationMeasures({metrics:b.data.metrics||[],queryableMetrics:E,modelFile:T,allItems:p,validatorOutput:i}),this.verifyDegenerateDimensionsInAModel(T,r,i)}),this.verifyDegenerateDimensionsInAllModels(_,r,i)}verifyDegenerateDimensionsInAModel(r,i,o,l=NO){if(!r.data?.dimensions)return;this.yamlDegenerateDimensionUtil.getDuplicatedDegenerateDimensions(l(i)).forEach((_,b)=>{let T=this.findDegenerateDimsUsedInSingleModel(_,r);T.length>1&&o.file(r).addWarning(UB.getDuplicatedDegeneratedDimensionsInModelError(T,b))})}findDegenerateDimsUsedInSingleModel(r,i){return r.reduce((o,l)=>{let p=i.data.dimensions?.find(_=>_===l.data.unique_name);return p&&o.push(p),o},[])}verifyDegenerateDimensionsInAllModels(r,i,o,l=NO){this.yamlDegenerateDimensionUtil.getDuplicatedDegenerateDimensions(l(i)).forEach((_,b)=>{let{degenerateDimsUsedInModels:T,modelsWithDuplicatedDegenerateDims:E}=this.findDuplicatedDegenerateDimsInMultipleModels(_,r,i),k=Array.from(new Set(T)),j=Array.from(new Set(E));k.length>1&&j.forEach(z=>{o.file(z).addWarning(UB.getDuplicatedDegeneratedDimensionsInMultipleModelsError(k,j.map(X=>X.data.unique_name),b))})})}findDuplicatedDegenerateDimsInMultipleModels(r,i,o){let l=[],p=[];return r.forEach(_=>{i.forEach(b=>{let T=XL(b,o);T.data.dimensions&&T.data.dimensions.find(k=>k===_.data.unique_name)&&(l.push(_.data.unique_name),p.push(T))})}),{degenerateDimsUsedInModels:l,modelsWithDuplicatedDegenerateDims:p}}verifyQueryNameMetricsDuplicates(r,i,o){let l=rl.groupBy(r,p=>[p.queryName.toLowerCase()]);Array.from(l.values()).filter(p=>p.length>1).forEach(p=>o.file(i).addError(UB.getDuplicateMetricError(i.data,p)))}verifyAllQueryNameMetricsDuplicates(r,i,o){let l=Mo.create();this.verifyQueryNameMetricsDuplicates(r,i,l),o.append(l),l.hasErrors||this.yamlModelCalcMeasuresCycleRefValidator.validate(r,i,o)}verifyModelCalculationMeasures({metrics:r,queryableMetrics:i,modelFile:o,allItems:l,validatorOutput:p}){this.getModelCalculatedMetrics(l,r.map(_=>_.unique_name)).forEach(_=>{this.verifyExpressionMeasures(_.data,i,o,p)})}getModelCalculatedMetrics(r,i){return i.reduce((o,l)=>{let p=r.get(l);return p&&_l.isMetricCalc(p.data)&&o.push(p),o},[])}verifyExpressionMeasures(r,i,o,l){uA(r.expression).forEach(p=>{i.some(b=>DQ(b.queryName,p))||l.file(o).addError(UB.getCalcMeasureContainsANonExistingMeasure(r.unique_name,p))})}};var ZL={missing:"Missing file with name global_settings, in the root folder",moreThanOne:"There is more than one global_settings file in the root folder",exists:"File with type global_settings exists in non global settings repository",otherYamlFiles:"Unknown yml file(s) exist in the global settings repository. Delete all yml/yaml files except the file with the name global_settings.yml/yaml",objectTypeMissing:"object_type is missing",notCorrectObjType:"the file name suggests its object_type to be global_settings",notCorrectFileName:"the file object_type suggests its name to be global_settings",notInRoot:"file is not located in the root folder"},fTe=["global_settings.yaml","global_settings.yml"],pTe=class n{constructor(r){this.isGlobalSettingsRepo=r;this.isFolderValidator=!0}static create(r){return new n(r)}validateFolderStructure(r){let i=Mo.create();return this.verifyGlobalSettingsFile(r,i),i}verifyGlobalSettingsFile(r,i){if(!this.isGlobalSettingsRepo){this.doesGlobalSettingsFileExist(r)&&i.addGlobalOutput("error",ZL.exists);return}let o=this.getCountFromRoot(r.files,fTe,i),l=o===0,p=o>1;l&&i.addGlobalOutput("error",ZL.missing),p&&i.addGlobalOutput("error",ZL.moreThanOne),this.otherYamlFilesExist(r)&&i.addGlobalOutput("error",ZL.otherYamlFiles),Ik.traverse(r,_=>{this.validateGlobalSettingsFile(_,i),this.validateFileNameByObjectType(_,i)})}doesGlobalSettingsFileExist(r){let i=!1;return Ik.traverse(r,o=>{o.data?.object_type==="global_settings"&&(i=!0)}),i}getCountFromRoot(r,i,o){let l=0;return r.forEach(p=>{let _=Ro.getFileNameFromPath(p.relativePath);i.includes(_)&&(this.validateFileObjectType(p,o),l++)}),l}validateFileObjectType(r,i){!r.data||Pa.hasNoProps(r.data,"object_type")?i.file(r).addError(ZL.objectTypeMissing):_l.isGlobalSettings(r.data)||i.file(r).addError(ZL.notCorrectObjType)}otherYamlFilesExist(r){let i=!1;return Ik.traverse(r,o=>{let l=Ro.getExtensionFromPath(o.relativePath),p=l&&["yaml","yml"].includes(l),_=Ro.getFileNameFromPath(o.relativePath),b=fTe.includes(_);p&&!b&&(i=!0)}),i}validateGlobalSettingsFile(r,i){if(!Ro.isFileOnRootLevel(r.relativePath)&&r.origin==="R"){let o=Ro.getFileNameFromPath(r.relativePath);fTe.includes(o)&&i.file(r).addError(ZL.notInRoot)}}validateFileNameByObjectType(r,i){if(r.data?.object_type==="global_settings"){let o=Ro.getFileNameFromPath(r.relativePath);fTe.includes(o)||i.file(r).addError(ZL.notCorrectFileName)}}};var JPr=[{major:1,minor:1,changes:{dimension:{calculation_groups:[{precedence:!0,is_hidden:!0,calculated_members:[{is_hidden:!0}]}]}}},{major:1,minor:2,changes:{catalog:{hidden_models:!0}}},{major:1,minor:3,changes:{catalog:{aggregate_store:{as_connection:!0,row_count_limit:!0,total_row_count_limit:!0}},dimension:{relationships:[{m2m:!0}]}}},{major:1,minor:4,changes:{composite_model:{aggregates:!0}}},{major:1,minor:5,changes:{metric:{compression:!0,named_quantiles:!0,custom_quantiles:!0},dimension:{hierarchies:[{levels:[{secondary_attributes:[{is_excel_pivot_table_property:!0,is_user_defined_property:!0}],aliases:[{is_excel_pivot_table_property:!0,is_user_defined_property:!0}]}]}]}}},{major:1,minor:6,changes:{catalog:{description:!0},model:{aggregates:[{attributes:[{row_security:!0}]}]}}}],UPr={newPropertiesDetected:(n,r)=>`Property with path: "${n}" was introduced in version "${r}"`},dTe=class n{constructor(r){this.smlSpecChanges=r}static create(r=JPr){return new n(r)}validate(r){let i=us.ensure(r.find(p=>p.data.object_type==="catalog"),"File with object_type catalog not found."),o=Mo.create(),l=this.smlSpecChanges.filter(p=>+`${p.major}.${p.minor}`>i.data.version);return l.length===0||r.forEach(p=>{l.filter(_=>_.changes[p.data.object_type]).forEach(_=>{this.getCommonKeyPaths(p.data,_.changes[p.data.object_type]).forEach(b=>{o.file(p).addError(UPr.newPropertiesDetected(b,`${_.major}.${_.minor}`),{type:"UpdateVersion",version:{major:_.major,minor:_.minor}})})})}),o}getCommonKeyPaths(r,i,o=""){let l=[];for(let p in r)if(Object.prototype.hasOwnProperty.call(i,p)){let _=r[p],b=i[p],T=o?`${o} -> ${p}`:p;if(this.isObject(_)&&!this.isObject(b)&&l.push(T),!this.isObject(_)&&!this.isObject(b)&&_!==void 0&&l.push(T),Array.isArray(_)&&Array.isArray(b))_.forEach((E,k)=>{let j=`${T}[${k}]`,z=this.getCommonKeyPaths(E,b[0],j);l.push(...z)});else if(this.isObject(_)&&_!==null&&this.isObject(b)&&b!==null){let E=this.getCommonKeyPaths(_,b,T);l.push(...E)}}return l}isObject(r){return typeof r=="object"}};var _Te=class n{constructor(){this.isFolderValidator=!0}static create(){return new n}validateFolderStructure(r){let i=Mo.create();return r.files.some(o=>o.relativePath===".gitmodules")&&i.addGlobalOutput("warning",`Git submodules are no longer supported. A '.gitmodules' file is detected in the repository. Consider using ${cC} file`),i}};var mTe={$id:"https://www.atscale.com/ml/package.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"package",type:"object",required:["version","packages"],properties:{version:{type:"number"},packages:{type:"array",items:{type:"object",required:["name","url","branch","version"],properties:{name:{type:"string",pattern:"^[a-zA-Z-_]*$",minLength:3,maxLength:128,errorMessage:{pattern:"should contains only a-z, A-Z, - or _ no spaces are allowed"}},url:{type:"string",pattern:"^(https?):\\/\\/[^\\s/$.?#].[^\\s]*$",maxLength:2048,errorMessage:{pattern:"should be valid with protocol http or https"}},version:{type:"string",pattern:"^commit:[a-fA-F0-9]{8,40}$",errorMessage:{pattern:"should start with 'commit:', followed by 8 to 40 characters that can only be letters (a-f, A-F) or digits (0-9)"}},branch:{type:"string",minLength:1}}}}}};var tkt=_u(vVe()),rkt=_u(MVe());var u7=class n extends Error{constructor(i){let o=i.join(",");super(o);this.errors=i}static fromAvjError(i){let l=us.ensure(i,"No errors provided").map(p=>p.message||p.keyword);return new n(l)}static single(i){return new n([i])}};var QTe=class{filterAnyOfErrors(r){try{let i=r.filter(p=>p.keyword==="anyOf");if(i.length===0)return r;let o=i.map(p=>r.find(b=>b.schemaPath.startsWith(p.schemaPath))??p);return[...r.filter(p=>i.every(_=>!p.schemaPath.startsWith(_.schemaPath)&&p.keyword!=="anyOf")),...o]}catch{return r}}formatErrors(r,i){return this.filterAnyOfErrors(r).reduce((l,p)=>{let _=this.formatSingleError(p,i);return l.push(_),l},[])}formatSingleError(r,i,o=""){let l=this.splitInstancePath(r.instancePath),[p,_]=l;if(!p)return o?`${o}${r.message}`:r.message;if(!_)return o=`${o}${p} ${r.message}`,o;let{subYamlObject:b,newErrorMessage:T,newInstancePath:E}=this.isIndex(_)?this.updateDataFromCollection(i,p,_,l,o):this.updateDataFromObject(i,p,_,l,o);return r.instancePath=E,this.formatSingleError(r,b,T)}updateDataFromCollection(r,i,o,l,p){let _=r[i][parseInt(o)],b=this.getDataName(_,o),T=l.slice(l.indexOf(o)+1).join("/"),E=`${p}${i}[${b}]`+this.getMessageSeparator(T);return{subYamlObject:_,newErrorMessage:E,newInstancePath:T}}updateDataFromObject(r,i,o,l,p){let _=r[i],b=l.slice(l.indexOf(o)).join("/"),T=`${p}${i}`+this.getMessageSeparator(b);return{subYamlObject:_,newErrorMessage:T,newInstancePath:b}}isIndex(r){return typeof r=="string"&&!Number.isNaN(parseInt(r))}getDataName(r,i){return r?Pa.hasProps(r,"name")?`name=${r.name}`:Pa.hasProps(r,"label")?`label=${r.label}`:Pa.hasProps(r,"unique_name")?`unique_name=${r.unique_name}`:`index: ${i}`:`index: ${i}`}getMessageSeparator(r){return this.splitInstancePath(r).length<=1?" ":" -> "}splitInstancePath(r){return r.split("/").filter(Boolean)}};var _C=class{constructor(r,i=new QTe){this.errorFormatter=i;this.ajv=new rkt.default(r),(0,tkt.default)(this.ajv)}compileSchema(r){return this.ajv.getSchema(r.$id)||this.ajv.addMetaSchema(r),this.compiledValidate=this.ajv.compile(r),this}validate(r){if(this.compiledValidate=us.ensure(this.compiledValidate,"Add compile schema before validating"),!this.compiledValidate(r.data)){let o=us.ensure(this.compiledValidate.errors,"AJV validation must contains errors"),l=this.errorFormatter.formatErrors(o,r.data);throw new u7(l)}return this}};var Xy=class{constructor(r,i){this.schemaValidator=r;this.jsonSchema=i}validateAML(r){try{this.schemaValidator.compileSchema(this.jsonSchema).validate(r)}catch(i){return i instanceof u7?{isValid:!1,errors:i.errors}:{isValid:!1,errors:[qd.getErrorMessage(i)]}}return{isValid:!0,errors:[]}}ensureRule(r,i){if(!r)throw u7.single(i)}};var Roe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var t4r={packagePropValueShouldBeUnique:(n,r)=>`package ${r} '${n}' should be unique`,packageNameShouldBeCorrect:n=>`packages[name=${n}] name should contains only a-z, A-Z, - or _ no spaces are allowed`,packageUrlShouldBeCorrect:n=>`packages[name=${n}] url should be valid with protocol http or https`,packageVersionShouldBeCorrect:n=>`packages[name=${n}] version should start with 'commit:', followed by 8 to 40 characters that can only be letters (a-f, A-F) or digits (0-9)`},r4r=[cC,cC.replace(".yml",".yaml")],YTe=class n{constructor(){this.isFolderValidator=!0}static create(){return new n}validateFolderStructure(r){let i=Mo.create();return r.files.forEach(o=>{let l=Ro.getFileNameFromPath(o.relativePath);if(r4r.includes(l)&&R1.isRawFile(o)){let _=JL.create().parse(o);R1.isPackageFile(_.data)&&this.validate(_.data).forEach(T=>i.addFileOutput(o.relativePath,T.severity,T.message))}}),i}validate(r){let i=[],o=new Roe(new _C({allErrors:!0}),mTe),l={data:r,relativePath:"",rawContent:"",compilationOutput:[]},p=o.validateAML(l);p.isValid||p.errors.forEach(T=>i.push({severity:"error",message:T}));let _=rl.groupBy(r.packages||[],T=>[T.name]);this.appendErrors("name",_,i);let b=rl.groupBy(r.packages||[],T=>[T.url]);return this.appendErrors("url",b,i),i}appendErrors(r,i,o){Array.from(i.values()).filter(l=>l.length>1).forEach(l=>l.forEach(p=>o.push({severity:"error",message:t4r.packagePropValueShouldBeUnique(p[r],r)})))}};var qk=class n{constructor(){this.getLevelContext=r=>({type:"level",level:r.itemUniqueName,hierarchy:r.hierarchyUniqueName,message:r.message,validationType:r.validationType});this.getLevelAttributeContext=r=>({type:"level-attribute",levelAttribute:r.itemUniqueName,message:r.message,validationType:r.validationType});this.getSecondaryAttributeContext=r=>({type:"secondary-attribute",secondaryAttribute:r.itemUniqueName,message:r.message,validationType:r.validationType});this.getLevelAliasContext=r=>({type:"level-alias",levelAlias:r.itemUniqueName,message:r.message,validationType:r.validationType})}static create(){return new n}};var Moe=class{constructor(){this.parentheses={"(":")","[":"]"};this.ignoredSymbolsInSquareParenthesis=new Set([")","("])}areParenthesesValid(r){let i=[],o=YH(r);for(let l of o)if(!(i[i.length-1]==="["&&this.ignoredSymbolsInSquareParenthesis.has(l))){if(l in this.parentheses)i.push(l);else if(this.isClosingParenthesis(l)){let _=i.pop();if(_===void 0||this.parentheses[_]!==l)return!1}}return!i.length}isClosingParenthesis(r){return Object.values(this.parentheses).some(i=>i===r)}};var Loe=class{validateObject(){return Mo.create()}};var LO=Object.freeze({major:1,minor:6});var jVe={noVisibleModels:n=>`No models to deploy. All models are hidden: "${n.join('", "')}"`,getDuplicateHiddenModelNames:(n,r)=>`Model "${n}" is used ${r} times in the hidden_models`,aggregateStoreCountLimit:"row_count_limit must be less than or equal to total_row_count_limit"},KTe=class{constructor(r,i){this.yamlModelValidator=r;this.yamlCommonReferenceValidator=i}validateObject(r,i){let o=Mo.create();this.yamlModelValidator.validateDatasetsProperties(o,r,i);let l=+`${LO.major}.${LO.minor}`;return r.data.version!==l&&o.file(r).addWarning(`Your current SML version is different from the latest supported version. Latest supported version: "${l}"`,{type:"UpdateVersion",version:{major:LO.major,minor:LO.minor}}),this.validateHiddenModels(r,i,o),this.validateAggregateStore(r,o),o}validateHiddenModels(r,i,o){if(!r.data.hidden_models)return;let l=rl.groupBy(r.data.hidden_models,_=>[_]);rl.appendErrorsIfDuplicates(l,o.file(r),jVe.getDuplicateHiddenModelNames);let p=!1;r.data.hidden_models.forEach(_=>{this.yamlCommonReferenceValidator.validateAndGetReferencedObject(_,i,r,"model",o)||(p=!0)}),p||this.validateAfterHiddenModelsThereIsAtLeastOneModelLeft(r,i,o)}validateAfterHiddenModelsThereIsAtLeastOneModelLeft(r,i,o){if(!r.data.hidden_models||r.data.hidden_models.length===0)return;let l=[];i.forEach(_=>{["composite_model","model"].includes(_.data.object_type)&&l.push(_.data.unique_name)}),l.filter(_=>!r.data.hidden_models?.includes(_)).length===0&&o.file(r).addError(jVe.noVisibleModels(r.data.hidden_models))}validateAggregateStore(r,i){let o=r.data.aggregate_store;!o?.row_count_limit||!o.total_row_count_limit||o.row_count_limit>o.total_row_count_limit&&i.file(r).addError(jVe.aggregateStoreCountLimit)}};var $Q=["bigint","int","long","date","datetime","timestamp"];var ih={referenceObjectNotExist:(n,r)=>`${n} "${r}" does not exist`,incorrectReference:(n,r,i)=>`Incorrect ${n} reference. ${n} "${r}" points to ${i}`,detachedRelationships:(n,r)=>`Relationship in ${n} has detached ${r} and will be skipped for the compilation`,invalidDatasetRelationship:(n,r,i)=>`Invalid relationship in Dataset ${n} located in ${r}. One or more connection columns are missing: ${i}`,invalidDimensionRelationship:(n,r,i)=>`Invalid relationship. The dimension "${n}" in "${r}" has no attribute: "${i}"`,invalidRelationshipPath:(n,r,i)=>`Invalid relationship path: ${n}. Object "${r}" in "${i}" has not existing relationship_path`,invalidRowSecurityRelationship:n=>`Invalid relationship. There is no row security with ${n}`,mismatchedRelationshipKeys:(n,r,i,o)=>`Invalid relationship. The number of join_columns in dataset ${n} (${r}) does not match the number of key_columns in level attribute ${i} (${o})`,getLevelDoesNotExistInDimensionError:(n,r)=>`Constraint_translation -> level "${n}" does not exist in dimension "${r}"`,getConstraintTranslationColumnsNotMatch:n=>`Constraint_translation -> from_columns number of items does not match the number of key_columns in level "${n}"`,getColumnNotExistInFactTable:(n,r)=>`Constraint_translation -> column "${n}" does not exist in dataset "${r}"`,getLevelMissingConstraintTranslationRank:(n,r,i)=>`Constraint_translation in relationship "${i}" references level "${n}" from "${r}". The level_attribute "${n}" must have a constraint_translation_rank property`,getFromColumnsNotMatchingKeyColumnTypes:(n,r,i,o)=>`Column type mismatch. Constraint_translation -> from_column "${i.name}" in relationship "${r}" has type "${i.data_type}" but key_column "${o.name}" in level "${n}" has type "${o.data_type}"`,getScdMissingColumn:(n,r,i)=>`Invalid relationship scd column "${r}". Relationship: "${n}". The target dataset "${i}" does not have column ${r}`,getScdColumnIsNotSimple:(n,r)=>`Invalid relationship "${n}" scd column "${r}". Column is not simple column. Mapped or derived columns are not allowed`,getScdInvalidColumnDataType:(n,r,i)=>`Relationship "${n}" scd_column "${r.name}" has invalid datatype: "${r.data_type}". Allowed types are: ${i.join(", ")}`,getScdTargetLevelIsNotFromOneDataset:(n,r,i)=>` Relationship "${n}" has SCD(Slowly Changing Dimension) incompatible reference to dimension ${r}, level ${i}. The level is not one dataset level.`,getScdTargetLevelHasNoSCDProps:(n,r,i)=>` Relationship "${n}" has scd_column set, but the referenced dimension ${r}, level ${i} is not configured to be Slowly Changing Dimension (has no scd_properties set).`,getScdRelationshipWithoutScdColumnToLevelWithScd:(n,r,i)=>`Relationship "${n}" has missing scd_column. The target level is marked as slowly changing dimension. Dimension: "${r}", Level: "${i}" `,getScdRelationshipIncompatibleDataType:(n,r)=>`Relationship "${n}" has SCD(Slowly Changing Dimension) incompatible type with the level. ScdColumn is ${r.scdColumn}:${r.scdDataType}, level scd effective start is ${r.effectiveStartColumn}:${r.effectiveStartDataType}`},joe=class{constructor(){this.validateScdRelationship=(r,i,o)=>{let l=Mo.create(),p=l.file(r),_=this.validateAndGetReferencedObject(i.to.dimension,o,r,"dimension",Mo.create()),b=_!==void 0?_.data.level_attributes?.find(k=>k.unique_name===i.to.level):void 0;if(!i.from.scd_column)return b&&ki.isLevelFromOneDataset(b)&&b.scd_properties!==void 0&&p.addError(ih.getScdRelationshipWithoutScdColumnToLevelWithScd(i.unique_name,i.to.dimension,i.to.level)),l;let T,E=this.validateAndGetReferencedObject(i.from.dataset,o,r,"dataset",Mo.create());if(E){let j=E.data.columns.find(z=>z.name===i.from.scd_column);j?Zl.isSimpleColumn(j)?$Q.includes(j.data_type)?T=j.data_type:p.addError(ih.getScdInvalidColumnDataType(i.unique_name,j,$Q)):p.addError(ih.getScdColumnIsNotSimple(i.unique_name,i.from.scd_column)):p.addError(ih.getScdMissingColumn(i.unique_name,i.from.scd_column,i.from.dataset))}if(_&&b)if(ki.isLevelFromOneDataset(b)){if(!b.scd_properties)p.addError(ih.getScdTargetLevelHasNoSCDProps(i.unique_name,i.to.dimension,i.to.level));else if(T!==void 0){let k=o.get(b.dataset);if(!k||k.data.object_type!=="dataset")return l;let j=k.data.columns.find(z=>z.name===b.scd_properties.effective_start.column);if(!j||!Zl.isSimpleColumn(j))return l;j.data_type!==T&&p.addError(ih.getScdRelationshipIncompatibleDataType(i.unique_name,{scdColumn:i.from.scd_column,scdDataType:T,effectiveStartColumn:j.name,effectiveStartDataType:j.data_type}))}}else p.addError(ih.getScdTargetLevelIsNotFromOneDataset(i.unique_name,i.to.dimension,i.to.level));return l}}validateAndGetReferencedObject(r,i,o,l,p){let _=i.get(r);if(!_){p.file(o).addError(ih.referenceObjectNotExist(l,r));return}if(_.data.object_type!==l){p.file(o).addError(ih.incorrectReference(l,r,_.data.object_type));return}return _}validateRelationships(r,i,o){let l=Mo.create(),{relationships:p}=r.data;return p&&p.forEach(_=>{if(ki.isRegularRelation(_)){let b=_.type==="snowflake"?r.data.unique_name:_.to.dimension;this.validateDetachedRelationship(l,r,_.from.dataset,"dataset"),this.validateDetachedRelationship(l,r,b,"dimension"),_.from.dataset.length&&b.length&&(l.append(this.validateLeftRelations(r,_,i,o)),l.append(this.validateRightRelations(r,_,i,o)),l.append(this.validateMismatchedRelationKeys(r,_,i,o)))}Ic.isRegularRelation(_)&&(_.constraint_translation&&l.append(this.validateConstraintTranslationInRelationships(_,r,i)),l.append(this.validateScdRelationship(r,_,i))),ki.isSecurityRelation(_)&&(this.validateDetachedRelationship(l,r,_.from.dataset,"dataset"),this.validateDetachedRelationship(l,r,_.to.row_security,"row_security"),_.from.dataset.length&&_.to.row_security.length&&(l.append(this.validateLeftRelations(r,_,i,o)),l.append(this.validateRightRelations(r,_,i,o))))}),l}validateConstraintTranslationRank(r,i,o,l){let p=Mo.create();return r.constraint_translation_rank===void 0&&p.file(i).addError(ih.getLevelMissingConstraintTranslationRank(l,o.to.dimension,o.unique_name)),p}validateNumberOfFromColumnsAndKeyColumns(r,i,o,l){let p=Mo.create();return r.key_columns.length!==o.length&&p.file(i).addError(ih.getConstraintTranslationColumnsNotMatch(l)),p}validateFromColumnsVsKeyColumnTypes(r,i,o,l,p){let _=Mo.create(),b=this.getFromColumnsWithTypes(r,o,p),T=this.getKeyColumnsWithTypes(r,l,i,_);if(T.length===b.length)for(let E=0;E<T.length;E++){let k=T[E],j=b[E];Zl.hasColumnDataTypeProp(k)&&Zl.hasColumnDataTypeProp(j)&&k.data_type!==j.data_type&&_.file(i).addError(ih.getFromColumnsNotMatchingKeyColumnTypes(l.unique_name,o.unique_name,j,k))}return _}validateColumnExistsInFactTable(r,i,o,l){let p=Mo.create(),_=r.get(o.from.dataset);return l.forEach(b=>{_&&_l.isDataset(_.data)&&(_.data.columns.find(E=>E.name===b)||p.file(i).addError(ih.getColumnNotExistInFactTable(b,_.data.unique_name)))}),p}getFromColumnsWithTypes(r,i,o){let l=[],p=r.get(i.from.dataset);return o.forEach(_=>{if(p&&_l.isDataset(p.data)){let b=p.data.columns.find(T=>T.name===_);b&&l.push(b)}}),l}getKeyColumnsWithTypes(r,i,o,l){let p=r.get(i.dataset);if(!p||!_l.isDataset(p.data))return l.file(o).addError(ih.referenceObjectNotExist("dataset",i.dataset)),[];let _=p.data.columns;return i.key_columns.flatMap(b=>{let T=_.find(E=>E.name===b);return T?[T]:[]})}validateConstraintTranslationInRelationships(r,i,o){let l=Mo.create();if(Ic.isRegularRelation(r)&&r.constraint_translation){let{level:p,from_columns:_}=r.constraint_translation,b=o.get(r.to.dimension);if(!b||!_l.isDimension(b.data))return l.file(i).addError(ih.referenceObjectNotExist("dimension",r.to.dimension)),l;let T=b.data.level_attributes.find(E=>E.unique_name===p);if(!T)return l.file(i).addError(ih.getLevelDoesNotExistInDimensionError(p,r.to.dimension)),l;ki.isLevelFromOneDataset(T)&&(l.append(this.validateConstraintTranslationRank(T,i,r,p)),l.append(this.validateNumberOfFromColumnsAndKeyColumns(T,i,_,p)),l.append(this.validateFromColumnsVsKeyColumnTypes(o,i,r,T,_))),l.append(this.validateColumnExistsInFactTable(o,i,r,_))}return l}validateRelationshipsReferences(r,i,o){if(_l.isModel(i.data)){let l=[...i.data.relationships];o.forEach(p=>{if(_l.isDimension(p.data)&&p.data.relationships){let _=p.data.relationships.filter(b=>ki.isEmbeddedRelation(b));l.push(..._)}}),i.data.drillthroughs&&i.data.drillthroughs.forEach(p=>this.validateReferencePath(r,i,p,l)),i.data.aggregates&&i.data.aggregates.forEach(p=>this.validateReferencePath(r,i,p,l))}return r}validateReferencePath(r,i,o,l){let p=[];return o.attributes?.filter(YL).forEach(_=>{_.relationships_path&&p.push(..._.relationships_path)}),p.forEach(_=>{l.some(b=>b.unique_name===_)||r.file(i).addError(ih.invalidRelationshipPath(_,o.unique_name,i.relativePath))}),r}validateAttributesReferences(r,i,o,l){l.forEach(p=>{let _=this.validateAndGetReferencedObject(p.dimension,o,i,"dimension",r);if(!_)return;let b=_.data,T=b.level_attributes.some(E=>E.unique_name===p.name);T=T||b.hierarchies.flatMap(E=>E.levels).flatMap(E=>[...E.secondary_attributes||[],...E.aliases||[],...E.metrics||[]]).some(E=>E?.unique_name===p.name),T||r.file(i).addError(`Dimension ${_.data.unique_name} has no referenced object ${p.name}`)})}validatePerspectiveDimensionReferences(r,i,o,l){l.forEach(p=>{this.validateAndGetReferencedObject(p.name,o,i,"dimension",r)})}validateMetricReferences(r,i,o,l){l.forEach(p=>{o.get(p)||r.file(i).addError(ih.referenceObjectNotExist("Metric or CalcMetric",p))})}validateDetachedRelationship(r,i,o,l){o?.length||r.file(i).addWarning(ih.detachedRelationships(i.data.unique_name,l))}validateLeftRelations(r,i,o,l){let p=Mo.create(),_=this.validateAndGetReferencedObject(i.from.dataset,o,r,"dataset",p);return _&&(l.add(i.from.dataset),!i.from.join_columns.every(T=>_.data.columns.some(E=>T===E.name))&&p.file(r).addError(ih.invalidDatasetRelationship(_.data.unique_name,_.relativePath,i.from.join_columns))),p}validateRightRelations(r,i,o,l){let p=Mo.create();if(ki.isSecurityRelation(i)||Ic.isSecurityRelation(i)){let _=this.validateAndGetReferencedObject(i.to.row_security,o,r,"row_security",p);return _&&(l.add(i.to.row_security),_||p.file(r).addError(ih.invalidRowSecurityRelationship(i.to.row_security))),p}else{let _=i.type==="snowflake"?r.data.unique_name:i.to.dimension,b=this.validateAndGetReferencedObject(_,o,r,"dimension",p);return b&&(l.add(_),!b.data.level_attributes.some(E=>E.unique_name===i.to.level)&&p.file(r).addError(ih.invalidDimensionRelationship(b.data.unique_name,b.relativePath,i.to.level))),p}}validateMismatchedRelationKeys(r,i,o,l){let p=Mo.create(),_=ki.isSnowflakeRelation(i)?r.data.unique_name:i.to.dimension,b=this.validateAndGetReferencedObject(_,o,r,"dimension",p);if(!b)return p;l.add(_);let{join_columns:T}=i.from,{level_attributes:E}=b.data,k=E.find(qL(i.to.level));if(!k)return p;let{key_columns:j}=k;if(T.length!==j.length){let z=ih.mismatchedRelationshipKeys(i.from.dataset,T.length,i.to.level,j.length);p.file(r).addError(z)}return p}};var qoe={getDuplicateMetricUniqueNames:(n,r)=>`Metric ${n.unique_name} is used ${r} times in composite model and its dependency models`,getDuplicateDimensionUniqueNames:(n,r)=>`Dimension ${n} is used ${r} times in composite model's dependency models`,getDuplicateQueryNameOverrides:(n,r)=>`Query name ${n} is used ${r} times in the overrides of composite model's dependency models`,commonRelationshipDimension:"Composite model's dependency models don't have a common dimension"};var XTe=class{constructor(r,i){this.yamlCommonReferenceValidator=r;this.yamlModelAggregateValidator=i}validateObject(r,i,o){let l=r.data,p=Mo.create();this.validateMetrics(r,l.metrics,i,o,p),this.validateModels(r,l,i,o,p);let _=Array.from(i.values()),b=XL(r,_);return this.yamlModelAggregateValidator.validateAggregates(p,b,i),p}validateMetrics(r,i,o,l,p){i?.forEach(_=>{this.yamlCommonReferenceValidator.validateAndGetReferencedObject(_.unique_name,o,r,"metric_calc",p)&&l.add(_.unique_name)})}validateModels(r,i,o,l,p){let _=i.metrics||[],b=[],T=[],E=[];i.models.forEach(j=>{let z=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(j,o,r,"model",p);if(!z)return;let X=z.data;_=_.concat(X.metrics),b=b.concat(X.dimensions||[]),T=T.concat(Object.values(X.overrides||[]).map(ue=>ue.query_name)),E.push(new Set(X.relationships.map(ue=>Ic.isRegularRelation(ue)?ue.to.dimension:"").filter(ue=>ue))),l.add(j)});let k=p.file(r);this.validateUniqueMetrics(k,_),this.validateUniqueDegenerateDimensions(k,b),this.validateUniqueQueryNameOverrides(k,T),this.validateCommonRelationshipDimension(k,E)}validateUniqueMetrics(r,i){let o=rl.groupBy(i,l=>[l.unique_name]);rl.appendErrorsIfDuplicates(o,r,qoe.getDuplicateMetricUniqueNames)}validateUniqueDegenerateDimensions(r,i){let o=rl.groupBy(i,l=>[l]);rl.appendErrorsIfDuplicates(o,r,qoe.getDuplicateDimensionUniqueNames)}validateCommonRelationshipDimension(r,i){if(i.length<2)return;rl.findCommonElement(i)||r.addError(qoe.commonRelationshipDimension)}validateUniqueQueryNameOverrides(r,i){let o=rl.groupBy(i,l=>[l]);rl.appendErrorsIfDuplicates(o,r,qoe.getDuplicateQueryNameOverrides)}};var ZTe=class{validateObject(r,i){let o=r.data,l=Mo.create();return i.forEach(p=>{let _=p.data;o.unique_name!==_.unique_name&&_.object_type==="connection"&&o.as_connection===_.as_connection&&o.database===_.database&&o.schema===_.schema&&l.file(r).addWarning(`Connection "${o.unique_name}" is duplicated with file ${p.relativePath}`)}),l}};var qVe=Ak.getAllValues(Pk),BVe=Ak.getAllValues(Y6),n4r=n=>{let r=qVe.find(i=>n.startsWith(i));if(r)return r},i4r=n=>qVe.some(r=>r===n),s4r=n=>{let r=BVe.find(i=>n.startsWith(i));if(r)return r},a4r=n=>BVe.some(r=>r===n),o4r=n=>{let r=BVe.find(l=>n.startsWith(l));if(!r)return!1;let i=n.replace(r,"");return/^\(\d*,\d*\)$/gm.test(i)},c4r={allDataTypes:qVe,getColumnTypeFromYaml:n4r,hasColumnExactMatch:i4r,isColumnPrecisionType:a4r,isValidPrecisionFormat:o4r,getColumnTypeWithPrecisionFromYaml:s4r},wx=c4r;var l4r=new RegExp(`^(${Object.values(Y6).join("|")})\\(\\d+,\\s*0\\)$`);function nkt(n){return l4r.test(n)}var ikt=["long","int","bigint"],u4r=["timestamp","datetime","date"],skt=[...ikt,...u4r],mC={parentColNotExist:n=>`Parent column "${n}" does not exist`,parentColIsTheSame:n=>`Parent column "${n}" should not be the same column`,parentColNoParent:n=>`Parent column "${n}" should not have parent property set`,invalidDataType:(n,r)=>`Column "${n}" has invalid data_type: "${r}". Supported data types are ${wx.allDataTypes.join(",")}`,invalidPrecisionDataType:(n,r,i)=>`Column "${n}" has invalid data_type: "${r}". Precision is not well formed. It should be "${i}(x,y)"`,datasetReferencesSameTable:(n,r)=>`There is another dataset referencing the same table/view. Unique name "${n}", filepath: "${r}"`,incrementColumnNotExist:n=>`Referenced column "${n}" in incremental does not exist`,incrementColumnInvalidColumnType:n=>`Referenced column "${n}" type is invalid. Supported column types: ${skt.join(", ")}`,invalidGracePeriod:"Invalid incremental grace_period.",invalidDurationGracePeriod:"Invalid incremental grace_period. The duration should contain a non-negative integer value, followed by time unit. Time unit can be 's' (second), 'm' (minute), 'h' (hour), 'd' (day) or 'w' (week). Example: '100s', '15d', '2w'.",invalidIntegerGracePeriod:"Invalid incremental grace_period. Grace period must be a non-negative integer for integer-like columns.",duplicateColumnName:(n,r)=>`Duplicate column name "${n}". ${r} duplicate items found`,missingDatabaseInConnectionIfQDSDataset:n=>`Connection file with name "${n}" must have specified "database", because dataset use table.`,missingSchemaInConnectionIfQDSDataset:n=>`Connection file with name "${n}" must have specified "schema", because dataset use table.`},eCe=class{constructor(r){this.yamlCommonReferenceValidator=r}validateObject(r,i,o){let l=Mo.create(),p=r.data,_=p.connection_id;this.validateConnectionAndAddReferenceObjectId(_,r,i,o,l,!Zl.hasDatasetSqlProp(p)),p.alternate!==void 0&&Zl.isAlternateTable(p.alternate)&&this.validateConnectionAndAddReferenceObjectId(p.alternate.connection_id,r,i,o,l,!!p.alternate.table),p.columns.filter(Zl.isDerivedColumn).forEach(k=>{if(k.name===k.parent_column)return l.file(r).addError(mC.parentColIsTheSame(k.name));let j=p.columns.find(z=>k.parent_column===z.name);j||l.file(r).addError(mC.parentColNotExist(k.parent_column)),j&&Zl.isDerivedColumn(j)&&l.file(r).addError(mC.parentColNoParent(j.name))}),p.columns.forEach(k=>{this.validateColumn(r,k,l)});let T=rl.groupBy(p.columns.map(k=>k.name),k=>[k]);return rl.appendErrorsIfDuplicates(T,l.file(r),mC.duplicateColumnName),Array.from(i.values()).filter(k=>{let j=k.data;return j.object_type==="dataset"&&j.table===p.table&&j.connection_id===p.connection_id&&j.unique_name!==p.unique_name&&!Zl.hasDatasetSqlProp(j)}).forEach(k=>l.file(r).addWarning(mC.datasetReferencesSameTable(k.data.unique_name,k.relativePath))),p.incremental&&this.validateIncremental(p.incremental,p.columns,l.file(r)),l}validateIncremental(r,i,o){let l=i.find(p=>p.name===r.column);l||o.addError(mC.incrementColumnNotExist(r.column)),l?.data_type&&!skt.includes(l?.data_type)&&!nkt(l?.data_type)&&o.addError(mC.incrementColumnInvalidColumnType(r.column)),this.validateGracePeriod(r.grace_period,l?.data_type,o)}validateGracePeriod(r,i,o){let l=i&&(ikt.includes(i)||nkt(i));(l?G6.isValidNonNegativeInteger(r):G6.isValidDuration(r))||o.addError(l?mC.invalidIntegerGracePeriod:mC.invalidDurationGracePeriod)}validateConnectionAndAddReferenceObjectId(r,i,o,l,p,_){let b=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(r,o,i,"connection",p);b&&(l.add(r),this.validateDatabaseAndSchemaInReferencedConnection(i,b.data,p,_))}validateDatabaseAndSchemaInReferencedConnection(r,i,o,l){if(!l)return;let p=r.data,_=i;_&&!_.database&&o.file(r).addError(mC.missingDatabaseInConnectionIfQDSDataset(p.connection_id)),_&&!_.schema&&o.file(r).addError(mC.missingSchemaInConnectionIfQDSDataset(p.connection_id))}validateColumn(r,i,o){if(Zl.hasColumnDataTypeProp(i)){if(!wx.getColumnTypeFromYaml(i.data_type)){o.file(r).addError(mC.invalidDataType(i.name,i.data_type));return}let p=wx.getColumnTypeWithPrecisionFromYaml(i.data_type);if(p!==void 0){if(!wx.hasColumnExactMatch(i.data_type)&&!wx.isValidPrecisionFormat(i.data_type)){o.file(r).addError(mC.invalidPrecisionDataType(i.name,i.data_type,p));return}}else wx.hasColumnExactMatch(i.data_type)||o.file(r).addError(mC.invalidDataType(i.name,i.data_type))}}};var Bb;(function(n){n.Int="int",n.Decimal="decimal",n.Long="long",n.Double="double",n.Float="float",n.String="string",n.DateTime="datetime",n.Date="date",n.Boolean="boolean",n.BigInt="bigint",n.TinyInt="tinyint",n.Number="number",n.TimeStamp="timestamp",n.Numeric="numeric"})(Bb||(Bb={}));var akt;(function(n){n.Numeric="numeric",n.Number="number",n.Decimal="decimal"})(akt||(akt={}));var Qh;(function(n){n.GeneralNumber="general number",n.Standard="standard",n.Scientific="scientific",n.Fixed="fixed",n.Percent="percent",n.GeneralDate="general date",n.LongDate="long date",n.MediumDate="medium date",n.ShortDate="short date",n.LongTime="long time",n.MediumTime="medium time",n.ShortTime="short time",n.YesNo="yes/no",n.TrueFalse="true/false",n.OnOff="on/off"})(Qh||(Qh={}));var tD=[Qh.GeneralNumber,Qh.Standard,Qh.Scientific],tCe=tD.concat([Qh.Fixed,Qh.Percent]),$Ve=[Qh.GeneralDate,Qh.LongDate,Qh.MediumDate,Qh.ShortDate,Qh.LongTime,Qh.MediumTime,Qh.ShortTime],f4r=[Qh.YesNo,Qh.TrueFalse,Qh.OnOff],f7={[Bb.Int]:tD,[Bb.Long]:tD,[Bb.Float]:tCe,[Bb.Double]:tCe,[Bb.Decimal]:tCe,[Bb.DateTime]:$Ve,[Bb.Date]:$Ve,[Bb.Boolean]:f4r,[Bb.String]:[],[Bb.BigInt]:tD,[Bb.TinyInt]:tD,[Bb.Number]:tD,[Bb.TimeStamp]:$Ve,[Bb.Numeric]:tCe},jO=n=>Array.from(new Set(Object.values(n).flat()));var rCe=n=>{let r=n.filter(Ic.isRegularRelation);return rl.groupBy(r,i=>[i.from.dataset,i.to.dimension,i.to.level,i.role_play])};var Ah={getDimensionDegenerateError:(n,r)=>`The dimension '${r}' should ${n?"be degenerative":"not be degenerative"}.`,getCalcMeasureContainsANonExistingMeasure:(n,r)=>`Calculated metric "${n}" expression contains a non-existing metric: ${r}.`,getDuplicateRelationshipsMessage:(n,r)=>Ic.isSecurityRelation(n)?`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}] to row_security: ${n.to.row_security}`:`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}] to dimension: ${n.to.dimension} and level: ${n.to.level}`,getMultiRelationshipsToLevelMessage:(n,r)=>Ic.isSecurityRelation(n)?`There are ${r} relationships from ${n.from.dataset} to ${n.to.row_security} - row security. Please specify unique role-playing templates in the relationships.`:Ic.isRegularRelation(n)?`There are ${r} relationships from ${n.from.dataset} to ${n.to.dimension} - Level ${n.to.level}. Please specify unique role-playing templates in the relationships.`:`There are ${r} relationships from ${n.from.dataset} to - Level ${n.to.level}. Please specify unique role-playing templates in the relationships.`,getDuplicateRelationshipsUniqueNameMessage:(n,r)=>`There are ${r} relationships with the same unique_name: ${n.unique_name}.`,getDuplicateMetricUniqueNames:(n,r)=>`Metrics must NOT have duplicate items (${n.unique_name} appears ${r} times)`,getDuplicateAggregatesUniqueNames:(n,r)=>`Aggregates must NOT have duplicate items (${n.unique_name} appears ${r} times)`,overridesInfo:"query_name overrides detected in model",getOverrideNotReferencedInModel:n=>`Override "${n}" is not referenced in the metrics or dimensions`,getOverridesDuplicateOnQueryNames:n=>`${n.map(r=>`${r.object_type} with unique_name "${r.unique_name}"`).join(", ")} have the same query_name "${n[0]?.query_name}"`,getDatasetForPropertiesNotExist:n=>`Dataset for dataset_properties ${n} not exist.`,getDatasetPropertiesIncorrectType:n=>`Dataset properties reference ${n} is not dataset`,getDrillThroughAttributeNotFoundInModel:(n,r)=>`Drillthrough "${n}" references dimension "${r}" that does not exist in the model.`,getDrillThroughMetricNotFoundInModel:(n,r)=>`Drillthrough "${n}" references metric "${r}" that does not exist in the model.`,getPerspectiveMetricNotFoundInModel:(n,r)=>`Perspective "${n}" references metric "${r}" that does not exist in the model.`,getPerspectiveDimensionNotFoundInModel:(n,r)=>`Perspective "${n}" references dimension "${r}" that does not exist in the model.`,getPerspectiveHierarchyLevelNotFound:(n,r,i,o)=>`Perspective "${n}" references hierarchy "${r}" with level "${i}" that does not exist in dimension "${o}".`,getPerspectiveHierarchyNotFound:(n,r,i)=>`Perspective "${n}" references hierarchy "${r}" that does not exist in dimension ${i}.`,getPerspectiveSecondaryAttributeNotFound:(n,r,i)=>`Perspective "${n}" references secondary attribute "${r}" that does not exist in dimension "${i}".`,getMaximumDepthOfNestedDimensionExceeded:n=>`A dimension referenced in perspectives or drill-through cannot have more than the maximum allowed depth of nested dimensions. Max depth allowed: ${n}`,getM2MPropDetectedInRelation:n=>`Property "m2m" detected in a relationship with unique_name: "${n}". It is allowed only in embedded dimensional relationships.`},nCe={getDrillTroughExistingWarning:"Warning: drillthroughs are not yet supported and will be skipped.",getTargetConnectionWarning:(n,r)=>`target_connection is obsolete. Please remove it. Aggregate at index ${r}, agg name: ${n}`,levelsPropDetectedInPerspective:(n,r,i)=>`An obsolete property "levels" detected in perspectives[unique_name=${n}] -> dimensions[name=${r}] -> hierarchies[name${i}]`};var d4r=n=>Pa.hasProps(n,"column"),okt=n=>d4r(n)?n.column:n.name_column,_4r=n=>{let r="";return n.forEach((i,o)=>{let l=i.map(p=>p.name).join(", ");r+=`Column: "${l}" with data type: ${o}. `}),r},ckt=n=>n?`Hierarchy "${n.hierarchyName}" with Level "${n.levelName}" with ${n.attributeType}`:"Level",rp={notExistingCol:(n,r)=>`Non-existing column "${n}" in dataset "${r}"`,notApplicableFormatForColType:n=>`Inapplicable formatting for column data_type. ${ckt(n.hierarchy)} "${n.attribute.unique_name}" should not have format property set for column type "${n.colType}" with name "${okt(n.attribute)}"`,formatNotCompatibleWithColType:(n,r)=>`Incompatible formatting for related column data_type. ${ckt(n.hierarchy)} "${n.attribute.unique_name}" with format "${n.attribute.format}" is incompatible with "${n.colType}" for column "${okt(n.attribute)}". Possible formats: ${r[n.colType].join(", ")}`,duplicateSnowflakeRelationshipsMessage:(n,r)=>`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}] to level: ${n.to.level}`,duplicateEmbeddedRelationshipsMessage:(n,r)=>`There are ${r} relationships with the same definition. From dataset: ${n.from.dataset} with join columns: [${n.from.join_columns.join(",")}], hierarchy: ${n.from.hierarchy} and level: ${n.from.level} to dimension: ${n.to.dimension} and level: ${n.to.level}`,formatNotCompatibleWithMetric:(n,r)=>`Incompatible format(${r}) for metric "${n}". Possible formats: ${tD.join(", ")}`,missingRelationshipHierarchy:n=>`Non-existing hierarchy named "${n}"`,invalidCalcMemberExpression:n=>`Invalid calculated member expression: ${n}`,duplicateCalcMemberNameInCalcGroup:n=>`There are calculated members with duplicated names in "${n}" calculation group`,timeUnitPropDetectedInLevel:(n,r)=>`Property "time_unit" detected in hierarchy: "${n}" with level: "${r}"`,customEmptyMemberSortNameMissing:(n,r)=>`Custom empty member should have sort_name property when sort_column is set. Affected ${r}: "${n}"`,timeUnitMissingInTimeDimension:n=>`Level "${n}" is part of a time dimension but property "time_unit" is missing`,sharedDegenerateLevelColumnsError:(n,r,i)=>`${n} for a level in a shared degenerate dimension should have the same data type. Affected level: ${r}. ${i}`,invalidLevelAttributeReference:(n,r)=>`hierarchy[${n.unique_name!==void 0?`unique_name="${n.unique_name}"`:n.label!=null?`label="${n.label}"`:`index=${n.index}`}], level "${r}" has no corresponding level_attribute definition`,inconsistentDuplicatedLevel:(n,r)=>`Level "${n}" is duplicated in the following hierarchies: ${r.map(i=>`"${i}"`).join(", ")}, but the levels below it differ. All levels below "${n}" must match across these hierarchies.`,invalidTimeUnitLevelOrder:n=>`hierarchy[${n.hierarchyName}], level "${n.levelName}" Time Units must be greater than or equal to the level below it (i.e. Hour -> Minute) in a time hierarchy`,duplicateDegenerateDimensionLevelAttributesMessage:(n,r,i)=>`Dataset "${n}" and key columns "${r.join(", ")}" combination is duplicated in level attributes: ${i.join(", ")}`,duplicateDegenerateDimensionLevelsMultipleDatasetsMessage:(n,r)=>`There are duplicated level attributes (${r.join(", ")}) using the same datasets (${n.join(", ")}) and the same key columns.`,sharedLevelAttributesNotPointingToSameDatasets:(n,r,i)=>`Level attributes should point to the same datasets. Dataset "${n}" is being used in ${r} out of ${i} level attributes.`,degenerateDimensionLevelAttributesTypeError:(n,r)=>`Level attributes in a degenerate dimension must be of the same type. The dimension has single dataset attributes: ${nh(n)} and multiple datasets attributes: ${nh(r)}`,secondaryAttributeInMultipleDatasetLAError:(n,r)=>`Secondary attributes are not allowed for level attributes with multiple datasets in degenerate dimensions. Affected level "${n}". Remove: "${r}"`,numberOfSortColumnsInMultipleDatasetsDegenerateError:n=>`Level "${n}" only has a sort column for some of its datasets. Either all datasets should have a sort column, or none should have one.`,multipleDatasetsInNormalDimensionNotAllowed:n=>`Only levels in a degenerate dimension can have multiple datasets. Property "shared_degenerate_columns" is not allowed for level "${n}".`,referredLevelNameIsEqualToParenLevelError:(n,r)=>`The referred level name "${n}" is equal to parent level name "${r}".`,referredLevelNameIsNotInTheSameHierarchyError:n=>`The referred level name "${n}" in parallel period is not in the same hierarchy.`,parallelPeriodShouldBeUseOnlyInTimeDimensionError:()=>"Parallel period should be use only in time dimension.",parallelPeriodKeyColumnIsNotExistInRelatedLevelDatasets:(n,r)=>`The parallel period key_column "${n}" does not exist in dataset "${r}"`,getM2MPropDetectedInRelation:n=>`Property "m2m" detected in a ${n} relationship. It is allowed only in embedded relationships.`,invalidReference:(n,r)=>`Invalid reference ${n.join(" -> ")}. ${r}`,scdOnlySimpleColumnsAreAllowed:(n,r)=>`Column "${r}" is not simple column. ${n.join(" -> ")}.`,scdInvalidDataType:(n,r,i)=>rp.invalidReference(n,`Column "${r.name}" has invalid data_type "${r.data_type}". Allowed types are: ${i.join(", ")}`),scdInvalidTemplateMissingPlaceholder:(n,r)=>`Invalid template. Missing "{0}" place holder. ${n.join(" -> ")}. Template: "${r}"`,scdInvalidTemplateMultiplePlaceholders:(n,r)=>`Invalid template. More than one place holders "{0}". ${n.join(" -> ")}. Template: "${r}"`,scdDuplicateColumns:(n,r)=>`Duplicate columns usage for ${r.join(", ")}. You cannot use same column. ${n.join(" -> ")}.`,scdGetMultipleLevelsWithScdOnOneHierarchy:(n,r,i)=>`Error in hierarchy "${n}" -> level "${r}". Multiple levels with slowly changing dimensions settings in one hierarchy is not supported. Other levels with SCD: ${i.join(", ")}`,scdColumnsDataTypesDoNotMatch:n=>`All slowly changing dimensions columns should have same data_type. Current: ${n.map(r=>`${r.column}:${r.data_type}`).join(", ")}`,rowSecurityScopeFactOnlyError:(n,r,i)=>`Security Dimension ${n}_attribute_${r} has scope \u201C${i}\u201D but is not connected to a fact dataset.`},iCe=class{constructor(r,i,o,l=f7){this.yamlCommonReferenceValidator=r,this.expressionValidator=i,this.formatMap=l,this.yamlErrorContextUtil=o}validateObject(r,i,o){let l=r.data,p=Mo.create(),_=[];return this.verifyDegenerateDimsLevelTypes(l,p.file(r)),l.level_attributes.forEach(b=>{this.validateCustomEmptyMember(b,p,r,"level"),this.validateTimeUnitProperty(b,l,p,r),this.verifyNormalDimensionsHaveASingleDataset(b,l,p.file(r)),this.verifyDimensionDatasetsAndColumns({levelAttribute:b,item:r,validatorOutput:p,elementsMap:i,referencedObjectIds:o}),this.verifyLevelAttributesForDegenerateDim(b,l,p.file(r)),ki.isLevelFromOneDataset(b)&&b.scd_properties&&(_.push(b.unique_name),this.validateSlowlyChangingDimensionProperties(r,b,i,p))}),p.append(this.yamlCommonReferenceValidator.validateRelationships(r,i,o)),l.relationships&&(this.validateUniqueRelationships(p.file(r),l.relationships.filter(ki.isEmbeddedRelation),rp.duplicateEmbeddedRelationshipsMessage),this.validateUniqueRelationships(p.file(r),l.relationships.filter(ki.isSnowflakeRelation),rp.duplicateSnowflakeRelationshipsMessage),this.validateRelationshipHierarchy(p.file(r),l.relationships.filter(ki.isEmbeddedRelation),l.hierarchies.map(b=>b.unique_name)),this.validateRelationshipM2MProp(p.file(r),l.relationships),this.validateSecurityRelationshipsWithRowSecurityScope(p.file(r),i,l.relationships.filter(ki.isSecurityRelation))),l.calculation_groups?.forEach(b=>{this.validateUniqueCalcMemberNameInCalcGroup(p.file(r),b.calculated_members.map(T=>T.unique_name),b.unique_name),b.calculated_members.forEach(T=>{let E=T.expression;E&&!this.expressionValidator.areParenthesesValid(E)&&p.file(r).addError(rp.invalidCalcMemberExpression(E))})}),l.hierarchies.forEach((b,T)=>{this.validateSlowlyChangingDimensionHierarchy(r,b,_,p),b.levels.forEach((E,k)=>{let j={hierarchyName:b.unique_name||b.label,levelName:E.unique_name};E.parallel_periods&&(this.validateParallelPeriodIsOnlyInTimeDimension(l,b.levels,p.file(r)),this.validateReferredLevelParallelPeriod(b,E,p.file(r)),this.validateParallelPeriodKeyColumnsExistsInTheRelatedLevelDatasets(l,E.parallel_periods,i,o,r,p));let z=l.level_attributes.find(X=>X.unique_name===E.unique_name);if(!z){let X=new qk().getLevelContext({hierarchyUniqueName:j.hierarchyName,validationType:"not_existing_level_reference",itemUniqueName:E.unique_name,message:"no corresponding level_attribute definition"});p.file(r).addErrorWithContext(rp.invalidLevelAttributeReference({...b,index:T},E.unique_name),X)}if(this.timeUnitLevelHasOrderError(l.level_attributes,z,b.levels[k-1])){let X=this.yamlErrorContextUtil.getLevelContext({hierarchyUniqueName:j.hierarchyName,validationType:"invalid_time_unit_order",itemUniqueName:j.levelName,message:"invalid time_unit level order"});p.file(r).addErrorWithContext(rp.invalidTimeUnitLevelOrder(j),X)}E.secondary_attributes?.forEach(X=>{this.validateDegenerateDimensionSecondaryAttribute(X,E,l,p.file(r)),this.validateCustomEmptyMember(X,p,r,"secondary-attribute");let ue=this.getYamlDataset(X.dataset,i,o,r,p),De={...j,attributeType:"secondary_attribute"};this.validateDatasetColumns(ue,X,r,p,De)}),E.aliases?.forEach(X=>{let ue=this.getYamlDataset(X.dataset,i,o,r,p),De={...j,attributeType:"level_alias"};this.validateDatasetColumns(ue,X,r,p,De)}),E.metrics?.forEach(X=>{let ue=this.getYamlDataset(X.dataset,i,o,r,p);if(!ue)return;let De=this.getDatasetColumn(ue,X.column,r,p);De&&Zl.hasColumnDataTypeProp(De)&&this.validateMetricFormatProperty(X,p.file(r))}),"time_unit"in E&&p.file(r).addError(rp.timeUnitPropDetectedInLevel(b.unique_name,E.unique_name))})}),this.validateInconsistentDuplicatedLevel(l.hierarchies,p.file(r)),this.validateUniqueMultipleRelationshipsToLevel(p.file(r),l),p}validateInconsistentDuplicatedLevel(r,i){let o=r.flatMap(({levels:p,unique_name:_})=>p.map(({unique_name:b},T)=>({levelName:b,hierarchyName:_,levelSubTree:p.slice(T).map(({unique_name:E})=>E)}))),l=rl.groupBy(o,({levelName:p})=>[p]);Array.from(l.values()).reverse().some(p=>{let _=p.map(({levelSubTree:E})=>E);if(fwt(_))return!1;let[{levelName:b}]=p,T=p.map(({hierarchyName:E})=>E);return i.addError(rp.inconsistentDuplicatedLevel(b,T)),!0})}validateUniqueMultipleRelationshipsToLevel(r,i){if(i.relationships){let o=rCe(i.relationships);rl.appendErrorsIfDuplicates(o,r,Ah.getMultiRelationshipsToLevelMessage)}}getParallelLevelDatasets(r,i,o,l,p,_){let b=new Set;return r.level_attributes.forEach(T=>{T.unique_name===i&&(ki.isLevelWithMultipleDatasets(T)?T.shared_degenerate_columns.forEach(E=>b.add(E.dataset)):b.add(T.dataset))}),Array.from(b).map(T=>this.getYamlDataset(T,o,l,p,_)).filter(T=>T!==void 0)}validateParallelPeriodKeyColumnsExistsInTheRelatedLevelDatasets(r,i,o,l,p,_){i.forEach(b=>{let T=this.getParallelLevelDatasets(r,b.level,o,l,p,_);b.key_columns.forEach(E=>{T.forEach(k=>{k.columns.some(j=>j.name===E)||_.file(p).addError(rp.parallelPeriodKeyColumnIsNotExistInRelatedLevelDatasets(E,k.unique_name))})})})}validateReferredLevelParallelPeriod(r,i,o){let l=us.ensure(i.parallel_periods,"Do not have parallel periods in level"),p=l.filter(b=>b.level===i.unique_name);p.length>0&&p.forEach(b=>{o.addError(rp.referredLevelNameIsEqualToParenLevelError(i.unique_name,b.level))});let _=l.filter(b=>!r.levels.some(T=>b.level===T.unique_name));_.length>0&&_.forEach(b=>{o.addError(rp.referredLevelNameIsNotInTheSameHierarchyError(b.level))})}validateParallelPeriodIsOnlyInTimeDimension(r,i,o){r.type!=="time"&&i.some(p=>p.parallel_periods!==void 0)&&o.addError(rp.parallelPeriodShouldBeUseOnlyInTimeDimensionError())}validateDegenerateDimensionSecondaryAttribute(r,i,o,l){let p=o.level_attributes.find(_=>_.unique_name===i.unique_name);p&&ki.isLevelWithMultipleDatasets(p)&&l.addError(rp.secondaryAttributeInMultipleDatasetLAError(i.unique_name,r.unique_name))}verifyDegenerateDimsLevelTypes(r,i){if(!r.is_degenerate)return;let o=r.level_attributes.filter(p=>ki.isLevelWithMultipleDatasets(p)),l=r.level_attributes.filter(p=>ki.isLevelFromOneDataset(p));if(o.length===r.level_attributes.length)this.verifySharedDegenerateDimsDatasetsUsage(r,i);else{if(l.length===r.level_attributes.length)return;i.addError(rp.degenerateDimensionLevelAttributesTypeError(l.map(p=>p.unique_name),o.map(p=>p.unique_name)))}}verifySharedDegenerateDimsDatasetsUsage(r,i){if(!r.is_degenerate)return;let o=r.level_attributes.length;this.groupSharedLevelAttributesByDataset(r).forEach((p,_)=>{p.length!==o&&i.addWarning(rp.sharedLevelAttributesNotPointingToSameDatasets(_,p.length,o))})}groupSharedLevelAttributesByDataset(r){let i=new Map;return r.is_degenerate&&r.level_attributes.forEach(o=>{ki.isLevelWithMultipleDatasets(o)&&o.shared_degenerate_columns.forEach(l=>{i.has(l.dataset)||i.set(l.dataset,[]);let p=i.get(l.dataset);p&&p.push(o.unique_name)})}),i}verifyNormalDimensionsHaveASingleDataset(r,i,o){!i.is_degenerate&&ki.isLevelWithMultipleDatasets(r)&&o.addError(rp.multipleDatasetsInNormalDimensionNotAllowed(r.unique_name))}verifyDimensionDatasetsAndColumns(r){let{levelAttribute:i,item:o,validatorOutput:l,elementsMap:p,referencedObjectIds:_}=r;if(ki.isLevelWithMultipleDatasets(i))this.verifyMultipleDatasetsColumns(r),i.shared_degenerate_columns.forEach(b=>{let T=this.getYamlDataset(b.dataset,p,_,o,l),E={dataset:b.dataset,name_column:b.name_column,key_columns:b.key_columns,sort_column:b.sort_column,is_unique_key:b.is_unique_key,unique_name:i.unique_name,label:i.label};this.validateDatasetColumns(T,E,o,l)});else{let b=this.getYamlDataset(i.dataset,p,_,o,l);this.validateDatasetColumns(b,i,o,l)}}getLevelAttributeColumnsByType(r){let{levelAttribute:i,item:o,validatorOutput:l,elementsMap:p,referencedObjectIds:_}=r,b=[],T=[],E=[];return ki.isLevelWithMultipleDatasets(i)&&i.shared_degenerate_columns.forEach(k=>{let j=this.getYamlDataset(k.dataset,p,_,o,l);if(!j)return;let z=this.getSharedDegenerateDimensionColumn(j,k.key_columns[0],r),X=this.getSharedDegenerateDimensionColumn(j,k.name_column,r),ue=k.sort_column?this.getSharedDegenerateDimensionColumn(j,k.sort_column,r):void 0;!z||!X||(b.push(z),T.push(X),ue&&E.push(ue))}),{groupedKeyColumns:b,groupedValueColumns:T,groupedSortColumns:E}}verifyMultipleDatasetsColumns(r){let{levelAttribute:i}=r;if(ki.isLevelWithMultipleDatasets(i)){let{groupedKeyColumns:o,groupedValueColumns:l,groupedSortColumns:p}=this.getLevelAttributeColumnsByType(r);this.validateSharedDegenerateDimensionColumn(o,"Key columns",r),this.validateSharedDegenerateDimensionColumn(l,"Value columns",r),this.validateSharedDegenerateDimensionColumn(p,"Sort columns",r),this.validateNumberOfSortColumnsColumn(o,p,i,r.item,r.validatorOutput)}}validateNumberOfSortColumnsColumn(r,i,o,l,p){i.length!==0&&i.length!==r.length&&p.file(l).addError(rp.numberOfSortColumnsInMultipleDatasetsDegenerateError(o.unique_name))}validateSharedDegenerateDimensionColumn(r,i,o){let{levelAttribute:l,item:p,validatorOutput:_}=o,b=rl.groupBy(r,T=>[T.data_type]);b.size>1&&_.file(p).addError(rp.sharedDegenerateLevelColumnsError(i,l.unique_name,_4r(b)))}getSharedDegenerateDimensionColumn(r,i,o){let{item:l,validatorOutput:p}=o,_=this.getDatasetColumn(r,i,l,p);if(_&&Zl.hasColumnDataTypeProp(_))return _}verifyLevelAttributesForDegenerateDim(r,i,o){if(!i.is_degenerate)return;let l=this.getLevelDataSources(r),p=i.level_attributes.filter(_=>this.areTwoLevelDataSourcesEqual(l,this.getLevelDataSources(_)));if(!(p.length<=1))if(l.size===1){let[[_,b]]=Array.from(l.entries());o.addError(rp.duplicateDegenerateDimensionLevelAttributesMessage(_,b,p.map(T=>T.unique_name)))}else{let _=Array.from(l.keys());o.addError(rp.duplicateDegenerateDimensionLevelsMultipleDatasetsMessage(_,p.map(b=>b.unique_name)))}}getLevelDataSources(r){let i=new Map;return ki.isLevelFromOneDataset(r)&&i.set(r.dataset,r.key_columns),ki.isLevelWithMultipleDatasets(r)&&r.shared_degenerate_columns.forEach(o=>{i.set(o.dataset,o.key_columns)}),i}areTwoLevelDataSourcesEqual(r,i){return r.size!==i.size?!1:Array.from(r.entries()).every(([o,l])=>{let p=i.get(o);if(!p||l.length!==p.length)return!1;let _=[...l].sort(),b=[...p].sort();return _.every((T,E)=>T===b[E])})}validateDatasetColumns(r,i,o,l,p){if(!r)return;i.key_columns?.forEach(b=>{this.getDatasetColumn(r,b,o,l)}),i.sort_column&&this.getDatasetColumn(r,i.sort_column,o,l);let _=this.getDatasetColumn(r,i.name_column,o,l);_&&Zl.hasColumnDataTypeProp(_)&&this.validateFormatProperty(i,_.data_type,o,l,p)}validateTimeUnitProperty(r,i,o,l){i.type==="time"&&!r.time_unit&&o.file(l).addErrorWithContext(rp.timeUnitMissingInTimeDimension(r.unique_name),this.yamlErrorContextUtil.getLevelAttributeContext({itemUniqueName:r.unique_name,message:"time_unit missing",validationType:"time_unit"}))}validateCustomEmptyMember(r,i,o,l){if(r.custom_empty_member&&ki.isLevelFromOneDataset(r)&&r.sort_column&&!r.custom_empty_member.sort_name){let p=l==="level"?this.yamlErrorContextUtil.getLevelAttributeContext:this.yamlErrorContextUtil.getSecondaryAttributeContext;i.file(o).addErrorWithContext(rp.customEmptyMemberSortNameMissing(r.unique_name,l),p({itemUniqueName:r.unique_name,message:"custom_empty_member missing sort key",validationType:"custom_empty_member"}))}}validateMetricFormatProperty(r,i){if(!r.format)return;let o=jO(this.formatMap).find(l=>l===r.format);o&&!tD.includes(o)&&i.addError(rp.formatNotCompatibleWithMetric(r.unique_name,r.format))}validateFormatProperty(r,i,o,l,p){if(!r.format)return;let _=wx.getColumnTypeFromYaml(i);if(!_)return;let b={attribute:r,colType:_,hierarchy:p};if(!this.formatMap[_].length){l.file(o).addError(rp.notApplicableFormatForColType(b));return}let T=jO(this.formatMap).find(E=>E===r.format);T&&!this.formatMap[_].includes(T)&&l.file(o).addError(rp.formatNotCompatibleWithColType(b,this.formatMap))}getYamlDataset(r,i,o,l,p){let _=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(r,i,l,"dataset",p);if(_)return o.add(r),_.data}getDatasetColumn(r,i,o,l,p){let _=r.columns.find(b=>b.name===i);if(!_){let b=rp.notExistingCol(i,r.unique_name),T=p?.contextItems?rp.invalidReference(p?.contextItems,b):b;p?.validationContext?l.file(o).addErrorWithContext(T,{...p.validationContext,message:T}):l.file(o).addError(T)}return _}validateUniqueRelationships(r,i,o){let l=rl.groupBy(i,p=>{let _=Object.values(p.from).concat(Object.values(p.to));return ki.isEmbeddedRelation(p)?_.concat(p.role_play?[p.role_play]:[]):_});rl.appendErrorsIfDuplicates(l,r,o)}validateRelationshipM2MProp(r,i){i.forEach(o=>{let l=ki.isSnowflakeRelation(o),p=l||ki.isSecurityRelation(o);if(Object.prototype.hasOwnProperty.call(o,"m2m")&&p){let _=l?"snowflake":"security";r.addError(rp.getM2MPropDetectedInRelation(_))}})}validateRelationshipHierarchy(r,i,o){i.forEach(l=>{o.includes(l.from.hierarchy)||r.addError(rp.missingRelationshipHierarchy(l.from.hierarchy))})}validateSecurityRelationshipsWithRowSecurityScope(r,i,o){o.forEach(l=>{if(ki.isEmbeddedRelation(l)&&ki.isSecurityRelation(l)){let p=i.get(l.to.row_security);if(!p)return;let{data:_}=p;_.scope==="fact_only"&&r.addError(rp.rowSecurityScopeFactOnlyError(l.to.row_security,_.filter_key_column,"fact_only"))}})}validateUniqueCalcMemberNameInCalcGroup(r,i,o){rl.checkIfDuplicateNameExists(i)&&r.addError(rp.duplicateCalcMemberNameInCalcGroup(o))}timeUnitLevelHasOrderError(r,i,o){if(!o||!i?.time_unit)return!1;let l=Object.values(iQ),p=l.indexOf(i.time_unit),_=r.find(T=>T.unique_name===o.unique_name),b=-1;return _?.time_unit&&(b=l.indexOf(_?.time_unit)),p<b&&_?.time_unit!=="undefined"}validateSlowlyChangingDimensionHierarchy(r,i,o,l){if(o.length<=1)return;let p=i.levels.filter(_=>o.includes(_.unique_name)).map(_=>_.unique_name);p.length>1&&p.forEach((_,b)=>{let T=p.filter((j,z)=>z!==b),E=rp.scdGetMultipleLevelsWithScdOnOneHierarchy(i.unique_name,_,T),k=qk.create().getLevelContext({validationType:"custom",hierarchyUniqueName:i.unique_name,itemUniqueName:_,message:E});l.file(r).addErrorWithContext(E,k)})}validateSlowlyChangingDimensionProperties(r,i,o,l){if(!i.scd_properties)return;let p=o.get(i.dataset);if(!p)return;let{data:_}=p;if(!_l.isDataset(_))return;let b=[`level_attributes[unique_name=${i.unique_name}]`,"scd_properties"],T=qk.create().getLevelAttributeContext({itemUniqueName:i.unique_name,validationType:"custom",message:"To be set later"}),E=[],k=this.getScdColumnType(r,{contextItems:[...b,"effective_start"],validationContext:T},i.scd_properties.effective_start,_,l);this.scdValidateTemplate(r,{contextItems:[...b,"effective_start"],validationContext:T},i.scd_properties.effective_start,l),E.push({scdKey:"effective_start",column:i.scd_properties.effective_start.column,data_type:k});let j=this.getScdColumnType(r,{contextItems:[...b,"effective_end"],validationContext:T},i.scd_properties.effective_end,_,l);if(this.scdValidateTemplate(r,{contextItems:[...b,"effective_end"],validationContext:T},i.scd_properties.effective_end,l),E.push({scdKey:"effective_end",column:i.scd_properties.effective_end.column,data_type:j}),i.scd_properties.created){let X=this.getScdColumnType(r,{contextItems:[...b,"created"],validationContext:T},i.scd_properties.created,_,l);this.scdValidateTemplate(r,{contextItems:[...b,"created"],validationContext:T},i.scd_properties.created,l),E.push({scdKey:"created",column:i.scd_properties.created.column,data_type:X})}this.scdValidateTemplate(r,{contextItems:[...b,"as_of_date"],validationContext:T},i.scd_properties.as_of_date,l),this.scdValidateTemplate(r,{contextItems:[...b,"is_latest"],validationContext:T},i.scd_properties.is_latest,l);let z=rl.groupBy(E,X=>[X.column]);if(Array.from(z.entries()).filter(([,X])=>X.length>1).forEach(([,X])=>{let ue=X.map(Je=>Je.scdKey),De=rp.scdDuplicateColumns(b,ue);l.file(r).addErrorWithContext(De,{...T,message:De})}),E.every(X=>X.data_type!==void 0)){let X=new Set;if(E.forEach(ue=>{X.add(ue.data_type)}),X.size>1){let ue=rp.scdColumnsDataTypesDoNotMatch(E);l.file(r).addErrorWithContext(ue,{...T,message:ue})}}}getScdColumnType(r,i,o,l,p){let _=[...i.contextItems,"column"],b=this.getDatasetColumn(l,o.column,r,p,{contextItems:_,validationContext:i.validationContext});if(b){if(!Zl.isSimpleColumn(b)){let T=rp.scdOnlySimpleColumnsAreAllowed(_,b.name);p.file(r).addErrorWithContext(T,{...i.validationContext,message:T});return}if(!$Q.includes(b.data_type)){let T=rp.scdInvalidDataType(_,b,$Q);p.file(r).addErrorWithContext(T,{...i.validationContext,message:T})}return b.data_type}}scdValidateTemplate(r,i,o,l){let p,_=[...i.contextItems,"display_name_template"],b=o.display_name_template.indexOf("{0}");b<0?p=rp.scdInvalidTemplateMissingPlaceholder(_,o.display_name_template):o.display_name_template.lastIndexOf("{0}")!==b&&(p=rp.scdInvalidTemplateMultiplePlaceholders(_,o.display_name_template)),p&&l.file(r).addErrorWithContext(p,{...i.validationContext,message:p})}};var m4r={formatNotCompatibleWithMeasureFormats:(n,r)=>`Invalid format value "${n}" you probably mean "${r}"!`},n$=class{static validate(r,i,o){let p=Ak.getAllValues(sQ,"string").find(_=>DQ(_,r));p&&p!==r&&o.file(i).addError(m4r.formatNotCompatibleWithMeasureFormats(r,p))}};var sCe=class{constructor(r){this.expressionValidator=r}validateObject(r){let i=r.data,o=Mo.create();return i.expression&&!this.expressionValidator.areParenthesesValid(i.expression)&&o.file(r).addError(`Invalid metric expression: ${i.expression}`),i.format&&n$.validate(i.format,r,o),o}};var i$="semi_additive ",gA={notExistingCol:(n,r)=>`Missing dataset column. Column "${n}" does not exist in "${r}" dataset`,notApplicableFormatForColType:(n,r)=>`Inapplicable formatting for column data_type. Measure "${n.unique_name}" should not have format property set for column type "${r}" with name "${n.column}"`,formatNotCompatibleWithColType:(n,r,i)=>`Incompatible formatting for related column data_type. Measure "${n.unique_name}" with format "${n.format}" is incompatible with "${r}" for column "${n.column}". ${i[r].length>0?"Possible formats: "+i[r].join(", "):""}`,calcMethodNotCompatibleWithColumnType:(n,r)=>`Measure "${n.unique_name}" with calculated_method "${n.calculation_method}", requires different column data_type than "${r}"`,semiAdditiveHasNoRelationshipsOrDegenerateDimensions:()=>`${i$} There should be at least one relationships or degenerate dimension in semi additive.`,semiAdditiveHasEmptyRelationship:()=>`${i$} Relationship in semi additive cannot be empty.`,semiAdditiveHasUnknownRelationship:(n,r)=>`${i$} Relationship "${n}" does not exist in any of the models containing the metric "${r}"`,semiAdditiveDegenerateDimensionHasUnknownLevel:(n,r)=>`${i$} Degenerate dimension ${n} references unknown level ${r}.`,modelHasNoValidAttributes:n=>`${i$} Model ${n} has no valid attributes for this measure.`,modelHasInvalidNestedRelationship:(n,r)=>`${i$} Relationship ${r.join(", ")} is invalid in model ${n}.`,semiAdditiveNestedRelationshipLengthExceeded:()=>`${i$} Semi-additive attributes are not supported in dimensions nested beyond two levels. You can reference semi-additive attributes in a dimension nested within another dimension (e.g., model -> dim 1 -> dim 2), but not in deeper levels (e.g., model -> dim 1 -> dim 2 -> dim 3)."`,validateSemiAdditiveAggregationType:(n,r)=>`Semi-additive metrics can only use Sum, Min or Max Aggregation types. Metric "${n}" has "${r}" Aggregation type.`},h4r=2,aCe=class{constructor(r,i=f7){this.yamlCommonReferenceValidator=r,this.formatMap=i}validateObject(r,i,o){let l=r.data,p=Mo.create();if(l.dataset){let _=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(l.dataset,i,r,"dataset",p);if(!_)return p;o.add(l.dataset);let T=_.data.columns.find(E=>E.name===l.column);if(!T)return p.file(r).addError(gA.notExistingCol(l.column,_.data.unique_name)),p;if(Zl.hasColumnDataTypeProp(T)){let E=wx.getColumnTypeFromYaml(T.data_type);if(!E)return p;let k=jO(this.formatMap).find(j=>j===l.format);k&&!tD.includes(k)&&!this.formatMap[E].find(j=>j===l.format)&&p.file(r).addError(gA.formatNotCompatibleWithColType(l,E,this.formatMap)),this.validateCalcMethod(p,r,E)}l.semi_additive&&(this.validateSemiAdditiveRelationships(p,r,i),this.validateSemiAdditiveByCalculationMethod(p,r))}return l.format&&n$.validate(l.format,r,p),p}validateSemiAdditiveRelationships(r,i,o){let l=i.data;if(l.semi_additive?.relationships===void 0&&l.semi_additive?.degenerate_dimensions===void 0){r.file(i).addError(gA.semiAdditiveHasNoRelationshipsOrDegenerateDimensions());return}if(l.semi_additive?.degenerate_dimensions===void 0&&l.semi_additive?.relationships?.length===0)return r.file(i).addError(gA.semiAdditiveHasEmptyRelationship());let p=[],_=[];o.forEach(b=>{if(b.data.object_type==="model"){let T=b.data;!!T.metrics.find(k=>k.unique_name===l.unique_name)&&p.push({unique_name:T.unique_name,degenerateDimensions:T.dimensions??[],relationships:T.relationships})}else if(b.data.object_type==="dimension"){let T=b.data;_.push(T)}}),l.semi_additive.relationships?.forEach(b=>{Array.isArray(b)?(b.length>h4r&&r.file(i).addError(gA.semiAdditiveNestedRelationshipLengthExceeded()),b.forEach(T=>{p.some(k=>k.relationships.map(j=>j.unique_name).includes(T))||_.some(k=>k.relationships?.find(j=>ki.isEmbeddedRelation(j)&&j.unique_name===T))||r.file(i).addWarning(gA.semiAdditiveHasUnknownRelationship(T,l.unique_name))}),p.forEach(T=>{b.every(k=>{let j=T.relationships.map(X=>X.unique_name).includes(k),z=_.some(X=>X.relationships?.find(ue=>ki.isEmbeddedRelation(ue)&&ue.unique_name===k));return j||z})||r.file(i).addWarning(gA.modelHasInvalidNestedRelationship(T.unique_name,b))})):p.some(E=>E.relationships.map(k=>k.unique_name).includes(b))||_.some(E=>E.relationships?.find(k=>ki.isEmbeddedRelation(k)&&k.unique_name===b))||r.file(i).addWarning(gA.semiAdditiveHasUnknownRelationship(b,l.unique_name))}),l.semi_additive.degenerate_dimensions&&l.semi_additive.degenerate_dimensions.forEach(b=>{if(p.every(E=>{let k=_.find(j=>j.is_degenerate&&j.unique_name===b.name&&E.degenerateDimensions.includes(b.name));return k?!k.level_attributes.find(j=>j.unique_name===b.level):!1}))return r.file(i).addError(gA.semiAdditiveDegenerateDimensionHasUnknownLevel(b.name,b.level)),!1}),p.forEach(b=>{let T=!1;l.semi_additive?.relationships?.forEach(E=>{T||(Array.isArray(E)?E.every(j=>!!(b.relationships.find(z=>z.unique_name===j)||_.find(z=>z.relationships?.find(X=>ki.isEmbeddedRelation(X)&&X.unique_name===j))))&&(T=!0):(b.relationships.find(j=>j.unique_name===E)||_.find(j=>j.relationships?.find(z=>ki.isEmbeddedRelation(z)&&z.unique_name===E)))&&(T=!0))}),l.semi_additive?.degenerate_dimensions?.forEach(E=>{T||b.degenerateDimensions.find(k=>E.name===k)&&(T=!0)}),T||r.file(i).addError(gA.modelHasNoValidAttributes(b.unique_name))})}validateSemiAdditiveByCalculationMethod(r,i){let o=i.data;sTe.includes(o.calculation_method)||r.file(i).addError(gA.validateSemiAdditiveAggregationType(o.unique_name,o.calculation_method))}validateCalcMethod(r,i,o){let l=i.data;aTe[o].includes(l.calculation_method)||r.file(i).addError(gA.calcMethodNotCompatibleWithColumnType(l,o))}};var JQ={referenceAggregateObjectNotExist:(n,r,i)=>`Incorrect aggregate reference. An aggregate with unique_name "${n}" references a ${i} "${r}" which is not referenced in the model`,wrongAttributeType:(n,r,i,o)=>`Incorrect aggregate attribute type. An aggregate with unique_name "${n}" references "${r}" as a ${i}, but it should be specified as a ${o}`,noCommonRelationFound:n=>{let r=n.metricDataset.path?` through dependency path: ${n.metricDataset?.path.join(" -> ")}`:"";return`Error in an aggregate with unique_name "${n.aggName}". There is no common relation between metric "${n.metric}" and dimension "${n.dimension}". The metric uses a dataset "${n.metricDataset.dataSet}"${r}, but the dimension has no relation to it in this model`}},Boe=class{constructor(r){this.yamlCommonReferenceValidator=r;this.getDimensionalAttributes=(r,i)=>r.filter(o=>this.isDimensionalAttribute(o,i));this.isDimensionalAttribute=(r,i)=>QL(r)&&r.dimension!==void 0&&i.get(r.dimension)?.data.object_type==="dimension"}validateAggregates(r,i,o){let l=i.data.aggregates;if(!l||l.length===0)return;let p=i.data.relationships.filter(Ic.isRegularRelation),_=this.getDatasetsForDimensions(p,o),b=i.data.dimensions&&i.data.dimensions.length>0?{..._,...this.getDatasetsForDegenerates(i.data.dimensions,o)}:_;this.validateUniqueAggregates(r.file(i),l);let T={};l.forEach((E,k)=>{let{attributes:j,metrics:z}=E;(j?.length??0)+(E.metrics?.length??0)<1&&r.file(i).addError(`Aggregate ${E.unique_name} should have at least one attribute or metric`);let ue=r.getFileOutputErrorCount(i);if(j&&this.validateAggregateAttributes(i,E,o,r),z){let De=j?j.filter($e=>YL($e)):[];this.yamlCommonReferenceValidator.validateMetricReferences(r,i,o,z),this.validateAggregateMetricsExistInModel(r,i,E);let Je=r.getFileOutputErrorCount(i);ue===Je&&z.forEach($e=>{this.getDatasetsForMetric($e,o,T).forEach(ht=>{De?.filter(cr=>!b[cr.dimension]?.includes(ht.dataSet)).forEach(cr=>{r.file(i).addError(JQ.noCommonRelationFound({aggName:E.unique_name,metric:$e,dimension:cr.dimension,metricDataset:ht}))})})})}Object.keys(E).includes("target_connection")&&r.file(i).addWarning(nCe.getTargetConnectionWarning(E.unique_name||E.label,k))})}validateAggregateAttributes(r,i,o,l){if(!i.attributes)return;let{referencedDimensionsInModel:p,referencedRowSecuritiesInModel:_}=this.getModelRelatedEntities(r,o),b=this.getDimensionalAttributes(i.attributes,o);this.yamlCommonReferenceValidator.validateAttributesReferences(l,r,o,b),this.validateAggregateDimensionReferencesNotMistyped(l,r,_,i),this.validateAggregateDimensionReferencesExist(l,r,p,i,_),this.validateAggregateRowSecurityReferencesNotMistyped(l,r,p,i),this.validateAggregateRowSecurityReferencesExist(l,r,_,i,p)}validateUniqueAggregates(r,i){let o=rl.groupBy(i,l=>[l.unique_name]);rl.appendErrorsIfDuplicates(o,r,Ah.getDuplicateAggregatesUniqueNames)}validateAggregateDimensionReferencesExist(r,i,o,l,p){this.getUniqueReferencedDimensions(l).filter(b=>!o.includes(b)).forEach(b=>{p.includes(b)||r.file(i).addError(JQ.referenceAggregateObjectNotExist(l.unique_name,b,"dimension"))})}validateAggregateDimensionReferencesNotMistyped(r,i,o,l){this.getUniqueReferencedDimensions(l).filter(_=>o.includes(_)).forEach(_=>{r.file(i).addError(JQ.wrongAttributeType(l.unique_name,_,"dimension","row_security"))})}getUniqueReferencedDimensions(r){let i=r.attributes?.filter(QL)||[];return[...new Set(i.map(o=>o.dimension))]}validateAggregateRowSecurityReferencesExist(r,i,o,l,p){this.getUniqueReferencedRowSecurities(l).filter(b=>!o.includes(b)).forEach(b=>{p.includes(b)||r.file(i).addError(JQ.referenceAggregateObjectNotExist(l.unique_name,b,"row_security"))})}validateAggregateRowSecurityReferencesNotMistyped(r,i,o,l){this.getUniqueReferencedRowSecurities(l).filter(_=>o.includes(_)).forEach(_=>{r.file(i).addError(JQ.wrongAttributeType(l.unique_name,_,"row_security","dimension"))})}getUniqueReferencedRowSecurities(r){let i=r.attributes?.filter(gQ)||[];return[...new Set(i.map(o=>o.row_security))]}validateAggregateMetricsExistInModel(r,i,o){o.metrics?.filter(l=>!i.data.metrics.some(p=>p.unique_name===l)).forEach(l=>{r.file(i).addError(JQ.referenceAggregateObjectNotExist(o.unique_name,l,"metric"))})}getModelRelatedEntities(r,i){let o=r.data.relationships.filter(Ic.isRegularRelation),l=r.data.relationships.filter(Ic.isSecurityRelation),p=o.flatMap(b=>this.resolveEmbeddedDimensions(b.to.dimension,i)).concat(r.data.dimensions??[]),_=l.flatMap(b=>this.resolveRowSecurityForAggregates(b.to.row_security,i));return{referencedDimensionsInModel:p,referencedRowSecuritiesInModel:_}}resolveRowSecurityForAggregates(r,i){let o=i.get(r);return!o||!_l.isRowSecurity(o.data)?[]:[o.data.unique_name]}resolveEmbeddedDimensions(r,i,o=new Set,l=1){us.ensure(l<=100,"Max recursion depth exceeded.");let p=i.get(r);if(!p||!_l.isDimension(p.data))return[];let _=p.data.unique_name;if(o.has(_))return[];o.add(_);let b=(p.data.relationships??[]).filter(ki.isEmbeddedRelation).flatMap(T=>this.resolveEmbeddedDimensions(T.to.dimension,i,o,l+1));return[_,...b]}getDatasetsForDimensions(r,i){return r.reduce((o,l)=>(this.resolveEmbeddedDimensions(l.to.dimension,i).forEach(p=>{let _=o[p]||[];_.includes(l.from.dataset)||_.push(l.from.dataset),o[p]=_}),o),{})}getDatasetsForDegenerates(r,i){return r.reduce((o,l)=>{let p=i.get(l);if(!p||!_l.isDimension(p.data))return o;let _=p.data.level_attributes.flatMap(b=>ki.isLevelFromOneDataset(b)?[b.dataset]:b.shared_degenerate_columns.map(T=>T.dataset));return o[l]=_,o},{})}getDatasetsForMetric(r,i,o,l=uA,p=1){if(us.ensure(p<=200,"Max recursion depth exceeded."),o[r])return o[r];let _=i.get(r);if(!_)return[];let b=_.data,T=[];return mQ.isCalcMetric(b)?l(b.expression).forEach(E=>{this.getDatasetsForMetric(E,i,o,l,p+1).forEach(k=>{T.some(j=>j.dataSet===k.dataSet)||T.push({dataSet:k.dataSet,path:[E,...k.path||[]]})})}):T.push({dataSet:b.dataset}),o[r]=T,T}};var lkt=50,oCe=class{constructor(r,i){this.yamlCommonReferenceValidator=r;this.yamlModelAggregateValidator=i}validateObject(r,i,o){let l=r.data,p=Mo.create(),_=[];l.relationships.forEach(T=>{Ic.isRegularRelation(T)&&_.push(T.to.dimension)}),this.validateMetrics(r,l.metrics,i,o,p),this.validateDimensions(p,r,i,o,!1,_),this.validateDimensions(p,r,i,o,!0,l.dimensions),p.append(this.yamlCommonReferenceValidator.validateRelationships(r,i,o)),this.yamlCommonReferenceValidator.validateRelationshipsReferences(p,r,i),this.validateRelationshipM2MProp(p.file(r),l.relationships),this.validateUniqueRelationships(p.file(r),l),this.validateUniqueMetrics(p.file(r),l),this.validateOverrides(p,r),this.validateDatasetsProperties(p,r,i);let b=r;return this.yamlModelAggregateValidator.validateAggregates(p,b,i),this.validateDrillThroughs(p,b,i),this.validatePerspectives(p,b,i),this.validateUniqueMultipleRelationshipsToLevel(p.file(r),l),p}validateUniqueMultipleRelationshipsToLevel(r,i){let o=rCe(i.relationships);rl.appendErrorsIfDuplicates(o,r,Ah.getMultiRelationshipsToLevelMessage)}validateDatasetsProperties(r,i,o){i.data.dataset_properties&&Object.keys(i.data.dataset_properties).forEach(l=>{let p=o.get(l);p||r.file(i).addError(Ah.getDatasetForPropertiesNotExist(l)),p&&p?.data.object_type!=="dataset"&&r.file(i).addError(Ah.getDatasetPropertiesIncorrectType(l))})}validateMetrics(r,i,o,l,p){i.forEach(_=>{let b=o.get(_.unique_name);if(!b){p.file(r).addError(ih.referenceObjectNotExist("metric",_.unique_name));return}if(b.data.object_type!=="metric"&&b.data.object_type!=="metric_calc"){p.file(r).addError(ih.incorrectReference("metric",_.unique_name,b.data.object_type));return}l.add(_.unique_name)})}validateDimensions(r,i,o,l,p,_){_?.forEach(b=>{let T=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(b,o,i,"dimension",r);if(!T)return;let E=T.data;E.is_degenerate||(E.is_degenerate=!1),E.is_degenerate!==p&&r.file(i).addError(Ah.getDimensionDegenerateError(p,b)),T&&l.add(b)})}getAllModelDimensions(r){return r.data.relationships.filter(Ic.hasDimensionProp).map(o=>o.to.dimension).concat(r.data.dimensions||[])}collectNestedDimensions(r){let{dimensionName:i,depth:o,result:l,elementsMap:p}=r;if(o>lkt)throw new Error(Ah.getMaximumDepthOfNestedDimensionExceeded(lkt));if(l.has(i))return;let _=p.get(i);if(_&&_.data.object_type==="dimension"){let b=_.data;if(l.set(i,b),b.relationships){for(let T of b.relationships)if(ki.isRegularRelation(T)&&ki.isEmbeddedRelation(T)){let E=T.to.dimension;this.collectNestedDimensions({dimensionName:E,depth:o+1,result:l,elementsMap:p})}}}}getAllModelDimensionsIncludingNestedDims(r,i){let o=new Map;return this.getAllModelDimensions(r).forEach(p=>{this.collectNestedDimensions({dimensionName:p,depth:1,result:o,elementsMap:i})}),o}validateDrillThroughAttributes(r){let{validatorOutput:i,file:o,elementsMap:l,dt:p,attributes:_}=r;if(_){this.yamlCommonReferenceValidator.validateAttributesReferences(i,o,l,_);let b=this.getAllModelDimensionsIncludingNestedDims(o,l);_.forEach(T=>{b.get(T.dimension)||i.file(o).addError(Ah.getDrillThroughAttributeNotFoundInModel(p.unique_name,T.dimension))})}}validateDrillThroughMetrics(r,i,o,l,p){p&&i.data.metrics&&(this.yamlCommonReferenceValidator.validateMetricReferences(r,i,o,p),p.forEach(_=>{i.data.metrics.find(T=>T.unique_name===_)||r.file(i).addError(Ah.getDrillThroughMetricNotFoundInModel(l.unique_name,_))}))}validateDrillThroughs(r,i,o){let{drillthroughs:l}=i.data;l&&l.forEach(p=>{let{attributes:_,metrics:b}=p;this.validateDrillThroughAttributes({validatorOutput:r,file:i,elementsMap:o,dt:p,attributes:_}),this.validateDrillThroughMetrics(r,i,o,p,b)})}validatePerspectivesDimensions(r,i,o,l,p){if(!p)return;this.yamlCommonReferenceValidator.validatePerspectiveDimensionReferences(r,i,o,p);let _=this.getAllModelDimensionsIncludingNestedDims(i,o);p.forEach(b=>{let T=_.get(b.name);if(!T){r.file(i).addError(Ah.getPerspectiveDimensionNotFoundInModel(l.unique_name,b.name));return}this.validatePerspectiveHierarchies(r,i,b,l,T)})}validatePerspectiveHierarchies(r,i,o,l,p){o.hierarchies&&o.hierarchies.forEach(_=>{if(!p.hierarchies?.find(T=>T.unique_name===_.name)){r.file(i).addError(Ah.getPerspectiveHierarchyNotFound(l.unique_name,_.name,o.name));return}if(_.level&&(p.level_attributes?.find(E=>E.unique_name===_.level)||r.file(i).addError(Ah.getPerspectiveHierarchyLevelNotFound(l.unique_name,_.name,_.level,o.name))),_.levels){let T=nCe.levelsPropDetectedInPerspective(l.unique_name,o.name,_.name);r.file(i).addWarning(T,{type:"PerspectiveLevelFix",context:{model:i.data.unique_name,perspective:l.unique_name,dimension:o.name,hierarchy:_.name}})}_.levels&&_.levels.forEach(T=>{p.level_attributes?.find(k=>k.unique_name===T)||r.file(i).addError(Ah.getPerspectiveHierarchyLevelNotFound(l.unique_name,_.name,T,o.name))})}),o.secondary_attributes&&o.secondary_attributes.forEach(_=>{p.hierarchies.flatMap(E=>E.levels).flatMap(E=>E.secondary_attributes||[])?.find(E=>E.unique_name===_)||r.file(i).addError(Ah.getPerspectiveSecondaryAttributeNotFound(l.unique_name,_,o.name))})}validatePerspectiveMetrics(r,i,o,l,p){p&&(this.yamlCommonReferenceValidator.validateMetricReferences(r,i,o,p),p.forEach(_=>{i.data.metrics?.find(T=>T.unique_name===_)||r.file(i).addError(Ah.getPerspectiveMetricNotFoundInModel(l.unique_name,_))}))}validatePerspectives(r,i,o){let{perspectives:l}=i.data;l&&l.forEach(p=>{let{dimensions:_,metrics:b}=p;this.validatePerspectivesDimensions(r,i,o,p,_),this.validatePerspectiveMetrics(r,i,o,p,b)})}validateUniqueRelationships(r,i){let o=rl.groupBy(i.relationships,p=>Object.values(p.from).concat(Object.values(p.to)));rl.appendErrorsIfDuplicates(o,r,Ah.getDuplicateRelationshipsMessage);let l=rl.groupBy(i.relationships,p=>[p.unique_name]);rl.appendErrorsIfDuplicates(l,r,Ah.getDuplicateRelationshipsUniqueNameMessage)}validateRelationshipM2MProp(r,i){i.forEach(o=>{Object.prototype.hasOwnProperty.call(o,"m2m")&&r.addError(Ah.getM2MPropDetectedInRelation(o.unique_name))})}validateUniqueMetrics(r,i){let o=rl.groupBy(i.metrics,l=>[l.unique_name]);rl.appendErrorsIfDuplicates(o,r,Ah.getDuplicateMetricUniqueNames)}validateOverrides(r,i){let o=i.data;if(!o.overrides)return;let l=o.overrides;r.file(i).addInfo(Ah.overridesInfo);let p=o.metrics.map(T=>T.unique_name).concat(o.dimensions||[]);Object.keys(l).filter(T=>!p.includes(T)).forEach(T=>{r.file(i).addError(Ah.getOverrideNotReferencedInModel(T))});let _=o.metrics.map(T=>this.getOverrideWithObjectType(T.unique_name,l,"metric")).concat(o.dimensions?.map(T=>this.getOverrideWithObjectType(T,l,"dimension"))||[]),b=rl.groupBy(_,T=>[T.query_name.toLowerCase()]);Array.from(b.values()).filter(T=>T.length>1).forEach(T=>{r.file(i).addError(Ah.getOverridesDuplicateOnQueryNames(T))})}getOverrideWithObjectType(r,i,o){return Object.keys(i).includes(r)?{query_name:i[r].query_name,unique_name:r,object_type:o}:{query_name:r,unique_name:r,object_type:o}}};var ukt={missingIdsColumn:(n,r)=>`Missing ids_column. Column "${n}" does not exist in "${r}" dataset`,missingFilterKeyColumn:(n,r)=>`Missing filter_key_column. Column "${n}" does not exist in "${r}" dataset`,notExistingDataset:n=>`Dataset "${n}" does not exist`},cCe=class{constructor(r){this.yamlCommonReferenceValidator=r}validateObject(r,i,o){let l=r.data,p=Mo.create();if(hQ.hasDatasetProp(l)){let _=this.yamlCommonReferenceValidator.validateAndGetReferencedObject(l.dataset,i,r,"dataset",p);if(!_)return p;o.add(l.dataset);let b=_.data,T=b.columns.find(k=>k.name===l.ids_column),E=b.columns.find(k=>k.name===l.filter_key_column);if(T||p.file(r).addError(ukt.missingIdsColumn(l.ids_column,_.data.unique_name)),!E)return p.file(r).addError(ukt.missingFilterKeyColumn(l.filter_key_column,_.data.unique_name)),p}return p}};var p7=new joe,fkt=new Moe,dkt=new Boe(p7),pkt=new oCe(p7,dkt),g4r=new qk,y4r={dataset:new eCe(p7),dimension:new iCe(p7,fkt,g4r),metric:new aCe(p7),metric_calc:new sCe(fkt),model:pkt,model_settings:new Loe,global_settings:new Loe,connection:new ZTe,row_security:new cCe(p7),catalog:new KTe(pkt,p7),composite_model:new XTe(p7,dkt)},lCe=class n{static create(){return new n}getObjectValidator(r){return y4r[r]}validate(r){let i=Mo.create(),o=new Set,l=new Map;return r.forEach(_=>l.set(_.data.unique_name,_)),r.forEach(_=>{let b=this.getObjectValidator(_.data.object_type);i.append(b.validateObject(_,l,o))}),r.filter(_=>_.data.object_type!=="model"&&_.data.object_type!=="composite_model"&&_.data.object_type!=="catalog"&&_.data.object_type!=="model_settings"&&_.data.object_type!=="global_settings").filter(_=>!o.has(_.data.unique_name)).forEach(_=>{i.file(_).addWarning("File not in use. File has no references to it.")}),i}};var mkt=(r=>(r.MetricalAttribute="metrical_attribute",r))(mkt||{});var Dvn={...dl,...mkt},$oe={globalScopeError:(n,r,i,o)=>`The "${i}" name "${n}" is not unique. The file "${r}" contains "${o}" with the same name`,fileScopeError:(n,r,i)=>`Duplicate ${n} and ${r} unique names: ${i}`,duplicatePermissionUniqueName:n=>{let r=n.map(i=>i.type==="perspective"?`a perspective unique_name in model ${i.modelFile.data.unique_name}`:`a file unique_name in model ${i.modelFile.data.unique_name}`);return`Unique_name "${n[0].unique_name}" is duplicated. It appears as: ${nh(r)};`},dimAttributesDuplicateUniqueName:n=>`Duplicate unique_names "${n.unique_name}". Hierarchy[${n.hierarchy}] -> ${n.level?`Level[${n.level}] -> ${n.objectType}`:`Level[${n.unique_name}]`}`},_kt=["metric_calc","metric","metrical_attribute"];var Joe={level:"Duplicate level unique name within the same hierarchy",levelAttribute:"Duplicate level_attribute unique names",duplicateUniqueName:"Duplicate unique names"},v4r=(n,r)=>{let i=_kt.includes(n.type),o=_kt.includes(r.type);return i&&o||!i&&!o},uCe=class n{constructor(r){this.hasDuplicatePerspectiveUniqueNames=r=>r.some(i=>i.type==="perspective");this.hasDuplicateUniqueNames=r=>Array.from(r.values()).some(i=>i.length>1);this.getLevelContext=(r,i)=>this.yamlErrorContextUtil.getLevelContext({itemUniqueName:r,message:Joe.level,validationType:"unique_name",hierarchyUniqueName:i||""});this.getLevelAttributeContext=r=>this.yamlErrorContextUtil.getLevelAttributeContext({itemUniqueName:r,message:Joe.levelAttribute,validationType:"unique_name"});this.getSecondaryAttributeContext=r=>this.yamlErrorContextUtil.getSecondaryAttributeContext({itemUniqueName:r,message:Joe.duplicateUniqueName,validationType:"unique_name"});this.yamlErrorContextUtil=r}static create(r){return new n(r)}validate(r){let i=new Array;this.addFiles(r,i),this.addMetricalAttributes(r,i);let o=Mo.create();return i.forEach((l,p)=>{i.forEach((_,b)=>{b>p&&DQ(l.uniqueName,_.uniqueName)&&v4r(l,_)&&this.addErrorsInDuplicatedFiles(_.uniqueName,l.file,l.type,_.file,_.type,o)})}),r.forEach(l=>{l.data.object_type==="dimension"&&this.validateDimension(l,o)}),this.validateModelPerspectiveUniqueNames(r,o),o}groupModelsAndPerspectivesByUniqueName(r,i){let o=r.flatMap(l=>{let p=XL(l,i),_=p.data.perspectives?.map(b=>({unique_name:b.unique_name,type:"perspective",modelFile:p}))||[];return[{unique_name:p.data.unique_name,type:"model",modelFile:p},..._]});return rl.groupBy(o,l=>[l.unique_name])}validateModelPerspectiveUniqueNames(r,i,o=KL){let l=o(r),p=this.groupModelsAndPerspectivesByUniqueName(l,r);this.hasDuplicateUniqueNames(p)&&this.addErrorsForDuplicateModelAndPerspectiveUniqueNames(p,i)}addErrorsForDuplicateModelAndPerspectiveUniqueNames(r,i){Array.from(r.values()).forEach(o=>{o.length>1&&this.hasDuplicatePerspectiveUniqueNames(o)&&this.getUniqueFilesWithDuplicateUniqueNames(o).forEach(p=>{i.file(p.modelFile).addError($oe.duplicatePermissionUniqueName(o))})})}getUniqueFilesWithDuplicateUniqueNames(r){return r.filter((i,o,l)=>o===l.findIndex(p=>p.modelFile.data.unique_name===i.modelFile.data.unique_name))}addMetricalAttributes(r,i){r.filter(o=>o.data.object_type==="dimension").forEach(o=>{o.data.hierarchies.forEach(p=>{p.levels.forEach(_=>{_.metrics&&_.metrics.forEach(b=>{i.push({file:o,uniqueName:b.unique_name,type:"metrical_attribute",path:o.relativePath})})})})})}addFiles(r,i){r.forEach(o=>{i.push({file:o,uniqueName:o.data.unique_name,type:o.data.object_type,path:o.relativePath})})}addErrorsInDuplicatedFiles(r,i,o,l,p,_){if(i.relativePath===l.relativePath){_.file(i).addError($oe.fileScopeError(o,p,r));return}_.file(i).addError($oe.globalScopeError(r,l.relativePath,o,p)),_.file(l).addError($oe.globalScopeError(r,i.relativePath,p,o))}validateDimension(r,i){let o=r.data;this.validateUniqueNames(o.level_attributes.map(l=>l.unique_name),"level_attribute",i.file(r),{getContext:this.getLevelAttributeContext}),this.validateUniqueNames(o.hierarchies.map(l=>l.unique_name),"hierarchy",i.file(r)),o.hierarchies.forEach(l=>{let p=l.levels.map(_=>_.unique_name);this.validateUniqueNames(p,"level",i.file(r),{getContext:this.getLevelContext,hierarchyUniqueName:l.unique_name})}),this.validateDimensionalAttributes(r,i)}validateUniqueNames(r,i,o,l){let p=this.groupUniqueNames(r);l?rl.appendErrorsWithContextIfDuplicates(p,o,this.getErrorMessage(i,l?.hierarchyUniqueName),l):rl.appendErrorsIfDuplicates(p,o,this.getErrorMessage(i))}getErrorMessage(r,i){return(l,p)=>i?`Duplicate ${r} unique_names "${l}" within hierarchy "${i}". ${p} duplicate items found.`:`Duplicate ${r} unique_names "${l}". ${p} duplicate items found.`}groupUniqueNames(r){return rl.groupBy(r,i=>[i])}validateDimensionalAttributes(r,i){let o=rl.groupBy(this.getAllDimensionalAttributes(r.data),l=>[l.unique_name]);rl.processDuplicates(o,l=>{l.forEach(p=>{i.file(r).addErrorWithContext($oe.dimAttributesDuplicateUniqueName(p),p.context)})})}getAllDimensionalAttributes(r){let i=r.hierarchies.flatMap(l=>l.levels.map(p=>({...p,hierarchy:l.unique_name}))),o=i.flatMap(l=>{let p=l.secondary_attributes?.map(b=>({unique_name:b.unique_name,hierarchy:l.hierarchy,objectType:"secondary_attribute",level:l.unique_name,context:this.getSecondaryAttributeContext(b.unique_name)}))||[],_=l.aliases?.map(b=>({unique_name:b.unique_name,hierarchy:l.hierarchy,objectType:"level_alias",level:l.unique_name,context:this.yamlErrorContextUtil.getLevelAliasContext({itemUniqueName:b.unique_name,message:Joe.duplicateUniqueName,validationType:"unique_name"})}))||[];return p.concat(_)});return[...this.getUniqueLevelsInDimension(i),...o]}getUniqueLevelsInDimension(r){let i=rl.groupBy(r,o=>[o.unique_name]);return Array.from(i.values()).flatMap(o=>o[0]).map(o=>({unique_name:o.unique_name,hierarchy:o.hierarchy,objectType:"level",context:this.yamlErrorContextUtil.getLevelContext({itemUniqueName:o.unique_name,message:Joe.duplicateUniqueName,validationType:"unique_name",hierarchyUniqueName:o.hierarchy})}))}};var fCe={$id:"https://www.atscale.com/ml/catalog.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"catalog",type:"object",required:["object_type","unique_name","label","version","aggressive_agg_promotion","build_speculative_aggs"],properties:{object_type:{const:"catalog"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},version:{type:"number",minimum:1},hidden_models:{type:"array",items:{type:"string",minLength:1}},aggressive_agg_promotion:{type:"boolean"},build_speculative_aggs:{type:"boolean"},description:{type:"string",minLength:1},dataset_properties:{type:"object",additionalProperties:{type:"object",properties:{allow_aggregates:{type:"boolean"},allow_local_aggs:{type:"boolean"},allow_peer_aggs:{type:"boolean"},allow_preferred_aggs:{type:"boolean"}}}},aggregate_store:{type:"object",required:["as_connection"],properties:{as_connection:{type:"string"},row_count_limit:{type:"integer",minimum:1,maximum:2147483648},total_row_count_limit:{type:"integer",minimum:1,maximum:2147483648}},additionalProperties:!1}}};var pCe={$id:"https://www.atscale.com/ml/connection.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Connection",type:"object",required:["object_type","unique_name","label","as_connection"],properties:{object_type:{const:"connection"},unique_name:{type:"string",minLength:1,maxLength:128},label:{type:"string",minLength:1,maxLength:128},database:{type:"string",minLength:1},schema:{type:"string",minLength:1},as_connection:{type:"string",minLength:1}}};var dCe={$id:"https://www.atscale.com/ml/dataset.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Dataset",type:"object",required:["object_type","unique_name","label","connection_id","columns"],oneOf:[{required:["sql"],errorMessage:"Missing sql prop - please add (sql) OR table property"},{required:["table"],errorMessage:"Missing table prop - please add (sql) OR table property"}],properties:{object_type:{const:"dataset"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},description:{type:"string",minLength:1},connection_id:{type:"string",minLength:1,maxLength:128},columns:{type:"array",contains:{type:"object"},items:{oneOf:[{required:["data_type"],errorMessage:"oneOf: if on a column the data_type is set then the map property should not be set",not:{required:["map"]}},{required:["map"],errorMessage:"oneOf: if on a column the map property is set then neither data_type nor parent_column should exists",not:{anyOf:[{required:["data_type"]},{required:["parent_column"]}]}}],type:"object",required:["name"],properties:{name:{type:"string",minLength:1},data_type:{type:"string",minLength:3,errorMessage:"invalid column data_type must be one of 'string', ' int', ' long', ' bigint', 'tinyint', 'float', 'double', 'decimal', 'decimal(x,y)', 'number', 'number(x,y)', 'numeric(x,y)', 'boolean', 'date', 'datetime', 'timestamp'"},sql:{type:"string",minLength:1},dialects:{type:"array",items:{type:"object",required:["dialect","sql"],properties:{dialect:{type:"string",minLength:1,enum:["Snowflake","BigQuery","Iris","Postgresql","DatabricksSQL"],errorMessage:"must have a value: 'Snowflake', 'BigQuery', 'Iris', 'Postgresql' or 'DatabricksSQL'"},sql:{type:"string",minLength:1}}}},map:{type:"object",required:["field_terminator","key_terminator","key_type","value_type"],properties:{field_terminator:{type:"string",minLength:1},key_terminator:{type:"string",minLength:1},key_type:{type:"string",minLength:1},value_type:{type:"string",minLength:1},is_prefixed:{type:"boolean"}}},parent_column:{type:"string",minLength:1}}}},table:{type:"string",minLength:1},sql:{type:"string",minLength:1},dialects:{type:"array",items:{type:"object",required:["dialect","sql"],properties:{dialect:{type:"string",minLength:1,enum:["Snowflake","BigQuery","Iris","Postgresql","DatabricksSQL"],errorMessage:"must have a value: 'Snowflake', 'BigQuery', 'Iris', 'Postgresql' or 'DatabricksSQL'"},sql:{type:"string",minLength:1}}}},immutable:{type:"boolean"},alternate:{oneOf:[{required:["sql"],errorMessage:"use (sql) OR (table + connection_id) properties",not:{anyOf:[{required:["table"]},{required:["connection_id"]}]}},{required:["table","connection_id"],errorMessage:"use (sql) OR (table + connection_id) properties",not:{required:["sql"]}}],type:"object",required:["type"],properties:{type:{type:"string",minLength:1},sql:{type:"string",minLength:1},connection_id:{type:"string",minLength:1,maxLength:128},table:{type:"string",minLength:1}}},incremental:{type:"object",required:["column","grace_period"],properties:{column:{type:"string",minLength:1,maxLength:128},grace_period:{type:"string",description:"A duration string (e.g. '100s', '15d', '2w') or a non-negative integer for integer-like columns.",maxLength:11,errorMessage:{maxLength:"must be at most 11 characters long."},oneOf:[{pattern:"^\\d{1,10}[smhdw]$",minLength:2,errorMessage:{minLength:"must be at least 2 characters long.",pattern:"Invalid value. Should be in format: integer + time unit. Example: '100s', '15d', '2w'."}},{pattern:"^\\d+$",minLength:1,errorMessage:{minLength:"must be at least 1 character long.",pattern:"Invalid value. Grace period must be a non-negative integer for integer-like columns."}}]}}}},errorMessage:{oneOf:"Cannot have both sql and table props - please add only one of them"}};var _Ce={$id:"https://www.atscale.com/ml/dimension.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Dimension",type:"object",required:["label","hierarchies","level_attributes","unique_name","object_type"],properties:{label:{type:"string",minLength:1,maxLength:63},description:{type:"string",minLength:1},type:{enum:["time","standard"],errorMessage:"must have a value: 'time' or 'standard'"},hierarchies:{type:"array",items:{type:"object",required:["label","unique_name","levels"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},levels:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},secondary_attributes:{type:"array",items:{type:"object",required:["unique_name","label","dataset","name_column","key_columns"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},dataset:{type:"string",minLength:1,maxLength:128},name_column:{type:"string",minLength:1},key_columns:{type:"array"},sort_column:{type:"string",minLength:1},description:{type:"string",minLength:1},is_hidden:{type:"boolean"},folder:{type:"string",minLength:1,maxLength:128},contains_unique_names:{type:"boolean"},allowed_calcs_for_dma:{type:"array",items:{type:"string",minLength:1}},exclude_from_dim_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},custom_empty_member:{type:"object",required:["key","name"],properties:{key:{type:"array"},name:{type:"string",minLength:1,maxLength:128},sort_name:{type:"string",minLength:1}}},is_excel_pivot_table_property:{type:"boolean"},is_user_defined_property:{type:"boolean"}}}},aliases:{type:"array",items:{type:"object",required:["unique_name","label","dataset","name_column"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},dataset:{type:"string",minLength:1,maxLength:128},name_column:{type:"string",minLength:1,maxLength:128},sort_column:{type:"string",minLength:1},description:{type:"string",minLength:1},is_hidden:{type:"boolean"},folder:{type:"string",minLength:1},format:{type:"string",minLength:1},exclude_from_dim_agg:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},custom_empty_member:{type:"object",required:["name"],properties:{key:{type:"array",items:{type:"string",minLength:1}},name:{type:"string",minLength:1,maxLength:128},sort_name:{minLength:1,maxLength:128}}},is_excel_pivot_table_property:{type:"boolean"},is_user_defined_property:{type:"boolean"}}}},metrics:{type:"array",items:{type:"object",required:["unique_name","label","dataset","column","calculation_method"],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:128},dataset:{type:"string",minLength:1,maxLength:128},column:{type:"string",minLength:1,maxLength:128},calculation_method:{type:"string",enum:["sum","minimum","maximum","count distinct","sum distinct","estimated count distinct","count non-null"],errorMessage:"Type must be: sum, minimum, maximum, count distinct, sum distinct, estimated count distinct, count non-null"},description:{type:"string",minLength:1},is_hidden:{type:"boolean"},folder:{type:"string",minLength:1},format:{type:"string",minLength:1},exclude_from_dim_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},custom_empty_member:{type:"object",required:["key","name","sort_name"],properties:{key:{type:"array"},name:{type:"string",minLength:1},sort_name:{type:"string",minLength:1}}},unrelated_dimensions_handling:{enum:["error","repeat","empty"],errorMessage:"Type must be: 'error', 'repeat', 'empty'"}}}},parallel_periods:{type:"array",items:{type:"object",required:["level","key_columns"],properties:{level:{type:"string",minLength:1},key_columns:{type:"array",items:{type:"string",minLength:1},minItems:1}}},minLength:1},is_hidden:{type:"boolean"}}}},description:{type:"string",minLength:1},folder:{type:"string",minLength:1},filter_empty:{type:"string",enum:["yes","no","always"],errorMessage:"must have a value: 'yes', 'no' or 'always'"},default_member:{type:"object",properties:{expression:{type:"string",minLength:1},apply_only_when_in_query:{type:"boolean"}},required:["expression"]}}}},level_attributes:{type:"array",items:{type:"object",required:["label","unique_name"],anyOf:[{required:["shared_degenerate_columns"],not:{anyOf:[{required:["dataset"]},{required:["name_column"]},{required:["key_columns"]}]},errorMessage:"Invalid configuration: Please provide either 'dataset', 'name_column', and 'key_columns' for a single dataset or 'shared_degenerate_columns' for multiple datasets, but not both or neither."},{required:["dataset","name_column","key_columns"],not:{required:["shared_degenerate_columns"]},errorMessage:{required:"Missing required properties for single-dataset syntax. The properties 'dataset', 'name_column', and 'key_columns' are required.",not:"Invalid configuration: Please provide either 'dataset', 'name_column', and 'key_columns' for a single dataset or 'shared_degenerate_columns' for multiple datasets, but not both or neither."}}],properties:{label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:63},dataset:{type:"string",minLength:1,maxLength:128},description:{type:"string",minLength:1},contains_unique_names:{type:"boolean"},name_column:{type:"string",minLength:1},key_columns:{type:"array",items:{type:"string",minLength:1}},sort_column:{type:"string",minLength:1},constraint_translation_rank:{type:"integer",minimum:-2147483648,maximum:2147483648},is_unique_key:{type:"boolean"},shared_degenerate_columns:{type:"array",minItems:1,maxItems:128,items:{type:"object",required:["dataset","name_column","key_columns"],properties:{dataset:{type:"string",minLength:1,maxLength:128},name_column:{type:"string",minLength:1},key_columns:{type:"array",minItems:1,maxItems:1,items:{type:"string",minLength:1,maxLength:128}},sort_column:{type:"string",minLength:1,maxLength:128},is_unique_key:{type:"boolean"}}}},is_hidden:{type:"boolean"},allowed_calcs_for_dma:{type:"array",items:{type:"string",minLength:1}},exclude_from_dim_agg:{type:"boolean"},is_aggregatable:{type:"boolean"},exclude_from_fact_agg:{type:"boolean"},custom_empty_member:{type:"object",required:["key","name"],properties:{key:{type:"array"},name:{type:"string",minLength:1,maxLength:128}}},time_unit:{type:"string",enum:["year","halfyear","trimester","quarter","month","week","day","hour","minute","second","undefined"]},scd_properties:{type:"object",description:"Defines the level as Slowly changing dimension.",$comment:"Introduced in SML version 1.6",required:["effective_interval_type","effective_start","effective_end","as_of_date","is_latest","join_on_fact_effective_key"],properties:{effective_interval_type:{type:"string",description:"It defines the interval handling of the effective start and effective end columns. It should have one of the standard values: 'right_open_interval' or 'left_open_interval' or 'closed'",enum:["right_open_interval","left_open_interval","closed"],errorMessage:"must have a value: 'right_open_interval' or 'left_open_interval' or 'closed'"},effective_start:{type:"object",description:"Defines the effective start setup of the Slowly changing dimension level",required:["column","display_name_template"],properties:{column:{type:"string",description:"This defines the effective start column for the Slowly changing dimension.",minLength:1},display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} effective-start'. It can be combined with role-playing relationships",minLength:1,examples:["{0} effective-start","{0} effective start"]},has_null_values:{type:"boolean",description:"Determines whether the effective start column has null values. Defaults to true",default:!0},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to false",default:!1}}},effective_end:{type:"object",description:"Defines the effective end setup of the Slowly changing dimension level",required:["column","display_name_template"],properties:{column:{type:"string",description:"This defines the effective end column for the Slowly changing dimension.",minLength:1},display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} effective-end'. It can be combined with role-playing relationships",minLength:1,examples:["{0} effective-end","{0} effective end"]},has_null_values:{type:"boolean",description:"Determines whether the effective end column has null values. Defaults to true",default:!0},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to false",default:!1}}},created:{type:"object",description:"Defines the 'created at' setup of the Slowly changing dimension level",required:["column","display_name_template"],properties:{column:{type:"string",description:"This defines the 'crated at' column for the Slowly changing dimension.",minLength:1},display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} Created'. It can be combined with role-playing relationships",minLength:1,examples:["{0} Created"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to false",default:!1}}},as_of_date:{type:"object",description:"Defines the 'as of date' attribute for the BI tool to consume",required:["display_name_template"],properties:{display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} As-Of-Date'. It can be combined with role-playing relationships",minLength:1,examples:["{0} As-Of-Date"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to true",default:!0}}},is_latest:{type:"object",description:"Defines the 'is latest' attribute for the BI tool to consume",required:["display_name_template"],properties:{display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} Is Latest'. It can be combined with role-playing relationships",minLength:1,examples:["{0} Is Latest"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to true",default:!0}}},join_on_fact_effective_key:{type:"object",description:"Defines the 'is join on fact effective' attribute for the BI tool to consume",required:["display_name_template"],properties:{display_name_template:{type:"string",description:"This defines the display name template which will be used to construct an attribute for the Bi tool. The '{0}' is the substitute item. For example: '{0} Join-On-Fact-Effective-Key'. It can be combined with role-playing relationships",minLength:1,examples:["{0} Join-On-Fact-Effective-Key"]},visible:{type:"boolean",description:"Determines whether attribute will be visible in the BI tool. Defaults to true",default:!0}}}}}}}},relationships:{type:"array",items:{type:"object",required:["from","to","type"],properties:{unique_name:{type:"string",minLength:1,maxLength:512},from:{type:"object",required:["dataset","join_columns"],properties:{dataset:{type:"string",minLength:1,maxLength:128},join_columns:{type:"array",items:{type:"string",minLength:1,maxLength:128}},hierarchy:{type:"string",items:{type:"string",minLength:1}},level:{type:"string",items:{type:"string",minLength:1,maxLength:128}}}},to:{type:"object",required:[],oneOf:[{required:["level"],errorMessage:"Missing level prop - please add row_security OR level property"},{required:["row_security"],errorMessage:"Missing row_security prop - please add row_security OR level property"}],properties:{dimension:{type:"string",minLength:1,maxLength:128},level:{type:"string",minLength:1,maxLength:128},row_security:{type:"string",minLength:1,maxLength:128}}},type:{type:"string",enum:["embedded","snowflake"],errorMessage:"must have a value: 'embedded' or 'snowflake'"},role_play:{type:"string",pattern:".*\\{0\\}.*",errorMessage:"template field must be a string that always contains {0} placeholder. The placeholder indicates where the role-played dimension's name should go."},m2m:{type:"boolean"}}}},calculation_groups:{type:"array",items:{type:"object",required:["unique_name","label","calculated_members"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},label:{type:"string",minLength:1,maxLength:128},is_hidden:{type:"boolean"},calculated_members:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},description:{type:"string",minLength:1},expression:{type:"string",minLength:1},is_hidden:{type:"boolean"},format:{type:"string",minLength:1},template:{type:"string",enum:["Current","Previous","Current vs Previous","Current vs Previous Pct","Next","Current vs Next","Current vs Next Pct","Pct of Total","Pct of Parent","Last Year","Current vs Last Year","Current vs Last Year Pct","Year to Date","Quarter to Date","Month to Date","Month Moving Average 3 Month","Moving Average 30 Period","Moving Average 5 Period","Moving Std Dev 30 Period","Moving Std Dev 5 Period"]},use_input_metric_format:{type:"boolean"}},anyOf:[{required:["expression"],not:{required:["template"]},errorMessage:"Invalid configuration: Please provide either 'expression' or 'template', but not both or neither."},{required:["template"],not:{required:["expression"]},errorMessage:{required:"Missing required properties. Please provide either 'expression' or 'template', but not both or neither.",not:"Invalid configuration: Please provide either 'expression' or 'template', but not both or neither."}}]}},description:{type:"string",minLength:1},folder:{type:"string",minLength:1,maxLength:128},precedence:{type:"number"}}}},unique_name:{type:"string",minLength:1,maxLength:128},object_type:{const:"dimension"},is_degenerate:{type:"boolean"}}};var mCe={$id:"https://www.atscale.com/ml/measure.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Measure",type:"object",required:["unique_name","object_type","label","dataset","column","calculation_method"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},object_type:{const:"metric"},label:{type:"string",minLength:1,maxLength:128},dataset:{type:"string",minLength:1,maxLength:128},column:{type:"string",minLength:1,maxLength:128},calculation_method:{type:"string",enum:["sum","average","minimum","maximum","count distinct","sum distinct","estimated count distinct","count non-null","stddev_samp","stddev_pop","var_samp","var_pop","percentile"],errorMessage:"Type must be: sum, average, minimum, maximum, count distinct, sum distinct, estimated count distinct, count non-null, stddev_samp, stddev_pop, var_samp, var_pop or percentile"},description:{type:"string",minLength:1},format:{type:"string",minLength:1},unrelated_dimensions_handling:{enum:["error","repeat","empty"],errorMessage:"Type must be: 'error', 'repeat', 'empty'"},semi_additive:{type:"object",required:["position"],anyOf:[{required:["relationships"],errorMessage:"There should be at least one attribute in the semi-additive. Please define either 'relationships' or 'degenerate_dimensions'."},{required:["degenerate_dimensions"],errorMessage:"There should be at least one attribute in the semi-additive. Please define either 'relationships' or 'degenerate_dimensions'."}],properties:{position:{type:"string",enum:["first","last","first_child","last_child"],errorMessage:"Supported values: 'first', 'last', 'first_child' and 'last_child'"},relationships:{type:"array",items:{type:["array","string"],items:{minLength:1,type:"string"}}},degenerate_dimensions:{type:"array",items:{type:"object",properties:{name:{type:"string",minLength:1,maxLength:128},level:{type:"string",minLength:1,maxLength:128}}}}}},compression:{type:"number",minimum:1,maximum:5e4},named_quantiles:{type:"string",enum:["median","quartiles","deciles"],errorMessage:"must be equal to one of the allowed values: median, quartiles or deciles"},custom_quantiles:{type:"array",minItems:1,items:{type:"number",minimum:0,maximum:1}},is_hidden:{type:"boolean"}},allOf:[{if:{required:["calculation_method"],properties:{calculation_method:{const:"percentile"}}},then:{required:["compression"],oneOf:[{required:["named_quantiles"]},{required:["custom_quantiles"]}]},errorMessage:"For calculation_method percentile, compression (number) and either named_quantiles (median, quartiles, deciles) or custom_quantiles (array of numbers) must be provided"}]};var hCe={$id:"https://www.atscale.com/ml/measureCalc.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"MeasureCalc",type:"object",required:["object_type","unique_name","label","expression"],properties:{object_type:{const:"metric_calc"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},expression:{type:"string",minLength:1},description:{type:"string",minLength:1},format:{type:"string",minLength:1},is_hidden:{type:"boolean"},mdx_aggregate_function:{type:"string",enum:["SUM","MAX","MIN","COUNT","AVG"],errorMessage:"must have a value: 'SUM', 'MAX', 'MIN', 'COUNT' or 'AVG'"}}};var gCe={$id:"https://www.atscale.com/ml/model.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"Model",type:"object",required:["object_type","unique_name","label","relationships","metrics"],properties:{object_type:{const:"model"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},include_default_drillthrough:{type:"boolean"},relationships:{type:"array",items:{type:"object",required:["unique_name","from","to"],properties:{unique_name:{type:"string",minLength:1,maxLength:512},from:{type:"object",required:["dataset","join_columns"],properties:{dataset:{type:"string",minLength:1,maxLength:128},join_columns:{type:"array",items:{type:"string",minLength:1,maxLength:128}},scd_column:{type:"string",minLength:1,maxLength:128,description:"The date column on the fact table which is used to evaluate the values of the Slowly changing dimension",$comment:"Introduced in SML version 1.6"}}},to:{type:"object",required:[],oneOf:[{required:["dimension","level"],errorMessage:"Missing level prop - please add row_security OR level property"},{required:["row_security"],errorMessage:"Missing row_security prop - please add row_security OR level property"}],properties:{dimension:{type:"string",minLength:1,maxLength:128},level:{type:"string",minLength:1,maxLength:128},row_security:{type:"string",minLength:1,maxLength:128}}},role_play:{type:"string",pattern:".*\\{0\\}.*",errorMessage:"template field must be a string that always contains {0} placeholder. The placeholder indicates where the role-played dimension's name should go."},constraint_translation:{type:"object",required:["level","from_columns"],properties:{level:{type:"string",minLength:1,maxLength:63},from_columns:{type:"array",items:{type:"string",minLength:1,maxLength:128},minItems:1,errorMessage:": a constraint_translation should have at least one join_column defined"}}}}}},dimensions:{type:"array",items:{type:"string",minLength:1,maxLength:128},uniqueItems:!0},metrics:{type:"array",minItems:1,errorMessage:": a model should have at least one metric defined",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},folder:{type:"string",minLength:1}}}},partitions:{type:"array",items:{type:"object",required:["unique_name","dimension","attribute","type"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},dimension:{type:"string",minLength:1,maxLength:128},attribute:{type:"string",minLength:1,maxLength:128},type:{type:"string",enum:["key","name","name+key"],errorMessage:"must be 'key', 'name' or 'name+key'",minLength:1}}}},description:{type:"string",minLength:1},perspectives:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},dimensions:{type:"array",items:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1,maxLength:128},hierarchies:{type:"array",items:{type:"object",required:["name"],not:{required:["level","levels"]},errorMessage:{not:"Properties 'level' and 'levels' are mutually exclusive and cannot be used together in a hierarchy item."},properties:{name:{type:"string",minLength:1,maxLength:128},levels:{type:"array",items:{type:"string",minLength:1,maxLength:128},minItems:1,maxItems:1},level:{type:"string",minLength:1,maxLength:128}}}},secondary_attributes:{type:"array",items:{type:"string",minLength:1,maxLength:128}}}}},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}}}}},drillthroughs:{type:"array",items:{type:"object",required:["metrics","unique_name"],properties:{notes:{type:"string",minLength:1},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}},attributes:{type:"array",items:{type:"object",required:["name","dimension"],properties:{name:{type:"string",minLength:1},dimension:{type:"string",minLength:1},relationships_path:{type:"array",items:{type:"string",minLength:1}}}}},unique_name:{type:"string",minLength:1,maxLength:128}}}},aggregates:{type:"array",items:{type:"object",required:["label","unique_name"],properties:{attributes:{type:"array",items:{type:"object",required:[],oneOf:[{required:["dimension","name"],errorMessage:"Missing name prop - please add row_security OR name property"},{required:["row_security"],errorMessage:"Missing row_security prop - please add row_security OR name property"}],properties:{name:{type:"string",minLength:1,maxLength:128},dimension:{type:"string",minLength:1,maxLength:128},row_security:{type:"string",minLength:1,maxLength:128},partition:{type:"string",minLength:1,maxLength:128},distribution:{type:"string",minLength:1},relationships_path:{type:"array",items:{type:"string",minLength:1}}}}},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}},label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:128},caching:{type:"string",enum:["engine-memory"],errorMessage:"must be 'engine-memory'",minLength:1}}}},overrides:{type:"object",additionalProperties:{type:"object",required:["query_name"],properties:{query_name:{type:"string",minLength:1,maxLength:128}}}},dataset_properties:{type:"object",additionalProperties:{type:"object",properties:{allow_aggregates:{type:"boolean"},allow_local_aggs:{type:"boolean"},allow_peer_aggs:{type:"boolean"},allow_preferred_aggs:{type:"boolean"},create_hinted_aggregate:{type:"boolean"}}}}}};var yCe={$id:"https://www.atscale.com/ml/rowSecurity.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"RowSecurity",type:"object",required:["unique_name","object_type","label","dataset","scope","ids_column","id_type","filter_key_column"],properties:{unique_name:{type:"string",minLength:1,maxLength:63},object_type:{const:"row_security"},label:{type:"string",minLength:1,maxLength:128},description:{type:"string"},dataset:{type:"string",minLength:1,maxLength:128},scope:{type:"string",enum:["fact","related","all","fact_only"],errorMessage:"must have a value: 'fact', 'fact_only', 'related' or 'all'"},ids_column:{type:"string",minLength:1},id_type:{type:"string",enum:["user","group"],errorMessage:"must have a value: 'user' or 'group'"},filter_key_column:{type:"string",minLength:1},use_filter_key:{type:"boolean"},secure_totals:{type:"boolean"}}};var UQ=class{validateAML(r){return{isValid:!0,errors:[]}}};var Uoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var vCe={$id:"https://www.atscale.com/ml/compositeModel.schema.json",$schema:"https://json-schema.org/draft/2020-12/schema",title:"CompositeModel",type:"object",required:["object_type","unique_name","label","models"],properties:{object_type:{const:"composite_model"},unique_name:{type:"string",minLength:1,maxLength:63},label:{type:"string",minLength:1,maxLength:128},models:{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:128},uniqueItems:!0},metrics:{type:"array",items:{type:"object",required:["unique_name"],properties:{unique_name:{type:"string",minLength:1,maxLength:128},folder:{type:"string",minLength:1}}}},description:{type:"string",minLength:1},aggregates:{type:"array",items:{type:"object",required:["label","unique_name"],properties:{attributes:{type:"array",items:{type:"object",required:["name","dimension"],properties:{name:{type:"string",minLength:1,maxLength:128},dimension:{type:"string",minLength:1,maxLength:128},partition:{type:"string",minLength:1,maxLength:128},distribution:{type:"string",minLength:1},relationships_path:{type:"array",items:{type:"string",minLength:1}}}}},metrics:{type:"array",items:{type:"string",minLength:1,maxLength:128}},label:{type:"string",minLength:1,maxLength:128},unique_name:{type:"string",minLength:1,maxLength:128},caching:{type:"string",enum:["engine-memory"],errorMessage:"must be 'engine-memory'",minLength:1}}}}}};var Woe=class extends Xy{constructor(i){super(i,vCe);this.schemaValidator=i}};var Voe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var WQ=class extends Xy{};var I4r=(n,r)=>{let i={foundKey:"dimension",object:"undefined unique name"},o=Object.values(dl).reduce((p,_)=>Object.keys(r.from).includes(_)?[...p,_]:Object.keys(r.to).includes(_)?[...p,_]:p,[]),l="";for(let p of o){let _=Pa.hasProps(r.from,p),b=Pa.hasProps(r.to,p);_&&L1.safeParse(r.from[p]).success&&(l=r.from[p],i={foundKey:p,object:l}),b&&L1.safeParse(r.to[p]).success&&(l=r.to[p],i={foundKey:p,object:l})}return o.forEach(p=>{let _=Pa.hasProps(r.from,p),b=L1.safeParse(r.from[p]).success;_&&b&&(l=r.from[p],i={foundKey:p,object:l});let T=Pa.hasProps(r.to,p),E=L1.safeParse(r.to[p]).success;T&&E&&(l=r.to[p],i={foundKey:p,object:l})}),_l.isModel(n.data)?UB.getRelationshipInModelError({object:Array.isArray(i.object)?i.object[0]:i.object,orphanType:i.foundKey}):CUe.getRelationshipInDimensionError({object:Array.isArray(i.object)?i.object[0]:i.object,orphanType:i.foundKey})},bCe=({result:n,orphanRelationships:r=[],file:i})=>{let o=aC.deep(n),l=r.map(_=>I4r(i,_)),p=[...o.errors,...l];return{errors:p,isValid:p.length===0}};var zoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}validateAML(i){let{data:o,...l}=aC.deep(i);if(!Array.isArray(o.relationships))return super.validateAML(i);let p=[],_=[];return o.relationships.forEach(b=>{ki.isOrphanRelation(b)?p.push(b):_.push(b)}),bCe({result:super.validateAML({...l,data:{...o,relationships:_}}),orphanRelationships:p,file:i})}};var Goe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}};var k4r={legacySchemaNotAllowed:()=>"semi_additive Unsupported properties in definition. ('dimension', 'hierarchy', and 'level' are not allowed.)"},Hoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}validateAML(i){let o=super.validateAML(i);if(i.data.semi_additive&&("dimension"in i.data.semi_additive||"hierarchy"in i.data.semi_additive||"level"in i.data.semi_additive)){let l="There should be at least one attribute in the semi-additive. Please define either 'relationships' or 'degenerate_dimensions'.";o.errors=[...o.errors.filter(p=>p.indexOf(l)===-1),k4r.legacySchemaNotAllowed()]}return o}};var Qoe=class extends Xy{constructor(i,o){super(i,o);this.schemaValidator=i;this.jsonSchema=o}validateAML(i){let{data:o,...l}=aC.deep(i);if(!Array.isArray(o.relationships))return super.validateAML(i);let p=[],_=[];return o.relationships.forEach(b=>{Ic.isOrphanRelation(b)?p.push(b):_.push(b)}),bCe({result:super.validateAML({...l,data:{...o,relationships:_}}),orphanRelationships:p,file:i})}};var P4r={model:new Qoe(new _C({allErrors:!0}),gCe),dimension:new zoe(new _C({allErrors:!0}),_Ce),row_security:new WQ(new _C({allErrors:!0}),yCe),dataset:new WQ(new _C({allErrors:!0}),dCe),metric:new Hoe(new _C({allErrors:!0}),mCe),metric_calc:new Goe(new _C({allErrors:!0}),hCe),connection:new Voe(new _C({allErrors:!0}),pCe),catalog:new Uoe(new _C({allErrors:!0}),fCe),composite_model:new Woe(new _C({allErrors:!0})),model_settings:new UQ,global_settings:new UQ},Yoe=class n{constructor(r=P4r){this.objectValidatorMappings=r}static create(){return new n}getValidator(r){return this.objectValidatorMappings[r]}validate(r){let i=Mo.create();return r.forEach(o=>{let l=this.getValidator(o.data.object_type).validateAML(o);l.isValid||l.errors.forEach(p=>i.file(o).addError(p))}),i}};var Koe=class{constructor(r={}){let i={yamlObjectTypeExtractor:new EB,objectValidator:new Jxe,repoParser:new UL,yamlErrorContextUtil:new qk,yamlDegenerateDimensionUtil:new JB};this.dependencies=Object.assign(i,r)}validateRepo(r,i){let o=new Mo,l=this.dependencies.repoParser.parseFolderStructure(r,o),p=this.dependencies.repoParser.extractYamlFiles(l,o);return p=this.dependencies.repoParser.getYamlFilesWithValidObjectType(p,o),o.append(this.validateYamlFiles(p,l,i)),{filesOutput:o.filesOutput,globalOutput:o.globalOutput}}validateYamlFiles(r,i,o=!1){let l=this.dependencies.objectValidator.addValidator(pTe.create(o));return o||l.addValidator(_Te.create()).addRequiredValidator(Yoe.create()).addRequiredValidator(YTe.create()).addRequiredValidator(uCe.create(this.dependencies.yamlErrorContextUtil)).addValidator(Xxe.create()).addValidator(nTe.create()).addValidator(lCe.create()).addValidator(Kxe.create()).addValidator(uTe.create(this.dependencies.yamlDegenerateDimensionUtil)).addValidator(tTe.create(this.dependencies.yamlDegenerateDimensionUtil)).addValidator(dTe.create()),l.validate(r,i)}getYamlFilesWithValidObjectType(r,i){let o=[];return r.forEach(l=>{this.dependencies.yamlObjectTypeExtractor.getType(l,i)&&o.push(l)}),o}};var s$=class extends Error{constructor(r,i){super(r),this.output=i}};var n3=(n,r)=>r(n.data),N4r={isConnectionFile(n){return n3(n,uC.isConnection)},isDatasetFile(n){return n3(n,uC.isDataset)},isDimensionFile(n){return n3(n,uC.isDimension)},isMeasureFile(n){return n3(n,uC.isMetric)},isModelFile(n){return n3(n,uC.isModel)},isCompositeModelFile(n){return n3(n,uC.isCompositeModel)},isMeasureCalcFile(n){return n3(n,uC.isMetricCalc)},isCatalogFile(n){return n3(n,uC.isCatalog)},isGlobalSettingsFile(n){return n3(n,uC.isGlobalSettings)}},WVe=N4r;var Xoe=class n extends Error{static getErrorMessage(r,i,o,l){return`Uuid ${r} detected. Uuid: ${i}.
672
672
  Previous generated chain: "${o.join(" -> ")}".
673
673
  Current generated chain: "${l.join(" -> ")}".`}constructor(r,i,o){super(n.getErrorMessage("collision",r,i,o)),this.uuid=r,this.prevChain=i,this.currentChain=o}},Ml;(function(n){n.Dataset="dataset",n.DatasetIncrementalAgg="datasetIncrementalAgg",n.UDA="uda",n.Dimension="dimension",n.DegenerateDimension="degenerateDimension",n.CalculationGroup="calculationGroup",n.RolePlayRelation="rolePlayRelation",n.Hierarchy="hierarchy",n.LevelAttribute="levelAttribute",n.SecondaryAttribute="secondaryAttribute",n.LevelAlias="levelAlias",n.AttributeKey="attributeKey",n.SortAttributeKey="sortAttributeKey",n.KeyedAttribute="keyedAttribute",n.DimensionEmbeddedRelation="dimensionEmbeddedRelation",n.DrillThrough="drillThrough",n.MeasureCalculation="measureCalculation",n.DimensionCalculation="dimensionCalculation",n.Measure="measure",n.DimensionMeasureAttribute="dimensionMeasureAttribute",n.Attribute="attribute",n.SnowflakeRelationship="snowflakeRelationship",n.Relation="relation",n.RolePlayReference="rolePlayReference",n.KeyRefProps="keyRefProps",n.DimensionLevelParallelPeriod="dimensionLevelParallelPeriod",n.DimensionLevelScdFactEffectiveDateKey="dimensionLevelFactEffectiveDateKey",n.VirtualFilterAttribute="virtualFilterAttribute",n.DimensionLevelScdEffectiveStart="dimensionLevelScdEffectiveStart",n.DimensionLevelScdEffectiveEnd="dimensionLevelScdEffectiveEnd",n.DimensionLevelScdCreatedDate="dimensionLevelScdCreatedDate",n.DimensionLevelScdAsOfDate="dimensionLevelScdAsOfDate",n.DimensionLevelScdIsLatest="dimensionLevelScdIsLatest",n.DimensionLevelScdJoinOnFactEffectiveKey="dimensionLevelScdJoinOnFactEffectiveKey"})(Ml||(Ml={}));var SCe=class n{constructor(r){this.logger=r,this.memory=new Map}static create(r){return new n(r)}static chainsAreTheSame(r,i){return r.length==i.length&&r.every((o,l)=>i[l]===o)}register(r,i){let o=this.memory.get(r);if(o)if(n.chainsAreTheSame(o,i)){let l=Xoe.getErrorMessage("same generation",r,o,i);this.logger.warn(l)}else throw new Xoe(r,o,i);this.memory.set(r,i)}};var O4r="4d2cacb5-5b53-4da4-b120-709089990e91",F4r=n=>jL(n,O4r),R4r=n=>Pa.hasProps(n,"name"),VVe=class n{constructor(r){this.namespaceUuid=r,us.should(z6(r),`Cannote create scoped UuidGenerator. The provided input is not valid uuid: "${r}"`)}fromString(r){return jL(r,this.namespaceUuid)}getNestedScope(r){let i=this.fromString(r);return new n(i)}},a$=class{generateNew(){return DB()}forNamespace(r){let i=R4r(r)?F4r(r.name):r.uuid;return new VVe(i)}fromString(r,i){return this.forNamespace(i).fromString(r)}};var L0=class{constructor(r,i,o,l){this.name=i,this.parentNames=o,this.uuidContext=l,this.uuid=r.fromString(i),this.uuidScope=r.getNestedScope(this.uuid)}getParentNames(){return[...this.parentNames,this.name]}getObjectName(r,i){return`type=${r}&name=${i}`}getUuid(){return this.uuidContext.register(this.uuid,this.getParentNames()),this.uuid}};var V_=class extends L0{};var hC=class extends L0{getVirtualFilterAttribute(){return new V_(this.uuidScope,this.getObjectName(Ml.VirtualFilterAttribute,""),this.getParentNames(),this.uuidContext)}forRolePlay(r){let i=`${r.prefix}_${r.attributeId}`;return new V_(this.uuidScope,this.getObjectName(Ml.RolePlayReference,i),this.getParentNames(),this.uuidContext)}getKeyedAttribute(){return new V_(this.uuidScope,this.getObjectName(Ml.KeyedAttribute,""),this.getParentNames(),this.uuidContext)}getSortAttribute(){return new V_(this.uuidScope,this.getObjectName(Ml.SortAttributeKey,""),this.getParentNames(),this.uuidContext)}getAttributeKey(){return new V_(this.uuidScope,this.getObjectName(Ml.AttributeKey,""),this.getParentNames(),this.uuidContext)}};var DCe=class extends hC{forScdEffectiveStart(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdEffectiveStart,""),this.getParentNames(),this.uuidContext)}forScdEffectiveEnd(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdEffectiveEnd,""),this.getParentNames(),this.uuidContext)}forScdCreatedDate(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdCreatedDate,""),this.getParentNames(),this.uuidContext)}forScdAsOfDate(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdAsOfDate,""),this.getParentNames(),this.uuidContext)}forScdIsLatest(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdIsLatest,""),this.getParentNames(),this.uuidContext)}forScdJoinOnFactEffectiveKey(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdJoinOnFactEffectiveKey,""),this.getParentNames(),this.uuidContext)}forScdFactEffectiveDateKey(){return new hC(this.uuidScope,this.getObjectName(Ml.DimensionLevelScdFactEffectiveDateKey,""),this.getParentNames(),this.uuidContext)}forParallelPeriod(r,i){let o=`${r.level}_${r.key_columns.join("_")}_${i}`;return new V_(this.uuidScope,this.getObjectName(Ml.DimensionLevelParallelPeriod,o),this.getParentNames(),this.uuidContext)}};var xCe=class extends L0{};var VQ=class extends L0{forRolePlay(r){let i=`${r.prefix}_${r.attributeId}`;return new V_(this.uuidScope,this.getObjectName(Ml.RolePlayReference,i),this.getParentNames(),this.uuidContext)}forAttributeKey(){return new V_(this.uuidScope,this.getObjectName(Ml.AttributeKey,""),this.getParentNames(),this.uuidContext)}forAttribute(){return new V_(this.uuidScope,this.getObjectName(Ml.Attribute,""),this.getParentNames(),this.uuidContext)}forQuantileGroupAttribute(){return new V_(this.uuidScope,this.getObjectName(Ml.Attribute,"group"),this.getParentNames(),this.uuidContext)}forQuantileInstanceAttribute(r){return new V_(this.uuidScope,this.getObjectName(Ml.Attribute,`instance_${r}`),this.getParentNames(),this.uuidContext)}};var i3=class extends L0{forRolePlay(r){let i=`${r.prefix}_${r.attributeId}`;return new V_(this.uuidScope,this.getObjectName(Ml.RolePlayReference,i),this.getParentNames(),this.uuidContext)}};var d7=class extends L0{forSnowflakeRelationship(r){let i=`${r.from.dataset}_${r.from.join_columns.join(",")}_${r.to.level}`;return new i3(this.uuidScope,this.getObjectName(Ml.SnowflakeRelationship,i),this.getParentNames(),this.uuidContext)}forCalculationGroup(r){return new V_(this.uuidScope,this.getObjectName(Ml.CalculationGroup,r.unique_name),this.getParentNames(),this.uuidContext)}forHierarchy(r){return new xCe(this.uuidScope,this.getObjectName(Ml.Hierarchy,r.unique_name),this.getParentNames(),this.uuidContext)}forSecondaryAttribute(r){return new hC(this.uuidScope,this.getObjectName(Ml.SecondaryAttribute,r.unique_name),this.getParentNames(),this.uuidContext)}forLevel(r){return new DCe(this.uuidScope,this.getObjectName(Ml.LevelAttribute,r.unique_name),this.getParentNames(),this.uuidContext)}forLevelAlias(r){return new hC(this.uuidScope,this.getObjectName(Ml.LevelAlias,r.unique_name),this.getParentNames(),this.uuidContext)}forEmbeddedRelation(r){return new i3(this.uuidScope,this.getObjectName(Ml.DimensionEmbeddedRelation,r.unique_name),this.getParentNames(),this.uuidContext)}forCalculation(r){return new V_(this.uuidScope,this.getObjectName(Ml.DimensionCalculation,r.unique_name),this.getParentNames(),this.uuidContext)}forMetrical(r){return new VQ(this.uuidScope,this.getObjectName(Ml.DimensionMeasureAttribute,`name=${r.unique_name}calcMethod=${r.calculation_method}`),this.getParentNames(),this.uuidContext)}};var o$=class n{constructor(r){this.normalisedPackageUrl=r}static forPackage(r){return new n(r)}get uuidScope(){return new a$().forNamespace({uuid:qJe.generateNewPredictable(this.normalisedPackageUrl)})}forDimension(r,i,o){return new d7(this.uuidScope,this.getObjectName(o,r),[this.normalisedPackageUrl],i)}getObjectName(r,i){return`type=${r}&name=${i}`}};var TCe=class extends L0{forRegularRelation(r){let i=`${r.to.dimension}_${r.unique_name}`;return new i3(this.uuidScope,this.getObjectName(Ml.Relation,i),this.getParentNames(),this.uuidContext)}forRolePlayRelation(r){let i=`${r.to.dimension}_${r.role_play}`;return new V_(this.uuidScope,this.getObjectName(Ml.RolePlayRelation,i),this.getParentNames(),this.uuidContext)}forMeasure(r){return new VQ(this.uuidScope,this.getObjectName(Ml.Measure,r.unique_name),this.getParentNames(),this.uuidContext)}forPerspective(r){return new V_(this.uuidScope,r,this.getParentNames(),this.uuidContext)}forUDA(r){return new V_(this.uuidScope,this.getObjectName(Ml.UDA,r.unique_name),this.getParentNames(),this.uuidContext)}forDimension(r){return r.metadata.repoUrl?o$.forPackage(r.metadata.repoUrl).forDimension(r.unique_name,this.uuidContext,Ml.DegenerateDimension):new d7(this.uuidScope,this.getObjectName(Ml.DegenerateDimension,r.unique_name),this.getParentNames(),this.uuidContext)}forDrillThrough(r){return new V_(this.uuidScope,this.getObjectName(Ml.DrillThrough,r.unique_name),this.getParentNames(),this.uuidContext)}forCalculation(r){return new V_(this.uuidScope,this.getObjectName(Ml.MeasureCalculation,r.unique_name),this.getParentNames(),this.uuidContext)}};var CCe=class extends L0{forKeyRefProps(r){let i=`${r.id}_${r.keyColumns.join(",")}_${r}`;return new i3(this.uuidScope,this.getObjectName(Ml.KeyRefProps,i),this.getParentNames(),this.uuidContext)}forIncrementalAgg(r){return new V_(this.uuidScope,this.getObjectName(Ml.DatasetIncrementalAgg,r.column),this.getParentNames(),this.uuidContext)}};var ECe=class extends L0{forCube(r){return new TCe(this.uuidScope,r,this.getParentNames(),this.uuidContext)}forDataset(r){return new CCe(this.uuidScope,this.getObjectName(Ml.Dataset,r.unique_name),this.getParentNames(),this.uuidContext)}forDimension(r){return r.metadata.repoUrl?o$.forPackage(r.metadata.repoUrl).forDimension(r.unique_name,this.uuidContext,Ml.Dimension):new d7(this.uuidScope,this.getObjectName(Ml.Dimension,r.unique_name),this.getParentNames(),this.uuidContext)}};var Zoe=class n{constructor(r){this.repoId=r}static forRepo(r){return new n(r)}get uuidScope(){return new a$().forNamespace({uuid:this.repoId})}forProject(r,i){return new ECe(this.uuidScope,r,[this.repoId],SCe.create(i))}};function M4r(n,r){try{new n(r)}catch{return!1}return!0}var ece=class{constructor(){this.dependencies=new Map}register(r,i){this.dependencies.set(r,i)}resolve(r){if(this.dependencies.get(r))return this.dependencies.get(r);throw new Error(`Dependency not found: ${r}`)}registerDecorator(r,i){this.register(r,i)}createDecorator(r,i){let o=this.dependencies.get(r);if(o)return M4r(o,i)?new o(i):o;throw new Error(`Dependency not found: ${r}`)}getSnapshot(){return new Map(this.dependencies)}restoreSnapshot(r){this.dependencies=new Map(r)}},wCe=new ece,s3=new ece;var ACe=class{findXmlLevel(r,i,o,l){let p=us.ensure(r.find(b=>b.name===i),`No dimension with name '${i}'`),_;if(!l)_=us.ensure(p.hierarchies.flatMap(b=>b.levels).find(b=>b.yamlUniqueName===o),`No level '${o}' in dimension '${p.name}'`);else{let b=us.ensure(p.hierarchies.find(T=>T.name===l),`Hierarchy ${l} doesn't exist`);_=us.ensure(b.levels.find(T=>T.yamlUniqueName===o),`No level '${o}' in hierarchy '${b.name}'`)}return _}findDatasetRefByName(r,i){return us.ensure(r.find(o=>o.yamlUniqueName===i),`No dataset references for dataset '${i}'`)}findKeyedAttributeById(r,i){return us.ensure(r.find(l=>l.id===i),`No keyed attribute with an id '${i}'`)}mergeAttributes(...r){return r.reduce((i,o)=>(i.push(...o||[]),i),[])}mergeDimensions(r,i){let o=[];return r&&o.push(...r),i?.dimension&&o.push(...i.dimension),o}findRelationshipsPathId(r,i=[],o=[]){var l;let p=[...i,...o];us.should(!!p.length,`No datasets for relationship ${r}`);let _=p.flatMap(b=>{var T;return((T=b.logical)===null||T===void 0?void 0:T.keyRef)||[]}).find(b=>b.yamlUniqueName===r);return us.ensure((l=_?.refPath)===null||l===void 0?void 0:l.refId,`Key reference for relationship: ${r} not found.`)}};var my=class{constructor(r,i=s3){this.data=r,this.dIContainer=i}};var tce=class extends my{constructor(r){super(r)}addAttribute(r,i){this.data[r]||(this.data[r]=[]),this.data[r].push(i)}addAttributes(r){Object.entries(r).forEach(([i,o])=>{i==="sortKeyedAttribute"&&(i="attributeKey"),i&&o&&this.addAttribute(i,o)})}};var zQ=class{constructor(r=wCe){this.dIContainer=r}};var c$=class extends zQ{getDatasetReference(r,i,o){let l={id:r,yamlUniqueName:i};return o&&(l.properties={allowAggregates:o.allow_aggregates,createHintedAggregate:o.create_hinted_aggregate,aggregateDestinations:this.dIContainer.resolve("XmlProjectFactory").getAggregateDestinations(o)}),l}getKeyReference({id:r,keyColumns:i,isComplete:o,rolePlay:l,refId:p,yamlUniqueName:_},b){o===void 0&&(o=!0);let T=Object.assign(Object.assign({},this.getBasicRefProps(r,o)),{unique:"false",column:i});return _&&(T.yamlUniqueName=_),l?this.getRolePlayKeyReference(T,l,b):(p&&(T.refPath={refId:p}),T)}getAttributeReference(r,i,o=!0){return Object.assign(Object.assign({},this.getBasicRefProps(r,o)),{column:[i]})}getXmlPartitionKeyRef(r,i){return{keyRef:this.getXmlFlatProtoAttributeRef(r,i)}}getXmlPartitionAttributeRef(r,i){return{attributeRef:this.getXmlFlatProtoAttributeRef(r,i)}}getLevelAttributeReference(r,i,o){let l={attributeId:r,yamlUniqueName:i,properties:{}};return o&&(l.properties.equivalentAttributeRef={attributeId:o}),l}getLevelAttributeReferenceRolePlay(r,i){return{refPath:{newRef:{refId:r,refNaming:i}}}}getXmlFlatProtoAttributeRef(r,i){return i?{id:r,referencePath:i}:{id:r}}getBasicRefProps(r,i){return{id:r,complete:i?"true":"false"}}getRolePlayKeyReference(r,i,o){return Object.assign(Object.assign({},r),{refPath:{attributeId:i.attributeId,refId:i.refId||o.forRolePlay(i).getUuid(),refNaming:i.prefix}})}};var hkt={isProject(n){return EO.hasProps(n,"cubes")}};var GQ;(function(n){n.Attribute="attribute",n.AttributeKey="attributeKey",n.KeyedAttribute="keyedAttribute",n.VirtualFilterAttribute="virtualFilterAttributes"})(GQ||(GQ={}));var nE;(function(n){n.Level="level",n.SecondaryAttribute="secondaryAttribute",n.LevelAlias="levelAlias",n.LevelScdEffectiveStart="levelScdEffectiveStart",n.LevelScdEffectiveEnd="levelScdEffectiveEnd",n.LevelScdCreated="levelScdCreated"})(nE||(nE={}));var L4r={levelAliasKeyedAttributeNotFound:"Level alias key attribute do not exist."},j4r={right_open_interval:"right-open",left_open_interval:"left-open",closed:"closed"},zVe=(n,r)=>`factEffectiveDateKey_${n}_${r}`,gkt=({template:n,levelUniqueName:r})=>n.replace("{0}",r),rce=class extends my{constructor(r){super(r),this.dimensionFactory=this.dIContainer.resolve("XmlDimensionFactory"),this.xmlReferenceFactory=this.dIContainer.resolve("XmlReferenceFactory"),this.xmlAttributeFactory=this.dIContainer.resolve("XmlAttributesFactory"),this.xmlSecondaryAttributesDecorator=this.dIContainer.createDecorator("XmlSecondaryAttributesDecorator",this.data)}addLevel(r,i,o,l,p){var _,b,T,E;let k=us.ensure(i.find(De=>De.unique_name===r.unique_name),`Attributes for level ${r.unique_name} Not Found.`),j,z=l.forLevel(r),X=(b=(_=this.data.attributes)===null||_===void 0?void 0:_.keyedAttribute)===null||b===void 0?void 0:b.find(De=>De.name===r.unique_name&&De.dimensionName===o);X?j=X.id:j=this.xmlSecondaryAttributesDecorator.addDimensionalAttributes(k,z,o,nE.Level);let ue=this.dimensionFactory.getLevel(j,k,$B.isLevelHidden(r,k));if(!p)this.addSecondaryAttributes(r,ue,l,o);else{let De=(E=(T=this.data.attributes)===null||T===void 0?void 0:T.attributeKey)===null||E===void 0?void 0:E.find(Je=>Je.yamlUniqueName===r.unique_name);this.addSecondaryAttributes(r,ue,l,o,p,De?.id)}return ki.isLevelFromOneDataset(k)&&k.scd_properties&&this.addSlowlyChangingDimension(ue,o,k,z),ue}addSlowlyChangingDimension(r,i,o,l){var p,_;if(!o.scd_properties)return;let b=us.ensure(r.properties,`Xml properties for level: ${r.yamlUniqueName} are not set`);if(!hkt.isProject(this.data))throw new Error(`Dimension ${i} s degenerate dimension, slowly changing dimension is not allowed to be degenerate dimension`);let T=this.addScdFactEffectiveDateAttributeKey(r,i,l),E=this.addScdEffectiveStartDateKeyedAttribute(i,l,o),k=this.addScdEffectiveEndDateKeyedAttribute(i,l,o),j=this.addScdAsOfDateVirtualFilterAttribute(o,o.scd_properties,l,this.data),z=this.addScdIsLatestVirtualFilterAttribute(o,o.scd_properties,l),X=this.addScdJoinOnFactEffectiveKeyVirtualFilterAttribute(o,o.scd_properties,l);if(b.slowlyChangingDimension={factEffectiveDateKey:{keyRef:T.id},effectiveStartDate:{keyedAttributeRef:E,hasNulls:(p=o.scd_properties.effective_start.has_null_values)!==null&&p!==void 0?p:!0},effectiveEndDate:{keyedAttributeRef:k,hasNulls:(_=o.scd_properties.effective_end.has_null_values)!==null&&_!==void 0?_:!0},effectiveIntervalType:j4r[o.scd_properties.effective_interval_type],asOfDate:{virtualFilterAttributeRef:j.id},isLatest:{virtualFilterAttributeRef:z.id},joinOnFactEffectiveKey:{virtualFilterAttributeRef:X.id}},o.scd_properties.created){let ue=this.addScdCreatedDateKeyedAttribute(i,l,o);b.slowlyChangingDimension.createdDate={keyedAttributeRef:ue}}}getProjectAttributes(){return this.data.attributes||(this.data.attributes={}),this.data.attributes}addScdFactEffectiveDateAttributeKey(r,i,o){let l=this.dIContainer.createDecorator("XmlAttributesDecorator",this.getProjectAttributes()),p=this.xmlAttributeFactory.getScdFactEffectiveAttributeKey(zVe(i,r.yamlUniqueName),o);return l.addAttribute(GQ.AttributeKey,p),p}addScdEffectiveStartDateKeyedAttribute(r,i,o){return this.addScdAttributes(r,i.forScdEffectiveStart(),o,nE.LevelScdEffectiveStart,o.scd_properties.effective_start)}addScdAttributes(r,i,o,l,p){let _={dataset:o.dataset,key_columns:[p.column],label:gkt({template:p.display_name_template,levelUniqueName:o.unique_name}),name_column:p.column,unique_name:`${l}_${o.unique_name}`};return this.xmlSecondaryAttributesDecorator.addDimensionalAttributes(_,i,r,l)}addScdEffectiveEndDateKeyedAttribute(r,i,o){return this.addScdAttributes(r,i.forScdEffectiveEnd(),o,nE.LevelScdEffectiveEnd,o.scd_properties.effective_end)}addScdCreatedDateKeyedAttribute(r,i,o){return this.addScdAttributes(r,i.forScdCreatedDate(),o,nE.LevelScdCreated,o.scd_properties.created)}addScdAsOfDateVirtualFilterAttribute(r,i,o,l){var p,_,b,T;let E=(T=(b=(_=(p=l.datasets.find(k=>k.name===r.dataset))===null||p===void 0?void 0:p.physical)===null||_===void 0?void 0:_.column)===null||b===void 0?void 0:b.find(k=>k.name===i.effective_start.column))===null||T===void 0?void 0:T.type;return this.addScdVirtualFilterAttribute(r,i.as_of_date,E||"DateTime",o.forScdAsOfDate())}addScdIsLatestVirtualFilterAttribute(r,i,o){return this.addScdVirtualFilterAttribute(r,i.is_latest,"Boolean",o.forScdIsLatest())}addScdJoinOnFactEffectiveKeyVirtualFilterAttribute(r,i,o){return this.addScdVirtualFilterAttribute(r,i.join_on_fact_effective_key,"Boolean",o.forScdJoinOnFactEffectiveKey())}addScdVirtualFilterAttribute(r,i,o,l){var p;let _=this.xmlAttributeFactory.getScdVirtualFilterAttribute({name:gkt({template:i.display_name_template,levelUniqueName:r.unique_name}),sqlType:o,visible:(p=i.visible)!==null&&p!==void 0?p:!0},l.getVirtualFilterAttribute());return this.dIContainer.createDecorator("XmlAttributesDecorator",this.getProjectAttributes()).addAttribute(GQ.VirtualFilterAttribute,_),_}addSecondaryAttributes(r,i,o,l,p,_){var b,T,E;let k=[],j=[];(b=r.secondary_attributes)===null||b===void 0||b.forEach(X=>p?j.push(X):k.push(X));let z=k.map(X=>this.xmlReferenceFactory.getLevelAttributeReference(this.xmlSecondaryAttributesDecorator.addDimensionalAttributes(X,o.forSecondaryAttribute(X),l,nE.SecondaryAttribute),X.unique_name));if(k.length&&(i.keyedAttributeRef=[...i.keyedAttributeRef||[],...z]),j.length&&(i.attributeReference||(i.attributeReference=[]),i.attributeReference.push(...j.map(X=>this.xmlSecondaryAttributesDecorator.createMetrical(Object.assign(Object.assign({},X),{column:X.name_column,calculation_method:"enum"}),o,p,_)))),r.aliases){let X=us.ensure((E=(T=this.data.attributes)===null||T===void 0?void 0:T.attributeKey)===null||E===void 0?void 0:E.find(De=>De.yamlUniqueName===r.unique_name),L4r.levelAliasKeyedAttributeNotFound),ue=r.aliases.map(De=>this.xmlSecondaryAttributesDecorator.createLevelAlias(De,X,i.primaryAttribute,o.forLevelAlias(De),l));i.keyedAttributeRef=[...i.keyedAttributeRef||[],...ue]}r.metrics&&(i.attributeReference=r.metrics.map(X=>{if(vQ(X.calculation_method)){let ue=this.xmlAttributeFactory.getAttributeKey(X,o.forMetrical(X).forAttributeKey()),De=this.dIContainer.createDecorator("XmlAttributesDecorator",this.getProjectAttributes()),Je=this.xmlAttributeFactory.createMetricalAttributeKeyRef(ue);return De.addAttribute(GQ.AttributeKey,Je),this.xmlSecondaryAttributesDecorator.createMetrical(X,o,void 0,ue.id)}else return this.xmlSecondaryAttributesDecorator.createMetrical(X,o)}))}};var q4r=(n,r)=>`Cannot find keyed attribute with name: ${n} in dimension with name: ${r}`,B4r=n=>`Cannot find keyed attribute with name: ${n} in row securities`,nce=class extends my{constructor(r){super(r),this.xmlQueries=this.dIContainer.resolve("XmlQueries"),this.xmlReferenceFactory=this.dIContainer.resolve("XmlReferenceFactory"),this.xmlCubeFactory=this.dIContainer.resolve("XmlCubeFactory"),this.cubeActionsFactory=this.dIContainer.resolve("XmlCubeActionsFactory")}addMeasures(r,i,o,l,p,_){r.forEach(b=>{var T,E,k;let j=us.ensure((T=this.data.datasets)===null||T===void 0?void 0:T.find(Je=>Je.yamlUniqueName===b.dataset),"Dataset do not exist."),z=this.getSemiAdditiveLevels(b,o.relationships,p??[],j,l,(E=this.data.dimensions)===null||E===void 0?void 0:E.dimension),X=this.xmlCubeFactory.getMeasure(b,i,z,_),ue=this.dIContainer.createDecorator("XmlDatasetDecorator",j);this.data.attributes||(this.data.attributes={});let De=this.dIContainer.createDecorator("XmlAttributesDecorator",this.data.attributes);De.addAttributes({attribute:X.attribute,attributeKey:X.attributeKey}),(k=X.additionalAttributes)===null||k===void 0||k.forEach(Je=>De.addAttributes({attribute:Je})),ue.addDatasetLogicalReferences(X,i.forMeasure(b))})}addDimensions(r,i,o,l,p){this.dIContainer.createDecorator("XmlDimensionDecorator",this.data).addDimensions(r,i,l,o,p)}addDatasetsReferences(r,i){r.forEach(o=>{this.data.datasets||(this.data.datasets=[]);let l=i?.[o.name],p=new c$().getDatasetReference(o.id,o.name,l);this.data.datasets.push(p)})}addCalculatedMeasureRefs(r,i){let o=[];i.forEach(l=>{let p=r.find(_=>_.name===l.unique_name);p&&o.push({id:p.id,yamlUniqueName:l.unique_name})}),this.data.calculatedMembers||(this.data.calculatedMembers=[]),this.data.calculatedMembers.push(...o)}addActions(r,i,o,l){this.data.actions=this.cubeActionsFactory.getCubeActions(r),this.dIContainer.createDecorator("XmlDrillThroughDecorator",this.data).addDrillThroughs(i,o,Object.assign(Object.assign({},l),{calculationMembersReferences:this.data.calculatedMembers}))}addRelationships(r,i){let o=r.yamlRelationships.filter(Ic.isRegularRelation);[...this.getModelRelationshipsWithRefId(o.filter(_=>_.role_play),i),...o.filter(_=>!_.role_play)].forEach(_=>{this.addRelationship(r,_,i)}),this.addSlowlyChangingDimensions(r,i)}addSlowlyChangingDimensions(r,i){r.yamlRelationships.filter(Ic.isRegularRelation).filter(l=>l.from.scd_column).forEach(l=>{let p=this.getXmlDatasetRef(l),_=this.dIContainer.createDecorator("XmlDatasetDecorator",p),b=zVe(l.to.dimension,l.to.level),T=r.attributeKeys.filter(k=>k.yamlUniqueName===b);us.ensure(T.length!==0,`Could not find attribute-key for the SCD Fact Effective Date Key. Searched metaUniqueName: "${b}"`),us.ensure(T.length===1,`Multiple attribute-keys for the SCD Fact Effective Date Key are found. Searched metaUniqueName: "${b}". Result count: ${T.length}`);let E=T[0];_.addKeyRefToDataset({id:E.id,keyColumns:[l.from.scd_column],isComplete:!1},i.forRegularRelation(l))})}addPartitions(r,i){var o;this.data.properties||(this.data.properties={visible:!1,partitions:[]}),this.data.properties.partitions||(this.data.properties.partitions=[]);let l=this.xmlQueries.mergeAttributes(i,(o=this.data.attributes)===null||o===void 0?void 0:o.keyedAttribute);r.forEach(p=>{var _;let b=l.find(T=>T.name===p.attribute);if(b)return this.addPartition((_=this.data.properties)===null||_===void 0?void 0:_.partitions,b,p.type)})}addAggregates(r,i,o=[],l=[],p=[]){var _;if(!r)return;let b=this.xmlQueries.mergeAttributes(o,(_=this.data.attributes)===null||_===void 0?void 0:_.keyedAttribute);this.data.aggregates=r.map(T=>{var E,k,j,z;let X={attributes:{attributeRef:[]}};if(!((E=T.attributes)===null||E===void 0)&&E.length&&(X=this.mapAggregateAttributes(T.attributes,b,p)),!((k=T.metrics)===null||k===void 0)&&k.length){let ue=this.extractMetricIds(T.metrics,(j=this.data.attributes)===null||j===void 0?void 0:j.attribute,l),De=us.ensure((z=X?.attributes)===null||z===void 0?void 0:z.attributeRef,"There is no attributeRefs");De?.push(...ue)}return this.xmlCubeFactory.getUDA(T,us.ensure(X.attributes,"Aggregate must contain attributes"),i,X.partitionReferences,X.distributionReferences)})}addRelationship(r,i,o){let l=this.getXmlDatasetRef(i),p=this.dIContainer.createDecorator("XmlDatasetDecorator",l);if(i.constraint_translation){let b=this.getXmlKeyRefProps(r,i,i.constraint_translation.level,i.constraint_translation.from_columns);p.addKeyRefToDataset(b,o.forRegularRelation(i))}let _=this.getXmlKeyRefProps(r,i,i.to.level,i.from.join_columns);p.addKeyRefToDataset(_,o.forRegularRelation(i))}getXmlDatasetRef(r){let i=us.ensure(this.data.datasets,`Non-existent datasets for cube '${this.data.name}'`);return this.xmlQueries.findDatasetRefByName(i,r.from.dataset)}addPartition(r,i,o,l){var p,_,b,T,E,k;if(o==="key"||o==="name+key"){let j=(b=(_=(p=l?.attributes)===null||p===void 0?void 0:p.keyRef)===null||_===void 0?void 0:_.find(z=>z.id===i.keyRef))===null||b===void 0?void 0:b.referencePath;r.push(this.xmlReferenceFactory.getXmlPartitionKeyRef(i.keyRef,j))}if(o==="name"||o==="name+key"){let j=(k=(E=(T=l?.attributes)===null||T===void 0?void 0:T.attributeRef)===null||E===void 0?void 0:E.find(z=>z.id===i.id))===null||k===void 0?void 0:k.referencePath;r.push(this.xmlReferenceFactory.getXmlPartitionAttributeRef(i.id,j))}}mapAggregateAttributes(r,i,o){let l={attributes:{attributeRef:[],keyRef:[]},distributionReferences:[],partitionReferences:[]},p=(_,b)=>{b&&(_.referencePath={references:b.map(T=>({id:this.xmlQueries.findRelationshipsPathId(T,this.data.datasets,o)}))})};return r.forEach(_=>{QL(_)&&this.createDimensionalUDA(l,i,_,p),gQ(_)&&this.createRowSecurityUDA(l,i,_,p)}),l}createRowSecurityUDA(r,i,o,l){let _={name:us.ensure(i.find(b=>b.dimensionName===o.row_security),B4r(o.row_security)).name,dimension:o.row_security,partition:o.partition,distribution:o.distribution};this.createDimensionalUDA(r,i,_,l)}createDimensionalUDA(r,i,o,l=()=>{}){var p,_,b,T,E,k;let j=us.ensure(i.find(X=>X.name===o.name&&X.dimensionName===o.dimension),q4r(o.name,o.dimension)),z=[];if(this.addPartition(z,j,"name"),(_=(p=r.attributes)===null||p===void 0?void 0:p.attributeRef)===null||_===void 0||_.push(...z.map(X=>{let ue=us.ensure(X.attributeRef,`There is no attribute with unique name ${X.attributeRef}`);return l(ue,o.relationships_path),ue})),o.partition){let X=[];this.addPartition(X,j,"key"),(T=(b=r.attributes)===null||b===void 0?void 0:b.keyRef)===null||T===void 0||T.push(...X.map(ue=>{let De=us.ensure(ue.keyRef,`There is no attribute with key name ${ue.keyRef}`);return l(De,o.relationships_path),De})),this.addPartition(r.partitionReferences,j,o.partition,r)}if(o.distribution){let X=[];this.addPartition(X,j,"key"),(k=(E=r.attributes)===null||E===void 0?void 0:E.keyRef)===null||k===void 0||k.push(...X.map(ue=>{let De=us.ensure(ue.keyRef,`There is no attribute with key name ${ue.keyRef}`);return l(De,o.relationships_path),De})),this.addPartition(r.distributionReferences,j,o.distribution,r)}}extractMetricIds(r,i,o){if(!i?.length&&!o?.length)return[];let l=i?.filter(_=>r.includes(_.name)).map(_=>({id:_.id}))||[],p=o?.filter(_=>r.includes(_.name)).map(_=>({id:_.id}))||[];return[...l,...p]}getModelRelationshipsWithRefId(r,i){let o=rl.groupBy(r,l=>[l.to.dimension,l.role_play]);return Array.from(o.values()).flatMap(l=>{let p=i.forRolePlayRelation(l[0]).getUuid();return l.map(_=>Object.assign(Object.assign({},_),{refId:p}))})}getSemiAdditiveLevels(r,i,o,l,p,_){var b,T,E,k;if(!r.semi_additive)return[];let j=[];return(T=(b=r.semi_additive)===null||b===void 0?void 0:b.relationships)===null||T===void 0||T.forEach(z=>{if(Array.isArray(z)&&!z.every($e=>{let Ke=i.map(cr=>cr.unique_name).includes($e),ht=p.some(cr=>ki.isEmbeddedRelation(cr)&&cr.unique_name===$e);return Ke||ht}))return;let X=Array.isArray(z)?z[z.length-1]:z,ue=i.find(Je=>Je.unique_name===X)||p.find(Je=>Je.unique_name===X);if(!ue)return;let De=this.generateLevelObject(ue,o,l);De&&j.push(De)}),(k=(E=r.semi_additive)===null||E===void 0?void 0:E.degenerate_dimensions)===null||k===void 0||k.forEach(z=>{if(_?.find(ue=>ue.name===z.name)){let ue=this.xmlQueries.findXmlLevel(_??[],z.name,z.level);if(ue){let De=this.xmlReferenceFactory.getLevelAttributeReference(ue.primaryAttribute,ue.yamlUniqueName);De&&j.push({level:De})}}}),j}generateLevelObject(r,i,o){var l,p,_,b,T,E;if(!r)return;let k=this.xmlQueries.findXmlLevel(i??[],(l=r.to)===null||l===void 0?void 0:l.dimension,(p=r.to)===null||p===void 0?void 0:p.level);if(k){let j,z=this.xmlReferenceFactory.getLevelAttributeReference(k.primaryAttribute,k.yamlUniqueName);if(z){if(r.role_play){let X=(b=(_=o?.logical)===null||_===void 0?void 0:_.keyRef)===null||b===void 0?void 0:b.find(ue=>ue.yamlUniqueName===r.unique_name);X&&(j=this.xmlReferenceFactory.getLevelAttributeReferenceRolePlay((E=(T=X?.refPath)===null||T===void 0?void 0:T.refId)!==null&&E!==void 0?E:"",r.role_play).refPath)}return{level:z,rolePlay:j}}}}getXmlKeyRefProps(r,i,o,l){let p=this.xmlQueries.findXmlLevel(r.dimensions,i.to.dimension,o),_=this.xmlQueries.findKeyedAttributeById(r.keyedAttributes,p.primaryAttribute),b=i.role_play?{attributeId:p.primaryAttribute,prefix:i.role_play,refId:i.refId}:void 0;return{id:_.keyRef,keyColumns:l,isComplete:!1,rolePlay:b,yamlUniqueName:i.unique_name}}};var ICe={notExist:n=>`${n} do not exist.`,providedDatasetType:()=>"To access property physical, the utilized dataset must be of type IXmlDataset"},ice=class extends my{constructor(r){super(r),this.xmlReferenceFactory=this.dIContainer.resolve("XmlReferenceFactory"),this.data.logical=this.data.logical||{attributeRef:[]},this.logical=this.data.logical}addDatasetLogicalReferences(r,i){var o,l,p;let _=r.attributeKey;if(_){let T=us.ensure(_.yamlKeyColumns||((o=r.attribute)===null||o===void 0?void 0:o.yamlColumnName),ICe.notExist("Key column"));typeof T=="string"&&(T=[T]),this.addKeyRefToDataset({id:_.id,keyColumns:T,isComplete:!0},i)}let b=((l=r.attribute)===null||l===void 0?void 0:l.yamlColumnName)||((p=r.keyedAttribute)===null||p===void 0?void 0:p.yamlNameColumn);if(b){let T;r.keyedAttribute&&(T=r.keyedAttribute.id),r.attribute&&(T=r.attribute.id),T=us.ensure(T,ICe.notExist("Attribute ID"));let E=this.xmlReferenceFactory.getAttributeReference(T,b);this.logical.attributeRef.push(E)}if(r.sortKeyedAttribute){let T=us.ensure(r.sortKeyedAttribute.yamlKeyColumns,ICe.notExist("Sort column"));this.logical.keyRef||(this.logical.keyRef=[]);let E={id:r.sortKeyedAttribute.id,keyColumns:T};this.logical.keyRef.push(this.xmlReferenceFactory.getKeyReference(E,i))}}addKeyRefToDataset(r,i){let o=this.xmlReferenceFactory.getKeyReference(r,i);this.logical.keyRef||(this.logical.keyRef=[]),this.logical.keyRef.push(o)}addAlternateToDataset(r,i){let o=us.ensure(Pa.hasProps(this.data,"physical")?this.data:void 0,ICe.providedDatasetType());!r.alternate||!o||(Zl.isAlternateSql(r.alternate)?this.addAlternateSql(o,r.alternate):this.addAlternateTable(o,r.alternate,i))}addIncrementalAgg(r,i){let o=i.forIncrementalAgg(r).getUuid(),l={id:o,keyColumns:[r.column],isComplete:!0};this.addKeyRefToDataset(l,i.forKeyRefProps(l));let p=G6.parse(r.grace_period),_=G6.toSeconds(p);return this.logical.incrementalIndicator={keyRef:{id:o},gracePeriod:_},Object.assign({},l)}addRolePlayToIncrementalAgg(r){var i,o,l,p,_,b;let T=(o=(i=this.logical)===null||i===void 0?void 0:i.keyRef)===null||o===void 0?void 0:o.find(E=>{var k,j,z;return E.id===((z=(j=(k=this.logical)===null||k===void 0?void 0:k.incrementalIndicator)===null||j===void 0?void 0:j.keyRef)===null||z===void 0?void 0:z.id)});if(T){let E=(p=(l=r.logical)===null||l===void 0?void 0:l.keyRef)===null||p===void 0?void 0:p.find(k=>JSON.stringify(k.column)===JSON.stringify(T.column));!((_=E?.refPath)===null||_===void 0)&&_.refId&&this.logical.keyRef&&(T.refPath=E.refPath,T.id=E.id,this.logical.incrementalIndicator=Object.assign(Object.assign({},this.logical.incrementalIndicator),{keyRef:{id:E.id,referencePath:{references:[{id:((b=E.refPath)===null||b===void 0?void 0:b.refId)||""}]}}}))}}addAlternateSql(r,i){r.physical.queries||(r.physical.queries=[]),r.physical.queries.push({alternate:i.type,sql:i.sql})}addAlternateTable(r,i,o){let l=o.get(i.connection_id);r.physical.table||(r.physical.table=[]),r.physical.table.push({schema:l?.schema||"",name:i.table||"",database:l?.database,alternate:i.type})}};var $4r={isCube(n){return Object.getOwnPropertyNames(n).includes("id")}},GVe=$4r;var sce=class extends my{constructor(r){super(r),this.xmlQueries=this.dIContainer.resolve("XmlQueries"),this.dimensionFactory=this.dIContainer.resolve("XmlDimensionFactory"),this.xmlHierarchyDecorator=this.dIContainer.createDecorator("XmlHierarchyDecorator",this.data)}createDimensionSecurityProps(r){return Object.assign({},r)}addDimensions(r,i,o,l,p){var _;let b=r.filter(E=>!this.dimensionExist(E.unique_name)),T=b.map(E=>{let k=o.forDimension(E),j=i.find(ue=>ue.unique_name===E.unique_name),z=j?this.createDimensionSecurityProps(j):void 0,X=this.dimensionFactory.getDimensionContainer({yamlDimension:E,rowSecurityProps:z,dimensionUUID:k.getUuid(),overrides:p});return this.xmlHierarchyDecorator.addHierarchies(E.hierarchies,E.level_attributes,X,k,z),E.calculation_groups&&l&&this.addCalculationGroups(E.calculation_groups,X,l,k),X});GVe.isCube(this.data)?(this.data.dimensions||(this.data.dimensions={dimension:[]}),(_=this.data.dimensions.dimension)===null||_===void 0||_.push(...T)):(this.data.dimensions||(this.data.dimensions=[]),this.data.dimensions.push(...T)),b.forEach(E=>{E.relationships&&this.addDimensionalRelationships(E.relationships,E.unique_name,o.forDimension(E))})}addCalculationGroups(r,i,o,l){r.forEach(p=>{if(!p.calculated_members.length)return;let _=this.dimensionFactory.getCalculationGroup(p,l.forCalculationGroup(p).getUuid()),b=o.addCalculatedMeasures(p.calculated_members,l,i.name);p.calculated_members.forEach((T,E)=>{let k=b.find(j=>j.name===T.unique_name);if(k){let j=this.dimensionFactory.getCalculatedMemberRef(k.id);E===0&&(j.default="true"),_.calculatedMemberRef.push(j)}}),i.calculationGroup||(i.calculationGroup=[]),i.calculationGroup.push(_)})}addDimensionalRelationships(r,i,o){r.forEach(l=>{var p;let _=us.ensure((p=this.data.datasets)===null||p===void 0?void 0:p.find(T=>T.name===l.from.dataset),`Dataset: ${l.from.dataset} doesn't exist`),b=this.dIContainer.createDecorator("XmlDatasetDecorator",_);ki.isRegularRelation(l)&&(l.type==="snowflake"&&b.addKeyRefToDataset({id:this.findXmlLevelAndAttribute(i,l.to.level).keyedAttribute.keyRef,keyColumns:l.from.join_columns,isComplete:!1},o.forSnowflakeRelationship(l)),l.type==="embedded"&&this.createEmbeddedRelationship(l,b,this.findXmlLevelAndAttribute(l.to.dimension,l.to.level).keyedAttribute,i,o))})}createEmbeddedRelationship(r,i,o,l,p){let _=us.ensure(r.from.hierarchy,`Relationship "from" does have a missing hierarchy in dimension: ${l}`),b=us.ensure(r.from.level,`Relationship "from" is missing level. Dimension: ${l}`),T=this.findXmlLevelAndAttribute(l,b,_),E=p.forEmbeddedRelation(r).getUuid();i.addKeyRefToDataset({id:o.keyRef,keyColumns:r.from.join_columns,isComplete:!1,refId:E,yamlUniqueName:r.unique_name},p.forEmbeddedRelation(r)),T.level.keyedAttributeRef||(T.level.keyedAttributeRef=[]);let k=this.dIContainer.resolve("XmlReferenceFactory"),j=k.getLevelAttributeReference(o.id,o.name);j.refId=E,r.role_play&&(j.properties=k.getLevelAttributeReferenceRolePlay(E,r.role_play)),r.m2m&&(j.properties=Object.assign(Object.assign({},j.properties),{multiplicity:!0})),T.level.keyedAttributeRef.push(j)}findXmlLevelAndAttribute(r,i,o){var l;let p=this.xmlQueries.findXmlLevel(this.data.dimensions,r,i,o),_=us.ensure((l=this.data.attributes)===null||l===void 0?void 0:l.keyedAttribute,"KeyedAttributes doesn't exist."),b=this.xmlQueries.findKeyedAttributeById(_,p.primaryAttribute);return{level:p,keyedAttribute:b}}dimensionExist(r){return this.data.dimensions&&!GVe.isCube(this.data)&&this.data.dimensions.some(i=>i.name===r)}};var kCe=class extends my{constructor(r){super(r),this.xmlQueries=this.dIContainer.resolve("XmlQueries"),this.xmlCubeActionsFactory=this.dIContainer.resolve("XmlCubeActionsFactory")}addDrillThroughs(r,i,o){this.data.actions&&!this.data.actions.drillThrough&&(this.data.actions.drillThrough=[]),r?.forEach(l=>{var p,_,b;let T=this.xmlCubeActionsFactory.getDrillThrough(l.unique_name,i.forDrillThrough(l).getUuid());l.metrics.forEach(k=>{var j,z;let X=this.xmlQueries.mergeAttributes((j=o?.projectAttributes)===null||j===void 0?void 0:j.attribute,(z=this.data.attributes)===null||z===void 0?void 0:z.attribute),ue=this.getMetricId(k,X,o?.calculationMembersReferences);this.addAttributeRefToDrillThrough(T,ue)});let E=this.xmlQueries.mergeDimensions(o?.projectDimensions,this.data.dimensions);(p=l.attributes)===null||p===void 0||p.forEach(k=>{if(E.length){let j=this.getAttributeId(k,E);this.addAttributeRefToDrillThrough(T,j,k.relationships_path,o?.projectDatasets)}}),l.notes&&(T.properties={name:l.unique_name,notes:l.notes}),(b=(_=this.data.actions)===null||_===void 0?void 0:_.drillThrough)===null||b===void 0||b.push(T)})}getMetricId(r,i,o){var l,p;let _=(l=i?.find(b=>b.name===r))===null||l===void 0?void 0:l.id;return _||(_=(p=o?.find(b=>b.yamlUniqueName===r))===null||p===void 0?void 0:p.id),_=us.ensure(_,`Metric: ${r} not found.`),_}getAttributeId(r,i){let o=us.ensure(i.find(p=>p.name===r.dimension),`Drill through attribute dimension: ${r.dimension} doesn't exist`),l;return o.hierarchies.forEach(p=>p.levels.forEach(_=>{var b;if(!l){if(_.yamlUniqueName===r.name){l=_.primaryAttribute;return}(b=_.keyedAttributeRef)===null||b===void 0||b.forEach(T=>{if(T.yamlUniqueName===r.name){l=T.attributeId;return}})}})),us.ensure(l,`Attribute id for attribute name: ${r.name}`)}addAttributeRefToDrillThrough(r,i,o,l){let p={id:i};o?.length&&(p.refPath=o.map(_=>us.ensure(this.xmlQueries.findRelationshipsPathId(_,this.data.datasets,l),`Key id reference for ${_} dose't exist.`))),r.participants.attributeRef.push(p)}};var ace=class extends my{constructor(r){super(r),this.dimensionFactory=this.dIContainer.resolve("XmlDimensionFactory"),this.xmlLevelDecorator=this.dIContainer.createDecorator("XmlLevelDecorator",this.data),this.data.attributes||(this.data.attributes={}),this.xmlAttributesDecorator=this.dIContainer.createDecorator("XmlAttributesDecorator",this.data.attributes)}addHierarchies(r,i,o,l,p){let _=r.map(b=>{let T=this.dimensionFactory.getHierarchyContainer(b,l);return T.levels=b.levels.map(E=>this.xmlLevelDecorator.addLevel(E,i,o.name,l,p)),b.levels.forEach(E=>{this.addParallelPeriod(E,T.levels,i,l)}),T});o.hierarchies.push(..._)}addParallelPeriod(r,i,o,l){var p;if(!r.parallel_periods)return;let _=i.find(b=>b.yamlUniqueName===r.unique_name);(p=r.parallel_periods)===null||p===void 0||p.map((b,T)=>{var E;if(b.level){let k=i.find(Ke=>Ke.yamlUniqueName===b.level),z=us.ensure(o.find(Ke=>Ke.unique_name===k?.yamlUniqueName),`Yaml: ${k?.yamlUniqueName} doesn't exist`).dataset,X=us.ensure((E=this.data.datasets)===null||E===void 0?void 0:E.find(Ke=>Ke.name===z),`Dataset: ${z} doesn't exist`),ue=this.dIContainer.createDecorator("XmlDatasetDecorator",X);if(!k)return;let De=l.forLevel(r).forParallelPeriod(b,T).getUuid();this.xmlAttributesDecorator.addAttributes({attributeKey:{id:De,properties:{visible:!0,columns:b.key_columns.length},yamlUniqueName:`We don't care ${De}`}}),ue.addKeyRefToDataset({id:De,keyColumns:b.key_columns},l.forLevel(r));let Je={levelReference:k.primaryAttribute,keyReference:De},$e=us.ensure(_?.properties,"XmlLevel doesn't have properties");$e.parallelPeriods?$e.parallelPeriods.push(Je):$e.parallelPeriods=[Je]}})}};var oce;(function(n){n.CalculatedMemberRefs="calculatedMemberRefs",n.FlatAttributeRef="flatAttributeRef"})(oce||(oce={}));var cce=class extends my{constructor(r){super(r),this.xmlProjectFactory=this.dIContainer.resolve("XmlProjectFactory"),this.xmlQueries=this.dIContainer.resolve("XmlQueries")}addPerspectives(r,i,o){let l=[];return r.forEach(p=>{var _;let b=this.xmlProjectFactory.getPerspective(o.forPerspective(p.unique_name).getUuid(),p,i.id);if(p.dimensions&&(b.flatDimensionRef=this.getFlatDimensions(p.dimensions,i),this.addSecondaryAttributes(p.dimensions,b)),p.metrics){let T=(_=i.attributes)===null||_===void 0?void 0:_.attribute,E=i.calculatedMembers;this.addFlatMetric(p.metrics,b,T,E)}l.push(b)}),l}addSecondaryAttributes(r,i){r?.forEach(o=>{o.secondary_attributes&&o.secondary_attributes.forEach(l=>{var p,_;let b=us.ensure((_=(p=this.data.attributes)===null||p===void 0?void 0:p.keyedAttribute)===null||_===void 0?void 0:_.find(T=>T.name===l),`Keyed attribute with name ${l} does't exist.`);this.addFlatAttribute(i,oce.FlatAttributeRef,b?.id)})})}addFlatMetric(r,i,o,l){r.forEach(p=>{let _=o?.find(T=>T.name===p);if(_)return this.addFlatAttribute(i,oce.FlatAttributeRef,_.id);let b=l?.find(T=>T.yamlUniqueName===p);if(b)return this.addFlatAttribute(i,oce.CalculatedMemberRefs,b.id);us.should(!!_||!!b,`Metric or Calculation ${p} not found.`)})}addFlatAttribute(r,i,o){var l;r[i]||(r[i]=[]),(l=r[i])===null||l===void 0||l.push(this.xmlProjectFactory.getFlatObject(o,!1))}getFlatDimensions(r,i){let o=this.xmlQueries.mergeDimensions(this.data.dimensions,i.dimensions);return r.map(l=>{var p,_,b;let T=us.ensure(o.find(ue=>ue.name===l.name),`Dimension: ${l.name} doesn't exist`),E=!!(!((p=l.hierarchies)===null||p===void 0)&&p.length),k=!!(!((_=l.secondary_attributes)===null||_===void 0)&&_.length),j=!!(!((b=l.relationships_path)===null||b===void 0)&&b.length),z=E||k||j,X=this.xmlProjectFactory.getFlatObject(T.id,z);return E&&(X.flatHierarchyRef=this.addFlatHierarchies(l.hierarchies,T.hierarchies)),l.relationships_path&&(X.flatRefs=this.findRelationshipsRefs(i,l.relationships_path).map(ue=>({id:ue}))),X})}findRelationshipsRefs(r,i){let o=[];return i.forEach(l=>{var p;return(p=r.datasets)===null||p===void 0?void 0:p.forEach(_=>{var b,T,E,k;let j=(k=(E=(T=(b=_.logical)===null||b===void 0?void 0:b.keyRef)===null||T===void 0?void 0:T.find(z=>z.yamlUniqueName===l))===null||E===void 0?void 0:E.refPath)===null||k===void 0?void 0:k.refId;j&&o.push(j)})}),o}addFlatHierarchies(r,i){return r.map(o=>{var l,p;let _=us.ensure(i.find(k=>k.name===o.name),`Hierarchy: ${o.name} doesn't exist`),b=(l=o.level)!==null&&l!==void 0?l:(p=o.levels)===null||p===void 0?void 0:p[0],T=b!==void 0,E=this.xmlProjectFactory.getFlatObject(_.id,T);return T&&(E.flatLevelRef=this.addFlatLevels([b],_.levels)),E})}addFlatLevels(r,i){return r.map(o=>{let l=us.ensure(i.find(p=>p.yamlUniqueName===o),`Level: ${o} doesn't exist`);return this.xmlProjectFactory.getFlatLevel(l.primaryAttribute,!1)})}};var lce=class extends my{constructor(r,i){super(r),this.datasetsProperties=i,this.xmlProjectFactory=this.dIContainer.resolve("XmlProjectFactory"),this.xmlProjectFactory=this.dIContainer.resolve("XmlProjectFactory"),this.yamlQueries=this.dIContainer.resolve("YamlQueries")}addModel(r,i,o){var l,p,_,b,T,E,k,j,z;let X=this.data;X.cubes||(X.cubes=[]);let ue=o.forCube(r.unique_name),De=this.xmlProjectFactory.getCube(r,ue.getUuid()),Je=this.dIContainer.createDecorator("XmlCubeDecorator",De),$e=this.yamlQueries.getMetricsByList(r.metrics,i.measures,!0),Ke=r.dimensions?this.yamlQueries.getModelDimensions(r.dimensions,i.dimensions):[],ht=r.relationships.map(Mn=>Mn.from.dataset),cr=$e.map(Mn=>Mn.dataset),Mr=Ke.map(Mn=>Mn.level_attributes).flat(),jr=Mr.filter(ki.isLevelFromOneDataset).flatMap(({dataset:Mn})=>Mn),ar=Mr.filter(ki.isLevelWithMultipleDatasets).flatMap(({shared_degenerate_columns:Mn})=>Mn).map(({dataset:Mn})=>Mn),_n=new Set([...ht,...cr,...jr,...ar]),rn=X.datasets.filter(Mn=>_n.has(Mn.name)),jn=this.yamlQueries.getAllEmbeddedRelationshipsFromProject(X);Je.addDatasetsReferences(rn,r.dataset_properties);let jt=this.addFoldersToMeasures(r.metrics,$e);if(r.dimensions){let Mn=this.yamlQueries.getModelDimensions(r.dimensions,i.dimensions);Je.addDimensions(Mn,[],this,ue,r.overrides)}let di;if(r.metrics.length&&i.calculations.size){let Mn=this.yamlQueries.getMetricsByList(r.metrics,i.calculations,!0),tr=this.addFoldersToCalcMeasures(r.metrics,Mn),dn=this.addCalculatedMeasures(tr,ue);di=us.ensure(dn,"Calculated Members do not exist."),Je.addCalculatedMeasureRefs(di,tr)}if(!((l=r.relationships)===null||l===void 0)&&l.length&&Je.addRelationships({yamlRelationships:r.relationships,datasets:X.datasets,dimensions:us.ensure(X.dimensions,`The project "${X.name}" does not have any dimensions`),keyedAttributes:us.ensure((p=X.attributes)===null||p===void 0?void 0:p.keyedAttribute,`The project "${X.name}" does not have any keyed attributes`),attributeKeys:((_=X.attributes)===null||_===void 0?void 0:_.attributeKey)||[]},ue),Je.addMeasures(jt,ue,r,jn,X.dimensions,r.overrides),!((b=r.partitions)===null||b===void 0)&&b.length&&Je.addPartitions(r.partitions,(T=X.attributes)===null||T===void 0?void 0:T.keyedAttribute),!((E=r.aggregates)===null||E===void 0)&&E.length&&Je.addAggregates(r.aggregates,ue,(k=X.attributes)===null||k===void 0?void 0:k.keyedAttribute,di,X.datasets),!((j=r.drillthroughs)===null||j===void 0)&&j.length&&Je.addActions(r.include_default_drillthrough||!1,r.drillthroughs,ue,{projectAttributes:X.attributes,projectDimensions:this.data.dimensions,projectDatasets:this.data.datasets}),r.perspectives){let tr=this.dIContainer.createDecorator("XmlPerspectiveDecorator",this.data).addPerspectives(r.perspectives,De,ue);X.perspectives=((z=X.perspectives)!==null&&z!==void 0?z:[]).concat(tr)}return this.addIncrementalAggRolePlayToDatasets(De,X),X.cubes.push(De),X}addIncrementalAggRolePlayToDatasets(r,i){var o;(o=r?.datasets)===null||o===void 0||o.forEach(l=>{var p;let _=i.datasets.find(b=>b.id===l.id);!((p=_?.logical)===null||p===void 0)&&p.incrementalIndicator&&this.dIContainer.createDecorator("XmlDatasetDecorator",_).addRolePlayToIncrementalAgg(l)})}addFoldersToMeasures(r,i){return i.map(l=>{let p=r.find(_=>_.unique_name===l.unique_name);return p?Object.assign(Object.assign({},l),{folder:p.folder}):l})}addFoldersToCalcMeasures(r,i){return i.map(l=>{let p=r.find(_=>_.unique_name===l.unique_name);return p?Object.assign(Object.assign({},l),{folder:p.folder}):l})}addDatasets(r,i,o){return r.length>0&&r.filter(l=>!this.data.datasets.some(p=>p.name===l.unique_name)).forEach(l=>{let p=this.xmlProjectFactory.getDataset(l,i,o,this.datasetsProperties&&this.datasetsProperties[l.unique_name]),_=this.dIContainer.createDecorator("XmlDatasetDecorator",p);if(_.addAlternateToDataset(l,i),l.incremental){let b=o.forDataset(l),T=_.addIncrementalAgg(l.incremental,b);this.data.attributes||(this.data.attributes={}),this.data.attributes.attributeKey||(this.data.attributes.attributeKey=[]),this.data.attributes.attributeKey.push({id:T.id,properties:{description:l.description,visible:!0,columns:1},yamlUniqueName:T.id})}this.data.datasets.push(p)}),this.data}addDimensions(r,i,o){return this.dIContainer.createDecorator("XmlDimensionDecorator",this.data).addDimensions(r,i,o,this),this.data}addCalculatedMeasures(r,i,o){let l=r.map(p=>this.xmlProjectFactory.getCalculatedMeasure(p,i,o));return this.data.calculatedMembers||(this.data.calculatedMembers=[]),this.data.calculatedMembers.push(...l),l}};var J4r={isIXmlDataset(n){return Object.getOwnPropertyNames(n).includes("name")}},ykt=J4r;var uce=class extends my{constructor(r){super(r),this.xmlAttributesFactory=this.dIContainer.resolve("XmlAttributesFactory"),this.xmlReferenceFactory=this.dIContainer.resolve("XmlReferenceFactory"),this.data.attributes||(this.data.attributes={}),this.xmlAttributesDecorator=this.dIContainer.createDecorator("XmlAttributesDecorator",this.data.attributes)}addDimensionalAttributes(r,i,o,l){let p=this.xmlAttributesFactory.getDimensionalAttributes(r,i,o,l),_=us.ensure(p.keyedAttribute,"Keyed Attribute do not exist");return this.xmlAttributesDecorator.addAttributes(p),ki.isLevelFromOneDataset(r)?this.addDataset(r.dataset,p,i):ki.isLevelWithMultipleDatasets(r)&&r.shared_degenerate_columns.forEach(b=>{this.updateXmlAttributesForDataset(p,b),this.addDataset(b.dataset,p,i)}),_.id}updateXmlAttributesForDataset(r,i){r.attributeKey&&(r.attributeKey.yamlKeyColumns=i.key_columns),r.keyedAttribute&&(r.keyedAttribute.yamlNameColumn=i.name_column),r.sortKeyedAttribute&&i.sort_column&&(r.sortKeyedAttribute.yamlKeyColumns=[i.sort_column])}addDataset(r,i,o){var l;let p=(l=this.data.datasets)===null||l===void 0?void 0:l.find(T=>this.isDatasetFound(T,r)),_=us.ensure(p,`Dataset ${r} Not Found.`);this.dIContainer.createDecorator("XmlDatasetDecorator",_).addDatasetLogicalReferences(i,o)}createLevelAlias(r,i,o,l,p){let _=us.ensure(i.yamlKeyColumns,`Yaml key columns: ${i.yamlKeyColumns} do not exist`),b=Object.assign(Object.assign({},r),{key_columns:_});return this.xmlReferenceFactory.getLevelAttributeReference(this.addDimensionalAttributes(b,l,p,nE.LevelAlias),r.unique_name,o)}createMetrical(r,i,o,l){let p=Object.assign(Object.assign({},r),{column:r.column,object_type:"metric"}),_=i.forMetrical(r),b=this.xmlAttributesFactory.getAttribute({metric:p,keyReferenceId:l,security:o,attributeId:_.forAttribute().getUuid()});this.xmlAttributesDecorator.addAttributes({attribute:b});let T=us.ensure(this.data.datasets.find(k=>this.isDatasetFound(k,b.yamlDataset)),`Dataset ${r.dataset} Not Found.`),E=this.dIContainer.createDecorator("XmlDatasetDecorator",T);if(vQ(r.calculation_method)){us.ensure(l,"Metrics with calculation_method Count require an attribute key id");let k={id:l,properties:{visible:!r.is_hidden},yamlUniqueName:`${b.name}_key`};E.addDatasetLogicalReferences({attribute:b,attributeKey:k},i.forMetrical(r))}else E.addDatasetLogicalReferences({attribute:b},i.forMetrical(r));return this.xmlReferenceFactory.getLevelAttributeReference(b.id,b.name)}isDatasetFound(r,i){return ykt.isIXmlDataset(r)?r.name===i:r.yamlUniqueName===i}};var fce=class{getObjectIndexForRowSecurity(r,i){let o=Object.assign({},r),l=new Map(r.dimensions);i.forEach(_=>{l.set(_.unique_name,_)});let p=this.getEmbeddedDimensionSecurityRelationships(l,i);return o.dimensions=p,o}createSecurityDimensions(r){let i=[];return r.forEach(o=>{i.push(this.createIYamlDimensionFromRowSecurity(o))}),i}createIYamlDimensionFromRowSecurity(r){return{unique_name:r.unique_name,label:r.label,object_type:"dimension",hierarchies:[{label:r.label,levels:[{secondary_attributes:[{dataset:r.dataset,is_hidden:!0,label:`${r.unique_name}_attribute_${r.ids_column}`,name_column:r.ids_column,unique_name:`${r.unique_name}_attribute_${r.ids_column}`}],unique_name:`${r.unique_name}_level_${r.ids_column}`}],unique_name:`${r.unique_name} hierarchy`}],level_attributes:[{dataset:r.dataset,key_columns:[r.filter_key_column],label:r.label,name_column:r.filter_key_column,unique_name:`${r.unique_name}_level_${r.ids_column}`,is_hidden:!0}],metadata:r.metadata}}getAllModelRelationships(r){let i=[];return r.forEach(o=>{Ic.isRegularRelation(o)&&i.push(o.to.dimension),Ic.isSecurityRelation(o)&&i.push(o.to.row_security)}),i}createModelSecurityRelationFromSecurityRow(r,i){return Object.assign(Object.assign({},r),{to:{level:i.hierarchies[0].levels[0].unique_name,dimension:i.unique_name}})}getEmbeddedSecurityRelationship(r,i){return Object.assign(Object.assign({},r),{to:{level:i.hierarchies[0].levels[0].unique_name,dimension:i.unique_name},unique_name:`${r.from.dataset}_${i.unique_name}`})}getEmbeddedDimensionSecurityRelationships(r,i){let o=r;return r.forEach(l=>{if(l.relationships){let p=[];l.relationships.forEach(_=>{if(ki.isSecurityRelation(_)){let b=i.find(T=>T.unique_name===_.to.row_security);b?p.push(this.getEmbeddedSecurityRelationship(_,b)):console.log(`Relationship unique name "${_.to.row_security}" does not exist as a row security`)}else p.push(_)}),l.relationships=p}o.set(l.unique_name,l)}),o}getYamlModelForRowSecurity(r,i){let o=Object.assign(Object.assign({},r),{relationships:[]});return r.relationships.forEach(l=>{let p=[];if(Ic.isSecurityRelation(l)){let _=i.find(b=>b.unique_name===l.to.row_security);_?p.push(this.createModelSecurityRelationFromSecurityRow(l,_)):console.log(`Relationship unique name "${l.to.row_security}" does not exist as a row security`)}else p.push(l);o.relationships.push(...p)}),o}};var vkt={"general number":"General Number",standard:"Standard",scientific:"Scientific",fixed:"Fixed",percent:"Percent","general date":"General Date","long date":"Long Date","medium date":"Medium Date","short date":"Short Date","long time":"Long Time","medium time":"Medium Time","short time":"Short Time","yes/no":"Yes/No","true/false":"True/False","on/off":"On/Off"};var PCe="Key reference is missing.",bkt=(n,r={default:!0})=>n===void 0?r.default:n,HVe=n=>Pa.hasProps(n,"folder"),l$=class{constructor(r=vkt){this.formatString=r,this.getOrderingObject=i=>{let o={sortKey:{}};return i?o.sortKey.keyRef={id:i}:(o.sortKey.order="ascending",o.sortKey.value=""),o}}getAttribute({metric:r,overrides:i,keyReferenceId:o,security:l,semiAdditiveLevels:p,attributeId:_}){var b;let T=r.calculation_method==="percentile",E={id:_,name:i&&((b=i[r.unique_name])===null||b===void 0?void 0:b.query_name)||r.unique_name,properties:{type:this.getAggregationType(r.calculation_method,{keyReferenceId:o,unrelatedDimensionsHandling:r.unrelated_dimensions_handling,semiAdditive:r.semi_additive,semiAdditiveLevels:p}),description:r.description,visible:!T,caption:r.label},yamlDataset:r.dataset,yamlColumnName:r.column};return r.is_hidden&&(E.properties.visible=!T&&!r.is_hidden),r.format&&(E.properties.formatting=this.getFormatting(r.format)),r.folder&&(E.properties.folder=r.folder),l&&(E.properties.dynamicConstraint=this.getSecurityDynamicConstraint(l,o)),E}getQuantileGroupAttribute({metric:r,attributeId:i,metricAttributeId:o,metricAttributeName:l}){var p;let _={id:i,name:`${l}_group`,properties:{type:{quantileGroup:{attributeRef:{id:o},compression:((p=r.compression)===null||p===void 0?void 0:p.toString())||"",unrelatedDimensionsHandling:r.unrelated_dimensions_handling}},description:r.description,visible:!1,caption:`${r.label}_group`},yamlDataset:r.dataset,yamlColumnName:r.column};return r.format&&(_.properties.formatting=this.getFormatting(r.format)),r.folder&&(_.properties.folder=r.folder),_}getQuantileInstanceAttribute({metric:r,attributeId:i,metricAttributeName:o,groupAttributeId:l,quantileValue:p}){let _={id:i,name:CQ(o,p),properties:{type:{quantileInstance:{quantileGroupRef:{id:l},quantileVal:p.toString()}},description:r.description,visible:!0,caption:TQ(r.label,p)},yamlDataset:r.dataset,yamlColumnName:r.column};return r.is_hidden&&(_.properties.visible=!r.is_hidden),r.format&&(_.properties.formatting=this.getFormatting(r.format)),r.folder&&(_.properties.folder=r.folder),_}getScdFactEffectiveAttributeKey(r,i){return{id:i.forScdFactEffectiveDateKey().getUuid(),properties:{visible:!0,columns:1},yamlUniqueName:r}}createMetricalAttributeKeyRef(r){return{id:r.id,name:r.name,yamlUniqueName:r.yamlUniqueName,properties:{visible:r.properties.visible,columns:1}}}getScdVirtualFilterAttribute(r,i){return{id:i.getUuid(),name:r.name,sqlType:r.sqlType,properties:{caption:r.name,visible:r.visible}}}getAttributeKey(r,i){let o=[];ki.isLevelWithMultipleDatasets(r)?o=r.shared_degenerate_columns[0].key_columns:o=r.key_columns;let l={id:i.getUuid(),properties:{visible:!r.is_hidden,columns:o?.length,description:r.description},yamlUniqueName:r.unique_name};o&&(l.yamlKeyColumns=o);let p=r.custom_empty_member;return p&&(l.properties.emptyValues={value:p.key}),r.exclude_from_dim_agg&&(l.properties.excludeFromDimensionalAgg=r.exclude_from_dim_agg),r.exclude_from_fact_agg&&(l.properties.excludeFromFactAgg=r.exclude_from_fact_agg),r.format&&(l.properties.formatting=this.getFormatting(r.format)),HVe(r)&&r.folder&&(l.properties.folder=r.folder),l}getAttributeKeySort(r,i){var o;let l;if(ki.isLevelWithMultipleDatasets(r)?l=r.shared_degenerate_columns[0].sort_column:l=r.sort_column,!l)return;let p=this.getAttributeKey(r,i.getSortAttribute());return l&&(p.yamlKeyColumns=[l],p.properties=Object.assign(Object.assign({},p.properties),{columns:1})),p.properties.emptyValues&&(!((o=r.custom_empty_member)===null||o===void 0)&&o.sort_name)&&(p.properties.emptyValues={value:r.custom_empty_member.sort_name}),HVe(r)&&r.folder&&(p.properties.folder=r.folder),p}getKeyedAttribute(r,{dimensionName:i,attributeKeyId:o,sortAttributeKeyId:l},p,_){var b;let T;ki.isLevelWithMultipleDatasets(r)?T=r.shared_degenerate_columns[0].name_column:T=r.name_column;let E={id:p.getKeyedAttribute().getUuid(),keyRef:o,name:r.unique_name,properties:{visible:!r.is_hidden,type:{enum:""},ordering:this.getOrderingObject(l),caption:r.label},yamlNameColumn:T,dimensionName:i};HVe(r)&&r.folder&&(E.properties.folder=r.folder),r.description&&(E.properties.description=r.description),r.exclude_from_dim_agg&&(E.properties.excludeFromDimensionalAgg=r.exclude_from_dim_agg),r.exclude_from_fact_agg&&(E.properties.excludeFromFactAgg=r.exclude_from_fact_agg),!((b=r.custom_empty_member)===null||b===void 0)&&b.name&&(E.properties.emptyValues={value:r.custom_empty_member.name});let k=r.allowed_calcs_for_dma;if(k&&(E.properties.allowedCalculationType={calculationType:k}),r.format&&(E.properties.formatting=this.getFormatting(r.format)),r.is_aggregatable===!1&&(E.properties.isAggregatable=r.is_aggregatable),_===nE.SecondaryAttribute||_===nE.LevelAlias){let j=r;E.properties.isExcelPivotTableProperty=bkt(j.is_excel_pivot_table_property,{default:!0}),E.properties.isUserDefinedProperty=bkt(j.is_user_defined_property,{default:!0})}return E}getDimensionalAttributes(r,i,o,l){var p;let _={};return _.attributeKey=this.getAttributeKey(r,i.getAttributeKey()),_.sortKeyedAttribute=this.getAttributeKeySort(r,i),_.keyedAttribute=this.getKeyedAttribute(r,{attributeKeyId:_.attributeKey.id,sortAttributeKeyId:(p=_?.sortKeyedAttribute)===null||p===void 0?void 0:p.id,dimensionName:o},i,l),_}getAggregationType(r,i){let o={};switch(r){case"sum":case"stddev_samp":case"var_samp":case"stddev_pop":case"var_pop":o.measure={defaultAggregation:r.toUpperCase()};break;case"average":o.measure={defaultAggregation:"AVG"};break;case"maximum":o.measure={defaultAggregation:"MAX"};break;case"minimum":o.measure={defaultAggregation:"MIN"};break;case"count distinct":o.distinctCount={keyReference:{id:us.ensure(i?.keyReferenceId,PCe)},approximate:!1};break;case"estimated count distinct":o.distinctCount={keyReference:{id:us.ensure(i?.keyReferenceId,PCe)},approximate:!0};break;case"sum distinct":o.distinctSum={keyReference:{id:us.ensure(i?.keyReferenceId,PCe)}};break;case"count non-null":o.count={keyReference:{id:us.ensure(i?.keyReferenceId,PCe)}};break;case"percentile":o.measure={defaultAggregation:"SUM"};break;case"enum":o.enum="";break}if(us.should(Object.keys(o).length>0,`Attribute type for "${r}" is not supported`),i?.unrelatedDimensionsHandling&&this.addUnrelatedDimensionsHandling(o,i.unrelatedDimensionsHandling),i?.semiAdditiveLevels){let l=i.semiAdditiveLevels.map(p=>({id:p.level.attributeId,referencePath:p.rolePlay}));this.addSemiAdditive(o,i.semiAdditive,l)}return o}getFormatting(r){let i=r.toLowerCase();return Object.keys(this.formatString).includes(i)?{nameFormat:this.formatString[i]}:{formatString:r}}getCalcMemberFormatting(r,i){let o=Object.assign({},this.getFormatting(r));return i&&(o.useInputMeasureFormat=i),o}getSecurityDynamicConstraint(r,i){let o={properties:{scope:{}}},l=`${r.id_type}Constraint`;if(o[l]={enabled:!0},r.use_filter_key&&i){let p=us.ensure(o[l],`Incorrect dynamicConstraint id type property: ${l}`);p.lookup={keyRef:{id:i}}}return r.scope&&(o.properties.scope[r.scope]={secureTotals:!!r.secure_totals}),o}addUnrelatedDimensionsHandling(r,i){r.measure&&(r.measure.unrelatedDimensions=this.getUnrelatedDimensionsHandling(i)),r.distinctCount&&(r.distinctCount.unrelatedDimensions=this.getUnrelatedDimensionsHandling(i)),r.count&&(r.count.unrelatedDimensions=this.getUnrelatedDimensionsHandling(i))}addSemiAdditive(r,i,o){if(!i)return;let l={first:"FirstNonEmpty",last:"LastNonEmpty",first_child:"FirstChild",last_child:"LastChild"};r.measure&&(r.measure.additivity={subspace:{aggregationFunction:l[i.position],attributeRef:o?.length?o:void 0}})}getUnrelatedDimensionsHandling(r){switch(r){case"empty":return{unrelatedDimensionsEmpty:""};case"error":return{unrelatedDimensionsError:""};case"repeat":return{unrelatedDimensionsRepeat:""}}}};var pce=class{getCubeActions(r){return{properties:{includeDefaultDrillThrough:r.toString()}}}getDrillThrough(r,i){return{id:i,name:r,participants:{attributeRef:[]}}}};var dce=class{getMeasure(r,i,o,l){var p;let _=new l$,b=us.ensure(r.calculation_method,"'calculation_method' do not exist."),T=i.forMeasure(r),E=T.forAttribute().getUuid();if(vQ(b)){let k=_.getAttributeKey(r,T.forAttributeKey());return this.buildXmlMeasureResult({attribute:_.getAttribute({metric:r,keyReferenceId:k.id,overrides:l,attributeId:E,semiAdditiveLevels:o}),attributeKey:k})}else if(b==="percentile"){let k=_.getAttribute({metric:r,semiAdditiveLevels:o,attributeId:E,overrides:l}),j=T.forQuantileGroupAttribute().getUuid(),z=_.getQuantileGroupAttribute({metric:r,attributeId:j,metricAttributeId:k.id,metricAttributeName:k.name}),X=xQ(r),ue=(p=X?.map(De=>{let Je=T.forQuantileInstanceAttribute(De).getUuid();return _.getQuantileInstanceAttribute({metric:r,attributeId:Je,metricAttributeName:k.name,groupAttributeId:z.id,quantileValue:De})}))!==null&&p!==void 0?p:[];return this.buildXmlMeasureResult({attribute:k,additionalAttributes:[z,...ue]})}return this.buildXmlMeasureResult({attribute:_.getAttribute({metric:r,semiAdditiveLevels:o,attributeId:E,overrides:l})})}buildXmlMeasureResult({attribute:r,attributeKey:i,additionalAttributes:o}){let l={attribute:r};return i&&(l.attributeKey=i),o&&(l.additionalAttributes=o),l}getUDA(r,i,o,l,p){let _={id:o.forUDA(r).getUuid(),name:r.unique_name,properties:{name:r.unique_name},attributes:i,distributionReferences:p,partitionReferences:l};return r.caching&&(_.properties.caching={engineMemory:r.caching}),_}};var U4r={yes:"Yes",no:"No",always:"Always"},W4r={year:"TimeYears",halfyear:"TimeHalfYears",quarter:"TimeQuarters",month:"TimeMonths",week:"TimeWeeks",day:"TimeDays",hour:"TimeHours",minute:"TimeMinutes",second:"TimeSeconds",trimester:"TimeTrimester",undefined:"TimeUndefined"},_ce=class{getDimensionContainer(r){var i,o;let{yamlDimension:l,rowSecurityProps:p,overrides:_}=r,b={id:r.dimensionUUID,name:l.is_degenerate&&_&&((i=_[l.unique_name])===null||i===void 0?void 0:i.query_name)||l.unique_name,hierarchies:[],properties:{visible:!p}};return l.description&&((o=b.properties)===null||o===void 0||o.description),l.label&&(b.properties.caption=l.label),l.relationships&&(b.embeddedRelationshipsMetadata=l.relationships.filter(T=>ki.isEmbeddedRelation(T))),l.type==="time"?b.properties.dimensionType="Time":l.type==="standard"&&(b.properties.dimensionType="Other"),b}getHierarchyContainer(r,i){var o;let l={id:i.forHierarchy(r).getUuid(),name:r.unique_name,properties:{visible:!0,caption:r.label,filterEmpty:this.getFilterEmptyXmlValue(r.filter_empty)},levels:[]};r.is_hidden&&(l.properties.visible=!r.is_hidden),r.folder&&(l.properties.folder=r.folder),r.description&&(l.properties.description=r.description);let p=r.default_member;return l.properties.defaultMember=p?{literalMember:p.expression,applyOnlyWhenInQuery:(o=p.apply_only_when_in_query)!==null&&o!==void 0?o:!1}:{allMember:""},l}getCalculatedMemberRef(r){return{id:r}}getCalculationGroup(r,i){let o={id:i,name:r.unique_name,properties:{visible:!r.is_hidden,caption:r.label},calculatedMemberRef:[]};return typeof r.precedence=="number"&&(o.precedence=r.precedence),r.description&&(o.properties.description=r.description),r.folder&&(o.properties.folder=r.folder),o}getLevel(r,i,o){let l={primaryAttribute:r,properties:{visible:!o,uniqueInParent:i.contains_unique_names||!1,partitionRank:ki.isLevelFromOneDataset(i)?i.constraint_translation_rank:void 0},yamlUniqueName:i.unique_name};return l.properties&&i.time_unit&&(l.properties.levelType=W4r[i.time_unit]),l}getFilterEmptyXmlValue(r){let i="always",o=r??i;return us.ensure(U4r[o],`Invalid filter empty value: "${r}"`)}};var Rg;(function(n){n.Current="Current",n.Previous="Previous",n.CurrentVsPrevious="Current vs Previous",n.CurrentVsPreviousPct="Current vs Previous Pct",n.Next="Next",n.CurrentVsNext="Current vs Next",n.CurrentVsNextPct="Current vs Next Pct",n.PctOfParent="Pct of Parent",n.PctOfTotal="Pct of Total",n.LastYear="Last Year",n.CurrentVsLastYear="Current vs Last Year",n.CurrentVsLastYearPct="Current vs Last Year Pct",n.YearToDate="Year to Date",n.QuarterToDate="Quarter to Date",n.MonthToDate="Month to Date",n.MonthMovingAverage3Month="Month Moving Average 3 Month",n.MovingAverage30Period="Moving Average 30 Period",n.MovingAverage5Period="Moving Average 5 Period",n.MovingStdDev30Period="Moving Std Dev 30 Period",n.MovingStdDev5Period="Moving Std Dev 5 Period"})(Rg||(Rg={}));var V4r={Current:"Current",PctOfParent:"Pct of Parent",PctOfTotal:"Pct of Total"},gxn={...V4r,Previous:"Previous",CurrentVsPrevious:"Current vs Previous",CurrentVsPreviousPct:"Current vs Previous Pct",Next:"Next",CurrentVsNext:"Current vs Next",CurrentVsNextPct:"Current vs Next Pct",LastYear:"Last Year",CurrentVsLastYear:"Current vs Last Year",CurrentVsLastYearPct:"Current vs Last Year Pct",YearToDate:"Year to Date",QuarterToDate:"Quarter to Date",MonthToDate:"Month to Date",MonthMovingAverage3Month:"Month Moving Average 3 Month",MovingAverage30Period:"Moving Average 30 Period",MovingAverage5Period:"Moving Average 5 Period",MovingStdDev30Period:"Moving Std Dev 30 Period",MovingStdDev5Period:"Moving Std Dev 5 Period"};var Skt={[Rg.Current]:{description:"The measure's value for the current dimension members in the query.",expression:"([${Dim}].CurrentMember, [Measures].currentMember)",useInputMetricFormat:!0},[Rg.Previous]:{description:"The measure value for the previous dimension member relative to the current dimension member.",expression:"([${Dim}].CurrentMember.prevMember, [Measures].currentMember)",useInputMetricFormat:!0},[Rg.CurrentVsPrevious]:{description:"Current measure value minus the previous Member's measure value.",expression:"([${Dim}].CurrentMember, [Measures].currentMember) - ([${Dim}].CurrentMember.prevMember, [Measures].currentMember)",useInputMetricFormat:!0},[Rg.CurrentVsPreviousPct]:{description:"Current measure value minus the previous Member's measure value expressed as a percent of the Prev value.",expression:"(([${Dim}].CurrentMember, [Measures].currentMember) - ([${Dim}].CurrentMember.prevMember, [Measures].currentMember)) / ([${Dim}].CurrentMember.prevMember, [Measures].currentMember)",defaultFormat:Qh.Percent},[Rg.Next]:{description:"The measure value for the next dimension member relative to the current dimension member.",expression:"([${Dim}].CurrentMember.nextMember, [Measures].currentMember)",useInputMetricFormat:!0},[Rg.CurrentVsNext]:{description:"Current measure value minus the Next Member's measure value.",expression:"([${Dim}].CurrentMember, [Measures].currentMember) - ([${Dim}].CurrentMember.nextMember, [Measures].currentMember)",useInputMetricFormat:!0},[Rg.CurrentVsNextPct]:{description:"Current measure value minus the Next Member's measure value expressed as a percent of the Next value.",expression:"(([${Dim}].CurrentMember, [Measures].currentMember) - ([${Dim}].CurrentMember.nextMember, [Measures].currentMember)) / ([${Dim}].CurrentMember.nextMember, [Measures].currentMember)",defaultFormat:Qh.Percent},[Rg.PctOfParent]:{description:"The measure's value as a percent of the dimension member's total value.",expression:"([${Dim}].CurrentMember, [Measures].currentMember) / ([${Dim}].CurrentMember.parent, [Measures].currentMember)",defaultFormat:Qh.Percent},[Rg.PctOfTotal]:{description:"The measure's value as a percent of the dimension's total value.",expression:"([${Dim}].CurrentMember, [Measures].currentMember) / ([${Dim}].[All], [Measures].currentMember)",defaultFormat:Qh.Percent},[Rg.LastYear]:{description:"Last Year's value for the current dimension member.",expression:"(ParallelPeriod([${Dim}].TimeYears, 1, [${Dim}].CurrentMember), [Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.CurrentVsLastYear]:{description:"Current value minus Last Year's value for the given dimension member.",expression:"(([${Dim}].CurrentMember, [Measures].currentMember) - (ParallelPeriod([${Dim}].TimeYears, 1, [${Dim}].CurrentMember), [Measures].currentMember ))",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.CurrentVsLastYearPct]:{description:"Current value minus Last Year's value for the given dimension member expressed as a percent of Last Year's value.",expression:"(([${Dim}].CurrentMember, [Measures].currentMember) - (ParallelPeriod([${Dim}].TimeYears, 1, [${Dim}].CurrentMember), [Measures].currentMember )) / (ParallelPeriod([${Dim}].TimeYears, 1, [${Dim}].CurrentMember), [Measures].currentMember)",defaultFormat:Qh.Percent,validOnlyForTimeDim:!0},[Rg.YearToDate]:{description:"Year to Date aggregation of [Measures] using each measure's aggregation function. Works for each level of the hierarchy, constraining each member to the set of siblings within the Ancestor Year.",expression:"Aggregate(PeriodsToDate([${Dim}].TimeYears, [${Dim}].CurrentMember),[Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.QuarterToDate]:{description:"Quarter to Date aggregation of [Measures] using each measure's aggregation function. Works for each level of the hierarchy, constraining each member to the set of siblings within the Ancestor Quarter.",expression:"Aggregate(PeriodsToDate([${Dim}].TimeQuarters, [${Dim}].CurrentMember),[Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.MonthToDate]:{description:"Month to Date aggregation of [Measures] using each measure's aggregation function. Works for each level of the hierarchy, constraining each member to the set of siblings within the Ancestor Month.",expression:"Aggregate(PeriodsToDate([${Dim}].TimeMonths, [${Dim}].CurrentMember),[Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.MonthMovingAverage3Month]:{description:"3 Month Moving Average. Works for the Month Level and below.",expression:"Avg(ParallelPeriod([${Dim}].TimeMonths, 2, [${Dim}].CurrentMember):[${Dim}].CurrentMember, [Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.MovingAverage30Period]:{description:"30 Period Moving Average. Periods depend on the level of evaluation. If requested at the Day level, this is a 30 Day Average. At the week level, this is a 30 week average.",expression:"Avg([${Dim}].CurrentMember.Lag(29):[${Dim}].CurrentMember, [Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.MovingAverage5Period]:{description:"5 Period Moving Average. Periods depend on the level of evaluation. If requested at the Day level, this is a 5 Day Average. At the week level, this is a 5 week average.",expression:"Avg([${Dim}].CurrentMember.Lag(4):[${Dim}].CurrentMember, [Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.MovingStdDev30Period]:{description:"30 Period Moving Standard Deviation. Periods depend on the level of evaluation. If requested at the Day level, this is the Stdev of 30 daily records. At the week level, this is the Stdev of 30 weekly records.",expression:"Stdev([${Dim}].CurrentMember.Lag(29):[${Dim}].CurrentMember, [Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0},[Rg.MovingStdDev5Period]:{description:"5 Period Moving Standard Deviation. Periods depend on the level of evaluation. If requested at the Day level, this is the Stdev of 5 daily records. At the week level, this is the Stdev of 5 weekly records.",expression:"Stdev([${Dim}].CurrentMember.Lag(4):[${Dim}].CurrentMember, [Measures].currentMember)",useInputMetricFormat:!0,validOnlyForTimeDim:!0}};function Dkt(n,r){return n.replace(/\${Dim}/g,r)}var xkt="http://www.w3.org/2001/XMLSchema",Tkt="http://www.atscale.com/xsd/project_2_0 ../../../../../core/src/main/resources/com/atscale/engine/schema/project_2_0.xsd",Ckt="http://www.w3.org/2001/XMLSchema-instance";var HQ={getXmlColumnType:{unsupportedConversion:"Unsupported conversion",unsupportedConversionXmlConversion:"Unsupported xml conversion",nonePrecisionTypeWithPrecisionSpec:"Unsupported column type. No exact match."},getDataset:{notFoundConnection:n=>`Cannot build dataset: ${n.unique_name}. Cannot find connection with id ${n.connection_id}`,sqlPropDoesNotExist:n=>`Sql property does not exist on dataset ${n}`},getConnection:{schemaPropDoesNotExist:n=>`Schema property does not exist on connection ${n}`}},mce=class extends zQ{constructor(){super(...arguments),this.getColumn=r=>{var i;let o={name:r.name,type:this.getXmlColumnType(r.data_type)};return r.sql&&(o=Object.assign(Object.assign({},o),{sql:r.sql,sqls:(i=r.dialects)===null||i===void 0?void 0:i.map(this.getXmlSql)})),o},this.columnMappings={int:"Int",decimal:"Decimal",long:"Long",double:"Double",float:"Float",string:"String",datetime:"DateTime",date:"Date",boolean:"Boolean",bigint:"BigInt",tinyint:"TinyInt",number:"Number",timestamp:"TimeStamp",numeric:"Numeric"}}getProjectContainer(r,i){return{projectMetadata:{version:"2.0",schema:xkt,schemaLocation:Tkt,schemaInstance:Ckt},name:i.projectQueryName,annotations:[{name:"migrationVersion",value:"2020.3.0.1"},{name:"engineId",value:i.projectId},{name:"version",value:"version-to-be-generated-on-deploy"}],properties:{caption:i.projectCaption,visible:!0,aggressiveAggregatePromotion:r.aggressive_agg_promotion,aggregatePrediction:{speculativeAggregates:r.build_speculative_aggs},preferredAggregateStores:r.aggregate_store?this.getPreferredAggregateStores(r.aggregate_store):void 0,description:r.description},datasets:[],cubes:[]}}getPreferredAggregateStores(...r){return{aggregateStore:r.map(i=>{var o,l;return{connection:{id:i.as_connection},promotedAggRowCountLimit:(o=i.row_count_limit)===null||o===void 0?void 0:o.toString(),promotedAggsTotalRowCountLimit:(l=i.total_row_count_limit)===null||l===void 0?void 0:l.toString()}})}}getCube(r,i){return{name:r.unique_name,id:i,properties:{description:r.description,caption:r.label,visible:!0}}}getDataset(r,i,o,l){var p;let _=k=>k.filter(Zl.isSimpleColumn).map(this.getColumn),b=us.ensure(i.get(r.connection_id),HQ.getDataset.notFoundConnection(r)),T={id:o.forDataset(r).getUuid(),name:r.unique_name,properties:{allowAggregates:!0},physical:{connection:{id:b.as_connection},immutable:"false",column:_(r.columns)}},E=r.columns.filter(k=>Zl.isMapColumn(k)||Zl.isDerivedColumn(k));if(E.length>0){let k=E.filter(j=>Zl.isMapColumn(j));T.physical.column.push(...k.map(j=>this.getColumn({name:j.name,data_type:"string"}))),T.physical.mapColumns=this.getMapColumns(E)}if(r.table){let k=us.ensure(b.schema,HQ.getConnection.schemaPropDoesNotExist(b.unique_name));T.physical.table=[{schema:k,database:b.database,name:r.table}]}else{let k=us.ensure(r.sql,HQ.getDataset.sqlPropDoesNotExist(r.unique_name)),j=(p=r.dialects)===null||p===void 0?void 0:p.map(this.getXmlSql);T.physical.queries=[{sql:k,sqls:j}]}return r?.immutable&&(T.physical.immutable=r?.immutable.toString()),typeof l?.allow_aggregates=="boolean"&&(T.properties.allowAggregates=l.allow_aggregates,T.properties.aggregateDestinations=this.getAggregateDestinations(l)),T}getCalculatedMeasure(r,i,o){let l=Pa.hasProps(r,"object_type"),_=i.forCalculation(r).getUuid();return l?this.getCalcMeasureFromCalculation(r,_):this.getCalcMeasureFromDimensionCalcMember(r,_,o)}getCalcMeasureFromCalculation(r,i){let o=r.is_hidden===void 0||!r.is_hidden,l={id:i,name:r.unique_name,properties:{visible:o,caption:r.label,description:r.description},expression:r.expression};return r.format&&(l.properties.formatting=this.xmlAttributesFactory.getFormatting(r.format)),r.folder&&(l.properties.folder=r.folder),r.mdx_aggregate_function&&(l.mdxAggregateFunction=r.mdx_aggregate_function),l}getCalcMeasureFromDimensionCalcMember(r,i,o){var l;let p=r.expression;if(r.template){let b=Skt[r.template].expression;if(!o)throw new Error(`Cannot resolve calculation memeber with name "${r.unique_name}", because it's using a template, but the dimenssion name is not provided.`);p=Dkt(b,o)}if(!p)throw new Error(`Coundn't resolve the expression of calculation member with name "${r.unique_name}".`);let _={id:i,name:r.unique_name,properties:{visible:(l=r.is_hidden)!==null&&l!==void 0?l:!0,description:r.description,type:{calculatedDimensionMember:""}},expression:p,visibleInCalculationGroup:!r.is_hidden};return r.format&&(_.properties.formatting=this.xmlAttributesFactory.getCalcMemberFormatting(r.format,r.use_input_metric_format)),_}get xmlAttributesFactory(){return this.dIContainer.resolve("XmlAttributesFactory")}getXmlSql(r){return{dialect:r.dialect,expression:r.sql}}getXmlColumnType(r){let i=p=>`${p}. yaml column type "${r}" is not supported`,o=us.ensure(wx.getColumnTypeFromYaml(r),i(HQ.getXmlColumnType.unsupportedConversion)),l=us.ensure(this.columnMappings[o],i(HQ.getXmlColumnType.unsupportedConversionXmlConversion));return wx.isColumnPrecisionType(o)?r.replace(o,l):(us.should(wx.hasColumnExactMatch(r),i(HQ.getXmlColumnType.nonePrecisionTypeWithPrecisionSpec)),l)}getMapColumns(r){let i=[],o=new Map;return r.forEach(l=>{if(Zl.isMapColumn(l)){let p={name:l.name,delimited:{fieldTerminator:l.map.field_terminator,keyTerminator:l.map.key_terminator,isPrefixed:l.map.is_prefixed||void 0},key:l.map.key_type,value:l.map.value_type,columns:[]};o.set(p.name,p)}Zl.isDerivedColumn(l)&&i.push(l)}),i.forEach(l=>{us.ensure(o.get(l.parent_column),`Parent column: ${l.parent_column} is missing.`).columns.push(this.getColumn(l))}),Array.from(o.values())}getPerspective(r,i,o){return{id:r,name:i.unique_name,cubeRef:o}}getFlatObject(r,i){return{id:r,properties:{visible:i}}}getFlatLevel(r,i){return{primaryAttributeId:r,properties:{visible:i}}}getAggregateDestinations(r){let i={};return typeof r.allow_local_aggs=="boolean"&&(i.allowLocal=r.allow_local_aggs),typeof r.allow_peer_aggs=="boolean"&&(i.allowPeer=r.allow_peer_aggs),typeof r.allow_preferred_aggs=="boolean"&&(i.allowPreferred=r.allow_preferred_aggs),r.allow_aggregates===!1&&(i.allowLocal||(i.allowLocal=!1),i.allowPeer||(i.allowPeer=!1),i.allowPreferred||(i.allowPreferred=!1)),i}};var QVe=n=>(n.register("XmlProjectFactory",new mce),n.register("XmlDimensionFactory",new _ce),n.register("XmlCubeFactory",new dce),n.register("XmlAttributesFactory",new l$),n.register("XmlReferenceFactory",new c$),n.register("XmlCubeActionsFactory",new pce),n.register("RowSecurityFactory",new fce),n),Ekt=n=>(n.register("YamlQueries",new pA),n.register("XmlQueries",new ACe),n),z4r=n=>(n=QVe(n),n=Ekt(n),n.registerDecorator("XmlProjectDecorator",lce),n.registerDecorator("XmlCubeDecorator",nce),n.registerDecorator("XmlDatasetDecorator",ice),n.registerDecorator("XmlDimensionDecorator",sce),n.registerDecorator("XmlAttributesDecorator",tce),n.registerDecorator("XmlDrillThroughDecorator",kCe),n.registerDecorator("XmlHierarchyDecorator",ace),n.registerDecorator("XmlLevelDecorator",rce),n.registerDecorator("XmlSecondaryAttributesDecorator",uce),n.registerDecorator("XmlPerspectiveDecorator",cce),QVe(n),Ekt(n),n);function wkt(){QVe(wCe)}function Akt(){z4r(s3)}var hce=class{constructor(r){wkt(),Akt(),this.logger=r.logger,this.yamlQueries=r.yamlQueries||s3.resolve("YamlQueries"),this.xmlProjectFactory=s3.resolve("XmlProjectFactory"),this.xmlProjectDecorator=s3.resolve("XmlProjectDecorator"),this.rowSecurityFactory=s3.resolve("RowSecurityFactory")}buildProject(r,i){r=pwt(r),r=this.removeHiddenModels(r);let o=this.buildObjectsIndex(r),l=us.ensure(r.find(WVe.isCatalogFile),"Missing catalog settings file. Make sure you have catalog.yml placed in the root folder. It should have object_type: Catalog");return this.buildXmlProject(o,l.data,i)}removeHiddenModels(r){let o=us.ensure(r.find(WVe.isCatalogFile),"Cannot find catalog file").data;if(!o.hidden_models||o.hidden_models.length===0)return r;let l=new Set(o.hidden_models);return r.filter(p=>{let _=l.has(p.data.unique_name);return _&&this.logger.info(`Model "${p.data.unique_name}" is marked as hidden and will not be compiled`),!_})}buildObjectsIndex(r){let i=this.yamlQueries.getYamlFilesWithoutDetachedRelationships(r);return this.yamlQueries.sortYamlModels(i)}buildXmlProject(r,i,o){var l,p;let _=kae.firstDefined((l=o.overrides)===null||l===void 0?void 0:l.catalog_unique_name,i.unique_name),b=kae.firstDefined((p=o.overrides)===null||p===void 0?void 0:p.catalog_caption,i.label);this.logger.info(`Catalog caption: ${b}`),this.logger.info(`Catalog query name: ${_}`);let T=Zoe.forRepo(o.repositoryId).forProject(_,this.logger),E=T.getUuid(),k=this.xmlProjectFactory.getProjectContainer(i,{projectQueryName:_,projectCaption:b,projectId:E});return r.models.forEach(j=>this.buildXmlModel(k,j,r,T,i)),{project:k,projectId:E}}buildXmlModel(r,i,o,l,p){let _=new this.xmlProjectDecorator(r,p.dataset_properties),b=this.rowSecurityFactory.createSecurityDimensions(o.rowSecurity),T=this.rowSecurityFactory.getYamlModelForRowSecurity(i,b),E=this.rowSecurityFactory.getObjectIndexForRowSecurity(o,b),k=this.yamlQueries.getModelDimensions(this.rowSecurityFactory.getAllModelRelationships(i.relationships),E.dimensions),j=i.dimensions?this.yamlQueries.getModelDimensions(i.dimensions,o.dimensions):[],z=[...k,...j],X=this.yamlQueries.getMetricsByList(i.metrics,o.measures,!0),ue=this.yamlQueries.getModelDatasets(E.datasets,z,T.relationships,X);r=_.addDatasets(ue,o.connections,l);let De=this.yamlQueries.getModelRowSecurityList(b.map(Je=>Je.unique_name),E.rowSecurity);_.addDimensions(k,De,l),_.addModel(T,E,l),this.logger.info(`Model ${i.unique_name} has been created`)}};var Fle=_u(I3());var _Ee=class n extends Q6{static create(){let r={tag:n.defaultTag,value:void 0,attributes:[]};return new n(r)}with(r){return super.with(r)}tag(r){return this.with({tag:r})}value(r){return this.with({value:r})}attribute(r,i){return this.with({attributes:[...this.clonedData.attributes,{name:r,value:i}]})}getObj(){let r=this.clonedData,i={"#":r.value};r.attributes.forEach(l=>{i[`@${l.name}`]=l.value});let o={};return o[r.tag]=i,o}};_Ee.defaultTag="not-set";var mD=_Ee;var xC=_u(I3());var IY=_u(I3());var kc={allowEmptyTags:!0},kle=mD.create(),L$=class n{static create(){return new n}flatProtoAttributeRefPath(r){var i;let o=(0,IY.fragment)().ele("ref-path");return r.newRef&&o.ele(kle.tag("new-ref").attribute("attribute-id",r.newRef.attributeId).attribute("ref-id",r.newRef.refId).getObj()).ele({"ref-naming":r.newRef.naming}),(i=r.references)===null||i===void 0||i.forEach(l=>{o.ele(kle.tag("ref").attribute("id",l.id).getObj())}),o.end(kc)}serializeCalculatedMemberFormatting(r){return(0,IY.fragment)().ele({formatting:{"named-format":r.nameFormat,"format-string":r.formatString,"use-input-measure-format":r.useInputMeasureFormat}}).end(kc)}commonVisiblePropertiesTag(r){return(0,IY.fragment)().ele("properties").ele({visible:r.visible,caption:r.caption}).end(kc)}serializeCalculatedMembers(r){let i=(0,IY.fragment)().ele("calculated-members");return r.forEach(o=>i.ele(kle.tag("calculated-member-ref").attribute("id",o.id).attribute("default",o.default).getObj())),i.end(kc)}serializeAttributeAndKeyReferences(r,i){let o=(0,IY.fragment)().ele(r);return i.forEach(l=>{if(l.attributeRef){let p=o.ele(this.attributeRefObj(l.attributeRef.id));l.attributeRef.referencePath&&p.ele(this.flatProtoAttributeRefPath(l.attributeRef.referencePath))}if(l.keyRef){let p=o.ele(this.keyRefObj(l.keyRef.id));l.keyRef.referencePath&&p.ele(this.flatProtoAttributeRefPath(l.keyRef.referencePath))}}),o.end(kc)}attributeRefObj(r){return kle.tag("attribute-ref").attribute("id",r).getObj()}keyRefObj(r){return kle.tag("key-ref").attribute("id",r).getObj()}};var DC=mD.create(),j$=class n{constructor(r){this.helper=r}static create(r){return new n(r)}serializeInput(r){let i=(0,xC.fragment)().ele("attributes");return r.attributeKey&&r.attributeKey.forEach(o=>i.ele(this.serializeAttributeKey(o))),r.keyedAttribute&&r.keyedAttribute.forEach(o=>i.ele(this.serializeKeyedAttribute(o))),r.attribute&&r.attribute.forEach(o=>i.ele(this.serializeAttributeProp(o))),r.virtualFilterAttributes&&r.virtualFilterAttributes.forEach(o=>i.ele(this.serializeVirtualFilterAttribute(o))),i.end(kc)}serializeAttributeKey(r){return(0,xC.fragment)().ele(DC.tag("attribute-key").attribute("id",r.id).attribute("name",r.name).getObj()).ele(this.serializeAttributeKeysProperties(r.properties)).end()}serializeAttributeKeysProperties(r){let i=(0,xC.fragment)().ele("properties");return i.ele({visible:r.visible,caption:r.caption,folder:r.folder,"high-cardinality":r.highCardinality,description:r.description,columns:r.columns}),r.formatting&&i.ele(this.serializeFormatting(r.formatting)),r.excludeFromDimensionalAgg&&i.ele({"exclude-from-dimensional-agg":r.excludeFromDimensionalAgg}),r.excludeFromFactAgg&&i.ele({"exclude-from-fact-agg":r.excludeFromFactAgg}),r.emptyValues&&i.ele("empty-values").ele({value:r.emptyValues.value}),i.end(kc)}serializeKeyedAttribute(r){return(0,xC.fragment)().ele(DC.tag("keyed-attribute").attribute("id",r.id).attribute("key-ref",r.keyRef).attribute("name",r.name).getObj()).ele(this.serializeAttributeProperties(r.properties)).end(kc)}serializeAttributeProperties(r){let i=(0,xC.fragment)().ele("properties");if(i.ele({visible:r.visible,caption:r.caption,folder:r.folder,"high-cardinality":r.highCardinality,unique:r.unique}),r.excludeFromDimensionalAgg&&i.ele({"exclude-from-dimensional-agg":r.excludeFromDimensionalAgg}),r.excludeFromFactAgg&&i.ele({"exclude-from-fact-agg":r.excludeFromFactAgg}),r.emptyValues&&i.ele("empty-values").ele({value:r.emptyValues.value}),r.formatting&&i.ele(this.serializeFormatting(r.formatting)),r.type&&i.ele(this.serializeAttributeType(r.type)),r.ordering&&i.ele(this.serializeAttributeOrdering(r.ordering)),r.description&&i.ele({description:r.description}),r.dynamicConstraint&&i.ele(this.serializeDynamicConstraint(r.dynamicConstraint)),r.allowedCalculationType){let o=i.ele("allowed-calculation-types");r.allowedCalculationType.calculationType.forEach(l=>{o.ele({"calculation-type":l})})}return r.isAggregatable===!1&&i.ele({"is-aggregatable":r.isAggregatable}),wO(r.isUserDefinedProperty)&&i.ele({"is-user-defined-property":r.isUserDefinedProperty}),wO(r.isExcelPivotTableProperty)&&i.ele({"is-excel-pivot-table-property":r.isExcelPivotTableProperty}),i.end(kc)}serializeAttributeOrdering(r){let i=(0,xC.fragment)().ele("ordering").ele("sort-key");return wO(r?.sortKey.order)&&i.ele({order:r.sortKey.order}),wO(r?.sortKey.value)&&i.ele({value:r.sortKey.value}),r?.sortKey.keyRef&&i.ele(this.helper.keyRefObj(r.sortKey.keyRef.id)),i.end(kc)}serializeDynamicConstraint(r){let i=(0,xC.fragment)().ele("dynamic-constraint");if(r.groupConstraint){let o=i.ele(DC.tag("group-constraint").attribute("enabled",r.groupConstraint.enabled).getObj());r.groupConstraint.lookup&&o.ele("lookup").ele(this.helper.keyRefObj(r.groupConstraint.lookup.keyRef.id))}if(r.userConstraint){let o=i.ele(DC.tag("user-constraint").attribute("enabled",r.userConstraint.enabled).getObj());r.userConstraint.lookup&&o.ele("lookup").ele(this.helper.keyRefObj(r.userConstraint.lookup.keyRef.id))}if(r.properties){let o=i.ele("properties").ele("scope");r.properties.scope.all&&o.ele(DC.tag("all").attribute("secure-totals",r.properties.scope.all.secureTotals).getObj()),r.properties.scope.related&&o.ele(DC.tag("related").attribute("secure-totals",r.properties.scope.related.secureTotals).getObj()),r.properties.scope.fact&&o.ele(DC.tag("fact").attribute("secure-totals",r.properties.scope.fact.secureTotals).getObj()),r.properties.scope.fact_only&&o.ele(DC.tag("fact-only").attribute("secure-totals",r.properties.scope.fact_only.secureTotals).getObj())}return i.end(kc)}serializeAttributeProp(r){return(0,xC.fragment)().ele(DC.tag("attribute").attribute("id",r.id).attribute("name",r.name).getObj()).ele(this.serializeAttributeProperties(r.properties)).end(kc)}serializeFormatting(r){return(0,xC.fragment)().ele({formatting:{"named-format":r.nameFormat,"format-string":r.formatString}}).end(kc)}serializeAttributeType(r){var i,o,l;let p=(0,xC.fragment)().ele("type");if(r.count){let _=p.ele("count-nonnull");_.ele(this.helper.keyRefObj(r.count.keyReference.id)),r.count.unrelatedDimensions&&_.ele(this.serializeUnrelatedDimensions(r.count.unrelatedDimensions))}if(wO(r.enum)&&p.ele({enum:r.enum}),r.measure){let _=p.ele("measure");if(_.ele({"default-aggregation":(i=r.measure)===null||i===void 0?void 0:i.defaultAggregation}),!((o=r.measure)===null||o===void 0)&&o.additivity){let b=_.ele("additivity").ele("subspace");b.ele({"aggregation-function":r.measure.additivity.subspace.aggregationFunction}),!((l=r.measure.additivity.subspace.attributeRef)===null||l===void 0)&&l.length&&r.measure.additivity.subspace.attributeRef.forEach(T=>{var E;let k=b.ele(this.helper.attributeRefObj(T.id));T.referencePath&&(!((E=T.referencePath.newRef)===null||E===void 0)&&E.refId)&&k.ele("ref-path").ele(DC.tag("ref").attribute("id",T.referencePath.newRef.refId).getObj())})}r.measure.unrelatedDimensions&&_.ele(this.serializeUnrelatedDimensions(r.measure.unrelatedDimensions))}if(r.distinctCount){let _=p.ele("count-distinct");_.ele(this.helper.keyRefObj(r.distinctCount.keyReference.id)),_.ele({approximate:r.distinctCount.approximate}),r.distinctCount.unrelatedDimensions&&_.ele(this.serializeUnrelatedDimensions(r.distinctCount.unrelatedDimensions))}if(r.distinctSum){let _=p.ele("sum-distinct");_.ele(this.helper.keyRefObj(r.distinctSum.keyReference.id)),r.distinctSum.unrelatedDimensions&&_.ele(this.serializeUnrelatedDimensions(r.distinctSum.unrelatedDimensions))}if(r.quantileGroup&&p.ele(this.serializeQuantileGroup(r.quantileGroup)),r.quantileInstance){let _=p.ele("quantile-instance");_.ele(DC.tag("quantile-group-ref").attribute("id",r.quantileInstance.quantileGroupRef.id).getObj()),_.ele(DC.tag("quantile-val").value(r.quantileInstance.quantileVal).getObj())}return p.end(kc)}serializeUnrelatedDimensions(r){let i={"unrelated-dimensions":{"unrelated-dimensions-error":r?.unrelatedDimensionsError,"unrelated-dimensions-empty":r?.unrelatedDimensionsEmpty,"unrelated-dimensions-repeat":r?.unrelatedDimensionsRepeat}};return(0,xC.fragment)().ele(i).end(kc)}serializeQuantileGroup(r){let i=(0,xC.fragment)().ele("quantile-group");return r.attributeRef&&i.ele(this.helper.attributeRefObj(r.attributeRef.id)),r.compression&&i.ele(DC.tag("compression").value(r.compression).getObj()),i.end(kc)}serializeVirtualFilterAttribute(r){return(0,xC.fragment)().ele(DC.tag("virtual-filter-attribute").attribute("id",r.id).attribute("name",r.name).attribute("sql-type",r.sqlType).getObj()).ele(this.serializeAttributeKeysProperties(r.properties)).end(kc)}};var FHe=_u(I3());var mEe=mD.create(),Ple=class n{constructor(r){this.helper=r}static create(r){return new n(r)}serializeInput(r){let i=(0,FHe.fragment)().ele("calculated-members");return r.forEach(o=>{let l=i.ele(mEe.tag("calculated-member").attribute("id",o.id).attribute("name",o.name).getObj());o.properties&&l.ele(this.serializeProperties(o.properties)),o.expression&&l.ele(mEe.tag("expression").value(o.expression).getObj()),o.properties.type&&o.visibleInCalculationGroup===!1&&l.ele(mEe.tag("visible-in-calculation-group").value(o.visibleInCalculationGroup).getObj()),o.mdxAggregateFunction&&l.ele(mEe.tag("mdx-aggregate-function").value(o.mdxAggregateFunction).getObj())}),i.end(kc)}serializeProperties(r){let i=(0,FHe.fragment)().ele("properties");return i.ele({caption:r.caption,visible:r.visible,description:r.description,folder:r.folder}),r.formatting&&i.ele(this.helper.serializeCalculatedMemberFormatting(r.formatting)),r.type&&i.ele({type:{"calculated-dimension-member":r.type.calculatedDimensionMember}}),i.end(kc)}};var P3=_u(I3());var k3=_u(I3());var J1=mD.create(),q$=class n{constructor(r,i){this.helper=r,this.attributeSerializer=i}static create(r,i){return new n(r,i)}serializeInput(r){let i=(0,k3.fragment)().ele("data-sets");return r.forEach(o=>{let l=i.ele(J1.tag("data-set").attribute("id",o.id).attribute("name",o.name).attribute("schema",o.schema).getObj());o.properties&&l.ele(this.serializeDatasetProperties(o.properties)),o.physical&&l.ele(this.serializePhysical(o.physical)),o.logical&&l.ele(this.serializeLogical(o.logical)),o.attributes&&this.attributeSerializer.serializeInput(o.attributes)}),i.end(kc)}serializeDatasetProperties(r){let i=(0,k3.fragment)().ele("properties");if(i.ele({"allow-aggregates":r.allowAggregates,invariant:r.invariant}),r.aggregateLocality){let o=i.ele("aggregate-locality");r.aggregateLocality.managed&&o.ele("managed"),r.aggregateLocality.collocated&&o.ele("collocated")}return r.aggregateDestinations&&Object.keys(r.aggregateDestinations).length>0&&i.ele(this.serializeAggDestinations(r.aggregateDestinations)),i.end(kc)}serializeAggDestinations(r){let i=(0,k3.fragment)().ele("aggregate-destinations"),{allowLocal:o,allowPeer:l,allowPreferred:p}=r,_={"allow-local":o,"allow-peer":l,"allow-preferred":p};return i.ele(_),i.end(kc)}serializePhysical(r){var i,o,l,p;let _=(0,k3.fragment)().ele("physical");_.ele(J1.tag("connection").attribute("id",r.connection.id).getObj()),r.udf&&_.ele({udf:r.udf}),(i=r.table)===null||i===void 0||i.forEach(T=>{let E=_.ele(J1.tag("table").attribute("alternate",T.alternate).getObj());T.database&&E.ele({database:T.database}),E.ele({schema:T.schema}),E.ele({name:T.name})});let b=T=>J1.tag("sql").attribute("dialect",T.dialect).value(T.expression).getObj();return(o=r.queries)===null||o===void 0||o.forEach(T=>{var E;let k=_.ele(J1.tag("query").attribute("alternate",T.alternate).getObj());T.sql&&k.ele({sql:T.sql}),(E=T.sqls)===null||E===void 0||E.forEach(j=>k.ele(b(j)))}),_.ele({immutable:r.immutable}),(l=r.column)===null||l===void 0||l.forEach(T=>{_.ele(this.serializeColumn(T))}),(p=r.mapColumns)===null||p===void 0||p.forEach(T=>{_.ele(this.serializeMapColumn(T))}),r.virtualDataset&&_.ele({"virtual-dataset":r.virtualDataset}),_.end(kc)}serializeColumn(r){var i;let o=(0,k3.fragment)().ele("column");return o.ele({name:r.name}),o.ele({sql:r.sql}),(i=r.sqls)===null||i===void 0||i.forEach(l=>o.ele(J1.tag("sql").attribute("dialect",l.dialect).value(l.expression).getObj())),o.ele({type:r.type}),o.end(kc)}serializeMapColumn(r){var i;let o=(0,k3.fragment)().ele("map-column");o.ele(J1.tag("name").value(r.name).getObj());let l=J1.tag("delimited");r.delimited.isPrefixed?l=l.attribute("prefixed",r.delimited.isPrefixed).getObj():l=l.getObj();let p=o.ele(l);p.ele(J1.tag("field-terminator").value(r.delimited.fieldTerminator).getObj()),p.ele(J1.tag("key-terminator").value(r.delimited.keyTerminator).getObj()),o.ele("map-key").ele(J1.tag("type").value(r.key).getObj()),o.ele("map-value").ele(J1.tag("type").value(r.value).getObj());let T=o.ele("columns");return(i=r.columns)===null||i===void 0||i.forEach(E=>{T.ele(this.serializeColumn(E))}),o.end(kc)}serializeLogical(r){var i,o;let l=(0,k3.fragment)().ele("logical");if((i=r.keyRef)===null||i===void 0||i.forEach(p=>{l.ele(this.serializeLogicalKeyRef(p))}),(o=r.attributeRef)===null||o===void 0||o.forEach(p=>{var _;let b=l.ele(J1.tag("attribute-ref").attribute("id",p.id).attribute("complete",p.complete).getObj());(_=p.column)===null||_===void 0||_.forEach(T=>b.ele({column:T}))}),r.incrementalIndicator){let p=l.ele("incremental-indicator");if(r.incrementalIndicator.keyRef){let{keyRef:_}=r.incrementalIndicator,b=p.ele(J1.tag("key-ref").attribute("id",_.id).getObj());_.referencePath&&b.ele(this.helper.flatProtoAttributeRefPath(_.referencePath))}if(r.incrementalIndicator.attributeRef){let{attributeRef:_}=r.incrementalIndicator,b=p.ele(this.helper.attributeRefObj(_.id));_.referencePath&&b.ele(this.helper.flatProtoAttributeRefPath(_.referencePath))}p.ele({"grace-period":r.incrementalIndicator.gracePeriod})}return l.end(kc)}serializeLogicalKeyRef(r){var i,o;let l=J1.tag("key-ref").attribute("id",r.id).attribute("unique",r.unique).attribute("complete",r.complete).getObj(),p=(0,k3.fragment)().ele(l);if(r.refPath){let _=p.ele("ref-path");r.refPath.refId&&!r.refPath.attributeId?_.ele(J1.tag("ref").attribute("id",r.refPath.refId).getObj()):_.ele(J1.tag("new-ref").attribute("attribute-id",r.refPath.attributeId).attribute("ref-id",r.refPath.refId).getObj()).ele({"ref-naming":r.refPath.refNaming}),(i=r.refPath.references)===null||i===void 0||i.forEach(b=>_.ele(J1.tag("ref").attribute("id",b.id).getObj()))}return(o=r.column)===null||o===void 0||o.forEach(_=>p.ele({column:_})),p.end(kc)}};var lE=_u(I3());var Wb=mD.create(),B$=class n{constructor(r){this.helper=r}static create(r){return new n(r)}serializeInput(r){let i=(0,lE.fragment)().ele("dimensions");return r.forEach(o=>{i.ele(this.serializeDimension(o))}),i.end()}serializeDimension(r){let i=(0,lE.fragment)().ele(Wb.tag("dimension").attribute("id",r.id).attribute("name",r.name).getObj());return r.properties&&i.ele(this.serializeProperties(r.properties)),r.hierarchies&&r.hierarchies.forEach(o=>{i.ele(this.serializeHierarchy(o))}),r.calculationGroup&&r.calculationGroup.length>0&&i.ele(this.serializeCalculationGroup(r.calculationGroup)),r.modelerMetadata&&i.ele({"modeler-metadata":{"global-id":r.modelerMetadata.globalId,version:r.modelerMetadata.version,modified:r.modelerMetadata.modified}}),i.end(kc)}serializeCalculationGroup(r){let i=(0,lE.fragment)();return r.forEach(o=>{let l=(0,lE.fragment)().ele(Wb.tag("calculation-group").attribute("name",o.name).attribute("id",o.id).attribute("precedence",o.precedence).getObj());o.properties&&l.ele({properties:{caption:o.properties.caption,visible:o.properties.visible,description:o.properties.description,folder:o.properties.folder}}),o.calculatedMemberRef&&l.ele(this.helper.serializeCalculatedMembers(o.calculatedMemberRef)),i.ele(l.end(kc))}),i.end(kc)}serializeProperties(r){let i=(0,lE.fragment)();return i.ele({properties:{visible:r.visible,description:r.description,caption:r.caption,"dimension-type":r.dimensionType,name:r.name,folder:r.folder}}),i.end(kc)}serializeLevel(r){var i,o,l,p,_;let b=(0,lE.fragment)().ele(Wb.tag("level").attribute("primary-attribute",r.primaryAttribute).getObj());if(r.properties){let T=b.ele({properties:{"unique-in-parent":(i=r.properties)===null||i===void 0?void 0:i.uniqueInParent,visible:(o=r.properties)===null||o===void 0?void 0:o.visible,caption:(l=r.properties)===null||l===void 0?void 0:l.caption,"level-type":(p=r.properties)===null||p===void 0?void 0:p.levelType,"ref-naming":(_=r.properties)===null||_===void 0?void 0:_.refNaming,"partition-rank":r.properties.partitionRank}});r.properties.parallelPeriods&&T.ele(this.serializeParallelPeriods(r.properties.parallelPeriods)),r.properties.slowlyChangingDimension&&T.ele(this.serializeSlowlyChangingDimensionProps(r.properties.slowlyChangingDimension))}return r.keyedAttributeRef&&r.keyedAttributeRef.forEach(T=>{b.ele(this.serializeLevelKeyedAttribute(T))}),r.attributeReference&&r.attributeReference.forEach(T=>{b.ele(this.serializeLevelAttributeRef(T))}),b.end(kc)}serializeSlowlyChangingDimensionProps(r){let i=(0,lE.fragment)().ele("slowly-changing-dimension");i.ele(Wb.tag("fact-effective-date-key").attribute("key-ref",r.factEffectiveDateKey.keyRef).getObj());let o=Wb.tag("effective-start-date").attribute("keyed-attribute-ref",r.effectiveStartDate.keyedAttributeRef);r.effectiveStartDate.hasNulls!==void 0&&(o=o.attribute("has-nulls",r.effectiveStartDate.hasNulls)),i.ele(o.getObj());let l=Wb.tag("effective-end-date").attribute("keyed-attribute-ref",r.effectiveEndDate.keyedAttributeRef);return r.effectiveEndDate.hasNulls!==void 0&&(l=l.attribute("has-nulls",r.effectiveEndDate.hasNulls)),i.ele(l.getObj()),i.ele(Wb.tag("effective-interval-type").value(r.effectiveIntervalType).getObj()),r.createdDate&&i.ele(Wb.tag("created-date").attribute("keyed-attribute-ref",r.createdDate.keyedAttributeRef).getObj()),i.ele(Wb.tag("as-of-date").attribute("virtual-filter-attribute-ref",r.asOfDate.virtualFilterAttributeRef).getObj()),i.ele(Wb.tag("is-latest").attribute("virtual-filter-attribute-ref",r.isLatest.virtualFilterAttributeRef).getObj()),i.ele(Wb.tag("join-on-fact-effective-key").attribute("virtual-filter-attribute-ref",r.joinOnFactEffectiveKey.virtualFilterAttributeRef).getObj()),i.end({allowEmptyTags:!1})}serializeParallelPeriods(r){let i=(0,lE.fragment)().ele("parallel-periods");return r.forEach(o=>{i.ele(Wb.tag("parallel-period").attribute("level-ref",o.levelReference).attribute("key-ref",o.keyReference).getObj())}),i.end(kc)}serializeLevelAttributeRef(r){let i=(0,lE.fragment)().ele(Wb.tag("attribute-ref").attribute("attribute-id",r.attributeId).attribute("complete",r.complete).attribute("unique",r.unique).getObj());return r.columns&&r.columns.forEach(o=>{i.ele({column:o})}),r.properties&&i.ele(this.serializeAttributesRefProperties(r.properties)),i.end(kc)}serializeAttributesRefProperties(r){var i,o;let l=(0,lE.fragment)().ele("properties");return r.refPath&&l.ele("ref-path").ele(Wb.tag("new-ref").attribute("ref-id",r.refPath.newRef.refId).getObj()).ele({"ref-naming":r.refPath.newRef.refNaming}),r.multiplicity&&l.ele("multiplicity").ele({"multi-valued":!0}),!((i=r.equivalentAttributeRef)===null||i===void 0)&&i.attributeId&&l.ele(Wb.tag("equivalent-attribute-ref").attribute("attribute-id",(o=r.equivalentAttributeRef)===null||o===void 0?void 0:o.attributeId).getObj()),l.ele({"date-filter":r.dateFilter,"ref-naming":r.naming}),l.end(kc)}serializeLevelKeyedAttribute(r){let i=(0,lE.fragment)().ele(Wb.tag("keyed-attribute-ref").attribute("attribute-id",r.attributeId).attribute("ref-id",r.refId).getObj());return r.properties&&i.ele(this.serializeAttributesRefProperties(r.properties)),i.end(kc)}serializeHierarchy(r){var i,o,l;let _=(0,lE.fragment)().ele(Wb.tag("hierarchy").attribute("id",r.id).attribute("name",r.name).getObj()),b=_.ele("properties");return b.ele({caption:r.properties.caption,visible:r.properties.visible,folder:r.properties.folder,description:r.properties.description,"filter-empty":r.properties.filterEmpty}),r.properties.defaultMember&&b.ele({"default-member":{"all-member":(i=r.properties.defaultMember)===null||i===void 0?void 0:i.allMember,"literal-member":(o=r.properties.defaultMember)===null||o===void 0?void 0:o.literalMember,"apply-only-when-in-query":(l=r.properties.defaultMember)===null||l===void 0?void 0:l.applyOnlyWhenInQuery}}),r.levels.forEach(T=>{_.ele(this.serializeLevel(T))}),_.end({allowEmptyTags:!0})}};var kY=mD.create(),Nle=class n{constructor(r={}){this.helper=r.helper||L$.create(),this.attributeSerializer=r.attributeSerializer||j$.create(this.helper),this.dimensionSerializer=r.dimensionSerializer||B$.create(this.helper),this.datasetSerializer=r.datasetSerializer||q$.create(this.helper,this.attributeSerializer)}static create(r={}){return new n(r)}serializeInput(r){let i=(0,P3.fragment)().ele("cubes");return r.forEach(o=>{let l=i.ele(kY.tag("cube").attribute("id",o.id).attribute("name",o.name).getObj());if(o.properties&&l.ele(this.serializeCubeProperties(o.properties)),o.attributes&&l.ele(this.attributeSerializer.serializeInput(o.attributes)),o.dimensions&&l.ele(this.serializeCubeDimensions(o.dimensions)),o.actions&&l.ele(this.serializeCubeActions(o.actions)),o.datasets&&l.ele(this.serializeCubeDatasets(o.datasets)),o.calculatedMembers&&l.ele(this.helper.serializeCalculatedMembers(o.calculatedMembers)),o.aggregates){let p=l.ele("aggregates");o.aggregates.forEach(_=>p.ele(this.serializeAggregate(_)))}}),i.end(kc)}serializeCubeDatasets(r){let i=(0,P3.fragment)().ele("data-sets");return r.forEach(o=>{let l=i.ele(kY.tag("data-set-ref").attribute("id",o.id).getObj());o.properties&&l.ele(this.serializeCubeDatasetsProperties(o.properties)),o.logical&&l.ele(this.datasetSerializer.serializeLogical(o.logical))}),i.end(kc)}serializeCubeDatasetsProperties(r){let i=(0,P3.fragment)().ele("properties"),o={"allow-aggregates":r.allowAggregates,"create-hinted-aggregate":r.createHintedAggregate};return i.ele(o),r.aggregateDestinations&&Object.keys(r.aggregateDestinations).length>0&&i.ele(this.datasetSerializer.serializeAggDestinations(r.aggregateDestinations)),i.end(kc)}serializeCubeDimensions(r){let i=(0,P3.fragment)().ele("dimensions");return r.dimensionReferences&&r.dimensionReferences.forEach(o=>{i.ele(kY.tag("dimension-ref").attribute("id",o.id).getObj())}),r.dimension&&r.dimension.forEach(o=>{i.ele(this.dimensionSerializer.serializeDimension(o))}),i.end(kc)}serializeCubeProperties(r){let i=(0,P3.fragment)().ele("properties");return i.ele({name:r.name,caption:r.caption,visible:r.visible,description:r.description,notes:r.notes}),r.partitions&&i.ele(this.helper.serializeAttributeAndKeyReferences("partitions",r.partitions)),i.end(kc)}serializeCubeActions(r){var i;let o=(0,P3.fragment)().ele("actions");return o.ele("properties").ele({"include-default-drill-through":r.properties.includeDefaultDrillThrough}),(i=r.drillThrough)===null||i===void 0||i.forEach(l=>{let p=o.ele(kY.tag("drill-through").attribute("id",l.id).attribute("name",l.name).getObj());if(l.properties){let b=p.ele("properties"),{name:T,description:E,notes:k}=l.properties;b.ele({name:T,description:E,notes:k})}let _=p.ele("participants");l.participants.attributeRef.forEach(b=>{var T;let E=_.ele(this.helper.attributeRefObj(b.id)).ele("ref-path");(T=b.refPath)===null||T===void 0||T.forEach(k=>E.ele(kY.tag("ref").attribute("id",k).getObj()))})}),o.end(kc)}serializeAggregate(r){let i=(0,P3.fragment)().ele(kY.tag("aggregate").attribute("id",r.id).attribute("name",r.name).getObj());if(r.properties){let{name:o,description:l,notes:p,caching:_}=r.properties,b=i.ele("properties");if(b.ele({name:o,description:l,notes:p}),_){let T=b.ele("caching");_.engineMemory&&T.ele("engine-memory")}}return r.attributes&&i.ele(this.serializeAggregateAttributes(r.attributes)),r.partitionReferences&&i.ele(this.helper.serializeAttributeAndKeyReferences("partitions",r.partitionReferences)),r.distributionReferences&&i.ele(this.helper.serializeAttributeAndKeyReferences("distribution-keys",r.distributionReferences)),i.end(kc)}serializeAggregateAttributes(r){let i=(0,P3.fragment)().ele("attributes"),{attributeRef:o,keyRef:l}=r;return o&&o.forEach(p=>{let _=i.ele(this.helper.attributeRefObj(p.id));p.referencePath&&_.ele(this.helper.flatProtoAttributeRefPath(p.referencePath))}),l&&l.forEach(p=>{let _=i.ele(this.helper.keyRefObj(p.id));p.referencePath&&_.ele(this.helper.flatProtoAttributeRefPath(p.referencePath))}),i.end(kc)}};var R7=_u(I3());var Qk=mD.create(),Ole=class n{constructor(r){this.helper=r}static create(r){return new n(r)}serializeInput(r){let i=(0,R7.fragment)().ele("perspectives");return r.forEach(o=>i.ele(this.serializePerspective(o))),i.end(kc)}serializePerspective(r){let i=Qk.tag("perspective").attribute("id",r.id).attribute("name",r.name).attribute("cube-ref",r.cubeRef).getObj(),o=(0,R7.fragment)().ele(i),l=o.ele("flat-attributes"),p=o.ele("flat-dimensions"),_=o.ele("calculated-members");return r.flatAttributeRef&&r.flatAttributeRef.forEach(b=>l.ele(this.serializeFlatAttrRef(b))),r.flatDimensionRef&&r.flatDimensionRef.forEach(b=>p.ele(this.serializeFlatDimensionRef(b))),r.calculatedMemberRefs&&r.calculatedMemberRefs.forEach(b=>{_.ele(this.serializeCalculatedMemberRef(b))}),o.end(kc)}serializeFlatAttrRef(r){let i=Qk.tag("flat-attribute-ref").attribute("id",r.id).getObj(),o=(0,R7.fragment)().ele(i);if(r.flatRefs){let l=o.ele("ref-path");r.flatRefs.forEach(p=>{let _=Qk.tag("ref").attribute("id",p.id).getObj();l.ele(_)})}return o.ele(this.helper.commonVisiblePropertiesTag(r.properties)),o.end(kc)}serializeFlatDimensionRef(r){var i,o;let l=Qk.tag("flat-dimension-ref").attribute("id",r.id).getObj(),p=(0,R7.fragment)().ele(l);if(r.flatRefs){let _=p.ele("ref-path");(i=r.flatRefs)===null||i===void 0||i.forEach(b=>{let T=Qk.tag("ref").attribute("id",b.id).getObj();_.ele(T)})}return p.ele(this.helper.commonVisiblePropertiesTag(r.properties)),(o=r.flatHierarchyRef)===null||o===void 0||o.forEach(_=>{p.ele(this.serializeFlatHierarchy(_))}),p.end(kc)}serializeFlatHierarchy(r){var i;let o=Qk.tag("flat-hierarchy-ref").attribute("id",r.id).getObj(),l=(0,R7.fragment)().ele(o);return r.properties&&l.ele(this.helper.commonVisiblePropertiesTag(r.properties)),(i=r.flatLevelRef)===null||i===void 0||i.forEach(p=>{let _=Qk.tag("flat-level-ref").attribute("primary-attribute",p.primaryAttributeId).getObj();l.ele(_).ele(this.helper.commonVisiblePropertiesTag(p.properties))}),l.end(kc)}serializeCalculatedMemberRef(r){let i=Qk.tag("calculated-member-ref").attribute("id",r.id).getObj();return(0,R7.fragment)().ele(i).ele(this.helper.commonVisiblePropertiesTag(r.properties)).end(kc)}serializePrincipals(r){var i,o;let l=(0,R7.fragment)().ele("properties").ele("security").ele("principals"),p=_=>Qk.tag("permission").attribute("name",_.name).attribute("restricted",_.restricted).getObj();return(i=r.user)===null||i===void 0||i.forEach(_=>{let b=l.ele(Qk.tag("user").attribute("name",_.username).getObj());_.permission.forEach(T=>b.ele(p(T)))}),(o=r.group)===null||o===void 0||o.forEach(_=>{let b=l.ele(Qk.tag("group").attribute("id",_.id).getObj());_.permission.forEach(T=>b.ele(p(T)))}),l.end(kc)}};var kRt=mD.create(),Rle=class n{constructor(r={}){this.helper=r.helper||L$.create(),this.attributeSerializer=r.attributeSerializer||j$.create(this.helper),this.dimensionSerializer=r.dimensionSerializer||B$.create(this.helper),this.datasetSerializer=r.datasetSerializer||q$.create(this.helper,this.attributeSerializer),this.perspectiveSerializer=r.perspectiveSerializer||Ole.create(this.helper),this.cubeSerializer=r.cubeSerializer||Nle.create({}),this.calculatedMemberSerializer=r.calculatedMemberSerializer||Ple.create(this.helper)}static create(r={}){return new n(r)}serializeInput(r){let i=this.serializeSchema(r.projectMetadata,r.name);return i.ele(this.serializeAnnotations(r.annotations)),i.ele(this.serializeProperties(r.properties)),r.attributes&&i.ele(this.attributeSerializer.serializeInput(r.attributes)),r.dimensions&&i.ele(this.dimensionSerializer.serializeInput(r.dimensions)),r.datasets&&i.ele(this.datasetSerializer.serializeInput(r.datasets)),r.calculatedMembers&&i.ele(this.calculatedMemberSerializer.serializeInput(r.calculatedMembers)),i.ele(this.cubeSerializer.serializeInput(r.cubes)),r.perspectives&&i.ele(this.perspectiveSerializer.serializeInput(r.perspectives)),i.end(Object.assign(Object.assign({},kc),{headless:!0}))}serializeSchema(r,i){return(0,Fle.create)({encoding:"UTF-8"}).ele("http://www.atscale.com/xsd/project_2_0","schema").att("name",i).att("version",r.version).att("xsi:schemaLocation",r.schemaLocation).att("xmlns:xsi",r.schemaInstance).att("xmlns:xsd",r.schema)}serializeAnnotations(r){let i=(0,Fle.fragment)().ele("annotations");return r.forEach(o=>i.ele(kRt.tag("annotation").value(o.value).attribute("name",o.name).getObj())),i.end(kc)}serializeProperties(r){var i;let o=(0,Fle.fragment)().ele("properties");if(o.ele({visible:r.visible}),r.caption&&o.ele({caption:r.caption}),r.aggregatePrediction&&o.ele("aggregate-prediction").ele({"speculative-aggregates":(i=r.aggregatePrediction)===null||i===void 0?void 0:i.speculativeAggregates}),r.aggressiveAggregatePromotion&&o.ele({"aggressive-aggregate-promotion":r.aggressiveAggregatePromotion}),r.preferredAggregateStores){let l=o.ele("preferred-aggregate-stores");r.preferredAggregateStores.aggregateStore.forEach(p=>{l.ele("aggregate-store").ele(Object.assign(Object.assign({},kRt.tag("connection").attribute("id",p.connection.id).getObj()),{"promoted-agg-row-count-limit":p.promotedAggRowCountLimit,"promoted-aggs-total-row-count-limit":p.promotedAggsTotalRowCountLimit}))})}return r.description&&o.ele({description:r.description}),o.end(kc)}};var Lzr=function(n,r,i,o){function l(p){return p instanceof i?p:new i(function(_){_(p)})}return new(i||(i=Promise))(function(p,_){function b(k){try{E(o.next(k))}catch(j){_(j)}}function T(k){try{E(o.throw(k))}catch(j){_(j)}}function E(k){k.done?p(k.value):l(k.value).then(b,T)}E((o=o.apply(n,r||[])).next())})};function jzr(n){return n.map(({relativePath:i,rawContent:o})=>({relativePath:i,rawContent:o}))}var Mle=class{constructor(r){this.logger=r.logger,this.fileService=r.fileService,this.xmlProjectBuilder=new hce({logger:this.logger}),this.xmlProjectSerializer=Rle.create(),this.validator=r.validator||new Koe}compile(r,i){return Lzr(this,void 0,void 0,function*(){let o=Mo.create(),p=yield new $xe({fileService:this.fileService,logger:this.logger}).parseFolder(r,o);return this.compileFolderStructure(p,i,o)})}compileFolderStructure(r,i,o=Mo.create()){let l=new UL,p=l.extractYamlFiles(r,o),_=l.getYamlFilesWithValidObjectType(p,o),b=this.validator.validateYamlFiles(_,r);if(o.append(b),this.printCompilationOutput(o),o.hasErrors)throw new s$("CompilationError. Validation of the files was not successful.",o.output);let T=jzr(_),{xmlProjectResult:E,serializedXML:k}=this.compileWithoutValidation(_,i);return{project:E.project,serializedXML:k,projectId:E.projectId,output:o.output,smlRawFiles:T}}compileWithoutValidation(r,i){let o=r.map(_=>Object.assign(Object.assign({},_),{data:Object.assign(Object.assign({},_.data),{metadata:{origin:_.origin,repoUrl:_.packageUrl}})})),l=this.xmlProjectBuilder.buildProject(o,i),p=this.xmlProjectSerializer.serializeInput(l.project);return{xmlProjectResult:l,serializedXML:p}}getLogFunction(r){return r==="error"?this.logger.error.bind(this.logger):r==="warning"?this.logger.warn.bind(this.logger):this.logger.info.bind(this.logger)}printCompilationOutput(r){r.globalOutput.forEach(i=>{this.getLogFunction(i.severity)(`GLOBAL ${i.message}`)}),r.filesOutput.forEach(i=>{i.compilationOutput.forEach(o=>{this.getLogFunction(o.severity)(`${i.relativePath} ${o.message}`)})})}};var qzr="http://localhost".replace(/\/+$/,""),$$=class{constructor(r={}){this.configuration=r}set config(r){this.configuration=r}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:qzr}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||PRt}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){let r=this.configuration.apiKey;if(r)return typeof r=="function"?r:()=>r}get accessToken(){let r=this.configuration.accessToken;if(r)return typeof r=="function"?r:async()=>r}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}},Bzr=new $$,TC=class n{constructor(r=Bzr){this.configuration=r;this.middleware=r.middleware}static jsonRegex=new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$","i");middleware;withMiddleware(...r){let i=this.clone();return i.middleware=i.middleware.concat(...r),i}withPreMiddleware(...r){let i=r.map(o=>({pre:o}));return this.withMiddleware(...i)}withPostMiddleware(...r){let i=r.map(o=>({post:o}));return this.withMiddleware(...i)}isJsonMime(r){return r?n.jsonRegex.test(r):!1}async request(r,i){let{url:o,init:l}=await this.createFetchParams(r,i),p=await this.fetchApi(o,l);if(p&&p.status>=200&&p.status<300)return p;throw new PY(p,"Response returned an error code")}async createFetchParams(r,i){let o=this.configuration.basePath+r.path;r.query!==void 0&&Object.keys(r.query).length!==0&&(o+="?"+this.configuration.queryParamsStringify(r.query));let l=Object.assign({},this.configuration.headers,r.headers);Object.keys(l).forEach(k=>l[k]===void 0?delete l[k]:{});let p=typeof i=="function"?i:async()=>i,_={method:r.method,headers:l,body:r.body,credentials:this.configuration.credentials},b={..._,...await p({init:_,context:r})},T;Jzr(b.body)||b.body instanceof URLSearchParams||$zr(b.body)?T=b.body:this.isJsonMime(l["Content-Type"])?T=JSON.stringify(b.body):T=b.body;let E={...b,body:T};return{url:o,init:E}}fetchApi=async(r,i)=>{let o={url:r,init:i};for(let p of this.middleware)p.pre&&(o=await p.pre({fetch:this.fetchApi,...o})||o);let l;try{l=await(this.configuration.fetchApi||fetch)(o.url,o.init)}catch(p){for(let _ of this.middleware)_.onError&&(l=await _.onError({fetch:this.fetchApi,url:o.url,init:o.init,error:p,response:l?l.clone():void 0})||l);if(l===void 0)throw p instanceof Error?new RHe(p,"The request failed and the interceptors did not return an alternative response"):p}for(let p of this.middleware)p.post&&(l=await p.post({fetch:this.fetchApi,url:o.url,init:o.init,response:l.clone()})||l);return l};clone(){let r=this.constructor,i=new r(this.configuration);return i.middleware=this.middleware.slice(),i}};function $zr(n){return typeof Blob<"u"&&n instanceof Blob}function Jzr(n){return typeof FormData<"u"&&n instanceof FormData}var PY=class extends Error{constructor(i,o){super(o);this.response=i}name="ResponseError"},RHe=class extends Error{constructor(i,o){super(o);this.cause=i}name="FetchError"},uE=class extends Error{constructor(i,o){super(o);this.field=i}name="RequiredError"};function PRt(n,r=""){return Object.keys(n).map(i=>NRt(i,n[i],r)).filter(i=>i.length>0).join("&")}function NRt(n,r,i=""){let o=i+(i.length?`[${n}]`:n);if(r instanceof Array){let l=r.map(p=>encodeURIComponent(String(p))).join(`&${encodeURIComponent(o)}=`);return`${encodeURIComponent(o)}=${l}`}if(r instanceof Set){let l=Array.from(r);return NRt(n,l,i)}return r instanceof Date?`${encodeURIComponent(o)}=${encodeURIComponent(r.toISOString())}`:r instanceof Object?PRt(r,o):`${encodeURIComponent(o)}=${encodeURIComponent(String(r))}`}var hD=class{constructor(r,i=o=>o){this.raw=r;this.transformer=i}async value(){return this.transformer(await this.raw.json())}};function ORt(n){return!(!("name"in n)||n.name===void 0||!("value"in n)||n.value===void 0)}function FRt(n,r){return n==null?n:{name:n.name,value:n.value}}function RRt(n){return!(!("name"in n)||n.name===void 0||!("value"in n)||n.value===void 0)}function MRt(n,r){return n==null?n:{name:n.name,value:n.value}}function LRt(n){return!(!("name"in n)||n.name===void 0||!("value"in n)||n.value===void 0)}function jRt(n,r){return n==null?n:{name:n.name,value:n.value}}function qRt(n){return!(!("name"in n)||n.name===void 0||!("value"in n)||n.value===void 0)}function BRt(n,r){return n==null?n:{name:n.name,value:n.value}}function $Rt(n){return!(!("name"in n)||n.name===void 0||!("value"in n)||n.value===void 0)}function JRt(n,r){return n==null?n:{name:n.name,value:n.value}}function URt(n){return Gzr(n,!1)}function Gzr(n,r){return n==null?n:ORt(n)?FRt(n,!0):RRt(n)?MRt(n,!0):LRt(n)?jRt(n,!0):qRt(n)?BRt(n,!0):$Rt(n)?JRt(n,!0):{}}function WRt(n){return Hzr(n,!1)}function Hzr(n,r){return n==null?n:{annotation:n.annotation.map(URt)}}function VRt(n){return Qzr(n,!1)}function Qzr(n,r){return n==null?n:{dataset:n.dataset}}function zRt(n){return Yzr(n,!1)}function Yzr(n,r){return n==null?n:{cube:n.cube}}function GRt(n){return Kzr(n,!1)}function Kzr(n,r){return n==null?n:{attributeKey:n["attribute-key"],keyedAttribute:n["keyed-attribute"]}}function HRt(n){return Xzr(n,!1)}function Xzr(n,r){return n==null?n:{calculatedMember:n["calculated-member"]}}function QRt(n){return Zzr(n,!1)}function Zzr(n,r){return n==null?n:{dimension:n.dimension}}function YRt(n){return eGr(n,!1)}function eGr(n,r){return n==null?n:{perspective:n.perspective}}function KRt(n){return tGr(n,!1)}function tGr(n,r){return n==null?n:{aggregatePrediction:n["aggregate-prediction"],aggressiveAggregatePromotion:n.aggressive_aggregate_promotion,caption:n.caption,visible:n.visible}}function XRt(n){return rGr(n,!1)}function rGr(n,r){return n==null?n:{name:n.name,version:n.version,properties:n.properties==null?void 0:KRt(n.properties),annotations:n.annotations==null?void 0:WRt(n.annotations),attributes:n.attributes==null?void 0:GRt(n.attributes),dimensions:n.dimensions==null?void 0:QRt(n.dimensions),datasets:n.datasets==null?void 0:VRt(n.datasets),calculatedMembers:n["calculated-members"]==null?void 0:HRt(n["calculated-members"]),cubes:n.cubes==null?void 0:zRt(n.cubes),perspectives:n.perspectives==null?void 0:YRt(n.perspectives)}}function o6t(n){return sGr(n,!1)}function sGr(n,r=!1){return n==null?n:{name:n.name,sites:n.sites}}function c6t(n){return aGr(n,!1)}function aGr(n,r=!1){return n==null?n:{catalogXml:n.catalogXml,repositoryId:n.repositoryId,tableauServers:n.tableauServers==null?void 0:n.tableauServers.map(o6t)}}function l6t(n){return oGr(n,!1)}function oGr(n,r){return n==null?n:{serverId:n.serverId,name:n.name,siteName:n.siteName,isSuccessful:n.isSuccessful,errorMessage:n.errorMessage==null?void 0:n.errorMessage}}function u6t(n){return cGr(n,!1)}function cGr(n,r){return n==null?n:{tableau:n.tableau==null?void 0:n.tableau.map(l6t)}}function f6t(n){return fGr(n,!1)}function fGr(n,r){return n==null?n:{id:n.id,name:n.name,url:n.url,visibleBranchesPattern:n.visibleBranchesPattern}}function p6t(n){return pGr(n,!1)}function pGr(n,r){return n==null?n:{id:n.id,name:n.name,caption:n.caption,description:n.description==null?void 0:n.description,connectionIds:n.connectionIds}}function d6t(n){return dGr(n,!1)}function dGr(n,r){return n==null?n:{id:n.id,name:n.name,caption:n.caption,publishedAt:n.publishedAt==null?null:new Date(n.publishedAt),publishedBy:n.publishedBy,models:n.models.map(p6t)}}var hEe=class extends TC{async deployRaw(r,i){if(r.deployCatalogRequestBodyDto==null)throw new uE("deployCatalogRequestBodyDto",'Required parameter "deployCatalogRequestBodyDto" was null or undefined when calling deploy().');let o={},l={};if(l["Content-Type"]="application/json",r.authorization!=null&&(l.Authorization=String(r.authorization)),this.configuration&&this.configuration.accessToken){let _=this.configuration.accessToken,b=await _("bearer",[]);b&&(l.Authorization=`Bearer ${b}`)}let p=await this.request({path:"/v1/public/catalogs",method:"POST",headers:l,query:o,body:c6t(r.deployCatalogRequestBodyDto)},i);return new hD(p,_=>u6t(_))}async deploy(r,i){return await(await this.deployRaw(r,i)).value()}async exportCatalogRepresentationRaw(r,i){if(r.accept==null)throw new uE("accept",'Required parameter "accept" was null or undefined when calling exportCatalogRepresentation().');if(r.catalogId==null)throw new uE("catalogId",'Required parameter "catalogId" was null or undefined when calling exportCatalogRepresentation().');let o={},l={};if(r.authorization!=null&&(l.Authorization=String(r.authorization)),r.accept!=null&&(l.Accept=String(r.accept)),this.configuration&&this.configuration.accessToken){let _=this.configuration.accessToken,b=await _("bearer",[]);b&&(l.Authorization=`Bearer ${b}`)}let p=await this.request({path:"/v1/public/catalogs/{catalogId}/export".replace("{catalogId}",encodeURIComponent(String(r.catalogId))),method:"GET",headers:l,query:o},i);return new hD(p,_=>XRt(_))}async exportCatalogRepresentation(r,i){return await(await this.exportCatalogRepresentationRaw(r,i)).value()}async getCatalogsRaw(r,i){let o={},l={};if(r.authorization!=null&&(l.Authorization=String(r.authorization)),this.configuration&&this.configuration.accessToken){let _=this.configuration.accessToken,b=await _("bearer",[]);b&&(l.Authorization=`Bearer ${b}`)}let p=await this.request({path:"/v1/public/catalogs",method:"GET",headers:l,query:o},i);return new hD(p,_=>_.map(d6t))}async getCatalogs(r={},i){return await(await this.getCatalogsRaw(r,i)).value()}};var gEe=class extends TC{async getCatalogReposRaw(r,i){let o={},l={};if(r.authorization!=null&&(l.Authorization=String(r.authorization)),this.configuration&&this.configuration.accessToken){let _=this.configuration.accessToken,b=await _("bearer",[]);b&&(l.Authorization=`Bearer ${b}`)}let p=await this.request({path:"/v1/public/repos",method:"GET",headers:l,query:o},i);return new hD(p,_=>_.map(f6t))}async getCatalogRepos(r={},i){return await(await this.getCatalogReposRaw(r,i)).value()}};var m6t=_u(require("fs/promises"));var _6t=_u(require("path"));var J$;(function(n){n.file="file",n.folder="folder"})(J$||(J$={}));var TA=function(n,r,i,o){function l(p){return p instanceof i?p:new i(function(_){_(p)})}return new(i||(i=Promise))(function(p,_){function b(k){try{E(o.next(k))}catch(j){_(j)}}function T(k){try{E(o.throw(k))}catch(j){_(j)}}function E(k){k.done?p(k.value):l(k.value).then(b,T)}E((o=o.apply(n,r||[])).next())})},vGr=[".git"],yEe=class{readFile(r){return this.getFileSystem().readFile(r,{encoding:"utf8"})}createFolder(r){return TA(this,void 0,void 0,function*(){yield this.getFileSystem().mkdir(r,{mode:511,encoding:"utf8"})})}getFolderPath(r,i){return`/${r.slice(0,i).join("/")}`}isFolderExist(r){return TA(this,void 0,void 0,function*(){try{return yield this.getFileSystem().stat(r),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}})}doesFileExist(r){return TA(this,void 0,void 0,function*(){try{return(yield this.getFileSystem().stat(r)).isFile()}catch(i){if(i.code==="ENOENT")return!1;throw i}})}createFile(r,i,o){return TA(this,void 0,void 0,function*(){let l=this.getFileSystem(),p=`/${r}/${i}`,_=p.split("/").filter(b=>b!=="");for(let b=1;b<_.length;b++){let T=this.getFolderPath(_,b);(yield this.isFolderExist(T))||(yield l.mkdir(T,{mode:511,encoding:"utf8"}))}return yield l.writeFile(p,o,{mode:511,encoding:"utf8"})})}updateFile(r,i,o){return this.createFile(r,i,o)}getFiles(r){return TA(this,void 0,void 0,function*(){return us.notEmpty(r,"getFiles requires none empty path"),(yield this.getItems(r)).filter(o=>o.type===J$.file).map(o=>o.name)})}getFileContent(r){return TA(this,void 0,void 0,function*(){try{let i=yield this.getFileSystem().readFile(r,{encoding:"utf8"});return Buffer.from(i).toString("utf8")}catch{return null}})}getFolders(r){return TA(this,void 0,void 0,function*(){return us.notEmpty(r,"getFolders requires none empty path"),(yield this.getItems(r)).filter(o=>o.type===J$.folder).map(o=>o.name)})}getItems(r){return TA(this,void 0,void 0,function*(){us.notEmpty(r,"getItems requires none empty path");let i=[],o=yield this.getFileSystem().readdir(r);for(let l of o){if(vGr.includes(l))continue;let p=_6t.default.join(r,l),_=yield this.getFileSystem().stat(p);if(!_.isDirectory()&&!_.isFile())continue;let b={name:l,fullPath:p,type:_.isDirectory()?J$.folder:J$.file};i.push(b)}return i})}rename(r,i,o){return TA(this,void 0,void 0,function*(){return this.getFileSystem().rename(`/${r}/${i}`,`/${r}/${o}`)})}rmDir(r){return TA(this,void 0,void 0,function*(){typeof r=="string"?yield this.rmDirInternal(r):yield this.rmDirInternal(Ro.join(r.repo,r.path))})}rmDirInternal(r){return TA(this,void 0,void 0,function*(){try{let i=yield this.getFileSystem().readdir(r);for(let o of i){let l=Ro.join(r,o);(yield this.getFileSystem().stat(l)).isDirectory()?yield this.rmDirInternal(l):this.getFileSystem().unlink(l)}return this.getFileSystem().rmdir(r,void 0,o=>{console.log(o)})}catch(i){console.log(i)}})}unlink(r,i){return TA(this,void 0,void 0,function*(){return this.getFileSystem().unlink(`/${r}/${i}`)})}};var N3=class extends yEe{getFileSystem(){return m6t.default}};var MHe=()=>{let n=process.env.ATSCALE_API_URL,r=process.env.ATSCALE_API_TOKEN;if(!n)throw new Error("Missing environment variable ATSCALE_API_URL.");if(!r)throw new Error("Missing environment variable ATSCALE_API_TOKEN.");return new $$({basePath:n,accessToken:r})};var y6t=_u(GH()),U$=_u(QH());var h6t;(function(n){n.UpdateVersion="UpdateVersion",n.PerspectiveLevelFix="PerspectiveLevelFix"})(h6t||(h6t={}));var O3;(function(n){n.Info="info",n.Warning="warning",n.Error="error"})(O3||(O3={}));var g6t;(function(n){n.Engine="engine",n.Compiler="compiler"})(g6t||(g6t={}));var v6t=_u(require("path")),bGr={error:U$.default.red,warning:U$.default.yellow,info:U$.default.blue},j7=class extends y6t.Command{formatMessage(r){let i=bGr[r.severity],o=i(`[${r.severity.toUpperCase()}] ${r.message}`);return r.context&&(o+=` (Context: ${JSON.stringify(r.context)})`),o}printValidationResults(r,i){let o=!1,l=r.globalOutput.filter(_=>_.severity!==O3.Info),p=r.filesOutput.map(_=>({..._,compilationOutput:_.compilationOutput.filter(b=>b.severity!==O3.Info)})).filter(_=>_.compilationOutput.length>0);return l.length>0&&(this.log(U$.default.bold("Global Validation Results:")),l.forEach(_=>{this.log(this.formatMessage(_)),_.severity===O3.Error&&(o=!0)}),this.log("")),p.length>0&&(this.log(U$.default.bold("File Validation Results:")),p.forEach(_=>{let b=v6t.default.join(i,_.relativePath);this.log(U$.default.underline(b)),_.compilationOutput.forEach(T=>{this.log(this.formatMessage(T)),T.severity===O3.Error&&(o=!0)}),this.log("")})),o}async exitWithResponseError(r,i){let o=`${r}
674
674
  Status: ${i.response.status} ${i.response.statusText}