@malloydata/render 0.0.270-dev250424204317 → 0.0.270-dev250428164815
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.
|
@@ -1529,7 +1529,7 @@ FROM ${r}
|
|
|
1529
1529
|
FROM ${p}
|
|
1530
1530
|
`),this.resultStage}}class btt extends ms{generateSQL(e){if(this.parent.structDef.type!=="sql_select")throw new Error("Invalid struct for QueryQueryRaw, currently only supports SQL");return e.addStage(this.parent.structDef.selectStr)}prepare(){}getResultStructDef(){if(!(0,Me.isSourceDef)(this.parent.structDef))throw new Error(`Result cannot be type ${this.parent.structDef.type}`);return{...this.parent.structDef,type:"query_result"}}getResultMetadata(e){}}class Ttt extends ms{constructor(e,r,i,s){super(e,r,i,s),this.stages=[],this.fieldDef=e,this.fieldsToStages()}fieldsToStages(){const e=this.firstSegment;if(this.parent.dialect.dontUnionIndex){this.stages=[e.indexFields];return}const r={};for(const i of e.indexFields){if(i.path.length>1){const s=Ale(i.path.slice(0,i.path.length-1)),o=r[s];if(o===void 0){const u=this.parent.nameMap.get(i.path[0]);if(u instanceof gs&&u.fieldDef.join==="many"&&u.fieldDef.fields.length>1){const a=[i];r[s]=a,this.stages.push(a);continue}}else{o.push(i);continue}}this.stages[0]===void 0&&(this.stages[0]=[]),this.stages[0].push(i)}}expandFields(e){}generateSQL(e){const r=this.firstSegment,i=[];for(const s of this.stages){const o=new Stt({...this.fieldDef,pipeline:[{...r,indexFields:s}]},this.parent,e,this.isJoinedSubquery);o.prepare(e);const u=o.generateSQL(e);i.push(u)}return i.length===1?this.resultStage=i[0]:this.resultStage=e.addStage(i.map(s=>`SELECT * FROM ${s}
|
|
1531
1531
|
`).join(` UNION ALL
|
|
1532
|
-
`)),this.resultStage}getResultStructDef(){const e={type:"query_result",name:this.resultStage||"result",dialect:this.parent.dialect.name,fields:[{type:"string",name:"fieldName"},{type:"string",name:"fieldPath"},{type:"string",name:"fieldValue"},{type:"string",name:"fieldType"},{type:"number",name:"weight",numberType:"integer"}],connection:this.parent.connectionName};return this.parent.structDef.modelAnnotation&&(e.modelAnnotation=this.parent.structDef.modelAnnotation),e}}class gs extends bB{constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new p0(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}class p0{constructor(e,r,i,s){if(this.structDef=e,this.sourceArguments=r,this.prepareResultOptions=s,this.nameMap=new Map,this._modelTag=void 0,this._arguments=void 0,this.setParent(i),"model"in i)if(this.model=i.model,this.pathAliasMap=new Map,(0,Me.isSourceDef)(e))this.connectionName=e.connection;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.dialect=(0,rtt.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,stt.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Me.isSourceDef)(this.structDef))return this.structDef.dialect;if(this.parent)return this.parent.findFirstDialect();throw new Error("Cannot create QueryStruct from record with model parent")}informOfAliasValue(e){this.recordAlias=e}maybeEmitParameterizedSourceUsage(){var e;if((0,Me.isSourceDef)(this.structDef)){const r={...this.structDef.parameters,...this.structDef.arguments};if(Object.values(r).length===0)return;(e=this.eventStream)===null||e===void 0||e.emit("parameterized-source-compiled",{parameters:r})}}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,Fn.exprMap)(e.value,r=>{if(r.node==="parameter"){if(this.parent===void 0)throw new Error("No parent from which to retrieve parameter value");const i=this.parent.arguments()[r.path[0]],s=this.parent.resolveParentParameterReferences(i);if(s.value===null)throw new Error("Invalid parameter value");return s.value}return r})}}arguments(){var e;if(this._arguments!==void 0)return this._arguments;if(this._arguments={},(0,Me.isSourceDef)(this.structDef)){const r=(e=this.structDef.parameters)!==null&&e!==void 0?e:{};for(const s in r)this._arguments[s]=r[s];const i={...this.structDef.arguments,...this.sourceArguments};for(const s in i){const o=i[s];this._arguments[s]=this.resolveParentParameterReferences(o)}}return this._arguments}addFieldsFromFieldList(e){for(const r of e){const i=(0,Me.getIdentifier)(r);if(r.type==="turtle")this.addFieldToNameMap(i,ms.makeQuery(r,this,void 0,!1));else if((0,Me.isAtomic)(r)||(0,Me.isJoinedSource)(r))this.addFieldToNameMap(i,this.makeQueryField(r));else throw new Error("mtoy did nit add field")}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new mtt({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),r=this.pathAliasMap.get(e);if(r===void 0){const i=Array.from(this.pathAliasMap.values()),s=utt((0,Me.getIdentifier)(this.structDef));let o=`${s}_0`,u=1;for(;i.includes(o)&&u<1e3;)u++,o=`${s}_${u}`;if(u<1e3)return this.pathAliasMap.set(e,o),o;throw new Error("Internal Error: cannot create unique alias name")}else return r}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Me.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlChildReference(e,r){let i=this.getSQLIdentifier();r&&(0,Me.isAtomic)(this.structDef)&&(0,Me.hasExpression)(this.structDef)&&(i=r.field.exprToSQL(r.result,this,this.structDef.e));let s="table";this.structDef.type==="record"?s="record":this.structDef.type==="array"?s=this.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":this.structDef.type==="nest_source"&&(s="nest source");const o=this.getChildByName(e),u=(o==null?void 0:o.fieldDef.type)||"unknown";return this.dialect.sqlFieldReference(i,s,e,u)}getIdentifier(){if((0,Me.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Me.hasExpression)(this.structDef)){if(this.recordAlias)return this.recordAlias;throw new Error("INTERNAL ERROR, record field alias not pre-computed")}return this.structDef.type==="record"&&this.parent?this.parent.sqlChildReference((0,Me.getIdentifier)(this.structDef),void 0):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Me.getIdentifier)(this.structDef)+".":""}needsSymetricCalculation(e){const r=this.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.structDef.type==="array"}getJoinableParent(){if(this.structDef.type==="record"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,r){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,r)}getPrimaryKeyField(e){let r;if(r=this.primaryKey())return r;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(){if(this.structDef.type==="query_source"){const e=this.model.loadQuery(this.structDef.query,void 0,this.prepareResultOptions).structs.pop();if(!e)throw new Error("Internal Error, query didn't produce a struct");const r={...this.structDef};for(const i of e.fields){const s=(0,Me.getIdentifier)(i);this.nameMap.has(s)||(r.fields.push(i),this.nameMap.set(s,this.makeQueryField(i)))}this.structDef=r,!this.structDef.primaryKey&&e.primaryKey&&(this.structDef.primaryKey=e.primaryKey)}for(const[,e]of this.nameMap)e instanceof gs&&e.queryStruct.resolveQueryFields()}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}get eventStream(){return this.getModel().eventStream}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e,r){switch(e.type){case"array":case"record":case"query_source":case"table":case"sql_select":case"composite":return new gs(e,void 0,this,this.prepareResultOptions);case"string":return new xtt(e,this,r);case"date":return new RB(e,this,r);case"timestamp":return new DB(e,this,r);case"number":return new dtt(e,this,r);case"boolean":return new TB(e,this,r);case"json":return new htt(e,this,r);case"sql native":return new ptt(e,this,r);case"turtle":return ms.makeQuery(e,this,void 0,!1);default:throw new Error(`unknown field definition ${JSON.stringify(e),2}`)}}structSourceSQL(e){var r,i;switch(this.structDef.type){case"table":return this.dialect.quoteTablePath(this.structDef.tablePath);case"composite":return"{COMPOSITE SOURCE}";case"finalize":return this.structDef.name;case"sql_select":return`(${this.structDef.selectStr})`;case"nest_source":return this.structDef.pipeSQL;case"query_source":return!((r=this.prepareResultOptions)===null||r===void 0)&&r.replaceMaterializedReferences&&(0,B4.shouldMaterialize)(this.structDef.query.annotation)?e.addMaterializedQuery((0,Me.getIdentifier)(this.structDef),this.structDef.query,(i=this.prepareResultOptions)===null||i===void 0?void 0:i.materializedTablePrefix):this.model.loadQuery(this.structDef.query,e,this.prepareResultOptions,!1,!0).lastStageName;default:throw new Error(`Cannot create SQL StageWriter from '${(0,Me.getIdentifier)(this.structDef)}' type '${this.structDef.type}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Me.isSourceDef)(this.structDef)&&this.structDef.primaryKey)return this.getDimensionByName([this.structDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){let r,i=this,s=e[0];for(const o of e){if(r=i==null?void 0:i.getChildByName(o),!r){s=o;break}i=r instanceof gs?r.queryStruct:void 0}if(r===void 0){const o=e.length>1?` in ${e.join(".")}`:"";throw new Error(`${s} not found${o}`)}return r}getQueryFieldByName(e){const r=this.getFieldByName(e);if(r instanceof gs)throw new Error(`Cannot reference ${e.join(".")} as a scalar'`);return r}getQueryFieldReference(e,r){const i=this.getFieldByName(e);if(r){if(i.parent===void 0)throw new Error("Inconcievable, field reference to orphaned query field");if(i instanceof gs){const s={...i.fieldDef,annotation:r};return new gs(s,void 0,i.parent,{},i.referenceId)}else{const s={...i.fieldDef,annotation:r};return i.parent.makeQueryField(s,i.referenceId)}}return i}getDimensionOrMeasureByName(e){const r=this.getFieldByName(e);if(!r.isAtomic())throw new Error(`${e} is not an atomic field? Inconceivable!`);return r}getDimensionByName(e){const r=this.getFieldByName(e);if(S2(r))return r;throw new Error(`${e} is not an atomic scalar field? Inconceivable!`)}getStructByName(e){if(e.length===0)return this;const r=this.getFieldByName(e);if(r instanceof gs)return r.queryStruct;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.structDef.type!=="record")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Asking a record for a primary key? Inconceivable!")}applyStructFiltersToTurtleDef(e){let r=e.pipeline;const i=e.annotation,s=e.filterList||[];return r=structuredClone(r),r[0].filterList=s.concat(r[0].filterList||[],(0,Me.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[]),{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}class P4{constructor(e,r){this.eventStream=r,this.dialect=new itt.StandardSQLDialect,this.modelDef=void 0,this.structs=new Map,this.exploreSearchSQLMap=new Map,e&&this.loadModelFromDef(e)}loadModelFromDef(e){this.modelDef=e;for(const r of Object.values(this.modelDef.contents)){let i;if((0,Me.isSourceDef)(r))i=new p0(r,void 0,{model:this},{}),this.structs.set((0,Me.getIdentifier)(r),i),i.resolveQueryFields();else if(r.type!=="query")throw new Error("Internal Error: Unknown structure type")}}getStructByName(e){const r=this.structs.get(e);if(r)return r;throw new Error(`Struct ${e} not found in model.`)}getStructFromRef(e,r,i){var s;if(i??(i={}),typeof e=="string"){const o=this.getStructByName(e);return r!==void 0?new p0(o.structDef,r,(s=o.parent)!==null&&s!==void 0?s:{model:this},i):o}return new p0(e,r,{model:this},i)}loadQuery(e,r,i,s=!1,o=!1){var u;const a="";r||(r=new C2(!0,void 0));const l={type:"turtle",name:"ignoreme",pipeline:e.pipeline,filterList:e.filterList},c=(u=e.compositeResolvedSourceDef)!==null&&u!==void 0?u:e.structRef,f=ms.makeQuery(l,this.getStructFromRef(c,e.sourceArguments,i),r,o),x=f.generateSQLFromPipeline(r);if(s&&f.parent.dialect.hasFinalStage){const h=[];for(const p of x.outputStruct.fields)if((0,Me.isAtomic)(p)){const m=f.parent.dialect.sqlMaybeQuoteIdentifier(p.name);h.push(m)}x.lastStageName=r.addStage(f.parent.dialect.sqlFinalStage(x.lastStageName,h))}return{lastStageName:x.lastStageName,malloy:a,stageWriter:r,structs:[x.outputStruct],connectionName:f.parent.connectionName}}addDefaultRowLimit(e,r){const i={query:e,addedDefaultRowLimit:void 0};if(r===void 0)return i;const s=e.pipeline[e.pipeline.length-1];return s.type==="raw"||s.limit!==void 0?i:{query:{...e,pipeline:[...e.pipeline.slice(0,-1),{...s,limit:r}]},addedDefaultRowLimit:r}}compileQuery(e,r,i=!0){var s,o;const u=this.addDefaultRowLimit(e,r==null?void 0:r.defaultRowLimit);e=u.query;const a=u.addedDefaultRowLimit,c=this.loadQuery(e,void 0,r,i,!1),f=(s=e.compositeResolvedSourceDef)!==null&&s!==void 0?s:e.structRef,x=typeof f=="string"?f:f.as||f.name;return i&&this.dialect.hasFinalStage&&(c.lastStageName=c.stageWriter.addStage(this.dialect.sqlFinalStage(c.lastStageName,[]))),{lastStageName:c.lastStageName,malloy:c.malloy,sql:c.stageWriter.generateSQLStages(),dependenciesToMaterialize:c.stageWriter.dependenciesToMaterialize,materialization:(0,B4.shouldMaterialize)(e.annotation)?(0,B4.buildQueryMaterializationSpec)((o=e.location)===null||o===void 0?void 0:o.url,e.name,r==null?void 0:r.materializedTablePrefix):void 0,structs:c.structs,sourceExplore:x,sourceFilters:e.filterList,queryName:e.name,connectionName:c.connectionName,annotation:e.annotation,queryTimezone:c.structs[0].queryTimezone,defaultRowLimitAdded:a}}async searchIndex(e,r,i,s=1e3,o=void 0){if(!e.canPersist())return;const u=this.getStructByName(r);let a=[];for(const[E,A]of u.nameMap)To(A)&&A.includeInWildcard()&&a.push({type:"fieldref",path:[E]});a=a.sort((E,A)=>E.path[0].localeCompare(A.path[0]));const l={structRef:r,pipeline:[{type:"index",indexFields:a,sample:u.dialect.defaultSampling}]},c=u.dialect.sqlMaybeQuoteIdentifier("fieldName"),f=u.dialect.sqlMaybeQuoteIdentifier("fieldPath"),x=u.dialect.sqlMaybeQuoteIdentifier("fieldValue"),h=u.dialect.sqlMaybeQuoteIdentifier("fieldType"),p=u.dialect.sqlMaybeQuoteIdentifier("weight");let m=this.exploreSearchSQLMap.get(r);m===void 0&&(m=this.compileQuery(l,void 0,!1).sql,this.exploreSearchSQLMap.set(r,m));let g=`SELECT
|
|
1532
|
+
`)),this.resultStage}getResultStructDef(){const e={type:"query_result",name:this.resultStage||"result",dialect:this.parent.dialect.name,fields:[{type:"string",name:"fieldName"},{type:"string",name:"fieldPath"},{type:"string",name:"fieldValue"},{type:"string",name:"fieldType"},{type:"number",name:"weight",numberType:"integer"}],connection:this.parent.connectionName};return this.parent.structDef.modelAnnotation&&(e.modelAnnotation=this.parent.structDef.modelAnnotation),e}}class gs extends bB{constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new p0(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}class p0{constructor(e,r,i,s){if(this.structDef=e,this.sourceArguments=r,this.prepareResultOptions=s,this.nameMap=new Map,this._modelTag=void 0,this._arguments=void 0,this.setParent(i),"model"in i)if(this.model=i.model,this.pathAliasMap=new Map,(0,Me.isSourceDef)(e))this.connectionName=e.connection;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.dialect=(0,rtt.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,stt.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Me.isSourceDef)(this.structDef))return this.structDef.dialect;if(this.parent)return this.parent.findFirstDialect();throw new Error("Cannot create QueryStruct from record with model parent")}informOfAliasValue(e){this.recordAlias=e}maybeEmitParameterizedSourceUsage(){var e;if((0,Me.isSourceDef)(this.structDef)){const r={...this.structDef.parameters,...this.structDef.arguments};if(Object.values(r).length===0)return;(e=this.eventStream)===null||e===void 0||e.emit("parameterized-source-compiled",{parameters:r})}}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,Fn.exprMap)(e.value,r=>{if(r.node==="parameter"){if(this.parent===void 0)throw new Error("No parent from which to retrieve parameter value");const i=this.parent.arguments()[r.path[0]],s=this.parent.resolveParentParameterReferences(i);if(s.value===null)throw new Error("Invalid parameter value");return s.value}return r})}}arguments(){var e;if(this._arguments!==void 0)return this._arguments;if(this._arguments={},(0,Me.isSourceDef)(this.structDef)){const r=(e=this.structDef.parameters)!==null&&e!==void 0?e:{};for(const s in r)this._arguments[s]=r[s];const i={...this.structDef.arguments,...this.sourceArguments};for(const s in i){const o=i[s];this._arguments[s]=this.resolveParentParameterReferences(o)}}return this._arguments}addFieldsFromFieldList(e){for(const r of e){const i=(0,Me.getIdentifier)(r);if(r.type==="turtle")this.addFieldToNameMap(i,ms.makeQuery(r,this,void 0,!1));else if((0,Me.isAtomic)(r)||(0,Me.isJoinedSource)(r))this.addFieldToNameMap(i,this.makeQueryField(r));else throw new Error("mtoy did nit add field")}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new mtt({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),r=this.pathAliasMap.get(e);if(r===void 0){const i=Array.from(this.pathAliasMap.values()),s=utt((0,Me.getIdentifier)(this.structDef));let o=`${s}_0`,u=1;for(;i.includes(o)&&u<1e3;)u++,o=`${s}_${u}`;if(u<1e3)return this.pathAliasMap.set(e,o),o;throw new Error("Internal Error: cannot create unique alias name")}else return r}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Me.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlChildReference(e,r){let i=this.getSQLIdentifier();if(r&&(0,Me.isAtomic)(this.structDef)&&(0,Me.hasExpression)(this.structDef)){if(!this.parent)throw new Error(`Cannot expand reference to ${e} without parent`);i=r.field.exprToSQL(r.result,this.parent,this.structDef.e)}let s="table";this.structDef.type==="record"?s="record":this.structDef.type==="array"?s=this.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":this.structDef.type==="nest_source"&&(s="nest source");const o=this.getChildByName(e),u=(o==null?void 0:o.fieldDef.type)||"unknown";return this.dialect.sqlFieldReference(i,s,e,u)}getIdentifier(){if((0,Me.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Me.hasExpression)(this.structDef)){if(this.recordAlias)return this.recordAlias;throw new Error("INTERNAL ERROR, record field alias not pre-computed")}return this.structDef.type==="record"&&this.parent?this.parent.sqlChildReference((0,Me.getIdentifier)(this.structDef),void 0):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Me.getIdentifier)(this.structDef)+".":""}needsSymetricCalculation(e){const r=this.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.structDef.type==="array"}getJoinableParent(){if(this.structDef.type==="record"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,r){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,r)}getPrimaryKeyField(e){let r;if(r=this.primaryKey())return r;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(){if(this.structDef.type==="query_source"){const e=this.model.loadQuery(this.structDef.query,void 0,this.prepareResultOptions).structs.pop();if(!e)throw new Error("Internal Error, query didn't produce a struct");const r={...this.structDef};for(const i of e.fields){const s=(0,Me.getIdentifier)(i);this.nameMap.has(s)||(r.fields.push(i),this.nameMap.set(s,this.makeQueryField(i)))}this.structDef=r,!this.structDef.primaryKey&&e.primaryKey&&(this.structDef.primaryKey=e.primaryKey)}for(const[,e]of this.nameMap)e instanceof gs&&e.queryStruct.resolveQueryFields()}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}get eventStream(){return this.getModel().eventStream}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e,r){switch(e.type){case"array":case"record":case"query_source":case"table":case"sql_select":case"composite":return new gs(e,void 0,this,this.prepareResultOptions);case"string":return new xtt(e,this,r);case"date":return new RB(e,this,r);case"timestamp":return new DB(e,this,r);case"number":return new dtt(e,this,r);case"boolean":return new TB(e,this,r);case"json":return new htt(e,this,r);case"sql native":return new ptt(e,this,r);case"turtle":return ms.makeQuery(e,this,void 0,!1);default:throw new Error(`unknown field definition ${JSON.stringify(e),2}`)}}structSourceSQL(e){var r,i;switch(this.structDef.type){case"table":return this.dialect.quoteTablePath(this.structDef.tablePath);case"composite":return"{COMPOSITE SOURCE}";case"finalize":return this.structDef.name;case"sql_select":return`(${this.structDef.selectStr})`;case"nest_source":return this.structDef.pipeSQL;case"query_source":return!((r=this.prepareResultOptions)===null||r===void 0)&&r.replaceMaterializedReferences&&(0,B4.shouldMaterialize)(this.structDef.query.annotation)?e.addMaterializedQuery((0,Me.getIdentifier)(this.structDef),this.structDef.query,(i=this.prepareResultOptions)===null||i===void 0?void 0:i.materializedTablePrefix):this.model.loadQuery(this.structDef.query,e,this.prepareResultOptions,!1,!0).lastStageName;default:throw new Error(`Cannot create SQL StageWriter from '${(0,Me.getIdentifier)(this.structDef)}' type '${this.structDef.type}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Me.isSourceDef)(this.structDef)&&this.structDef.primaryKey)return this.getDimensionByName([this.structDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){let r,i=this,s=e[0];for(const o of e){if(r=i==null?void 0:i.getChildByName(o),!r){s=o;break}i=r instanceof gs?r.queryStruct:void 0}if(r===void 0){const o=e.length>1?` in ${e.join(".")}`:"";throw new Error(`${s} not found${o}`)}return r}getQueryFieldByName(e){const r=this.getFieldByName(e);if(r instanceof gs)throw new Error(`Cannot reference ${e.join(".")} as a scalar'`);return r}getQueryFieldReference(e,r){const i=this.getFieldByName(e);if(r){if(i.parent===void 0)throw new Error("Inconcievable, field reference to orphaned query field");if(i instanceof gs){const s={...i.fieldDef,annotation:r};return new gs(s,void 0,i.parent,{},i.referenceId)}else{const s={...i.fieldDef,annotation:r};return i.parent.makeQueryField(s,i.referenceId)}}return i}getDimensionOrMeasureByName(e){const r=this.getFieldByName(e);if(!r.isAtomic())throw new Error(`${e} is not an atomic field? Inconceivable!`);return r}getDimensionByName(e){const r=this.getFieldByName(e);if(S2(r))return r;throw new Error(`${e} is not an atomic scalar field? Inconceivable!`)}getStructByName(e){if(e.length===0)return this;const r=this.getFieldByName(e);if(r instanceof gs)return r.queryStruct;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.structDef.type!=="record")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Asking a record for a primary key? Inconceivable!")}applyStructFiltersToTurtleDef(e){let r=e.pipeline;const i=e.annotation,s=e.filterList||[];return r=structuredClone(r),r[0].filterList=s.concat(r[0].filterList||[],(0,Me.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[]),{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}class P4{constructor(e,r){this.eventStream=r,this.dialect=new itt.StandardSQLDialect,this.modelDef=void 0,this.structs=new Map,this.exploreSearchSQLMap=new Map,e&&this.loadModelFromDef(e)}loadModelFromDef(e){this.modelDef=e;for(const r of Object.values(this.modelDef.contents)){let i;if((0,Me.isSourceDef)(r))i=new p0(r,void 0,{model:this},{}),this.structs.set((0,Me.getIdentifier)(r),i),i.resolveQueryFields();else if(r.type!=="query")throw new Error("Internal Error: Unknown structure type")}}getStructByName(e){const r=this.structs.get(e);if(r)return r;throw new Error(`Struct ${e} not found in model.`)}getStructFromRef(e,r,i){var s;if(i??(i={}),typeof e=="string"){const o=this.getStructByName(e);return r!==void 0?new p0(o.structDef,r,(s=o.parent)!==null&&s!==void 0?s:{model:this},i):o}return new p0(e,r,{model:this},i)}loadQuery(e,r,i,s=!1,o=!1){var u;const a="";r||(r=new C2(!0,void 0));const l={type:"turtle",name:"ignoreme",pipeline:e.pipeline,filterList:e.filterList},c=(u=e.compositeResolvedSourceDef)!==null&&u!==void 0?u:e.structRef,f=ms.makeQuery(l,this.getStructFromRef(c,e.sourceArguments,i),r,o),x=f.generateSQLFromPipeline(r);if(s&&f.parent.dialect.hasFinalStage){const h=[];for(const p of x.outputStruct.fields)if((0,Me.isAtomic)(p)){const m=f.parent.dialect.sqlMaybeQuoteIdentifier(p.name);h.push(m)}x.lastStageName=r.addStage(f.parent.dialect.sqlFinalStage(x.lastStageName,h))}return{lastStageName:x.lastStageName,malloy:a,stageWriter:r,structs:[x.outputStruct],connectionName:f.parent.connectionName}}addDefaultRowLimit(e,r){const i={query:e,addedDefaultRowLimit:void 0};if(r===void 0)return i;const s=e.pipeline[e.pipeline.length-1];return s.type==="raw"||s.limit!==void 0?i:{query:{...e,pipeline:[...e.pipeline.slice(0,-1),{...s,limit:r}]},addedDefaultRowLimit:r}}compileQuery(e,r,i=!0){var s,o;const u=this.addDefaultRowLimit(e,r==null?void 0:r.defaultRowLimit);e=u.query;const a=u.addedDefaultRowLimit,c=this.loadQuery(e,void 0,r,i,!1),f=(s=e.compositeResolvedSourceDef)!==null&&s!==void 0?s:e.structRef,x=typeof f=="string"?f:f.as||f.name;return i&&this.dialect.hasFinalStage&&(c.lastStageName=c.stageWriter.addStage(this.dialect.sqlFinalStage(c.lastStageName,[]))),{lastStageName:c.lastStageName,malloy:c.malloy,sql:c.stageWriter.generateSQLStages(),dependenciesToMaterialize:c.stageWriter.dependenciesToMaterialize,materialization:(0,B4.shouldMaterialize)(e.annotation)?(0,B4.buildQueryMaterializationSpec)((o=e.location)===null||o===void 0?void 0:o.url,e.name,r==null?void 0:r.materializedTablePrefix):void 0,structs:c.structs,sourceExplore:x,sourceFilters:e.filterList,queryName:e.name,connectionName:c.connectionName,annotation:e.annotation,queryTimezone:c.structs[0].queryTimezone,defaultRowLimitAdded:a}}async searchIndex(e,r,i,s=1e3,o=void 0){if(!e.canPersist())return;const u=this.getStructByName(r);let a=[];for(const[E,A]of u.nameMap)To(A)&&A.includeInWildcard()&&a.push({type:"fieldref",path:[E]});a=a.sort((E,A)=>E.path[0].localeCompare(A.path[0]));const l={structRef:r,pipeline:[{type:"index",indexFields:a,sample:u.dialect.defaultSampling}]},c=u.dialect.sqlMaybeQuoteIdentifier("fieldName"),f=u.dialect.sqlMaybeQuoteIdentifier("fieldPath"),x=u.dialect.sqlMaybeQuoteIdentifier("fieldValue"),h=u.dialect.sqlMaybeQuoteIdentifier("fieldType"),p=u.dialect.sqlMaybeQuoteIdentifier("weight");let m=this.exploreSearchSQLMap.get(r);m===void 0&&(m=this.compileQuery(l,void 0,!1).sql,this.exploreSearchSQLMap.set(r,m));let g=`SELECT
|
|
1533
1533
|
${c},
|
|
1534
1534
|
${f},
|
|
1535
1535
|
${x},
|
|
@@ -1552,7 +1552,7 @@ ${i} ${o}: [`,u.length>0&&(s+=`
|
|
|
1552
1552
|
${i} `),s+="]")}return s}*walk(){for(const e of Object.keys(this.children)){const r=this.children[e];if(r instanceof Ua)yield r;else for(const i of r)yield i}}varInfo(){let e="";for(const[r,i]of Object.entries(this))r!=="elementType"&&(typeof i=="boolean"?e+=i?` ${r}`:` !${r}`:(typeof i=="string"||typeof i=="number")&&(e+=` ${r}=${i}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const r of this.walk()){const i=r.needs(e);if(i)return i}}inExperiment(e,r=!1){var i;const s=(i=this.translator())===null||i===void 0?void 0:i.compilerFlags.tag("experimental");return s&&(s.bare()||s.has(e))?!0:(r||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}et.MalloyElement=Ua;class ont extends Ua{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}et.Unimplemented=ont;class LB extends Ua{constructor(e){super(),this.name=e,this.elementType="modelEntryReference"}get refString(){return this.name}toString(){return this.refString}getNamed(){var e;return(e=this.modelEntry(this))===null||e===void 0?void 0:e.entry}}et.ModelEntryReference=LB;class unt extends Ua{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}et.ExperimentalExperiment=unt;function kle(t){return t.execute!==void 0}et.isDocStatement=kle;function ant(t){return t instanceof lE||kle(t)}et.isDocStatementOrDocStatementList=ant;class Mle extends Ua{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const r of this.elements){const i=r.needs(e);if(i)return i}}}et.ListOf=Mle;class lE extends Mle{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Ble.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Ble.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof lE){const i=r.executeList(e);if(i)return i}else{const i=r.needs(e);if(i)return i;r.execute(e)}this.execCursor+=1}}}et.DocStatementList=lE;const lnt="5a79a191-06bc-43cf-9b12-58741cd82970";function Ple(t){const e=t.inherits?Ple(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(r=>r.text)),t.notes&&e.push(...t.notes.map(r=>r.text)),e}function cnt(t){const e=Ple(t).join("");return(0,snt.v5)(e,lnt)}class IB extends Ua{constructor(e){super(),this.elementType="document",this.globalNameSpace=new int.GlobalNameSpace,this.documentModel={},this.queryList=[],this.didInitModel=!1,this.annotation={},this.experiments=new ent.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new lE(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[r,i]of Object.entries(e.contents)){const s=structuredClone(i);if((0,Q4.isSourceDef)(s)||s.type==="query"||s.type==="function"){const o=e.exports.includes(r);this.setEntry(r,{entry:s,exported:o})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),r=this.modelDef();if(e===void 0)for(const s of this.queryList)s.modelAnnotation===void 0&&r.annotation&&(s.modelAnnotation=r.annotation);if(r.annotation)for(const s of this.modelAnnotationTodoList)s.modelAnnotation||(s.modelAnnotation=r.annotation);return{modelDef:{...r,queryList:this.queryList},needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=cnt(e),e}}modelDef(){const e={name:"",exports:[],contents:{},queryList:[],dependencies:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const r in this.documentModel){const i=this.documentModel[r].entry;if((0,Q4.isSourceDef)(i)||i.type==="query"){this.documentModel[r].exported&&e.exports.push(r);const s=structuredClone(i);s.modelAnnotation===void 0&&e.annotation&&(s.modelAnnotation=e.annotation),e.contents[r]=s}}return e}getEntry(e){var r;return(r=this.globalNameSpace.getEntry(e))!==null&&r!==void 0?r:this.documentModel[e]}setEntry(e,r){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,Q4.isSourceDef)(r.entry)&&this.checkExperimentalDialect(this,r.entry.dialect),this.documentModel[e]=r}checkExperimentalDialect(e,r){const i=this.translator();i&&i.firstReferenceToDialect(r)&&(0,$le.getDialect)(r).experimental&&!i.experimentalDialectEnabled(r)&&e.logError("experimental-dialect-not-enabled",{dialect:r})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const r=(0,$le.getDialect)(e),i=new rnt.DialectNameSpace(r);return this.dialectNameSpaces.set(e,i),i}}et.Document=IB;var z4={},D2={},nn={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=Gi,r=dt;function i(f,x="scalar",h="constant"){return{type:f,expressionType:x,evalSpace:h,compositeFieldUsage:(0,r.emptyCompositeFieldUsage)()}}t.nullT=i("null"),t.numberT=i("number"),t.stringT=i("string"),t.dateT=i("date"),t.timestampT=i("timestamp"),t.boolT=i("boolean"),t.errorT=i("error"),t.viewT=i("turtle"),t.aggregateBoolT=i("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function s(f,x){return f?x.find(p=>o(p,f))!==void 0:!1}t.any=s;function o(f,x){return x!==void 0&&e.TD.eq(f,x)&&f.expressionType===x.expressionType}t.eq=o;function u(f,x){return f?x.find(p=>a(p,f))!==void 0:!1}t.typeIn=u;function a(f,x,h=!1,p=!0){const m=e.TD.eq(f,x),g=h&&(f.type==="null"||x.type==="null"),y=p&&(f.type==="error"||x.type==="error");return m||g||y}t.typeEq=a;function l(...f){return f.map(h=>{if(h){let p=h.type;return(0,e.expressionIsScalar)(h.expressionType)||(p=`${h.expressionType} ${p}`),p}return"undefined"}).join(",")}t.inspect=l;function c(f){if(e.TD.isAtomic(f))switch(f.type){case"array":return(0,e.isRepeatedRecord)(f)?{type:"array",elementTypeDef:f.elementTypeDef,fields:f.fields}:{type:"array",elementTypeDef:f.elementTypeDef};case"record":return{type:"record",fields:f.fields};case"number":return f.numberType?{type:"number",numberType:f.numberType}:{type:"number"};case"sql native":return f.rawType?{type:"sql native",rawType:f.rawType}:{type:"sql native"};default:return{type:f.type}}return{type:"error"}}t.atomicDef=c})(nn);var zr={},Gc={};Object.defineProperty(Gc,"__esModule",{value:!0}),Gc.canMakeEntry=Gc.SpaceEntry=void 0;class fnt{}Gc.SpaceEntry=fnt;function xnt(t){return"makeEntry"in t}Gc.canMakeEntry=xnt,Object.defineProperty(zr,"__esModule",{value:!0}),zr.SpaceField=void 0;const dnt=Gc,hnt=dt;class pnt extends dnt.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var r,i,s;const o=e.expressionType||"scalar";return{...e,expressionType:o,evalSpace:"input",compositeFieldUsage:(r=e.compositeFieldUsage)!==null&&r!==void 0?r:((i=e.e)===null||i===void 0?void 0:i.node)==="compositeField"?{fields:[(s=e.as)!==null&&s!==void 0?s:e.name],joinedUsage:{}}:(0,hnt.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}zr.SpaceField=pnt;var mnt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),gnt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ynt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mnt(e,t,r);return gnt(e,t),e};Object.defineProperty(D2,"__esModule",{value:!0}),D2.ViewField=void 0;const Ent=dt,Ant=ynt(nn),_nt=zr;class vnt extends _nt.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const r=this.fieldDef();return{...Ant.viewT,compositeFieldUsage:(e=r.compositeFieldUsage)!==null&&e!==void 0?e:(0,Ent.emptyCompositeFieldUsage)()}}}D2.ViewField=vnt,Object.defineProperty(z4,"__esModule",{value:!0}),z4.ASTViewField=void 0;const Cnt=D2;class Snt extends Cnt.ViewField{constructor(e,r,i){super(e),this.view=r,this.name=i,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}z4.ASTViewField=Snt,Object.defineProperty(aE,"__esModule",{value:!0}),aE.ViewFieldDeclaration=void 0;const bnt=et,Tnt=Qr,Rnt=b2,Dnt=z4;class Ont extends bnt.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=Tnt.extendNoteMethod}makeEntry(e){const r=new Dnt.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getName(){return this.name}getFieldDef(e){const{pipeline:r,annotation:i}=this.view.pipelineComp(e),s=(0,Rnt.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:i},location:this.location}}}aE.ViewFieldDeclaration=Ont;var Wn={};Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.LegalRefinementStage=Wn.QueryClass=void 0;var Ule;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(Ule||(Wn.QueryClass=Ule={}));var jle;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(jle||(Wn.LegalRefinementStage=jle={}));var Fnt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),wnt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nnt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Fnt(e,t,r);return wnt(e,t),e};Object.defineProperty(uE,"__esModule",{value:!0}),uE.NestFieldDeclaration=void 0;const Lnt=Nnt(tt),Int=b2,$nt=aE,qle=Wn;class Bnt extends $nt.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=qle.LegalRefinementStage.Single,this.forceQueryClass=qle.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:r,annotation:i}=this.view.pipelineComp(e,e.outputSpace()),s=r[0]&&Lnt.isQuerySegment(r[0])?r[0].compositeFieldUsage:void 0,o=(0,Int.detectAndRemovePartialStages)(r,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:o,annotation:{...this.note,inherits:i},location:this.location,compositeFieldUsage:s},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}uE.NestFieldDeclaration=Bnt;var O2={},gi={};Object.defineProperty(gi,"__esModule",{value:!0}),gi.ErrorFactory=void 0;const Hle="~malformed~";class $B{static get structDef(){return{type:"table",name:Hle,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:Hle,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:$B.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}gi.ErrorFactory=$B,Object.defineProperty(O2,"__esModule",{value:!0}),O2.DefineSourceList=O2.DefineSource=void 0;const knt=gi,Qle=et,Mnt=Qr;class Pnt extends Qle.MalloyElement{constructor(e,r,i,s){super(),this.name=e,this.sourceExpr=r,this.exported=i,this.parameters=s,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=Mnt.extendNoteMethod,r&&this.has({sourceExpr:r}),s&&this.has({parameters:s})}execute(e){var r;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const i=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(i===void 0)return;const s=this.deduplicatedParameters(),o=i.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(s,o),knt.ErrorFactory.didCreate(o))return;const u={...o,as:this.name,location:this.location};this.note&&(u.annotation=o.annotation?{...this.note,inherits:o.annotation}:this.note),e.setEntry(this.name,{entry:u,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},r=[];for(const i of this.parameters)i.name in e&&i.logError("parameter-name-conflict",`Cannot redefine parameter \`${i.name}\``),e[i.name]=!0,r.push(i);return r}validateParameterShadowing(e,r){for(const i of e)r.fields.find(s=>{var o;return((o=s.as)!==null&&o!==void 0?o:s.name)===i.name})&&i.logError("parameter-shadowing-field",`Illegal shadowing of field \`${i.name}\` by parameter with the same name`)}}O2.DefineSource=Pnt;class Unt extends Qle.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}O2.DefineSourceList=Unt;var F2={};Object.defineProperty(F2,"__esModule",{value:!0}),F2.DefineQueryList=F2.DefineQuery=void 0;const zle=et,jnt=Qr;class qnt extends zle.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=jnt.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const i=this.queryExpr.getQuery();if(!i){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const s={...i.query(),type:"query",name:this.name,location:this.location};this.note&&(s.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:!0})}}F2.DefineQuery=qnt;class Hnt extends zle.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}F2.DefineQueryList=Hnt;var Ro={};Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.Source=void 0;const Qnt=et;class znt extends Qnt.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const r={};for(const i of e){const s=i.parameter();r[s.name]=s}return r}withParameters(e,r){return{...this.getSourceDef(e),parameters:this.packParameters(r)}}}Ro.Source=znt;var cE={},w2={},W4={},Vc={};Object.defineProperty(Vc,"__esModule",{value:!0}),Vc.mergeFields=Vc.nameFromDef=void 0;function BB(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Vc.nameFromDef=BB;function Wnt(t,e){if(t===void 0)return e;const r=new Set(e.map(s=>BB(s))),i=t.filter(s=>!r.has(BB(s)));return i.push(...e),i}Vc.mergeFields=Wnt;var fE={},Wr={},ja={},Gnt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Vnt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ynt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Gnt(e,t,r);return Vnt(e,t),e};Object.defineProperty(ja,"__esModule",{value:!0}),ja.DefinedParameter=ja.AbstractParameter=ja.SpaceParam=void 0;const Knt=Gc,Wle=Ynt(nn),Gle=dt;class kB extends Knt.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}ja.SpaceParam=kB;class Jnt extends kB{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:Wle.atomicDef(e),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,Gle.emptyCompositeFieldUsage)()}}}ja.AbstractParameter=Jnt;class Xnt extends kB{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:Wle.atomicDef(e),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,Gle.emptyCompositeFieldUsage)()}}}ja.DefinedParameter=Xnt;var Cd={},Znt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ert=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),trt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Znt(e,t,r);return ert(e,t),e};Object.defineProperty(Cd,"__esModule",{value:!0}),Cd.StructSpaceFieldBase=void 0;const Vle=dt,nrt=tt,rrt=trt(nn),irt=zr;class srt extends irt.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,r;return(0,nrt.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,Vle.emptyCompositeFieldUsage)()}:{...rrt.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(r=this.structDef.onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Vle.emptyCompositeFieldUsage)()}}}Cd.StructSpaceFieldBase=srt;var xE={};Object.defineProperty(xE,"__esModule",{value:!0}),xE.ColumnSpaceField=void 0;const ort=zr;class urt extends ort.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}xE.ColumnSpaceField=urt;var G4={};Object.defineProperty(G4,"__esModule",{value:!0}),G4.IRViewField=void 0;const art=D2;class lrt extends art.ViewField{constructor(e,r){super(e),this.turtleDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}G4.IRViewField=lrt,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.StaticSourceSpace=Wr.StructSpaceField=Wr.StaticSpace=void 0;const crt=ka,N2=tt,frt=ja,xrt=zr,dE=Cd,drt=xE,hrt=G4;class MB{constructor(e,r){this.type="fieldSpace",this.fromStruct=e,this.structDialect=r}dialectName(){return this.structDialect}dialectObj(){try{return(0,crt.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,N2.isJoined)(e)?new PB(e,this.structDialect):(0,N2.isTurtle)(e)?new hrt.IRViewField(this,e):new drt.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if((0,N2.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,r]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new frt.DefinedParameter(r))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,r){this.map[e]=r}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,N2.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const r=e[0],i=e.slice(1);let s=this.entry(r.refString);if(!s)return{error:{message:`'${r}' is not defined`,code:"field-not-found"},found:s};if(s instanceof xrt.SpaceField){const u=s.fieldDef();if(u&&(!(s instanceof dE.StructSpaceFieldBase)&&(0,N2.isJoined)(u)&&(s=new PB(u,this.structDialect)),r.addReference({type:s instanceof dE.StructSpaceFieldBase?"joinReference":"fieldReference",definition:u,location:r.location,text:r.refString})),u!=null&&u.accessModifier&&!(this.isProtectedAccessSpace()&&u.accessModifier==="internal"&&e.length===1))return{error:{message:`'${r}' is ${u==null?void 0:u.accessModifier}`,code:"field-not-accessible"},found:void 0}}const o=s instanceof dE.StructSpaceFieldBase?[{...s.joinPathElement,name:r.refString}]:[];if(i.length){if(s instanceof dE.StructSpaceFieldBase){const u=s.fieldSpace.lookup(i);return u.found?{...u,joinPath:[...o,...u.joinPath]}:u}return{error:{message:`'${r}' cannot contain a '${i[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:s,error:void 0,joinPath:o,isOutputField:!1}}isQueryFieldSpace(){return!1}}Wr.StaticSpace=MB;class PB extends dE.StructSpaceFieldBase{constructor(e,r){super(e),this.forDialect=r}get fieldSpace(){return(0,N2.isSourceDef)(this.structDef)?new Yle(this.structDef):new MB(this.structDef,this.forDialect)}}Wr.StructSpaceField=PB;class Yle extends MB{constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}Wr.StaticSourceSpace=Yle,Object.defineProperty(fE,"__esModule",{value:!0}),fE.JoinSpaceField=void 0;const prt=Wr;class mrt extends prt.StructSpaceField{constructor(e,r,i){super(r.getStructDef(e),i),this.parameterSpace=e,this.join=r}}fE.JoinSpaceField=mrt;var L2={};Object.defineProperty(L2,"__esModule",{value:!0}),L2.ParameterSpace=void 0;const grt=ja;class yrt{constructor(e){this.type="fieldSpace",this._map={};for(const r of e)this._map[r.name]=new grt.AbstractParameter(r)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const r=e[0];if(r===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const i=this.entry(r.refString);return i===void 0?{error:{message:`\`${r}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${r}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:i,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}L2.ParameterSpace=yrt;var Ert=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Art=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_rt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ert(e,t,r);return Art(e,t),e};Object.defineProperty(W4,"__esModule",{value:!0}),W4.DynamicSpace=void 0;const vrt=_rt(tt),Crt=Vc,Srt=gi,brt=zr,Trt=fE,Rrt=D2,Kle=ja,Drt=Wr,Ort=Cd,Frt=L2;class wrt extends Drt.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,r){if(this.complete)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(const r of e)this.entry(r.name)===void 0&&(this.parameters.push(r),this.setEntry(r.name,new Kle.AbstractParameter(r)));return this}parameterSpace(){return new Frt.ParameterSpace(this.parameters)}newEntry(e,r,i){if(this.entry(e)){r.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,i)}renameEntry(e,r,i){this.dropEntry(e),this.setEntry(r,i)}addFieldDef(e){this.setEntry((0,Crt.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof Kle.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const r=new Map,i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof Ort.StructSpaceFieldBase?s.push([l,c]):c instanceof Rrt.ViewField?o.push([l,c]):c instanceof brt.SpaceField&&i.push([l,c]);const u=[...i,...s,...o],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof Trt.JoinSpaceField){const f=c.join.getStructDef(a);Srt.ErrorFactory.didCreate(f)||(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),c.join.fixupJoinOn(this,f))}else{const f=c.fieldDef();f&&(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&vrt.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}W4.DynamicSpace=wrt;var hE={};Object.defineProperty(hE,"__esModule",{value:!0}),hE.RenameSpaceField=void 0;const Nrt=zr;class Lrt extends Nrt.SpaceField{constructor(e,r,i){super(),this.otherField=e,this.newName=r,this.location=i}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}hE.RenameSpaceField=Lrt,Object.defineProperty(w2,"__esModule",{value:!0}),w2.RefinedSpace=void 0;const Irt=W4,$rt=Gc,Brt=hE,krt=zr;class UB extends Irt.DynamicSpace{static filteredFrom(e,r,i,s,o){const u=new UB(e),a=new Map;for(const l of s??[])a.has(l.name.refString)?l.name.logError("already-renamed",`${l.name.refString} already renamed to ${l.as}`):a.set(l.name.refString,{as:l.as,location:l.location,logTo:l.name});if(i!==void 0){const l=u.entries();u.dropEntries();for(const[c,f]of l)if(i.has(c)){const x=a.get(c);x?f instanceof krt.SpaceField?u.setEntry(x.as,new Brt.RenameSpaceField(f,x.as,x.location)):x.logTo.logError("cannot-rename-non-field",`Cannot rename \`${c}\` which is not a field`):u.setEntry(c,f)}r!==void 0&&r.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(r){const l=r.refs.list,c=u.entries();for(const f of l)c.find(([h])=>h===f.refString)===void 0&&(o!=null&&o.entry(f.refString)?f.logError(`${r.edit}-parameter`,`Illegal \`${r.edit}:\` of parameter`):f.logError("field-list-edit-not-found",`\`${f.refString}\` is not defined`));u.dropEntries();for(const[f,x]of c){const h=!!l.find(m=>m.refString===f),p=r.edit==="accept";h===p&&u.setEntry(f,x)}}return u}pushFields(...e){for(const r of e)this.addField(r)}addField(e){(0,$rt.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[r,i]of e)this.newAccessModifiers.set(r,i)}addNotes(e){for(const[r,i]of e)this.newNotes.set(r,i)}isProtectedAccessSpace(){return!0}}w2.RefinedSpace=UB;var Yc={},Qs={};Object.defineProperty(Qs,"__esModule",{value:!0}),Qs.DefinitionList=void 0;const Mrt=et,Jle=Qr;class Prt extends Mrt.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,Jle.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,Jle.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Qs.DefinitionList=Prt,Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.DeclareFields=void 0;const Urt=Qs,jrt=Wn;class qrt extends Urt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="declareFields",this.queryRefinementStage=jrt.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r)}get delarationNames(){return this.list.map(e=>e.defineName)}}Yc.DeclareFields=qrt;var qa={};Object.defineProperty(qa,"__esModule",{value:!0}),qa.Filter=qa.FilterElement=void 0;const Xle=tt,Hrt=zn,Zle=et,jB=Wn;class Qrt extends Zle.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterCondition(e){const r=this.expr.getExpression(e);return r.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:r.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:r.value,expressionType:r.expressionType,compositeFieldUsage:r.compositeFieldUsage}}}qa.FilterElement=Qrt;class zrt extends Zle.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=jB.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?jB.LegalRefinementStage.Tail:jB.LegalRefinementStage.Head}checkedFilterCondition(e,r){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,Xle.expressionIsAggregate)(i.expressionType),o=(0,Xle.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(o){r.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else s&&r.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return i}getFilterList(e){return this.list.map(r=>this.checkedFilterCondition(e,r)).filter(Hrt.isNotUndefined)}queryExecute(e){const r=this.havingClause?e.resultFS:e.inputFS;for(const i of this.list){const s=this.checkedFilterCondition(r,i);s!==void 0&&(e.filters.push(s),e.resultFS.addCompositeFieldUserFromFilter(s,i))}}}qa.Filter=zrt;var I2={};Object.defineProperty(I2,"__esModule",{value:!0}),I2.FieldListEdit=void 0;const Wrt=et;class Grt extends Wrt.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}}I2.FieldListEdit=Grt;var $2={};Object.defineProperty($2,"__esModule",{value:!0}),$2.PrimaryKey=void 0;const Vrt=et;class Yrt extends Vrt.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}$2.PrimaryKey=Yrt;var B2={};Object.defineProperty(B2,"__esModule",{value:!0}),B2.Views=void 0;const Krt=Qs;class Jrt extends Krt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}B2.Views=Jrt;var k2={};Object.defineProperty(k2,"__esModule",{value:!0}),k2.TimezoneStatement=void 0;const Xrt=et,Zrt=qr;class eit extends Xrt.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return Zrt.DateTime.fromISO("2020-02-19T00:00:00",{zone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}k2.TimezoneStatement=eit;var Kc={};Object.defineProperty(Kc,"__esModule",{value:!0}),Kc.ModelAnnotation=Kc.ObjectAnnotation=void 0;const tit=et,nit=mi;class e0e extends tit.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Kc.ObjectAnnotation=e0e;class rit extends e0e{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){const i=(0,nit.annotationToTag)({notes:this.notes},{prefix:/^##! /,extending:e});return i.log.forEach(s=>r.log(s)),i.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}Kc.ModelAnnotation=rit;var Jc={};Object.defineProperty(Jc,"__esModule",{value:!0}),Jc.Renames=Jc.RenameField=void 0;const iit=hE,t0e=et,sit=zr;class oit extends t0e.MalloyElement{constructor(e,r){super(),this.newName=e,this.oldName=r,this.elementType="renameField",this.has({oldName:r})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const r=this.oldName.getField(e);r.found?r.found instanceof sit.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new iit.RenameSpaceField(r.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}Jc.RenameField=oit;class uit extends t0e.ListOf{constructor(e,r){super(e),this.accessModifier=r,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}Jc.Renames=uit;var ys={};Object.defineProperty(ys,"__esModule",{value:!0}),ys.JoinStatement=ys.ExpressionJoin=ys.KeyJoin=ys.Join=void 0;const qB=tt,ait=fE,lit=Qs,cit=et,fit=Qr,n0e=gi,xit=Wn;class HB extends cit.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=fit.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new ait.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const r=this.sourceExpr.getSource();return r?r.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),n0e.ErrorFactory.structDef)}}ys.Join=HB;class dit extends HB{constructor(e,r,i){super({name:e,sourceExpr:r,keyExpr:i}),this.name=e,this.sourceExpr=r,this.keyExpr=i,this.elementType="joinOnKey"}getStructDef(e){var r;const i=this.getStructDefFromExpr(e);if(!(0,qB.isJoinable)(i))throw this.internalError(`Cannot join struct type '${i.type}'`);const s={...i,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete s.as,this.note&&(s.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),s}fixupJoinOn(e,r){const i=this.keyExpr.getExpression(e);if((0,qB.isSourceDef)(r)&&r.primaryKey){const s=r.fields.find(o=>(o.as||o.name)===r.primaryKey);if(s)if(s.type===i.type){r.join="one",r.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,r.primaryKey]},right:i.value}},r.onCompositeFieldUsage=i.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${i.type}/${s.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${s}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}ys.KeyJoin=dit;class hit extends HB{constructor(e,r){super({name:e,sourceExpr:r}),this.name=e,this.sourceExpr=r,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,r){if(this.expr===void 0)return;const i=this.expr.getExpression(e);if(i.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}r.onExpression=i.value,r.onCompositeFieldUsage=i.compositeFieldUsage}getStructDef(e){var r;const i=this.sourceExpr.getSource();if(!i)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),n0e.ErrorFactory.joinDef;const s=i.getSourceDef(e);let o="left";if(this.inExperiment("join_types",!0)&&(o=this.matrixOperation),!(0,qB.isJoinable)(s))throw this.internalError(`Can't join struct type ${s.type}`);const u={...s,name:this.name.refString,join:this.joinType,matrixOperation:o,location:this.location};return delete u.as,this.note&&(u.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}ys.ExpressionJoin=hit;class pit extends lit.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=xit.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r),e.alwaysJoins.push(r.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}ys.JoinStatement=pit;var bu={};Object.defineProperty(bu,"__esModule",{value:!0}),bu.IncludeListItem=bu.IncludeExceptItem=bu.IncludeAccessItem=bu.IncludeItem=void 0;const r0e=et,i0e=Qr;class QB extends r0e.MalloyElement{}bu.IncludeItem=QB;class mit extends QB{constructor(e,r){super(),this.kind=e,this.fields=r,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=i0e.extendNoteMethod,this.has({fields:r})}}bu.IncludeAccessItem=mit;class git extends QB{constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}bu.IncludeExceptItem=git;class yit extends r0e.MalloyElement{constructor(e,r){super({name:e}),this.name=e,this.as=r,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=i0e.extendNoteMethod}}bu.IncludeListItem=yit;var _t={},pE={},Eit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Ait=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_it=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eit(e,t,r);return Ait(e,t),e};Object.defineProperty(pE,"__esModule",{value:!0}),pE.ReferenceField=void 0;const s0e=tt,o0e=_it(nn),u0e=zr,vit=dt;class Cit extends u0e.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.path;if(r.found&&r.found.refType==="parameter"){const o=r.found.typeDesc();if(s0e.TD.isAtomic(o))this.queryFieldDef={...(0,s0e.mkFieldDef)(o0e.atomicDef(o),i[0]),e:{node:"parameter",path:i}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:i};const s=this.referenceTo;if(s instanceof u0e.SpaceField){const o=s.constructorFieldDef();if(o){const u=this.fieldRef.note;if(o.annotation||u){const a=u||{};o.annotation&&(a.inherits=o.annotation),this.queryFieldDef.annotation=a}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const r=this.fieldRef.list.slice(0,-1).map(s=>s.refString),i=e.typeDesc();return this.memoTypeDesc={...i,compositeFieldUsage:(0,vit.joinedCompositeFieldUsage)(r,i.compositeFieldUsage)},this.memoTypeDesc}return o0e.errorT}}pE.ReferenceField=Cit;var lr={};Object.defineProperty(lr,"__esModule",{value:!0}),lr.typecheckGroupBy=lr.typecheckAggregate=lr.typecheckCalculate=lr.typecheckDeclare=lr.typecheckMeasure=lr.typecheckDimension=lr.typecheckIndex=lr.typecheckProject=void 0;const Mn=Gi;function Sit(t,e){if(t.type==="turtle"||!(0,Mn.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="select-of-view";else if((0,Mn.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="select-of-analytic";else if((0,Mn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a select operation, did you mean to use ${r} operation instead?`)}}lr.typecheckProject=Sit;function bit(t,e){if(t.type==="turtle"||!(0,Mn.expressionIsScalar)(t.expressionType)){let r,i;if(t.type==="turtle")r="a view",i="index-of-view";else if((0,Mn.expressionIsAnalytic)(t.expressionType))r="an analytic",i="index-of-analytic";else if((0,Mn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in an index operation`)}}lr.typecheckIndex=bit;function Tit(t,e){if(!(0,Mn.expressionIsScalar)(t.expressionType))if((0,Mn.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,Mn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}lr.typecheckDimension=Tit;function Rit(t,e){if(!(0,Mn.expressionIsAggregate)(t.expressionType))if((0,Mn.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,Mn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}lr.typecheckMeasure=Rit;function Dit(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,Mn.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}lr.typecheckDeclare=Dit;function Oit(t,e){if(t.type==="turtle"||!(0,Mn.expressionIsAnalytic)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="calculate-of-view";else if((0,Mn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="calculate-of-aggregate";else if((0,Mn.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a calculate operation, did you mean to use ${r} operation instead?`)}}lr.typecheckCalculate=Oit;function Fit(t,e){if(t.type==="turtle"||!(0,Mn.expressionIsAggregate)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="aggregate-of-view";else if((0,Mn.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="aggregate-of-analytic";else if((0,Mn.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(s,`Cannot use ${i} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}lr.typecheckAggregate=Fit;function wit(t,e){if(t.type==="turtle"||!(0,Mn.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="group-by-view";else if((0,Mn.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="group-by-analytic";else if((0,Mn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a group_by operation, did you mean to use ${r} operation instead?`)}}lr.typecheckGroupBy=wit,Object.defineProperty(_t,"__esModule",{value:!0}),_t.FieldReferences=_t.WildcardFieldReference=_t.ViewOrScalarFieldReference=_t.DimensionFieldReference=_t.MeasureFieldReference=_t.DeclareFieldReference=_t.ProjectFieldReference=_t.GroupByFieldReference=_t.AggregateFieldReference=_t.IndexFieldReference=_t.CalculateFieldReference=_t.ParameterFieldReference=_t.PartitionByFieldReference=_t.ExpressionFieldReference=_t.AccessModifierFieldReference=_t.AcceptExceptFieldReference=_t.FieldReference=void 0;const Nit=pE,Lit=Qs,a0e=et,l0e=Qr,Xc=lr;class Yi extends a0e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=l0e.extendNoteMethod}makeEntry(e){const r=this.outputName;if(e.entry(r))this.logError("output-name-conflict",`Output already has a field named '${r}'`);else{const i=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Nit.ReferenceField(this,i))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const r=e.lookup(this.list);if(r.found){const i=r.found.typeDesc();this.typecheck(i)}return r}}_t.FieldReference=Yi;class Iit extends Yi{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}_t.AcceptExceptFieldReference=Iit;class $it extends Yi{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}_t.AccessModifierFieldReference=$it;class Bit extends Yi{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}_t.ExpressionFieldReference=Bit;class kit extends Yi{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}_t.PartitionByFieldReference=kit;class Mit extends Yi{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}_t.ParameterFieldReference=Mit;class Pit extends Yi{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Xc.typecheckCalculate)(e,this)}}_t.CalculateFieldReference=Pit;class zB extends Yi{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Xc.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return zB.indexOutputName(this.path)}}_t.IndexFieldReference=zB;class Uit extends Yi{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Xc.typecheckAggregate)(e,this)}}_t.AggregateFieldReference=Uit;class jit extends Yi{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Xc.typecheckGroupBy)(e,this)}}_t.GroupByFieldReference=jit;class qit extends Yi{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Xc.typecheckProject)(e,this)}}_t.ProjectFieldReference=qit;class Hit extends Yi{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Xc.typecheckDeclare)(e,this)}}_t.DeclareFieldReference=Hit;class Qit extends Yi{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Xc.typecheckMeasure)(e,this)}}_t.MeasureFieldReference=Qit;class zit extends Yi{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Xc.typecheckDimension)(e,this)}}_t.DimensionFieldReference=zit;class Wit extends Yi{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}_t.ViewOrScalarFieldReference=Wit;class Git extends a0e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=l0e.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}_t.WildcardFieldReference=Git;class Vit extends Lit.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}_t.FieldReferences=Vit,Object.defineProperty(cE,"__esModule",{value:!0}),cE.RefinedSource=void 0;const Yit=tt,Kit=w2,Jit=Yc,Xit=qa,Zit=I2,est=$2,tst=B2,nst=Ro,rst=k2,ist=Kc,sst=Jc,ost=L2,ust=ys,c0e=bu,WB=_t;class ast extends nst.Source{constructor(e,r,i){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.includeList=i,this.elementType="refinedSource",i&&this.has({includeList:i})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;let s,o;const u=[],a=[];let l;const c=[];for(const v of this.refinement.list){if(v instanceof ist.ObjectAnnotation)continue;const C=v;if(v instanceof est.PrimaryKey){if(s){const S="multiple-primary-keys";s.logError(S,"Primary key already defined"),v.logError(S,"Primary key redefined")}s=v}else if(v instanceof Zit.FieldListEdit){if(o){const S="multiple-field-list-edits";o.logError(S,"Too many accept/except statements"),v.logError(S,"Too many accept/except statements")}o=v}else v instanceof Jit.DeclareFields||v instanceof ust.JoinStatement||v instanceof tst.Views||v instanceof sst.Renames?(u.push(...v.list),v.accessModifier&&c.push({fields:v.delarationNames,access:v.accessModifier})):v instanceof Xit.Filter?a.push(v):v instanceof rst.TimezoneStatement?l=v.tz:C.logError("unexpected-source-property",`Unexpected source property: '${C.elementType}'`)}const f=r?new ost.ParameterSpace(r):void 0,x=structuredClone(this.source.getSourceDef(f)),{fieldsToInclude:h,modifiers:p,renames:m,notes:g}=lst(this.includeList,x);for(const v of c)for(const C of v.fields)p.set(C,v.access);s&&(x.primaryKey=s.field.name);const y=Kit.RefinedSpace.filteredFrom(x,o,h,m,f);if(l&&y.setTimezone(l),r&&y.addParameters(r),y.pushFields(...u),s){const v=s.field.getField(y);v.error&&s.logError(v.error.code,v.error.message)}y.addAccessModifiers(p),y.addNotes(g);const E=y.structDef(),A=E.filterList||[];let _=!1;for(const v of a)for(const C of v.list){const S=C.filterCondition(y);(0,Yit.expressionIsCalculation)(S.expressionType)?C.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(A.push(S),_=!0)}return _?{...E,filterList:A}:((i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(E),E)}}cE.RefinedSource=ast;function lst(t,e){var r,i,s,o,u,a,l,c,f;const x=new Set(e.fields.map(S=>S.name)),h=new Set(e.fields.filter(S=>S.accessModifier==="private").map(S=>S.name));let p;const m=new Set;let g,y;const E=new Map,A=[],_=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:E,renames:A,notes:_};for(const S of t)if(S instanceof c0e.IncludeAccessItem)for(const b of S.fields)if(b.name instanceof WB.WildcardFieldReference)b.name.joinPath&&b.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),g!==void 0?S.logError("already-used-star-in-include","Wildcard already used in this include block"):(g=(r=S.kind)!==null&&r!==void 0?r:"inherit",y={notes:(s=(i=b.note)===null||i===void 0?void 0:i.notes)!==null&&s!==void 0?s:[],blockNotes:(u=(o=S.note)===null||o===void 0?void 0:o.blockNotes)!==null&&u!==void 0?u:[]});else{if(p==="exclude"){S.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}p="include";const R=b.name.refString;h.has(R)&&b.logError("cannot-expand-access",`Cannot expand access of \`${R}\` from private to ${S.kind}`),E.has(R)?b.logError("duplicate-include",`Field \`${R}\` already referenced in include list`):(S.kind!==void 0&&E.set(R,S.kind),m.add(R),(b.note||S.note)&&_.set(R,{notes:(l=(a=b.note)===null||a===void 0?void 0:a.notes)!==null&&l!==void 0?l:[],blockNotes:(f=(c=S.note)===null||c===void 0?void 0:c.blockNotes)!==null&&f!==void 0?f:[]})),b.as&&(b.name instanceof WB.WildcardFieldReference?b.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):A.push({name:b.name,as:b.as,location:b.location}))}else if(S instanceof c0e.IncludeExceptItem)for(const b of S.fields)b instanceof WB.WildcardFieldReference?b.joinPath?b.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):b.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):p==="include"?S.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(p="exclude",g="inherit",m.add(b.refString));const v=new Set(x);m.forEach(S=>v.delete(S)),h.forEach(S=>v.delete(S));let C;if(g!==void 0)for(const S of v)g!=="inherit"&&E.set(S,g),y&&_.set(S,{...y});return p!=="exclude"?g!==void 0?C=x:C=m:C=v,{fieldsToInclude:C,modifiers:E,renames:A,notes:_}}var Tu={};Object.defineProperty(Tu,"__esModule",{value:!0}),Tu.SourceQueryElement=void 0;const cst=et;class GB extends cst.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,r,i){return this.isErrorFree()&&this.logError(e,r,i),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const r of this.walk())if(r instanceof GB&&r.errored){e=!1;break}return e}}Tu.SourceQueryElement=GB;var V4={},Sd={};Object.defineProperty(Sd,"__esModule",{value:!0}),Sd.QuerySource=void 0;const fst=Ro,xst=m2;class dst extends fst.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,r){var i;const s=this.query.queryComp(!1),o={...s.outputStruct,name:`QuerySource-${(0,xst.v4)()}`,type:"query_source",query:s.query};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(o),{...o,parameters:this.packParameters(r)}}}Sd.QuerySource=dst;var M2={},mE={};Object.defineProperty(mE,"__esModule",{value:!0}),mE.QueryBase=void 0;const VB=dt,f0e=tt,hst=b2,pst=et;class mst extends pst.MalloyElement{resolveCompositeSource(e,r){var i;const s=r.pipeline[0];if(s&&((0,f0e.isQuerySegment)(s)||(0,f0e.isIndexSegment)(s))){const o=(i=s.compositeFieldUsage)!==null&&i!==void 0?i:(0,VB.emptyCompositeFieldUsage)();if(!(0,VB.isEmptyCompositeFieldUsage)(o)||e.type==="composite")return(0,VB.resolveCompositeSources)(e,o).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,hst.detectAndRemovePartialStages)(e.pipeline,this)}}}mE.QueryBase=mst,Object.defineProperty(M2,"__esModule",{value:!0}),M2.QueryArrow=void 0;const gst=tt,yst=Ro,x0e=Wr,Est=mE;class Ast extends Est.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){var r;let i,s,o;if(this.source instanceof yst.Source){const h=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};s={type:"query",...h,pipeline:[],location:this.location},i=(0,gst.refIsStructDef)(h.structRef)?h.structRef:this.source.getSourceDef(void 0),o=new x0e.StaticSourceSpace(i)}else{const h=this.source.queryComp(e);s=h.query,i=h.outputStruct,o=new x0e.StaticSourceSpace(h.outputStruct)}const{pipeline:u,annotation:a,outputStruct:l,name:c}=this.view.pipelineComp(o),f={...s,name:c,annotation:a,pipeline:[...s.pipeline,...u]},x=(r=f.compositeResolvedSourceDef)!==null&&r!==void 0?r:this.resolveCompositeSource(i,f);return{query:{...f,compositeResolvedSourceDef:x},outputStruct:l,inputStruct:i}}}M2.QueryArrow=Ast,Object.defineProperty(V4,"__esModule",{value:!0}),V4.SQArrow=void 0;const _st=Tu,vst=Sd,Cst=M2;class Sst extends _st.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const r=new Cst.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const r=new vst.QuerySource(e);return this.has({asSource:r}),r}}V4.SQArrow=Sst;var Y4={},P2={},zs={};Object.defineProperty(zs,"__esModule",{value:!0}),zs.getStructFieldDef=zs.getFinalStruct=zs.opOutputStruct=void 0;const d0e=D0,bst=js,K4=tt,h0e=gi;function p0e(t,e,r){const i=h0e.ErrorFactory.didCreate(e)||(0,K4.structHasErrors)(e);(0,K4.isPartialSegment)(r)&&(r={...r,type:"reduce"});const s=(0,K4.segmentHasErrors)(r);if(!i&&!s)try{const o=bst.Segment.nextStructDef(e,r);if((0,K4.isSourceDef)(o))return o;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
|
|
1553
1553
|
STRUCTDEF: ${(0,d0e.inspect)(o,{breakLength:72,depth:1/0})}`)}catch(o){t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: ${o.message}
|
|
1554
1554
|
QUERY: ${(0,d0e.inspect)(r,{breakLength:72,depth:1/0})}`)}return h0e.ErrorFactory.structDef}zs.opOutputStruct=p0e;function Tst(t,e,r){for(const i of r)e=p0e(t,e,i);return e}zs.getFinalStruct=Tst;function Rst(t,e){return t.fields.find(r=>(r.as||r.name)===e)}zs.getStructFieldDef=Rst,Object.defineProperty(P2,"__esModule",{value:!0}),P2.QueryRefine=void 0;const Dst=Wr,Ost=zs,Fst=mE;class wst extends Fst.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){const r=this.base.queryComp(e),i=new Dst.StaticSourceSpace(r.inputStruct),s=this.refinement.refine(i,r.query.pipeline,void 0),o={...r.query,pipeline:s},u=this.resolveCompositeSource(r.inputStruct,o);return{query:{...o,compositeResolvedSourceDef:u},outputStruct:(0,Ost.getFinalStruct)(this.refinement,r.inputStruct,s),inputStruct:r.inputStruct}}}P2.QueryRefine=wst;var gE={},U2={},Es={};Object.defineProperty(Es,"__esModule",{value:!0}),Es.mkTimeResult=Es.resolution=Es.castTo=Es.timeOffset=void 0;const YB=tt;function Nst(t,e,r,i,s){return{node:"delta",kids:{base:(0,YB.mkTemporal)(e,t),delta:i},op:r,units:s}}Es.timeOffset=Nst;function Lst(t,e,r,i=!1){let s;return typeof t!="string"?s={node:"cast",dstSQLType:t.raw,e,safe:i}:s={node:"cast",dstType:{type:t},e,safe:i},(0,YB.isCastType)(r)&&(s.srcType={type:r}),s}Es.castTo=Lst;function Ist(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Es.resolution=Ist;function $st(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,YB.isDateUnit)(e))return{...t,timeframe:e}}return t}Es.mkTimeResult=$st;var bd={},ht={},Yt={};Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.literalTimeResult=Yt.literalExprValue=Yt.computedErrorExprValue=Yt.computedTimeResult=Yt.computedExprValue=void 0;const m0e=Gi,KB=dt;function yE({value:t,dataType:e,from:r}){return{...e,value:t,expressionType:(0,m0e.maxOfExpressionTypes)(r.map(i=>i.expressionType)),evalSpace:(0,m0e.mergeEvalSpaces)(...r.map(i=>i.evalSpace)),compositeFieldUsage:(0,KB.mergeCompositeFieldUsage)(...r.map(i=>i.compositeFieldUsage))}}Yt.computedExprValue=yE;function Bst({value:t,dataType:e,from:r,timeframe:i}){const s=yE({value:t,dataType:e,from:r}),o={...e,expressionType:s.expressionType,evalSpace:s.evalSpace,value:s.value,compositeFieldUsage:(0,KB.mergeCompositeFieldUsage)(...r.map(u=>u.compositeFieldUsage))};return i&&(o.timeframe=i),o}Yt.computedTimeResult=Bst;function kst({dataType:t,from:e,error:r}){return yE({dataType:t??{type:"error"},value:{node:"error",message:r},from:e})}Yt.computedErrorExprValue=kst;function Mst(t){return yE({...t,from:[]})}Yt.literalExprValue=Mst;function Pst({value:t,dataType:e,timeframe:r}){const i=yE({value:t,dataType:e,from:[]}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,KB.emptyCompositeFieldUsage)()};return r&&(s.timeframe=r),s}Yt.literalTimeResult=Pst;var j2={};Object.defineProperty(j2,"__esModule",{value:!0}),j2.isGranularResult=void 0;function Ust(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}j2.isGranularResult=Ust;var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.isComparison=Ru.isEquality=Ru.getExprNode=void 0;function jst(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}Ru.getExprNode=jst;function g0e(t){return t==="="||t==="!="||t==="~"||t==="!~"}Ru.isEquality=g0e;function qst(t){return g0e(t)||t===">="||t==="<="||t===">"||t==="<"}Ru.isComparison=qst;var Hst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Qst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hst(e,t,r);return Qst(e,t),e};Object.defineProperty(ht,"__esModule",{value:!0}),ht.checkFilterExpression=ht.applyBinary=ht.getMorphicValue=ht.ExprDuration=ht.ExpressionDef=ht.ATNodeType=void 0;const Zc=tt,Td=zst(nn),JB=Hs,m0=Yt,Wst=Es,y0e=j2,Gst=et,EE=Ru,AE=iE;class Vst extends Error{}var XB;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(XB||(ht.ATNodeType=XB={}));class E0e extends Gst.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Td.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.type!=="error"&&!Td.any(r,this.legalChildTypes)?(r.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${Td.inspect(r)}`),!1):!0}apply(e,r,i,s=!1){return C0e(e,i,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Zc.expressionIsAggregate)(e.expressionType)}atNodeType(){return XB.Value}atExpr(){return this}}ht.ExpressionDef=E0e;class ZB extends E0e{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Td.timestampT,Td.dateT]}apply(e,r,i){const s=i.getExpression(e);if(this.typeCheck(this,s),(0,Zc.isTemporalType)(s.type)&&(r==="+"||r==="-")){const o=this.n.getExpression(e);if(!Td.typeEq(o,Td.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${o.type}`),(0,JB.errorFor)("illegal unit expression");let u;return(0,y0e.isGranularResult)(s)&&s.timeframe===this.timeframe&&(u=s.timeframe),s.type==="date"&&!(0,Zc.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,m0.computedTimeResult)({dataType:{type:s.type},value:(0,Wst.timeOffset)(s.type,s.value,r,o.value,this.timeframe),timeframe:u,from:[s,o]})}return super.apply(e,r,i)}getExpression(e){const r=this.n.getExpression(e);return(0,m0.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[r]})}}ht.ExprDuration=ZB;function A0e(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function Yst(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,m0.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}ht.getMorphicValue=Yst;function _0e(t,e,r,i){const s=(0,Zc.isTemporalType)(e.type),o=(0,Zc.isTemporalType)(i.type),u=(0,EE.getExprNode)(r);if(s&&o)if(e.type!==i.type){const a=A0e(e,"timestamp"),l=A0e(i,"timestamp");if(a&&l)return{node:u,kids:{left:a,right:a}}}else return{node:u,kids:{left:e.value,right:i.value}};if((s||o)&&e.type!=="null"&&i.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${i.type}`),{node:"false"}}function Kst(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function Jst(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=(0,EE.getExprNode)(r),a=_E("boolean",s,o);if(a)return a;const l=Zc.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=Zc.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=vE(e,s,i,o);if(h)return{...h,type:"boolean"}}let f;if(o.type==="filter expression"){if(r!=="~"&&r!=="!~")return i.loggedErrorExpr("filter-expression-error",`Cannot use the '${r}' operator with a filter expression`);if((0,AE.isFilterable)(s.type)){let x=o.value;for(;x.node==="()";)x=x.e;x.node!=="parameter"&&S0e(i,s.type,x);const h={node:"filterMatch",dataType:s.type,kids:{filterExpr:o.value,expr:s.value}};r==="!~"&&(h.notMatch=!0),f=h}else return e.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${s.type}'`)}else if(f=_0e(e,s,r,o)||{node:u,kids:{left:s.value,right:o.value}},s.type!=="error"&&o.type!=="error"&&(r==="~"||r==="!~")&&(s.type!=="string"||o.type!=="string")){let x=Kst(s,o);if(x)r[0]==="!"&&(x={node:"not",e:{...x}});else throw new Vst("Incompatible types for match('~') operator");f=x}return(0,m0.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function Xst(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=_E("boolean",s,o);if(u)return u;const a=vE(e,s,i,o);if(a)return{...a,type:"boolean"};const l=_0e(e,s,r,o)||{node:(0,EE.getExprNode)(r),kids:{left:s.value,right:o.value}};return(0,m0.computedExprValue)({dataType:{type:"boolean"},value:l,from:[s,o]})}function v0e(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=_E("number",s,o);if(u)return u;const a=vE(e,s,i,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${s.type}'`);else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${o.type}'`);else return(0,m0.computedExprValue)({dataType:{type:"number"},value:{node:r,kids:{left:s.value,right:o.value}},from:[s,o]});return(0,JB.errorFor)("numbers required")}function Zst(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=vE(e,s,i,o);if(u)return u;const a=(0,Zc.isTemporalType)(s.type),l=_E(a?"error":"number",s,o);if(l)return l;if(a){let c=i;if(o.type!=="duration")if((0,y0e.isGranularResult)(s))c=new ZB(i,s.timeframe);else if(s.type==="date")c=new ZB(i,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${o.type}'`);return c.apply(t,r,e)}return v0e(t,e,r,i)}function C0e(t,e,r,i){if((0,EE.isEquality)(r))return Jst(t,e,r,i);if((0,EE.isComparison)(r))return Xst(t,e,r,i);if(r==="+"||r==="-")return Zst(t,e,r,i);if(r==="*")return v0e(t,e,r,i);if(r==="/"||r==="%"){const s=e.getExpression(t),o=i.getExpression(t),u=vE(e,s,i,o);if(u)return u;const a=_E("number",s,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const l={node:r,kids:{left:s.value,right:o.value}};return(0,m0.computedExprValue)({dataType:{type:"number"},value:l,from:[s,o]})}return(0,JB.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${r} operator here`)}ht.applyBinary=C0e;function _E(t,...e){if(e.some(r=>r.type==="error"))return(0,m0.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function vE(t,e,r,i){const s=(0,m0.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,i]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),s.type=i.type,s;if(i.type==="sql native")return r.logError("sql-native-not-allowed-in-expression",{rawType:i.rawType}),s}function S0e(t,e,r){for(var i,s,o,u;r.node==="()";)r=r.e;if(r.node!=="filterLiteral"){t.logError("filter-expression-error","Expected a filter expression literal here");return}const a=r.filterSrc;let l;e==="date"||e==="timestamp"?l=(i=AE.TemporalFilterExpression.parse(a).log[0])===null||i===void 0?void 0:i.message:e==="string"?l=(s=AE.StringFilterExpression.parse(a).log[0])===null||s===void 0?void 0:s.message:e==="number"?l=(o=AE.NumberFilterExpression.parse(a).log[0])===null||o===void 0?void 0:o.message:e==="boolean"?l=(u=AE.BooleanFilterExpression.parse(a).log[0])===null||u===void 0?void 0:u.message:t.logError("filter-expression-type",`Cannot apply filter expression to type ${e}`),l!==void 0&&t.logError("filter-expression-error",`Filter syntax error: ${l}`)}ht.checkFilterExpression=S0e,Object.defineProperty(bd,"__esModule",{value:!0}),bd.ExprIdReference=void 0;const eot=tt,tot=ht,not=dt;class rot extends tot.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const r=this.fieldReference.getField(e),i=this.fieldReference.list.map(s=>s.name).slice(0,-1);if(r.found){const s=r.found.typeDesc(),o=(0,not.joinedCompositeFieldUsage)(i,s.compositeFieldUsage);if(r.isOutputField)return{...s,evalSpace:s.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:o};const u={node:r.found.refType,path:this.fieldReference.path},a=(0,eot.expressionIsAggregate)(s.expressionType)?"output":s.evalSpace;return{...s,value:u,evalSpace:a,compositeFieldUsage:o}}return this.loggedErrorExpr(r.error.code,r.error.message)}}bd.ExprIdReference=rot,Object.defineProperty(U2,"__esModule",{value:!0}),U2.NamedSource=void 0;const ek=tt,iot=Ro,sot=gi,oot=Es,b0e=et,uot=bd,aot=L2,lot=ht;class cot extends iot.Source{constructor(e,r,i){super(),this.ref=e,this.sourceArguments=r,this.args=i,this.elementType="namedSource",i&&this.has({args:i}),e instanceof b0e.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof b0e.ModelEntryReference?this.ref.name:this.ref}structRef(e){const r=this.modelEntry(this.ref);return r&&!r.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,r,i){typeof this.ref=="string"?this.logError(e,r,i):this.ref.logError(e,r,i)}modelStruct(){var e;const r=this.modelEntry(this.ref),i=r==null?void 0:r.entry;if(!i){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(i.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(i.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(i.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,i.dialect),(0,ek.isSourceDef)(i))return{...i};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const r=this.modelStruct();return r===void 0?{}:this.evaluateArguments(e,r.parameters,[])}evaluateArguments(e,r,i){var s,o;const u={...this.sourceArguments},a=new Set;for(const l of(s=this.args)!==null&&s!==void 0?s:[]){const c=(o=l.id)!==null&&o!==void 0?o:l.value instanceof uot.ExprIdReference?l.value.fieldReference:void 0;if(c===void 0){l.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const f=c.outputName;if(a.has(f)){l.logError("duplicate-source-argument",`Cannot pass argument for \`${f}\` more than once`);continue}a.add(f);const x=(r??{})[f];if(!x)c.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${c.refString}\``);else{const h=e??new aot.ParameterSpace(i??[]),p=l.value.getExpression(h);let m=p.value;p.type==="filter expression"&&x.type==="filter expression"&&x.filterType&&(0,lot.checkFilterExpression)(l.value,x.filterType,m),p.type!==x.type&&(0,ek.isCastType)(x.type)&&(m=(0,oot.castTo)(x.type,p.value,p.type,!0)),u[f]={...x,value:m}}}for(const l in r)l in u||((0,ek.paramHasValue)(r[l])?u[l]={...r[l]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${l}\``));return u}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;const s=this.modelStruct();if(!s){const l=sot.ErrorFactory.structDef,c=`${this.refName}-undefined`;return l.name=l.name+c,l.dialect=l.dialect+c,l}const o={};for(const l of r??[]){const c=l.parameter();o[c.name]=c}const u=this.evaluateArguments(e,s.parameters,r),a={...s,parameters:o,arguments:u};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(a),a}}U2.NamedSource=cot;var CE={},J4={};Object.defineProperty(J4,"__esModule",{value:!0}),J4.QueryHeadStruct=void 0;const fot=tt,xot=Ro,dot=U2;class hot extends xot.Source{constructor(e,r){super(),this.fromRef=e,this.sourceArguments=r,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,fot.refIsStructDef)(this.fromRef))return this.fromRef;const r=new dot.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:r}),r.getSourceDef(e)}}J4.QueryHeadStruct=hot,Object.defineProperty(CE,"__esModule",{value:!0}),CE.QueryReference=void 0;const tk=gi,pot=et,mot=J4,got=tt,yot=zs;class Eot extends pot.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const r=this.modelEntry(this.name),i=r==null?void 0:r.entry,s=function(){return{inputStruct:tk.ErrorFactory.structDef,outputStruct:tk.ErrorFactory.structDef,query:tk.ErrorFactory.query}};if(!i)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),s();if(i.type==="query"){const o=new mot.QueryHeadStruct(i.structRef,i.sourceArguments);this.has({queryHead:o});const u=o.getSourceDef(void 0),a=(0,yot.getFinalStruct)(this,u,i.pipeline);return{query:e||(0,got.refIsStructDef)(i.structRef)?i:{...i,structRef:u},outputStruct:a,inputStruct:u}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),s()}query(){return this.queryComp(!0).query}}CE.QueryReference=Eot,Object.defineProperty(gE,"__esModule",{value:!0}),gE.SQReference=void 0;const Aot=Tu,_ot=Sd,vot=U2,T0e=CE,R0e=Gi;class Cot extends Aot.SourceQueryElement{constructor(e,r){super({ref:e}),this.ref=e,this.args=r,this.elementType="sq-reference",r!==void 0&&this.has({args:r})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const r=new T0e.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,R0e.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const r=new T0e.QueryReference(this.ref);this.asSource=new _ot.QuerySource(r)}else if((0,R0e.isSourceDef)(e))this.asSource=new vot.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}gE.SQReference=Cot,Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.SQRefine=void 0;const Sot=Tu,bot=Sd,Tot=P2,Rot=gE;class Dot extends Sot.SourceQueryElement{constructor(e,r){super({toRefine:e,refine:r}),this.toRefine=e,this.refine=r,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof Rot.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const r=new Tot.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){const e=this.getQuery();if(e){const r=new bot.QuerySource(e);return this.has({queryAsSource:r}),r}}}Y4.SQRefine=Dot;var X4={},SE={};Object.defineProperty(SE,"__esModule",{value:!0}),SE.QueryRaw=void 0;const Oot=tt,Fot=et;class wot extends Fot.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const r=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},i=(0,Oot.refIsStructDef)(r.structRef)?r.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:i,inputStruct:i}}query(){return this.queryComp(!0).query}}SE.QueryRaw=wot;var bE={},g0={};Object.defineProperty(g0,"__esModule",{value:!0}),g0.sqlKey=g0.compileSQLInterpolation=void 0;const Not=js,Lot=tt,Iot=kt;function $ot(t,e,r){let i,s="",o=!1;for(const u of t)if((0,Lot.isSegmentSQL)(u))s+=u.sql,o=u.sql.match(/\(\s*$/)!==null;else{if(!i){if(!r)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new Not.QueryModel(r)}const a=i.compileQuery(u,{defaultRowLimit:void 0},!1).sql;s+=o?a:`(${a})`,o=!1}return{connection:e,selectStr:s}}g0.compileSQLInterpolation=$ot;function Bot(t,e){return`sql://${t}/${(0,Iot.generateHash)(e)}`}g0.sqlKey=Bot,Object.defineProperty(bE,"__esModule",{value:!0}),bE.SQLSource=void 0;const nk=g0,kot=Ro,TE=gi;class Mot extends kot.Source{constructor(e,r){super({connectionName:e,select:r}),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSourceRequest(e){const r=this.select.containsQueries?e.modelDef():void 0;return(0,nk.compileSQLInterpolation)(this.select.sqlPhrases(),this.connectionName.refString,r)}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;const i=super.needs(e);if(i)return i;this.requestBlock===void 0&&(this.requestBlock=this.sqlSourceRequest(e));const s=this.requestBlock,o=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!o){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}const u=(0,nk.sqlKey)(s.connection,s.selectStr);o.reference(u,this.location);const a=o.getEntry(u);if(a.status==="reference")return{compileSQL:s};a.status==="present"&&e.checkExperimentalDialect(this,a.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return TE.ErrorFactory.structDef;const r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),TE.ErrorFactory.structDef;if(this.requestBlock===void 0)return this.logError("failed-to-fetch-sql-source-schema","Expected to have already compiled the sql block"),TE.ErrorFactory.structDef;const i=this.requestBlock,s=(0,nk.sqlKey)(i.connection,i.selectStr);r.reference(s,this.location);const o=r.getEntry(s);if(o.status==="error"){const u=o.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+u.join(`
|
|
1555
|
-
`)),TE.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),TE.ErrorFactory.structDef}}bE.SQLSource=Mot,Object.defineProperty(X4,"__esModule",{value:!0}),X4.SQSource=void 0;const Pot=Tu,Uot=SE,jot=bE;class qot extends Pot.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof jot.SQLSource){const e=new Uot.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}X4.SQSource=qot;var Z4={};Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.SQExtend=void 0;const Hot=cE,Qot=Tu;class zot extends Qot.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new Hot.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}Z4.SQExtend=zot;var eT={},tT={};Object.defineProperty(tT,"__esModule",{value:!0}),tT.CompositeSource=void 0;const Wot=tt,Got=Ro;class Vot extends Got.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,Wot.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,g=l.get(m);if(g===void 0){const y={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,y),a.push(y)}else p.accessModifier==="internal"&&(g.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}tT.CompositeSource=Vot,Object.defineProperty(eT,"__esModule",{value:!0}),eT.SQCompose=void 0;const Yot=tT,Kot=Tu;class Jot extends Kot.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(Xot(e))return this.asSource=new Yot.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}eT.SQCompose=Jot;function Xot(t){return t.every(e=>e!==void 0)}var nT={},y0={},RE={},Zot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),eut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zot(e,t,r);return eut(e,t),e};Object.defineProperty(RE,"__esModule",{value:!0}),RE.BinaryBoolean=void 0;const nut=Hs,rut=tut(nn),iut=Ru,sut=Yt,out=ht;class uut extends out.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[rut.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,sut.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,iut.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,nut.errorFor)("logical-op expected boolean")}}RE.BinaryBoolean=uut;var aut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),lut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),cut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&aut(e,t,r);return lut(e,t),e};Object.defineProperty(y0,"__esModule",{value:!0}),y0.ExprLegacyIn=y0.ExprEquality=y0.ExprCompare=void 0;const hn=cut(nn),fut=Yt,xut=ht,dut=RE,hut={"~":[hn.stringT],"!~":[hn.stringT],"<":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"<=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"!=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT]};class D0e extends dut.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=hut[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}y0.ExprCompare=D0e;class put extends D0e{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}y0.ExprEquality=put;class mut extends xut.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,fut.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}y0.ExprLegacyIn=mut;var DE={},q2={};Object.defineProperty(q2,"__esModule",{value:!0}),q2.ExprTime=void 0;const gut=tt,yut=Yt,Eut=ht;class rk extends Eut.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,yut.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,gut.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new rk(e,i,[r])}}q2.ExprTime=rk;var ef={};Object.defineProperty(ef,"__esModule",{value:!0}),ef.Range=void 0;const Aut=Hs,_ut=Yt,vut=ht;class Cut extends vut.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,_ut.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Aut.errorFor)("a range is not a value")}}ef.Range=Cut;var Sut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),but=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Tut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Sut(e,t,r);return but(e,t),e};Object.defineProperty(DE,"__esModule",{value:!0}),DE.ExprGranularTime=void 0;const ik=tt,Rut=Hs,O0e=Tut(nn),F0e=Es,Dut=ht,rT=q2,w0e=ef;class Out extends Dut.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[O0e.timestampT,O0e.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(ik.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,ik.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,ik.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,Rut.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=rT.ExprTime.fromValue("timestamp",r),l=new rT.ExprTime("timestamp",(0,F0e.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new w0e.Range(a,l)}const s=new rT.ExprTime("date",r.value,[r]),o=(0,F0e.timeOffset)("date",r.value,"+",i,this.units),u=new rT.ExprTime("date",o,[r]);return new w0e.Range(s,u)}}DE.ExprGranularTime=Out,Object.defineProperty(nT,"__esModule",{value:!0}),nT.Apply=void 0;const Fut=y0,wut=j2,N0e=DE;class Nut extends Fut.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,wut.isGranularResult)(i)&&(r=new N0e.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof N0e.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}nT.Apply=Nut;var H2={},Lut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Iut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$ut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lut(e,t,r);return Iut(e,t),e};Object.defineProperty(H2,"__esModule",{value:!0}),H2.BinaryNumeric=void 0;const But=$ut(nn),kut=ht;class Mut extends kut.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[But.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}H2.BinaryNumeric=Mut;var iT={},Put=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Uut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Put(e,t,r);return Uut(e,t),e};Object.defineProperty(iT,"__esModule",{value:!0}),iT.Boolean=void 0;const qut=ht,Hut=jut(nn);let Qut=class extends qut.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Hut.boolT,value:{node:this.value}}}};iT.Boolean=Qut;var Q2={};Object.defineProperty(Q2,"__esModule",{value:!0}),Q2.ConstantExpression=Q2.ConstantFieldSpace=void 0;const zut=ht;class L0e{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}Q2.ConstantFieldSpace=L0e;class Wut extends zut.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new L0e),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}Q2.ConstantExpression=Wut;var tf={};Object.defineProperty(tf,"__esModule",{value:!0}),tf.FunctionOrdering=tf.FunctionOrderBy=void 0;const sk=tt,I0e=et,Gut=bd;class Vut extends I0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,sk.expressionIsAggregate)(r.expressionType)||((0,sk.expressionIsScalar)(r.expressionType)?(!(this.field instanceof Gut.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,sk.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}tf.FunctionOrderBy=Vut;class Yut extends I0e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}tf.FunctionOrdering=Yut;var sT={};Object.defineProperty(sT,"__esModule",{value:!0}),sT.ExprAddSub=void 0;const Kut=H2;class Jut extends Kut.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}sT.ExprAddSub=Jut;var E0={},Xut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Zut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),eat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Xut(e,t,r);return Zut(e,t),e};Object.defineProperty(E0,"__esModule",{value:!0}),E0.ExprAggregateFunction=void 0;const OE=tt,tat=kt,nat=Hs,$0e=Wr,B0e=eat(nn),rat=_t,iat=ht,sat=zr,oat=bd;class uat extends iat.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[B0e.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof $0e.StructSpaceField))if((0,OE.isAtomicFieldType)(p.type)){u=this.source,a={...B0e.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(y=>aat(y,m[0])))&&(l=m[0].map(y=>y.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,OE.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=uk(c,x),g=ak(this.elementType,m),y=h?g==null?void 0:g.message:"Join path is required for this calculation";if(y){const E=lat(y,x,u,this.elementType),A=(s=g==null?void 0:g.code)!==null&&s!==void 0?s:"bad-join-usage";g?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,nat.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...ok(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...ok(e,i))}return r}}E0.ExprAggregateFunction=uat;function aat(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function ok(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof $0e.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof sat.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,tat.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,OE.isAtomic)(u)&&!(0,OE.isJoined)(u))if((0,OE.hasExpression)(u)){const a=ok(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function uk(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function ak(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function lat(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let g=0;g<s.length;g++){const y=s[g],E=m[g];if(y.name!==E.name){s=s.slice(0,g);break}}const o=uk(s,e),u=ak(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=uk(c,e),x=ak(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof rat.FieldReference?`${r.refString}.${i}()`:r instanceof oat.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,g=`${p}.${i}(${r.code})`;let y=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(y+=` or \`${g}\` to get a result weighted with respect to \`${p}\``),y}}var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.ExprAlternationTree=void 0;const k0e=Yt,z2=ht,cat=Ru;function lk(t){const e=t.atExpr();switch(e.atNodeType()){case z2.ATNodeType.And:case z2.ATNodeType.Partial:return;case z2.ATNodeType.Or:{if(e instanceof M0e){const r=lk(e.left);if(r){const i=lk(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class M0e extends z2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=lk(this)||[]),this.inList}apply(e,r,i,s){if((0,cat.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,k0e.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,k0e.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?z2.ATNodeType.Or:z2.ATNodeType.And}}oT.ExprAlternationTree=M0e;var W2={};Object.defineProperty(W2,"__esModule",{value:!0}),W2.ExprAsymmetric=void 0;const fat=E0;class xat extends fat.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}W2.ExprAsymmetric=xat;var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.ExprAvg=void 0;const dat=W2;class hat extends dat.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}uT.ExprAvg=hat;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.ExprCast=void 0;const pat=Es,mat=Yt,gat=ht;class yat extends gat.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,mat.computedExprValue)({dataType:i,value:(0,pat.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}aT.ExprCast=yat;var lT={},Eat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Aat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_at=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eat(e,t,r);return Aat(e,t),e};Object.defineProperty(lT,"__esModule",{value:!0}),lT.ExprCoalesce=void 0;const P0e=Gi,U0e=_at(nn),vat=ht;class Cat extends vat.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=U0e.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(U0e.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,P0e.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,P0e.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}lT.ExprCoalesce=Cat;var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.ExprCount=void 0;const Sat=dt,bat=E0;class Tat extends bat.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,Sat.emptyCompositeFieldUsage)()}}}cT.ExprCount=Tat;var fT={},Rat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Dat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rat(e,t,r);return Dat(e,t),e};Object.defineProperty(fT,"__esModule",{value:!0}),fT.ExprCountDistinct=void 0;const xT=Oat(nn),Fat=E0;class wat extends Fat.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[xT.numberT,xT.stringT,xT.dateT,xT.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}fT.ExprCountDistinct=wat;var dT={},nf={};Object.defineProperty(nf,"__esModule",{value:!0}),nf.Limit=void 0;const Nat=et,Lat=Wn;class Iat extends Nat.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Lat.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}nf.Limit=Iat;var G2={};Object.defineProperty(G2,"__esModule",{value:!0}),G2.PartitionBy=void 0;const $at=et;class Bat extends $at.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}G2.PartitionBy=Bat;var FE={},rf={};Object.defineProperty(rf,"__esModule",{value:!0}),rf.FieldName=void 0;const kat=et;class Mat extends kat.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}rf.FieldName=Mat;var Pat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Uat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Pat(e,t,r);return Uat(e,t),e};Object.defineProperty(FE,"__esModule",{value:!0}),FE.ExprFunc=void 0;const Or=tt,qat=Hs,Hat=Cd,Qat=Yt,zat=ht,Wat=rf,j0e=kt,q0e=jat(nn),Gat=dt;class Vat extends zat.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map(B=>B.getExpression(e));if(this.isRaw){const B=[`${this.name}(`];a.forEach((U,V)=>{V!==0&&B.push(","),B.push(U.value)}),B.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},$=this.rawType?{type:this.rawType}:D;return(0,Qat.computedExprValue)({dataType:$,value:(0,j0e.composeSQLExpr)(B),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,qat.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const $=D.typeDesc();if((0,Or.isAtomicFieldType)($.type))x={...q0e.atomicDef($),expressionType:$.expressionType,value:{node:"field",path:this.source.path},evalSpace:$.evalSpace,compositeFieldUsage:$.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Hat.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${$.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=Yat(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map(B=>B.type).join(", ")})`);const{overload:g,expressionTypeErrors:y,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const B of y){const D=B.argIndex-(x?1:0),$=(0,Or.expressionIsScalar)(B.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualExpressionType}`)}for(const B of E){const D=B.argIndex-(x?1:0),$=B.maxEvalSpace==="literal"?"literal":B.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualEvalSpace}`)}for(const B of A){const D=B.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=g.returnType,C=(0,Or.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map(B=>B.expressionType)]);if(!(0,Or.expressionIsAggregate)(g.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map(B=>B.type).join(", ")}) with source`);const S={node:"function_call",overload:g,name:this.name,kids:{args:p.map(B=>B.value)},expressionType:C,structPath:h};let b=S;if(r!=null&&r.orderBys&&r.orderBys.length>0){const B=(0,Or.expressionIsAnalytic)(g.returnType.expressionType);if(B||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),g.supportsOrderBy||B){const D=g.supportsOrderBy!=="only_default",$=r.orderBys.flatMap(U=>B?U.getAnalyticOrderBy(e):U.getAggregateOrderBy(e,D));S.kids.orderBy=$}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(g.supportsLimit?S.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const B=[];for(const D of r.partitionBys)for(const $ of D.partitionFields){const U=$.getField(e);U.found===void 0?$.logError("partition-by-not-found",`${$.refString} is not defined`):(0,Or.expressionIsAnalytic)(U.found.typeDesc().expressionType)||(0,Or.expressionIsUngroupedAggregate)(U.found.typeDesc().expressionType)?$.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):B.push($.nameString)}S.partitionBy=B}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const B=p[0].value;if(B.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=B.literal,$=Kat(D),U=$.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(U.length>0){const Q=U.length===1?`'.' paths are not yet supported in sql interpolations, found ${U.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${U.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Q)}const V=[];for(const Q of $)if(Q.type==="string")V.push(Q.value);else if(Q.name==="TABLE")V.push({node:"source-reference"});else{const Z=new Wat.FieldName(Q.name);this.has({name:Z});const xe=e.lookup([Z]);if(xe.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${xe.error.message}`);if(xe.found.typeDesc().type==="filter expression")return this.loggedErrorExpr("filter-expression-error","Filter expressions cannot be used in sql_ functions");xe.found.refType==="parameter"?V.push({node:"parameter",path:[Q.name]}):V.push({node:"field",path:[Q.name]})}b=(0,j0e.composeSQLExpr)(V)}}const R=(0,Or.mergeEvalSpaces)(...p.map(B=>B.evalSpace)),O=R==="constant"?"constant":(0,Or.expressionIsScalar)(C)?R:"output";return{...(0,Or.isAtomic)(_)?q0e.atomicDef(_):_,expressionType:C,value:b,evalSpace:O,compositeFieldUsage:(0,Gat.mergeCompositeFieldUsage)(...p.map(B=>B.compositeFieldUsage))}}}FE.ExprFunc=Vat;function Yat(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],g=i.params[o];if(g===void 0){u=!1;break}if(!g.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=V2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Or.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:g})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Or.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:g,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:g}),_})){u=!1;break}g.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=hT(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function Kat(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function V2(t,e,r,i){var s,o,u,a;if(Or.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Or.isBasicArray)(r))return(0,Or.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:V2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Or.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return V2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=V2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return V2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=V2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Or.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function hT(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=hT(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=hT(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Or.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=hT(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var Jat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jat(e,t,r);return Xat(e,t),e};Object.defineProperty(dT,"__esModule",{value:!0}),dT.ExprProps=void 0;const elt=tt,tlt=Hs,nlt=Zat(nn),rlt=tf,ilt=nf,slt=G2,olt=ht,ult=FE,alt=dt;class llt extends olt.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=nlt.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,elt.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,alt.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,tlt.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof slt.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof ilt.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof rlt.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof ult.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}dT.ExprProps=llt;var pT={},clt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),flt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&clt(e,t,r);return flt(e,t),e};Object.defineProperty(pT,"__esModule",{value:!0}),pT.ExprLogicalOp=void 0;const dlt=RE,H0e=xlt(nn);class hlt extends dlt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[H0e.boolT,H0e.aggregateBoolT]}}pT.ExprLogicalOp=hlt;var mT={},plt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),mlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),glt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&plt(e,t,r);return mlt(e,t),e};Object.defineProperty(mT,"__esModule",{value:!0}),mT.ExprMax=void 0;const gT=glt(nn),ylt=E0;class Elt extends ylt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[gT.numberT,gT.stringT,gT.dateT,gT.timestampT]}returns(e){return e}}mT.ExprMax=Elt;var yT={},Alt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),_lt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Alt(e,t,r);return _lt(e,t),e};Object.defineProperty(yT,"__esModule",{value:!0}),yT.ExprMin=void 0;const ET=vlt(nn),Clt=E0;class Slt extends Clt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[ET.numberT,ET.stringT,ET.dateT,ET.timestampT]}returns(e){return e}}yT.ExprMin=Slt;var AT={},blt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Tlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Rlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&blt(e,t,r);return Tlt(e,t),e};Object.defineProperty(AT,"__esModule",{value:!0}),AT.ExprMinus=void 0;const Dlt=Hs,Q0e=Rlt(nn),Olt=ht;class Flt extends Olt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Q0e.numberT]}getExpression(e){const r=this.expr.getExpression(e);return Q0e.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Dlt.errorFor)("negate requires number")}}AT.ExprMinus=Flt;var _T={};Object.defineProperty(_T,"__esModule",{value:!0}),_T.ExprMulDiv=void 0;const wlt=H2;class Nlt extends wlt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}_T.ExprMulDiv=Nlt;var vT={},wE={};Object.defineProperty(wE,"__esModule",{value:!0}),wE.Unary=void 0;const Llt=ht;class Ilt extends Llt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}wE.Unary=Ilt;var $lt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Blt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),klt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$lt(e,t,r);return Blt(e,t),e};Object.defineProperty(vT,"__esModule",{value:!0}),vT.ExprNot=void 0;const ck=klt(nn),Mlt=wE;class Plt extends Mlt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[ck.boolT,ck.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(ck.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}vT.ExprNot=Plt;var CT={};Object.defineProperty(CT,"__esModule",{value:!0}),CT.ExprNow=void 0;const Ult=ht,jlt=dt;class qlt extends Ult.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,jlt.emptyCompositeFieldUsage)()}}}CT.ExprNow=qlt;var sf={};Object.defineProperty(sf,"__esModule",{value:!0}),sf.ExprIsNull=sf.PartialIsNull=sf.ExprNULL=void 0;const Hlt=Yt,ST=ht;function fk(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class Qlt extends ST.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Hlt.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?fk(e,r,i):super.apply(e,r,i,!0)}}sf.ExprNULL=Qlt;class zlt extends ST.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return fk(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return ST.ATNodeType.Partial}}sf.PartialIsNull=zlt;class Wlt extends ST.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return fk(e,this.op,this.expr)}}sf.ExprIsNull=Wlt;var bT={};Object.defineProperty(bT,"__esModule",{value:!0}),bT.ExprNumber=void 0;const Glt=Yt,Vlt=ht;class Ylt extends Vlt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,Glt.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}bT.ExprNumber=Ylt;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.ExprParens=void 0;const xk=ht;class Klt extends xk.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===xk.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,xk.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}TT.ExprParens=Klt;var RT={};Object.defineProperty(RT,"__esModule",{value:!0}),RT.ExprFilterExpression=void 0;const Jlt=ht;class Xlt extends Jlt.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return{type:"filter expression",value:{node:"filterLiteral",filterSrc:this.filterText},expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:{fields:[],joinedUsage:{}}}}}RT.ExprFilterExpression=Xlt;var DT={};Object.defineProperty(DT,"__esModule",{value:!0}),DT.ExprRegEx=void 0;const Zlt=Yt,e0t=ht;class t0t extends e0t.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,Zlt.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}DT.ExprRegEx=t0t;var OT={};Object.defineProperty(OT,"__esModule",{value:!0}),OT.ExprString=void 0;const n0t=ht,r0t=Yt;class i0t extends n0t.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,r0t.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}OT.ExprString=i0t;var FT={};Object.defineProperty(FT,"__esModule",{value:!0}),FT.ExprSum=void 0;const s0t=W2;class o0t extends s0t.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}FT.ExprSum=o0t;var wT={};Object.defineProperty(wT,"__esModule",{value:!0}),wT.ExprTimeExtract=void 0;const A0=tt,NT=Yt,dk=ht,u0t=ef;class NE extends dk.ExpressionDef{static extractor(e){const r=NE.pluralMap[e];if(r)return r;if((0,A0.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=NE.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof u0t.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,NT.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,A0.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,A0.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!A0.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,dk.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,dk.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,A0.isTimestampUnit)(r)?(0,NT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,A0.mkTemporal)(s.value,u),right:(0,A0.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,A0.isTemporalType)(s.type)?(0,NT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,A0.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,NT.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}wT.ExprTimeExtract=NE,NE.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var LT={},Du={},IT={};Object.defineProperty(IT,"__esModule",{value:!0}),IT.QueryInputSpace=void 0;const a0t=ys,l0t=w2;class c0t extends l0t.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof a0t.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}IT.QueryInputSpace=c0t;var f0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),x0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),d0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&f0t(e,t,r);return x0t(e,t),e};Object.defineProperty(Du,"__esModule",{value:!0}),Du.ReduceFieldSpace=Du.QuerySpace=Du.QueryOperationSpace=void 0;const $T=d0t(tt),hk=Vc,z0e=rf,W0e=zr,h0t=_t,p0t=w2,m0t=xE,g0t=Wr,y0t=IT,Ha=dt,E0t=Cd;class G0e extends p0t.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new y0t.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof g0t.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();$T.TD.isAtomic(c)&&$T.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof W0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new z0e.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof E0t.StructSpaceFieldBase)return(0,Ha.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Ha.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Ha.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Ha.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof W0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Ha.compositeFieldUsageDifference)(s,r));if(r=(0,Ha.mergeCompositeFieldUsage)(r,u),!(0,Ha.isEmptyCompositeFieldUsage)(u)){const a=(0,Ha.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}Du.QueryOperationSpace=G0e;class V0e extends G0e{addRefineFromFields(e){var r;if($T.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new z0e.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new m0t.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof h0t.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Ha.emptyCompositeFieldUsage)(),i=(0,Ha.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!_0t(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if($T.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,hk.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,hk.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,hk.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Du.QuerySpace=V0e;class A0t extends V0e{constructor(){super(...arguments),this.segmentType="reduce"}}Du.ReduceFieldSpace=A0t;function _0t(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var v0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),C0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),S0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&v0t(e,t,r);return C0t(e,t),e};Object.defineProperty(LT,"__esModule",{value:!0}),LT.ExprUngroup=void 0;const Y0e=tt,b0t=Du,K0e=S0t(nn),T0t=ht;class R0t extends T0t.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=K0e.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Y0e.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Y0e.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof b0t.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...K0e.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}LT.ExprUngroup=R0t;var BT={},D0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),O0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),F0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&D0t(e,t,r);return O0t(e,t),e};Object.defineProperty(BT,"__esModule",{value:!0}),BT.ForRange=void 0;const w0t=Hs,J0e=F0t(nn),kT=Es,N0t=Yt,L0t=ht,MT=q2,X0e=ef;class I0t extends L0t.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[J0e.timestampT,J0e.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,w0t.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,N0t.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,kT.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,g=(0,kT.timeOffset)("date",s.value,"+",u.value,a),y=new MT.ExprTime("date",g);return new X0e.Range(m,y).apply(e,r,i)}const c=MT.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,kT.castTo)("timestamp",x,"date"),f=new MT.ExprTime("timestamp",x,[s])}const h=(0,kT.timeOffset)("timestamp",x,"+",u.value,a),p=new MT.ExprTime("timestamp",h,[s,u]);return new X0e.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}BT.ForRange=I0t;var Fr={};Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.LiteralYear=Fr.LiteralQuarter=Fr.LiteralMonth=Fr.LiteralWeek=Fr.LiteralDay=Fr.LiteralHour=Fr.LiteralTimestamp=Fr.TimeFormatError=void 0;const of=qr,$0t=tt,B0t=Yt,k0t=ef,Z0e=q2,pk=ht;class M0t extends Error{}Fr.TimeFormatError=M0t;function Rd(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const ece="yyyy",tce=`${ece}-LL`,Do=`${tce}-dd`,nce=`${Do} HH`,rce=`${nce}:mm`,mk=`${rce}:ss`;class ice extends pk.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,B0t.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class gk extends ice{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=Rd(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=of.DateTime.fromFormat(e,mk);if(o.isValid)return new gk(i,r);if(o=of.DateTime.fromFormat(e,rce),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(mk);return new yk(i,r,"timestamp",u)}}}Fr.LiteralTimestamp=gk;class yk extends ice{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,pk.getMorphicValue)(s,"timestamp"),l=(0,pk.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,$0t.isTemporalType)(u.type)){const a=u.type;return new k0t.Range(new Z0e.ExprTime(a,s.value),new Z0e.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class Ek extends yk{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,nce);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(mk),new Ek(r,i)}}Fr.LiteralHour=Ek;class LE extends yk{constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class Ak extends LE{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,Do);if(s.isValid)return i=s.plus({day:1}).toFormat(Do),new Ak(r,i)}}Fr.LiteralDay=Ak;class _k extends LE{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=r.text.slice(0,10),o=of.DateTime.fromFormat(s,Do);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Do),i=a.toFormat(Do),new _k(r,i)}}}Fr.LiteralWeek=_k;class vk extends LE{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,tce);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new vk(r,i)}}}Fr.LiteralMonth=vk;class Ck extends LE{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=of.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Do),i=a.toFormat(Do),new Ck(r,i)}}}Fr.LiteralQuarter=Ck;class Sk extends LE{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,ece);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new Sk(r,i)}}}Fr.LiteralYear=Sk;var PT={};Object.defineProperty(PT,"__esModule",{value:!0}),PT.PartialCompare=void 0;const sce=ht;class P0t extends sce.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return sce.ATNodeType.Partial}}PT.PartialCompare=P0t;var Y2={},U0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),j0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),q0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&U0t(e,t,r);return j0t(e,t),e};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.PickWhen=Y2.Pick=void 0;const K2=q0t(nn),oce=Yt,H0t=ht,Q0t=et;function UT(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class z0t extends H0t.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!K2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=UT(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=UT(u,f);return K2.typeEq(x,f,!0)?x.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(o.kids.caseElse=f.value,(0,oce.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!K2.typeEq(l.when,K2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!K2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=UT(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=UT(o,u);return K2.typeEq(a,u,!0)?a.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(r.kids.caseElse=u.value,(0,oce.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}Y2.Pick=z0t;class W0t extends Q0t.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}Y2.PickWhen=W0t;var J2={},G0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),V0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Y0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&G0t(e,t,r);return V0t(e,t),e};Object.defineProperty(J2,"__esModule",{value:!0}),J2.CaseWhen=J2.Case=void 0;const K0t=Yt,J0t=ht,X0t=et,X2=Y0t(nn);function uce(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Z0t extends J0t.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!X2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!X2.typeEq(a.when,X2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!X2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=uce(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!X2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=uce(u,a),i.push(a),r.kids.caseElse=a.value}return(0,K0t.computedExprValue)({value:r,dataType:u?X2.atomicDef(u):{type:"null"},from:i})}}J2.Case=Z0t;class ect extends X0t.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}J2.CaseWhen=ect;var jT={},Dd={},tct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),nct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&tct(e,t,r);return nct(e,t),e};Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.RecordLiteral=Dd.RecordElement=void 0;const ace=Gi,ict=Yt,sct=ht,oct=et,uct=rct(nn);class act extends oct.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}Dd.RecordElement=act;class lct extends sct.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);ace.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,ace.mkFieldDef)(uct.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,ict.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}Dd.RecordLiteral=lct;var cct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),fct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cct(e,t,r);return fct(e,t),e};Object.defineProperty(jT,"__esModule",{value:!0}),jT.ArrayLiteral=void 0;const dct=Yt,hct=ht,lce=xct(nn),pct=Dd;class mct extends hct.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof pct.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!lce.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=lce.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,dct.computedExprValue)({dataType:u,value:a,from:i})}}jT.ArrayLiteral=mct;var qT={};Object.defineProperty(qT,"__esModule",{value:!0}),qT.Timeframe=void 0;const gct=tt,yct=et;class Ect extends yct.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,gct.isTimestampUnit)(r)?r:"second"}}qT.Timeframe=Ect;var uf={};Object.defineProperty(uf,"__esModule",{value:!0}),uf.ImportStatement=uf.ImportSelect=uf.ImportSourceName=void 0;const bk=et;class Act extends bk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}uf.ImportSourceName=Act;class _ct extends bk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}uf.ImportSelect=_ct;class vct extends bk.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}uf.ImportStatement=vct;var IE={};Object.defineProperty(IE,"__esModule",{value:!0}),IE.ExtendBlock=void 0;const Cct=et,Sct=Wn;class bct extends Cct.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Sct.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}IE.ExtendBlock=bct;var HT={};Object.defineProperty(HT,"__esModule",{value:!0}),HT.Argument=void 0;const Tct=et;class Rct extends Tct.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}HT.Argument=Rct;var QT={};Object.defineProperty(QT,"__esModule",{value:!0}),QT.HasParameter=void 0;const cce=tt,Dct=et,Oct=ht;class Fct extends Dct.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,cce.isParameterType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default})),e.filterType&&(this.filterType=e.filterType)}parameter(){var e;let r;if(this.default!==void 0){const i=this.default.constantValue();if(this.type&&this.type!==i.type&&i.type!=="null"&&i.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),i.type==="null")return this.type?{type:this.type,value:i.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:i.value,name:this.name,type:"error"});if(i.type==="filter expression")return this.type!=="filter expression"&&this.logError("parameter-missing-default-or-type",`Filter expression parameters must have expicit filter type, for example '${this.name}::filter<string>'`),this.filterType&&(0,Oct.checkFilterExpression)(this,this.filterType,i.value),{value:i.value,name:this.name,type:i.type};if(!(0,cce.isCastType)(i.type)&&i.type!=="error")return this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${i.type}\``),{value:i.value,name:this.name,type:"error"};r={value:i.value,name:this.name,type:i.type}}else this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),r={value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"};return r.type==="filter expression"&&this.filterType&&(r.filterType=this.filterType),r}}QT.HasParameter=Fct;var zT={};Object.defineProperty(zT,"__esModule",{value:!0}),zT.AnonymousQuery=void 0;const wct=et,Nct=Qr;class Lct extends wct.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Nct.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}zT.AnonymousQuery=Lct;var af={};Object.defineProperty(af,"__esModule",{value:!0}),af.View=void 0;const Ict=et;class $ct extends Ict.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}af.View=$ct;var WT={};Object.defineProperty(WT,"__esModule",{value:!0}),WT.ViewArrow=void 0;const Bct=Wr,kct=af;class Mct extends kct.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new Bct.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}WT.ViewArrow=Mct;var GT={},$E={};Object.defineProperty($E,"__esModule",{value:!0}),$E.refine=void 0;const Tk=Gi,Pct=dt,Rk=Vc;function Uct(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,Tk.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,Tk.isQuerySegment)(u)&&(0,Tk.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,Rk.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,Rk.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(Rk.nameFromDef)}`),o.compositeFieldUsage=(0,Pct.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}$E.refine=Uct,Object.defineProperty(GT,"__esModule",{value:!0}),GT.ViewRefine=void 0;const jct=gi,qct=zs,Hct=$E,Qct=af;class zct extends Qct.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,qct.getFinalStruct)(this.refinement,e.structDef(),s):jct.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Hct.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}GT.ViewRefine=zct;var VT={};Object.defineProperty(VT,"__esModule",{value:!0}),VT.ReferenceView=void 0;const Dk=tt,fce=gi,Wct=zs,Gct=zr,Vct=$E,Yct=af;class Kct extends Yct.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:fce.ErrorFactory.structDef,outputStruct:fce.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof Gct.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,Dk.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,Dk.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,Dk.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,Wct.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,Vct.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}VT.ReferenceView=Kct;var YT={},BE={},KT={},kE={};Object.defineProperty(kE,"__esModule",{value:!0}),kE.Index=void 0;const Jct=et,Xct=Wn;class Zct extends Jct.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=Xct.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}kE.Index=Zct;var ME={};Object.defineProperty(ME,"__esModule",{value:!0}),ME.SampleProperty=void 0;const eft=et,xce=Wn;class tft extends eft.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=xce.LegalRefinementStage.Tail,this.forceQueryClass=xce.QueryClass.Index}sampling(){return this.sample}}ME.SampleProperty=tft;var JT={};Object.defineProperty(JT,"__esModule",{value:!0}),JT.IndexFieldSpace=void 0;const dce=dt,hce=tt,Ok=_t,nft=zr,rft=Du,ift=pE,sft=Wr;class oft extends rft.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof Ok.FieldReference?super.pushFields(r):r instanceof Ok.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,dce.emptyCompositeFieldUsage)(),i=(0,dce.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof nft.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof ift.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof sft.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=Ok.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();hce.TD.isBasicAtomic(f)&&(0,hce.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}JT.IndexFieldSpace=oft,Object.defineProperty(KT,"__esModule",{value:!0}),KT.IndexBuilder=void 0;const Fk=tt,uft=gi,aft=qa,lft=kE,cft=nf,fft=ME,xft=JT,wk=dt;class dft{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new xft.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof aft.Filter?e.queryExecute(this):e instanceof cft.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof lft.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof fft.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,Fk.isIndexSegment)(e)&&!(0,Fk.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),uft.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,Fk.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,wk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,wk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}KT.IndexBuilder=dft;var XT={},PE={};Object.defineProperty(PE,"__esModule",{value:!0}),PE.GroupBy=void 0;const hft=Qs,pce=Wn;class pft extends hft.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=pce.LegalRefinementStage.Single,this.forceQueryClass=pce.QueryClass.Grouping}}PE.GroupBy=pft;var ZT={};Object.defineProperty(ZT,"__esModule",{value:!0}),ZT.ProjectFieldSpace=void 0;const eR=tt,mft=Du;class gft extends mft.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!eR.TD.isAtomic(e)||(0,eR.expressionIsAggregate)(e.expressionType)?!1:(0,eR.expressionInvolvesAggregate)(e.expressionType)&&(0,eR.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}ZT.ProjectFieldSpace=gft;var lf={},Od={};Object.defineProperty(Od,"__esModule",{value:!0}),Od.Ordering=Od.OrderBy=void 0;const yft=tt,mce=rf,gce=et,Eft=Wn;class Aft extends gce.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof mce.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof mce.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,yft.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}Od.OrderBy=Aft;class _ft extends gce.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Eft.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}Od.Ordering=_ft,Object.defineProperty(lf,"__esModule",{value:!0}),lf.ReduceBuilder=lf.QuerySegmentBuilder=void 0;const Ou=tt,vft=gi,Cft=rf,Sft=nf,bft=Od,Tft=Du,Rft=Qs,Nk=dt;function yce(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class Ece{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Rft.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Sft.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof bft.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,Ou.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,Nk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,Nk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}lf.QuerySegmentBuilder=Ece;class Dft extends Ece{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Tft.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,Ou.isReduceSegment)(e)||(0,Ou.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),vft.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=yce(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=yce(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Cft.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,Ou.expressionIsAggregate)(h.expressionType),a=(0,Ou.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAggregate)(o.expressionType),a=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAnalytic)(o.expressionType);if((0,Ou.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,Ou.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}lf.ReduceBuilder=Dft,Object.defineProperty(XT,"__esModule",{value:!0}),XT.ProjectBuilder=void 0;const Ace=tt,Oft=gi,Fft=PE,wft=ZT,Nft=lf;class Lft extends Nft.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new wft.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Fft.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,Ace.isProjectSegment)(e)||(0,Ace.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),Oft.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}XT.ProjectBuilder=Lft;var tR={};Object.defineProperty(tR,"__esModule",{value:!0}),tR.PartialBuilder=void 0;const Ift=Gi,$ft=lf;class Bft extends $ft.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,Ift.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}tR.PartialBuilder=Bft,Object.defineProperty(BE,"__esModule",{value:!0}),BE.QOpDesc=void 0;const kft=KT,Mft=XT,Pft=lf,Uft=et,jft=zs,qft=Wr,Fd=Wn,Hft=tR;class Qft extends Uft.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=Fd.QueryClass.Grouping:this.refineThis.type==="project"?r=Fd.QueryClass.Project:this.refineThis.type==="index"&&(r=Fd.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=Fd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case Fd.QueryClass.Grouping:return new Pft.ReduceBuilder(e,this.refineThis,r,i);case Fd.QueryClass.Project:return new Mft.ProjectBuilder(e,this.refineThis,r,i);case Fd.QueryClass.Index:return new kft.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Hft.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new qft.StaticSourceSpace((0,jft.opOutputStruct)(this,e.structDef(),s))}}}BE.QOpDesc=Qft,Object.defineProperty(YT,"__esModule",{value:!0}),YT.QOpDescView=void 0;const zft=tt,Wft=Wr,_ce=BE,Gft=zs,Lk=Wn,Vft=af;class Yft extends Vft.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,zft.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new _ce.QOpDesc([]),u=new _ce.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case Lk.LegalRefinementStage.Head:o.push(a);break;case Lk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case Lk.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,Gft.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new Wft.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}YT.QOpDescView=Yft;var wn={},Kft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Jft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kft(e,t,r);return Jft(e,t),e};Object.defineProperty(wn,"__esModule",{value:!0}),wn.FieldDefinitionValue=wn.DefSpace=wn.DimensionFieldDeclaration=wn.MeasureFieldDeclaration=wn.DeclareFieldDeclaration=wn.ProjectFieldDeclaration=wn.GroupByFieldDeclaration=wn.AggregateFieldDeclaration=wn.CalculateFieldDeclaration=wn.AtomicFieldDeclaration=void 0;const Ik=tt,vce=Xft(nn),Zft=j2,ext=et,wd=lr,txt=Qr,nxt=zr;class cf extends ext.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=txt.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new $k(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,Ik.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,Ik.mkFieldDef)(vce.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,Zft.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof $k&&e.foundCircle)&&i.type!=="error"){const u=vce.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new Cce(e,this))}}wn.AtomicFieldDeclaration=cf;class rxt extends cf{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}wn.CalculateFieldDeclaration=rxt;class ixt extends cf{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckAggregate)(e,this)}}wn.AggregateFieldDeclaration=ixt;class sxt extends cf{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckGroupBy)(e,this)}}wn.GroupByFieldDeclaration=sxt;class oxt extends cf{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckProject)(e,this)}}wn.ProjectFieldDeclaration=oxt;class uxt extends cf{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckDeclare)(e,this)}}wn.DeclareFieldDeclaration=uxt;class axt extends cf{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckMeasure)(e,this)}}wn.MeasureFieldDeclaration=axt;class lxt extends cf{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckDimension)(e,this)}}wn.DimensionFieldDeclaration=lxt;class $k{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}wn.DefSpace=$k;class Cce extends nxt.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,Ik.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}wn.FieldDefinitionValue=Cce;var nR={};Object.defineProperty(nR,"__esModule",{value:!0}),nR.Aggregate=void 0;const cxt=Qs,Sce=Wn;class fxt extends cxt.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=Sce.LegalRefinementStage.Single,this.forceQueryClass=Sce.QueryClass.Grouping}}nR.Aggregate=fxt;var rR={};Object.defineProperty(rR,"__esModule",{value:!0}),rR.Calculate=void 0;const xxt=Qs,dxt=Wn;class hxt extends xxt.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=dxt.LegalRefinementStage.Single}}rR.Calculate=hxt;var UE={};Object.defineProperty(UE,"__esModule",{value:!0}),UE.Dimensions=void 0;const pxt=Yc;class mxt extends pxt.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}UE.Dimensions=mxt;var jE={};Object.defineProperty(jE,"__esModule",{value:!0}),jE.Measures=void 0;const gxt=Yc;class yxt extends gxt.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}jE.Measures=yxt;var iR={};Object.defineProperty(iR,"__esModule",{value:!0}),iR.Nests=void 0;const Ext=Qs,bce=Wn;class Axt extends Ext.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=bce.LegalRefinementStage.Single,this.forceQueryClass=bce.QueryClass.Grouping}}iR.Nests=Axt;var sR={};Object.defineProperty(sR,"__esModule",{value:!0}),sR.ProjectStatement=void 0;const _xt=Qs,Tce=Wn;class vxt extends _xt.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=Tce.QueryClass.Project,this.queryRefinementStage=Tce.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}sR.ProjectStatement=vxt;var ff={},_0={},Pn={};Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.getPlainString=Pn.unIndent=Pn.getOptionalId=Pn.idToStr=Pn.getId=Pn.getStringParts=Pn.getStringIfShort=Pn.getShortString=void 0;const Rce=$o;function Dce(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?Rce.ParseUtil.parseString(i,i[0]):""}Pn.getShortString=Dce;function Oce(t){const e=t.string().shortString();if(e)return Dce(e)}Pn.getStringIfShort=Oce;function*Fce(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Pn.getStringParts=Fce;function wce(t){return Nce(t.id())}Pn.getId=wce;function Nce(t){const e=t.BQ_STRING();return e?Rce.ParseUtil.parseString(e.text,"`"):t.text}Pn.idToStr=Nce;function Cxt(t){function e(r){return"id"in r}if(e(t)&&t.id())return wce(t)}Pn.getOptionalId=Cxt;function*Lce(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function Sxt(t){let e;for(const r of Lce(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function Ice(t){let e;for(const r of t)if(typeof r=="string"){const i=Sxt(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of Lce(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Pn.unIndent=Ice;function bxt(t,e=!1){const r=[],i=Oce(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of Fce(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return Ice(s),[s.join(""),r]}return["",r]}Pn.getPlainString=bxt,Object.defineProperty(_0,"__esModule",{value:!0}),_0.findReferences=_0.deprecatedParseTableURI=_0.constructTableKey=void 0;const Txt=T0,Bk=Pn;function $ce(t){const e=(0,Bk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,Bk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class Rxt{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=Bce(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterExploreTable(e){const r=(0,Bk.getId)(e.connectionId()),i=$ce(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const r=$ce(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function Bce(t,e){return t===void 0?e:`${t}:${e}`}_0.constructTableKey=Bce;function Dxt(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}_0.deprecatedParseTableURI=Dxt;function Oxt(t,e,r){const i=new Rxt(t,e),s=i;return Txt.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}_0.findReferences=Oxt,Object.defineProperty(ff,"__esModule",{value:!0}),ff.TableFunctionSource=ff.TableMethodSource=ff.TableSource=void 0;const kce=_0,Fxt=Ro,Mce=gi;class kk extends Fxt.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return Mce.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,kce.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),Mce.ErrorFactory.structDef}}ff.TableSource=kk;class wxt extends kk{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}ff.TableMethodSource=wxt;class Nxt extends kk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,kce.deprecatedParseTableURI)(this.tableURI)}}ff.TableFunctionSource=Nxt;var oR={};Object.defineProperty(oR,"__esModule",{value:!0}),oR.SQLString=void 0;const Lxt=et,Pce=Tu;class Ixt extends Lxt.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter($xt)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof Pce.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}oR.SQLString=Ixt;function $xt(t){return t instanceof Pce.SourceQueryElement}var uR={};Object.defineProperty(uR,"__esModule",{value:!0}),uR.SourceDesc=void 0;const Bxt=et;class kxt extends Bxt.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}uR.SourceDesc=kxt;var aR={};Object.defineProperty(aR,"__esModule",{value:!0}),aR.isSourceProperty=void 0;const Mxt=qa,Pxt=Yc,Uxt=I2,jxt=Jc,qxt=$2,Hxt=B2,Qxt=k2,zxt=Kc,Wxt=ys;function Gxt(t){return t instanceof Mxt.Filter||t instanceof Wxt.JoinStatement||t instanceof Pxt.DeclareFields||t instanceof Uxt.FieldListEdit||t instanceof jxt.Renames||t instanceof qxt.PrimaryKey||t instanceof zxt.ObjectAnnotation||t instanceof Hxt.Views||t instanceof Qxt.TimezoneStatement}aR.isSourceProperty=Gxt;var lR={};Object.defineProperty(lR,"__esModule",{value:!0}),lR.isFieldCollectionMember=void 0;const Vxt=wn,Uce=_t;function Yxt(t){return t instanceof Uce.FieldReference||t instanceof Uce.WildcardFieldReference||t instanceof Vxt.AtomicFieldDeclaration}lR.isFieldCollectionMember=Yxt;var cR={};Object.defineProperty(cR,"__esModule",{value:!0}),cR.isQueryElement=void 0;const Kxt=M2,Jxt=P2,Xxt=CE,Zxt=SE;function edt(t){return t instanceof Kxt.QueryArrow||t instanceof Jxt.QueryRefine||t instanceof Xxt.QueryReference||t instanceof Zxt.QueryRaw}cR.isQueryElement=edt;var jce={};Object.defineProperty(jce,"__esModule",{value:!0});var fR={};Object.defineProperty(fR,"__esModule",{value:!0}),fR.isQueryProperty=void 0;function tdt(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}fR.isQueryProperty=tdt;var xR={};Object.defineProperty(xR,"__esModule",{value:!0}),xR.isQueryExtendProperty=void 0;const ndt=UE,rdt=ys,idt=jE;function sdt(t){return t instanceof ndt.Dimensions||t instanceof idt.Measures||t instanceof rdt.JoinStatement}xR.isQueryExtendProperty=sdt;var dR={};Object.defineProperty(dR,"__esModule",{value:!0}),dR.isFieldPropStatement=void 0;const odt=tf,udt=qa,adt=nf,ldt=G2;function cdt(t){return t instanceof udt.Filter||t instanceof adt.Limit||t instanceof ldt.PartitionBy||t instanceof odt.FunctionOrdering}dR.isFieldPropStatement=cdt,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(uE,t),r(O2,t),r(F2,t),r(Ro,t),r(cE,t),r(Tu,t),r(V4,t),r(Y4,t),r(X4,t),r(gE,t),r(Z4,t),r(eT,t),r(bu,t),r(I2,t),r($2,t),r(Jc,t),r(B2,t),r(k2,t),r(nT,t),r(H2,t),r(iT,t),r(Q2,t),r(tf,t),r(sT,t),r(E0,t),r(oT,t),r(W2,t),r(uT,t),r(aT,t),r(lT,t),r(y0,t),r(cT,t),r(fT,t),r(dT,t),r(FE,t),r(DE,t),r(bd,t),r(pT,t),r(mT,t),r(yT,t),r(AT,t),r(_T,t),r(vT,t),r(CT,t),r(sf,t),r(bT,t),r(TT,t),r(RT,t),r(DT,t),r(OT,t),r(FT,t),r(wT,t),r(LT,t),r(BT,t),r(Fr,t),r(PT,t),r(G2,t),r(Y2,t),r(J2,t),r(jT,t),r(Dd,t),r(ef,t),r(qT,t),r(wE,t),r(uf,t),r(IE,t),r(HT,t),r(QT,t),r(zT,t),r(P2,t),r(M2,t),r(af,t),r(WT,t),r(GT,t),r(VT,t),r(YT,t),r(wn,t),r(_t,t),r(nR,t),r(rR,t),r(Yc,t),r(UE,t),r(IE,t),r(qa,t),r(PE,t),r(kE,t),r(ys,t),r(aE,t),r(nf,t),r(jE,t),r(uE,t),r(iR,t),r(Od,t),r(sR,t),r(BE,t),r(ME,t),r(U2,t),r(Sd,t),r(bE,t),r(ff,t),r(oR,t),r(Kc,t),r(Ru,t),r(uR,t),r(aR,t),r(ht,t),r(lR,t),r(rf,t),r(et,t),r(cR,t),r(jce,t),r(fR,t),r(xR,t),r(dR,t)}(j4);var hR={},fdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),xdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ddt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fdt(e,t,r);return xdt(e,t),e};Object.defineProperty(hR,"__esModule",{value:!0}),hR.MalloyToAST=void 0;const qce=ig,hdt=qd,oe=ddt(j4),Mk=T2,Hce=xr,pdt=j4,Xn=Pn,pR=tt,mdt=$o,Qce=zn,gdt=iE;class zce extends oe.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Pk extends oe.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const ydt=[];class Edt extends hdt.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of ydt){const o=mdt.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,Mk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,Qce.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new Hce.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,Mk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,Mk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Pk||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new oe.FieldName((0,Xn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new oe.ModelEntryReference((0,Xn.getId)(e)),e.id())}defaultResult(){return new oe.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new Hce.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new oe.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof oe.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Xn.getPlainString)(e);for(const s of i)s instanceof qce.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of(0,Xn.getStringParts)(e))i instanceof qce.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new oe.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>oe.isDocStatementOrDocStatementList(i)&&i,"statement");return new oe.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new oe.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=(0,Xn.getId)(e.parameterNameDef());let i,s;const o=e.legalParamType();if(o){const l=o.malloyType();if(l){const f=this.getMalloyType(l);(0,gdt.isFilterable)(f)?s=f:this.contextError(o,"parameter-illegal-default-type",`Unknown filter type ${f}`)}const c=o.FILTER()?"filter expression":o.text.toLowerCase();if(!(0,pR.isParameterType)(c))return this.contextError(o,"parameter-illegal-default-type",`Unknown parameter type ${c}`),null;i=c}const u=e.fieldExpr();let a;if(u){const l=new oe.ConstantExpression(this.getFieldExpr(u));a=this.astAt(l,u)}return this.astAt(new oe.HasParameter({name:r,type:i,default:a,filterType:s}),e)}getSourceParameters(e){if(e===void 0)return[];this.inExperiment("parameters",e);function r(i){return i!==null}return e.sourceParameter().map(i=>this.getSourceParameter(i)).filter(r)}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new oe.DefineSource((0,Xn.getId)(e.sourceNameDef()),r instanceof oe.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>oe.isSourceProperty(s)&&s,"source property");return new oe.SourceDesc(r)}visitExploreTable(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new oe.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new oe.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Xn.getShortString)(u));const a=new oe.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof oe.Join&&(i.push(u),u instanceof oe.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof oe.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new oe.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof oe.Join&&(s.push(u),u instanceof oe.ExpressionJoin&&(u.joinType="one"));const o=new oe.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof oe.Join&&(s.push(u),u instanceof oe.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new oe.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof oe.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new oe.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new oe.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new oe.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,pR.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new oe.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Xn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),oe.DimensionFieldDeclaration),s=new oe.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),oe.MeasureFieldDeclaration),s=new oe.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(oe.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new oe.ExtendBlock(r);return this.astAt(s,e)}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new oe.RenameField((0,Xn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new oe.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new oe.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new oe.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),s}visitDefExplorePrimaryKey(e){const r=new oe.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new oe.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new oe.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),oe.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new oe.SQExtend(r,new oe.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new oe.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>oe.isQueryProperty(i)&&i,"query statement");return new oe.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof oe.FieldReference||s instanceof oe.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new oe.Aggregate(this.getQueryItems(e.queryFieldList(),oe.AggregateFieldDeclaration,oe.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new oe.GroupBy(this.getQueryItems(e.queryFieldList(),oe.GroupByFieldDeclaration,oe.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new oe.Calculate(this.getQueryItems(e.queryFieldList(),oe.CalculateFieldDeclaration,oe.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),oe.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new oe.ExprGranularTime(new oe.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new oe.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,oe.ProjectFieldDeclaration,oe.ProjectFieldReference));return this.astAt(new oe.ProjectStatement(r),e)}visitProjectStatement(e){const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,oe.ProjectFieldReference):void 0,o=this.astAt(new oe.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Xn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new oe.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,oe.IndexFieldReference);return i.STAR()?this.astAt(new oe.WildcardFieldReference(o),e):this.astAt(o,e)});return new oe.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new oe.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new oe.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new oe.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new oe.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new oe.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new oe.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new oe.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new oe.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new oe.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Xn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof oe.SourceQueryElement){const o=new oe.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new oe.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new oe.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof oe.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Xn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new oe.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Xn.getId)(e.exploreQueryNameDef()),i=new oe.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new oe.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new oe.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new oe.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new oe.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new oe.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new oe.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new oe.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(oe.isComparison(r))return this.astAt(new oe.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new oe.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new oe.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
|
|
1555
|
+
`)),TE.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),TE.ErrorFactory.structDef}}bE.SQLSource=Mot,Object.defineProperty(X4,"__esModule",{value:!0}),X4.SQSource=void 0;const Pot=Tu,Uot=SE,jot=bE;class qot extends Pot.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof jot.SQLSource){const e=new Uot.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}X4.SQSource=qot;var Z4={};Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.SQExtend=void 0;const Hot=cE,Qot=Tu;class zot extends Qot.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new Hot.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}Z4.SQExtend=zot;var eT={},tT={};Object.defineProperty(tT,"__esModule",{value:!0}),tT.CompositeSource=void 0;const Wot=tt,Got=Ro;class Vot extends Got.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,Wot.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,g=l.get(m);if(g===void 0){const y={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,y),a.push(y)}else p.accessModifier==="internal"&&(g.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}tT.CompositeSource=Vot,Object.defineProperty(eT,"__esModule",{value:!0}),eT.SQCompose=void 0;const Yot=tT,Kot=Tu;class Jot extends Kot.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(Xot(e))return this.asSource=new Yot.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}eT.SQCompose=Jot;function Xot(t){return t.every(e=>e!==void 0)}var nT={},y0={},RE={},Zot=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),eut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zot(e,t,r);return eut(e,t),e};Object.defineProperty(RE,"__esModule",{value:!0}),RE.BinaryBoolean=void 0;const nut=Hs,rut=tut(nn),iut=Ru,sut=Yt,out=ht;class uut extends out.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[rut.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,sut.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,iut.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,nut.errorFor)("logical-op expected boolean")}}RE.BinaryBoolean=uut;var aut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),lut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),cut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&aut(e,t,r);return lut(e,t),e};Object.defineProperty(y0,"__esModule",{value:!0}),y0.ExprLegacyIn=y0.ExprEquality=y0.ExprCompare=void 0;const hn=cut(nn),fut=Yt,xut=ht,dut=RE,hut={"~":[hn.stringT],"!~":[hn.stringT],"<":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"<=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"!=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT]};class D0e extends dut.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=hut[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}y0.ExprCompare=D0e;class put extends D0e{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}y0.ExprEquality=put;class mut extends xut.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,fut.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}y0.ExprLegacyIn=mut;var DE={},q2={};Object.defineProperty(q2,"__esModule",{value:!0}),q2.ExprTime=void 0;const gut=tt,yut=Yt,Eut=ht;class rk extends Eut.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,yut.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,gut.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new rk(e,i,[r])}}q2.ExprTime=rk;var ef={};Object.defineProperty(ef,"__esModule",{value:!0}),ef.Range=void 0;const Aut=Hs,_ut=Yt,vut=ht;class Cut extends vut.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,_ut.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Aut.errorFor)("a range is not a value")}}ef.Range=Cut;var Sut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),but=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Tut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Sut(e,t,r);return but(e,t),e};Object.defineProperty(DE,"__esModule",{value:!0}),DE.ExprGranularTime=void 0;const ik=tt,Rut=Hs,O0e=Tut(nn),F0e=Es,Dut=ht,rT=q2,w0e=ef;class Out extends Dut.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[O0e.timestampT,O0e.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(ik.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,ik.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,ik.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,Rut.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=rT.ExprTime.fromValue("timestamp",r),l=new rT.ExprTime("timestamp",(0,F0e.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new w0e.Range(a,l)}const s=new rT.ExprTime("date",r.value,[r]),o=(0,F0e.timeOffset)("date",r.value,"+",i,this.units),u=new rT.ExprTime("date",o,[r]);return new w0e.Range(s,u)}}DE.ExprGranularTime=Out,Object.defineProperty(nT,"__esModule",{value:!0}),nT.Apply=void 0;const Fut=y0,wut=j2,N0e=DE;class Nut extends Fut.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,wut.isGranularResult)(i)&&(r=new N0e.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof N0e.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}nT.Apply=Nut;var H2={},Lut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Iut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$ut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lut(e,t,r);return Iut(e,t),e};Object.defineProperty(H2,"__esModule",{value:!0}),H2.BinaryNumeric=void 0;const But=$ut(nn),kut=ht;class Mut extends kut.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[But.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}H2.BinaryNumeric=Mut;var iT={},Put=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Uut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Put(e,t,r);return Uut(e,t),e};Object.defineProperty(iT,"__esModule",{value:!0}),iT.Boolean=void 0;const qut=ht,Hut=jut(nn);let Qut=class extends qut.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Hut.boolT,value:{node:this.value}}}};iT.Boolean=Qut;var Q2={};Object.defineProperty(Q2,"__esModule",{value:!0}),Q2.ConstantExpression=Q2.ConstantFieldSpace=void 0;const zut=ht;class L0e{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}Q2.ConstantFieldSpace=L0e;class Wut extends zut.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new L0e),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}Q2.ConstantExpression=Wut;var tf={};Object.defineProperty(tf,"__esModule",{value:!0}),tf.FunctionOrdering=tf.FunctionOrderBy=void 0;const sk=tt,I0e=et,Gut=bd;class Vut extends I0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,sk.expressionIsAggregate)(r.expressionType)||((0,sk.expressionIsScalar)(r.expressionType)?(!(this.field instanceof Gut.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,sk.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}tf.FunctionOrderBy=Vut;class Yut extends I0e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}tf.FunctionOrdering=Yut;var sT={};Object.defineProperty(sT,"__esModule",{value:!0}),sT.ExprAddSub=void 0;const Kut=H2;class Jut extends Kut.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}sT.ExprAddSub=Jut;var E0={},Xut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Zut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),eat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Xut(e,t,r);return Zut(e,t),e};Object.defineProperty(E0,"__esModule",{value:!0}),E0.ExprAggregateFunction=void 0;const OE=tt,tat=kt,nat=Hs,$0e=Wr,B0e=eat(nn),rat=_t,iat=ht,sat=zr,oat=bd;class uat extends iat.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[B0e.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof $0e.StructSpaceField))if((0,OE.isAtomicFieldType)(p.type)){u=this.source,a={...B0e.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(y=>aat(y,m[0])))&&(l=m[0].map(y=>y.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,OE.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=uk(c,x),g=ak(this.elementType,m),y=h?g==null?void 0:g.message:"Join path is required for this calculation";if(y){const E=lat(y,x,u,this.elementType),A=(s=g==null?void 0:g.code)!==null&&s!==void 0?s:"bad-join-usage";g?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,nat.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...ok(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...ok(e,i))}return r}}E0.ExprAggregateFunction=uat;function aat(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function ok(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof $0e.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof sat.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,tat.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,OE.isAtomic)(u)&&!(0,OE.isJoined)(u))if((0,OE.hasExpression)(u)){const a=ok(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function uk(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function ak(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function lat(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let g=0;g<s.length&&g<m.length;g++){const y=s[g],E=m[g];if(y.name!==E.name){s=s.slice(0,g);break}}const o=uk(s,e),u=ak(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=uk(c,e),x=ak(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof rat.FieldReference?`${r.refString}.${i}()`:r instanceof oat.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,g=`${p}.${i}(${r.code})`;let y=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(y+=` or \`${g}\` to get a result weighted with respect to \`${p}\``),y}}var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.ExprAlternationTree=void 0;const k0e=Yt,z2=ht,cat=Ru;function lk(t){const e=t.atExpr();switch(e.atNodeType()){case z2.ATNodeType.And:case z2.ATNodeType.Partial:return;case z2.ATNodeType.Or:{if(e instanceof M0e){const r=lk(e.left);if(r){const i=lk(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class M0e extends z2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=lk(this)||[]),this.inList}apply(e,r,i,s){if((0,cat.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,k0e.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,k0e.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?z2.ATNodeType.Or:z2.ATNodeType.And}}oT.ExprAlternationTree=M0e;var W2={};Object.defineProperty(W2,"__esModule",{value:!0}),W2.ExprAsymmetric=void 0;const fat=E0;class xat extends fat.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}W2.ExprAsymmetric=xat;var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.ExprAvg=void 0;const dat=W2;class hat extends dat.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}uT.ExprAvg=hat;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.ExprCast=void 0;const pat=Es,mat=Yt,gat=ht;class yat extends gat.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,mat.computedExprValue)({dataType:i,value:(0,pat.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}aT.ExprCast=yat;var lT={},Eat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Aat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_at=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eat(e,t,r);return Aat(e,t),e};Object.defineProperty(lT,"__esModule",{value:!0}),lT.ExprCoalesce=void 0;const P0e=Gi,U0e=_at(nn),vat=ht;class Cat extends vat.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=U0e.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(U0e.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,P0e.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,P0e.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}lT.ExprCoalesce=Cat;var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.ExprCount=void 0;const Sat=dt,bat=E0;class Tat extends bat.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,Sat.emptyCompositeFieldUsage)()}}}cT.ExprCount=Tat;var fT={},Rat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Dat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rat(e,t,r);return Dat(e,t),e};Object.defineProperty(fT,"__esModule",{value:!0}),fT.ExprCountDistinct=void 0;const xT=Oat(nn),Fat=E0;class wat extends Fat.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[xT.numberT,xT.stringT,xT.dateT,xT.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}fT.ExprCountDistinct=wat;var dT={},nf={};Object.defineProperty(nf,"__esModule",{value:!0}),nf.Limit=void 0;const Nat=et,Lat=Wn;class Iat extends Nat.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Lat.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}nf.Limit=Iat;var G2={};Object.defineProperty(G2,"__esModule",{value:!0}),G2.PartitionBy=void 0;const $at=et;class Bat extends $at.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}G2.PartitionBy=Bat;var FE={},rf={};Object.defineProperty(rf,"__esModule",{value:!0}),rf.FieldName=void 0;const kat=et;class Mat extends kat.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}rf.FieldName=Mat;var Pat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Uat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Pat(e,t,r);return Uat(e,t),e};Object.defineProperty(FE,"__esModule",{value:!0}),FE.ExprFunc=void 0;const Or=tt,qat=Hs,Hat=Cd,Qat=Yt,zat=ht,Wat=rf,j0e=kt,q0e=jat(nn),Gat=dt;class Vat extends zat.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map(B=>B.getExpression(e));if(this.isRaw){const B=[`${this.name}(`];a.forEach((U,V)=>{V!==0&&B.push(","),B.push(U.value)}),B.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},$=this.rawType?{type:this.rawType}:D;return(0,Qat.computedExprValue)({dataType:$,value:(0,j0e.composeSQLExpr)(B),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,qat.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const $=D.typeDesc();if((0,Or.isAtomicFieldType)($.type))x={...q0e.atomicDef($),expressionType:$.expressionType,value:{node:"field",path:this.source.path},evalSpace:$.evalSpace,compositeFieldUsage:$.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Hat.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${$.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=Yat(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map(B=>B.type).join(", ")})`);const{overload:g,expressionTypeErrors:y,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const B of y){const D=B.argIndex-(x?1:0),$=(0,Or.expressionIsScalar)(B.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualExpressionType}`)}for(const B of E){const D=B.argIndex-(x?1:0),$=B.maxEvalSpace==="literal"?"literal":B.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualEvalSpace}`)}for(const B of A){const D=B.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=g.returnType,C=(0,Or.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map(B=>B.expressionType)]);if(!(0,Or.expressionIsAggregate)(g.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map(B=>B.type).join(", ")}) with source`);const S={node:"function_call",overload:g,name:this.name,kids:{args:p.map(B=>B.value)},expressionType:C,structPath:h};let b=S;if(r!=null&&r.orderBys&&r.orderBys.length>0){const B=(0,Or.expressionIsAnalytic)(g.returnType.expressionType);if(B||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),g.supportsOrderBy||B){const D=g.supportsOrderBy!=="only_default",$=r.orderBys.flatMap(U=>B?U.getAnalyticOrderBy(e):U.getAggregateOrderBy(e,D));S.kids.orderBy=$}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(g.supportsLimit?S.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const B=[];for(const D of r.partitionBys)for(const $ of D.partitionFields){const U=$.getField(e);U.found===void 0?$.logError("partition-by-not-found",`${$.refString} is not defined`):(0,Or.expressionIsAnalytic)(U.found.typeDesc().expressionType)||(0,Or.expressionIsUngroupedAggregate)(U.found.typeDesc().expressionType)?$.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):B.push($.nameString)}S.partitionBy=B}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const B=p[0].value;if(B.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=B.literal,$=Kat(D),U=$.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(U.length>0){const Q=U.length===1?`'.' paths are not yet supported in sql interpolations, found ${U.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${U.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Q)}const V=[];for(const Q of $)if(Q.type==="string")V.push(Q.value);else if(Q.name==="TABLE")V.push({node:"source-reference"});else{const Z=new Wat.FieldName(Q.name);this.has({name:Z});const xe=e.lookup([Z]);if(xe.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${xe.error.message}`);if(xe.found.typeDesc().type==="filter expression")return this.loggedErrorExpr("filter-expression-error","Filter expressions cannot be used in sql_ functions");xe.found.refType==="parameter"?V.push({node:"parameter",path:[Q.name]}):V.push({node:"field",path:[Q.name]})}b=(0,j0e.composeSQLExpr)(V)}}const R=(0,Or.mergeEvalSpaces)(...p.map(B=>B.evalSpace)),O=R==="constant"?"constant":(0,Or.expressionIsScalar)(C)?R:"output";return{...(0,Or.isAtomic)(_)?q0e.atomicDef(_):_,expressionType:C,value:b,evalSpace:O,compositeFieldUsage:(0,Gat.mergeCompositeFieldUsage)(...p.map(B=>B.compositeFieldUsage))}}}FE.ExprFunc=Vat;function Yat(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],g=i.params[o];if(g===void 0){u=!1;break}if(!g.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=V2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Or.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:g})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Or.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:g,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:g}),_})){u=!1;break}g.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=hT(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function Kat(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function V2(t,e,r,i){var s,o,u,a;if(Or.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Or.isBasicArray)(r))return(0,Or.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:V2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Or.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return V2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=V2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return V2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=V2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Or.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function hT(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=hT(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=hT(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Or.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=hT(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var Jat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jat(e,t,r);return Xat(e,t),e};Object.defineProperty(dT,"__esModule",{value:!0}),dT.ExprProps=void 0;const elt=tt,tlt=Hs,nlt=Zat(nn),rlt=tf,ilt=nf,slt=G2,olt=ht,ult=FE,alt=dt;class llt extends olt.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=nlt.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,elt.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,alt.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,tlt.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof slt.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof ilt.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof rlt.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof ult.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}dT.ExprProps=llt;var pT={},clt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),flt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&clt(e,t,r);return flt(e,t),e};Object.defineProperty(pT,"__esModule",{value:!0}),pT.ExprLogicalOp=void 0;const dlt=RE,H0e=xlt(nn);class hlt extends dlt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[H0e.boolT,H0e.aggregateBoolT]}}pT.ExprLogicalOp=hlt;var mT={},plt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),mlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),glt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&plt(e,t,r);return mlt(e,t),e};Object.defineProperty(mT,"__esModule",{value:!0}),mT.ExprMax=void 0;const gT=glt(nn),ylt=E0;class Elt extends ylt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[gT.numberT,gT.stringT,gT.dateT,gT.timestampT]}returns(e){return e}}mT.ExprMax=Elt;var yT={},Alt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),_lt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Alt(e,t,r);return _lt(e,t),e};Object.defineProperty(yT,"__esModule",{value:!0}),yT.ExprMin=void 0;const ET=vlt(nn),Clt=E0;class Slt extends Clt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[ET.numberT,ET.stringT,ET.dateT,ET.timestampT]}returns(e){return e}}yT.ExprMin=Slt;var AT={},blt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Tlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Rlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&blt(e,t,r);return Tlt(e,t),e};Object.defineProperty(AT,"__esModule",{value:!0}),AT.ExprMinus=void 0;const Dlt=Hs,Q0e=Rlt(nn),Olt=ht;class Flt extends Olt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Q0e.numberT]}getExpression(e){const r=this.expr.getExpression(e);return Q0e.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Dlt.errorFor)("negate requires number")}}AT.ExprMinus=Flt;var _T={};Object.defineProperty(_T,"__esModule",{value:!0}),_T.ExprMulDiv=void 0;const wlt=H2;class Nlt extends wlt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}_T.ExprMulDiv=Nlt;var vT={},wE={};Object.defineProperty(wE,"__esModule",{value:!0}),wE.Unary=void 0;const Llt=ht;class Ilt extends Llt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}wE.Unary=Ilt;var $lt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Blt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),klt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$lt(e,t,r);return Blt(e,t),e};Object.defineProperty(vT,"__esModule",{value:!0}),vT.ExprNot=void 0;const ck=klt(nn),Mlt=wE;class Plt extends Mlt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[ck.boolT,ck.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(ck.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}vT.ExprNot=Plt;var CT={};Object.defineProperty(CT,"__esModule",{value:!0}),CT.ExprNow=void 0;const Ult=ht,jlt=dt;class qlt extends Ult.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,jlt.emptyCompositeFieldUsage)()}}}CT.ExprNow=qlt;var sf={};Object.defineProperty(sf,"__esModule",{value:!0}),sf.ExprIsNull=sf.PartialIsNull=sf.ExprNULL=void 0;const Hlt=Yt,ST=ht;function fk(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class Qlt extends ST.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Hlt.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?fk(e,r,i):super.apply(e,r,i,!0)}}sf.ExprNULL=Qlt;class zlt extends ST.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return fk(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return ST.ATNodeType.Partial}}sf.PartialIsNull=zlt;class Wlt extends ST.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return fk(e,this.op,this.expr)}}sf.ExprIsNull=Wlt;var bT={};Object.defineProperty(bT,"__esModule",{value:!0}),bT.ExprNumber=void 0;const Glt=Yt,Vlt=ht;class Ylt extends Vlt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,Glt.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}bT.ExprNumber=Ylt;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.ExprParens=void 0;const xk=ht;class Klt extends xk.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===xk.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,xk.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}TT.ExprParens=Klt;var RT={};Object.defineProperty(RT,"__esModule",{value:!0}),RT.ExprFilterExpression=void 0;const Jlt=ht;class Xlt extends Jlt.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return{type:"filter expression",value:{node:"filterLiteral",filterSrc:this.filterText},expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:{fields:[],joinedUsage:{}}}}}RT.ExprFilterExpression=Xlt;var DT={};Object.defineProperty(DT,"__esModule",{value:!0}),DT.ExprRegEx=void 0;const Zlt=Yt,e0t=ht;class t0t extends e0t.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,Zlt.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}DT.ExprRegEx=t0t;var OT={};Object.defineProperty(OT,"__esModule",{value:!0}),OT.ExprString=void 0;const n0t=ht,r0t=Yt;class i0t extends n0t.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,r0t.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}OT.ExprString=i0t;var FT={};Object.defineProperty(FT,"__esModule",{value:!0}),FT.ExprSum=void 0;const s0t=W2;class o0t extends s0t.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}FT.ExprSum=o0t;var wT={};Object.defineProperty(wT,"__esModule",{value:!0}),wT.ExprTimeExtract=void 0;const A0=tt,NT=Yt,dk=ht,u0t=ef;class NE extends dk.ExpressionDef{static extractor(e){const r=NE.pluralMap[e];if(r)return r;if((0,A0.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=NE.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof u0t.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,NT.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,A0.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,A0.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!A0.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,dk.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,dk.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,A0.isTimestampUnit)(r)?(0,NT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,A0.mkTemporal)(s.value,u),right:(0,A0.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,A0.isTemporalType)(s.type)?(0,NT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,A0.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,NT.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}wT.ExprTimeExtract=NE,NE.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var LT={},Du={},IT={};Object.defineProperty(IT,"__esModule",{value:!0}),IT.QueryInputSpace=void 0;const a0t=ys,l0t=w2;class c0t extends l0t.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof a0t.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}IT.QueryInputSpace=c0t;var f0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),x0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),d0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&f0t(e,t,r);return x0t(e,t),e};Object.defineProperty(Du,"__esModule",{value:!0}),Du.ReduceFieldSpace=Du.QuerySpace=Du.QueryOperationSpace=void 0;const $T=d0t(tt),hk=Vc,z0e=rf,W0e=zr,h0t=_t,p0t=w2,m0t=xE,g0t=Wr,y0t=IT,Ha=dt,E0t=Cd;class G0e extends p0t.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new y0t.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof g0t.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();$T.TD.isAtomic(c)&&$T.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof W0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new z0e.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof E0t.StructSpaceFieldBase)return(0,Ha.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Ha.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Ha.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Ha.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof W0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Ha.compositeFieldUsageDifference)(s,r));if(r=(0,Ha.mergeCompositeFieldUsage)(r,u),!(0,Ha.isEmptyCompositeFieldUsage)(u)){const a=(0,Ha.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}Du.QueryOperationSpace=G0e;class V0e extends G0e{addRefineFromFields(e){var r;if($T.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new z0e.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new m0t.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof h0t.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Ha.emptyCompositeFieldUsage)(),i=(0,Ha.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!_0t(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if($T.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,hk.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,hk.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,hk.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Du.QuerySpace=V0e;class A0t extends V0e{constructor(){super(...arguments),this.segmentType="reduce"}}Du.ReduceFieldSpace=A0t;function _0t(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var v0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),C0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),S0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&v0t(e,t,r);return C0t(e,t),e};Object.defineProperty(LT,"__esModule",{value:!0}),LT.ExprUngroup=void 0;const Y0e=tt,b0t=Du,K0e=S0t(nn),T0t=ht;class R0t extends T0t.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=K0e.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Y0e.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Y0e.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof b0t.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...K0e.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}LT.ExprUngroup=R0t;var BT={},D0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),O0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),F0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&D0t(e,t,r);return O0t(e,t),e};Object.defineProperty(BT,"__esModule",{value:!0}),BT.ForRange=void 0;const w0t=Hs,J0e=F0t(nn),kT=Es,N0t=Yt,L0t=ht,MT=q2,X0e=ef;class I0t extends L0t.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[J0e.timestampT,J0e.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,w0t.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,N0t.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,kT.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,g=(0,kT.timeOffset)("date",s.value,"+",u.value,a),y=new MT.ExprTime("date",g);return new X0e.Range(m,y).apply(e,r,i)}const c=MT.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,kT.castTo)("timestamp",x,"date"),f=new MT.ExprTime("timestamp",x,[s])}const h=(0,kT.timeOffset)("timestamp",x,"+",u.value,a),p=new MT.ExprTime("timestamp",h,[s,u]);return new X0e.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}BT.ForRange=I0t;var Fr={};Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.LiteralYear=Fr.LiteralQuarter=Fr.LiteralMonth=Fr.LiteralWeek=Fr.LiteralDay=Fr.LiteralHour=Fr.LiteralTimestamp=Fr.TimeFormatError=void 0;const of=qr,$0t=tt,B0t=Yt,k0t=ef,Z0e=q2,pk=ht;class M0t extends Error{}Fr.TimeFormatError=M0t;function Rd(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const ece="yyyy",tce=`${ece}-LL`,Do=`${tce}-dd`,nce=`${Do} HH`,rce=`${nce}:mm`,mk=`${rce}:ss`;class ice extends pk.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,B0t.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class gk extends ice{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=Rd(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=of.DateTime.fromFormat(e,mk);if(o.isValid)return new gk(i,r);if(o=of.DateTime.fromFormat(e,rce),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(mk);return new yk(i,r,"timestamp",u)}}}Fr.LiteralTimestamp=gk;class yk extends ice{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,pk.getMorphicValue)(s,"timestamp"),l=(0,pk.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,$0t.isTemporalType)(u.type)){const a=u.type;return new k0t.Range(new Z0e.ExprTime(a,s.value),new Z0e.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class Ek extends yk{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,nce);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(mk),new Ek(r,i)}}Fr.LiteralHour=Ek;class LE extends yk{constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class Ak extends LE{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,Do);if(s.isValid)return i=s.plus({day:1}).toFormat(Do),new Ak(r,i)}}Fr.LiteralDay=Ak;class _k extends LE{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=r.text.slice(0,10),o=of.DateTime.fromFormat(s,Do);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Do),i=a.toFormat(Do),new _k(r,i)}}}Fr.LiteralWeek=_k;class vk extends LE{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,tce);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new vk(r,i)}}}Fr.LiteralMonth=vk;class Ck extends LE{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=of.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Do),i=a.toFormat(Do),new Ck(r,i)}}}Fr.LiteralQuarter=Ck;class Sk extends LE{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=Rd(e,!1);let i=r.text;const s=of.DateTime.fromFormat(r.text,ece);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new Sk(r,i)}}}Fr.LiteralYear=Sk;var PT={};Object.defineProperty(PT,"__esModule",{value:!0}),PT.PartialCompare=void 0;const sce=ht;class P0t extends sce.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return sce.ATNodeType.Partial}}PT.PartialCompare=P0t;var Y2={},U0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),j0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),q0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&U0t(e,t,r);return j0t(e,t),e};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.PickWhen=Y2.Pick=void 0;const K2=q0t(nn),oce=Yt,H0t=ht,Q0t=et;function UT(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class z0t extends H0t.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!K2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=UT(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=UT(u,f);return K2.typeEq(x,f,!0)?x.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(o.kids.caseElse=f.value,(0,oce.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!K2.typeEq(l.when,K2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!K2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=UT(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=UT(o,u);return K2.typeEq(a,u,!0)?a.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(r.kids.caseElse=u.value,(0,oce.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}Y2.Pick=z0t;class W0t extends Q0t.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}Y2.PickWhen=W0t;var J2={},G0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),V0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Y0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&G0t(e,t,r);return V0t(e,t),e};Object.defineProperty(J2,"__esModule",{value:!0}),J2.CaseWhen=J2.Case=void 0;const K0t=Yt,J0t=ht,X0t=et,X2=Y0t(nn);function uce(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Z0t extends J0t.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!X2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!X2.typeEq(a.when,X2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!X2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=uce(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!X2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=uce(u,a),i.push(a),r.kids.caseElse=a.value}return(0,K0t.computedExprValue)({value:r,dataType:u?X2.atomicDef(u):{type:"null"},from:i})}}J2.Case=Z0t;class ect extends X0t.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}J2.CaseWhen=ect;var jT={},Dd={},tct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),nct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&tct(e,t,r);return nct(e,t),e};Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.RecordLiteral=Dd.RecordElement=void 0;const ace=Gi,ict=Yt,sct=ht,oct=et,uct=rct(nn);class act extends oct.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}Dd.RecordElement=act;class lct extends sct.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);ace.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,ace.mkFieldDef)(uct.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,ict.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}Dd.RecordLiteral=lct;var cct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),fct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cct(e,t,r);return fct(e,t),e};Object.defineProperty(jT,"__esModule",{value:!0}),jT.ArrayLiteral=void 0;const dct=Yt,hct=ht,lce=xct(nn),pct=Dd;class mct extends hct.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof pct.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!lce.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=lce.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,dct.computedExprValue)({dataType:u,value:a,from:i})}}jT.ArrayLiteral=mct;var qT={};Object.defineProperty(qT,"__esModule",{value:!0}),qT.Timeframe=void 0;const gct=tt,yct=et;class Ect extends yct.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,gct.isTimestampUnit)(r)?r:"second"}}qT.Timeframe=Ect;var uf={};Object.defineProperty(uf,"__esModule",{value:!0}),uf.ImportStatement=uf.ImportSelect=uf.ImportSourceName=void 0;const bk=et;class Act extends bk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}uf.ImportSourceName=Act;class _ct extends bk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}uf.ImportSelect=_ct;class vct extends bk.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}uf.ImportStatement=vct;var IE={};Object.defineProperty(IE,"__esModule",{value:!0}),IE.ExtendBlock=void 0;const Cct=et,Sct=Wn;class bct extends Cct.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Sct.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}IE.ExtendBlock=bct;var HT={};Object.defineProperty(HT,"__esModule",{value:!0}),HT.Argument=void 0;const Tct=et;class Rct extends Tct.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}HT.Argument=Rct;var QT={};Object.defineProperty(QT,"__esModule",{value:!0}),QT.HasParameter=void 0;const cce=tt,Dct=et,Oct=ht;class Fct extends Dct.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,cce.isParameterType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default})),e.filterType&&(this.filterType=e.filterType)}parameter(){var e;let r;if(this.default!==void 0){const i=this.default.constantValue();if(this.type&&this.type!==i.type&&i.type!=="null"&&i.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),i.type==="null")return this.type?{type:this.type,value:i.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:i.value,name:this.name,type:"error"});if(i.type==="filter expression")return this.type!=="filter expression"&&this.logError("parameter-missing-default-or-type",`Filter expression parameters must have expicit filter type, for example '${this.name}::filter<string>'`),this.filterType&&(0,Oct.checkFilterExpression)(this,this.filterType,i.value),{value:i.value,name:this.name,type:i.type};if(!(0,cce.isCastType)(i.type)&&i.type!=="error")return this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${i.type}\``),{value:i.value,name:this.name,type:"error"};r={value:i.value,name:this.name,type:i.type}}else this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),r={value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"};return r.type==="filter expression"&&this.filterType&&(r.filterType=this.filterType),r}}QT.HasParameter=Fct;var zT={};Object.defineProperty(zT,"__esModule",{value:!0}),zT.AnonymousQuery=void 0;const wct=et,Nct=Qr;class Lct extends wct.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Nct.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}zT.AnonymousQuery=Lct;var af={};Object.defineProperty(af,"__esModule",{value:!0}),af.View=void 0;const Ict=et;class $ct extends Ict.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}af.View=$ct;var WT={};Object.defineProperty(WT,"__esModule",{value:!0}),WT.ViewArrow=void 0;const Bct=Wr,kct=af;class Mct extends kct.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new Bct.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}WT.ViewArrow=Mct;var GT={},$E={};Object.defineProperty($E,"__esModule",{value:!0}),$E.refine=void 0;const Tk=Gi,Pct=dt,Rk=Vc;function Uct(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,Tk.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,Tk.isQuerySegment)(u)&&(0,Tk.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,Rk.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,Rk.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(Rk.nameFromDef)}`),o.compositeFieldUsage=(0,Pct.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}$E.refine=Uct,Object.defineProperty(GT,"__esModule",{value:!0}),GT.ViewRefine=void 0;const jct=gi,qct=zs,Hct=$E,Qct=af;class zct extends Qct.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,qct.getFinalStruct)(this.refinement,e.structDef(),s):jct.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Hct.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}GT.ViewRefine=zct;var VT={};Object.defineProperty(VT,"__esModule",{value:!0}),VT.ReferenceView=void 0;const Dk=tt,fce=gi,Wct=zs,Gct=zr,Vct=$E,Yct=af;class Kct extends Yct.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:fce.ErrorFactory.structDef,outputStruct:fce.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof Gct.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,Dk.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,Dk.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,Dk.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,Wct.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,Vct.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}VT.ReferenceView=Kct;var YT={},BE={},KT={},kE={};Object.defineProperty(kE,"__esModule",{value:!0}),kE.Index=void 0;const Jct=et,Xct=Wn;class Zct extends Jct.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=Xct.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}kE.Index=Zct;var ME={};Object.defineProperty(ME,"__esModule",{value:!0}),ME.SampleProperty=void 0;const eft=et,xce=Wn;class tft extends eft.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=xce.LegalRefinementStage.Tail,this.forceQueryClass=xce.QueryClass.Index}sampling(){return this.sample}}ME.SampleProperty=tft;var JT={};Object.defineProperty(JT,"__esModule",{value:!0}),JT.IndexFieldSpace=void 0;const dce=dt,hce=tt,Ok=_t,nft=zr,rft=Du,ift=pE,sft=Wr;class oft extends rft.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof Ok.FieldReference?super.pushFields(r):r instanceof Ok.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,dce.emptyCompositeFieldUsage)(),i=(0,dce.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof nft.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof ift.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof sft.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=Ok.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();hce.TD.isBasicAtomic(f)&&(0,hce.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}JT.IndexFieldSpace=oft,Object.defineProperty(KT,"__esModule",{value:!0}),KT.IndexBuilder=void 0;const Fk=tt,uft=gi,aft=qa,lft=kE,cft=nf,fft=ME,xft=JT,wk=dt;class dft{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new xft.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof aft.Filter?e.queryExecute(this):e instanceof cft.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof lft.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof fft.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,Fk.isIndexSegment)(e)&&!(0,Fk.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),uft.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,Fk.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,wk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,wk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}KT.IndexBuilder=dft;var XT={},PE={};Object.defineProperty(PE,"__esModule",{value:!0}),PE.GroupBy=void 0;const hft=Qs,pce=Wn;class pft extends hft.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=pce.LegalRefinementStage.Single,this.forceQueryClass=pce.QueryClass.Grouping}}PE.GroupBy=pft;var ZT={};Object.defineProperty(ZT,"__esModule",{value:!0}),ZT.ProjectFieldSpace=void 0;const eR=tt,mft=Du;class gft extends mft.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!eR.TD.isAtomic(e)||(0,eR.expressionIsAggregate)(e.expressionType)?!1:(0,eR.expressionInvolvesAggregate)(e.expressionType)&&(0,eR.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}ZT.ProjectFieldSpace=gft;var lf={},Od={};Object.defineProperty(Od,"__esModule",{value:!0}),Od.Ordering=Od.OrderBy=void 0;const yft=tt,mce=rf,gce=et,Eft=Wn;class Aft extends gce.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof mce.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof mce.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,yft.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}Od.OrderBy=Aft;class _ft extends gce.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Eft.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}Od.Ordering=_ft,Object.defineProperty(lf,"__esModule",{value:!0}),lf.ReduceBuilder=lf.QuerySegmentBuilder=void 0;const Ou=tt,vft=gi,Cft=rf,Sft=nf,bft=Od,Tft=Du,Rft=Qs,Nk=dt;function yce(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class Ece{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Rft.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Sft.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof bft.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,Ou.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,Nk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,Nk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}lf.QuerySegmentBuilder=Ece;class Dft extends Ece{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Tft.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,Ou.isReduceSegment)(e)||(0,Ou.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),vft.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=yce(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=yce(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Cft.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,Ou.expressionIsAggregate)(h.expressionType),a=(0,Ou.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAggregate)(o.expressionType),a=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAnalytic)(o.expressionType);if((0,Ou.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,Ou.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}lf.ReduceBuilder=Dft,Object.defineProperty(XT,"__esModule",{value:!0}),XT.ProjectBuilder=void 0;const Ace=tt,Oft=gi,Fft=PE,wft=ZT,Nft=lf;class Lft extends Nft.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new wft.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Fft.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,Ace.isProjectSegment)(e)||(0,Ace.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),Oft.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}XT.ProjectBuilder=Lft;var tR={};Object.defineProperty(tR,"__esModule",{value:!0}),tR.PartialBuilder=void 0;const Ift=Gi,$ft=lf;class Bft extends $ft.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,Ift.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}tR.PartialBuilder=Bft,Object.defineProperty(BE,"__esModule",{value:!0}),BE.QOpDesc=void 0;const kft=KT,Mft=XT,Pft=lf,Uft=et,jft=zs,qft=Wr,Fd=Wn,Hft=tR;class Qft extends Uft.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=Fd.QueryClass.Grouping:this.refineThis.type==="project"?r=Fd.QueryClass.Project:this.refineThis.type==="index"&&(r=Fd.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=Fd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case Fd.QueryClass.Grouping:return new Pft.ReduceBuilder(e,this.refineThis,r,i);case Fd.QueryClass.Project:return new Mft.ProjectBuilder(e,this.refineThis,r,i);case Fd.QueryClass.Index:return new kft.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Hft.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new qft.StaticSourceSpace((0,jft.opOutputStruct)(this,e.structDef(),s))}}}BE.QOpDesc=Qft,Object.defineProperty(YT,"__esModule",{value:!0}),YT.QOpDescView=void 0;const zft=tt,Wft=Wr,_ce=BE,Gft=zs,Lk=Wn,Vft=af;class Yft extends Vft.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,zft.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new _ce.QOpDesc([]),u=new _ce.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case Lk.LegalRefinementStage.Head:o.push(a);break;case Lk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case Lk.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,Gft.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new Wft.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}YT.QOpDescView=Yft;var wn={},Kft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Jft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kft(e,t,r);return Jft(e,t),e};Object.defineProperty(wn,"__esModule",{value:!0}),wn.FieldDefinitionValue=wn.DefSpace=wn.DimensionFieldDeclaration=wn.MeasureFieldDeclaration=wn.DeclareFieldDeclaration=wn.ProjectFieldDeclaration=wn.GroupByFieldDeclaration=wn.AggregateFieldDeclaration=wn.CalculateFieldDeclaration=wn.AtomicFieldDeclaration=void 0;const Ik=tt,vce=Xft(nn),Zft=j2,ext=et,wd=lr,txt=Qr,nxt=zr;class cf extends ext.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=txt.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new $k(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,Ik.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,Ik.mkFieldDef)(vce.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,Zft.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof $k&&e.foundCircle)&&i.type!=="error"){const u=vce.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new Cce(e,this))}}wn.AtomicFieldDeclaration=cf;class rxt extends cf{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}wn.CalculateFieldDeclaration=rxt;class ixt extends cf{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckAggregate)(e,this)}}wn.AggregateFieldDeclaration=ixt;class sxt extends cf{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckGroupBy)(e,this)}}wn.GroupByFieldDeclaration=sxt;class oxt extends cf{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckProject)(e,this)}}wn.ProjectFieldDeclaration=oxt;class uxt extends cf{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckDeclare)(e,this)}}wn.DeclareFieldDeclaration=uxt;class axt extends cf{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckMeasure)(e,this)}}wn.MeasureFieldDeclaration=axt;class lxt extends cf{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,wd.typecheckDimension)(e,this)}}wn.DimensionFieldDeclaration=lxt;class $k{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}wn.DefSpace=$k;class Cce extends nxt.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,Ik.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}wn.FieldDefinitionValue=Cce;var nR={};Object.defineProperty(nR,"__esModule",{value:!0}),nR.Aggregate=void 0;const cxt=Qs,Sce=Wn;class fxt extends cxt.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=Sce.LegalRefinementStage.Single,this.forceQueryClass=Sce.QueryClass.Grouping}}nR.Aggregate=fxt;var rR={};Object.defineProperty(rR,"__esModule",{value:!0}),rR.Calculate=void 0;const xxt=Qs,dxt=Wn;class hxt extends xxt.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=dxt.LegalRefinementStage.Single}}rR.Calculate=hxt;var UE={};Object.defineProperty(UE,"__esModule",{value:!0}),UE.Dimensions=void 0;const pxt=Yc;class mxt extends pxt.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}UE.Dimensions=mxt;var jE={};Object.defineProperty(jE,"__esModule",{value:!0}),jE.Measures=void 0;const gxt=Yc;class yxt extends gxt.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}jE.Measures=yxt;var iR={};Object.defineProperty(iR,"__esModule",{value:!0}),iR.Nests=void 0;const Ext=Qs,bce=Wn;class Axt extends Ext.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=bce.LegalRefinementStage.Single,this.forceQueryClass=bce.QueryClass.Grouping}}iR.Nests=Axt;var sR={};Object.defineProperty(sR,"__esModule",{value:!0}),sR.ProjectStatement=void 0;const _xt=Qs,Tce=Wn;class vxt extends _xt.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=Tce.QueryClass.Project,this.queryRefinementStage=Tce.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}sR.ProjectStatement=vxt;var ff={},_0={},Pn={};Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.getPlainString=Pn.unIndent=Pn.getOptionalId=Pn.idToStr=Pn.getId=Pn.getStringParts=Pn.getStringIfShort=Pn.getShortString=void 0;const Rce=$o;function Dce(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?Rce.ParseUtil.parseString(i,i[0]):""}Pn.getShortString=Dce;function Oce(t){const e=t.string().shortString();if(e)return Dce(e)}Pn.getStringIfShort=Oce;function*Fce(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Pn.getStringParts=Fce;function wce(t){return Nce(t.id())}Pn.getId=wce;function Nce(t){const e=t.BQ_STRING();return e?Rce.ParseUtil.parseString(e.text,"`"):t.text}Pn.idToStr=Nce;function Cxt(t){function e(r){return"id"in r}if(e(t)&&t.id())return wce(t)}Pn.getOptionalId=Cxt;function*Lce(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function Sxt(t){let e;for(const r of Lce(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function Ice(t){let e;for(const r of t)if(typeof r=="string"){const i=Sxt(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of Lce(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Pn.unIndent=Ice;function bxt(t,e=!1){const r=[],i=Oce(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of Fce(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return Ice(s),[s.join(""),r]}return["",r]}Pn.getPlainString=bxt,Object.defineProperty(_0,"__esModule",{value:!0}),_0.findReferences=_0.deprecatedParseTableURI=_0.constructTableKey=void 0;const Txt=T0,Bk=Pn;function $ce(t){const e=(0,Bk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,Bk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class Rxt{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=Bce(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterExploreTable(e){const r=(0,Bk.getId)(e.connectionId()),i=$ce(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const r=$ce(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function Bce(t,e){return t===void 0?e:`${t}:${e}`}_0.constructTableKey=Bce;function Dxt(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}_0.deprecatedParseTableURI=Dxt;function Oxt(t,e,r){const i=new Rxt(t,e),s=i;return Txt.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}_0.findReferences=Oxt,Object.defineProperty(ff,"__esModule",{value:!0}),ff.TableFunctionSource=ff.TableMethodSource=ff.TableSource=void 0;const kce=_0,Fxt=Ro,Mce=gi;class kk extends Fxt.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return Mce.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,kce.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),Mce.ErrorFactory.structDef}}ff.TableSource=kk;class wxt extends kk{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}ff.TableMethodSource=wxt;class Nxt extends kk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,kce.deprecatedParseTableURI)(this.tableURI)}}ff.TableFunctionSource=Nxt;var oR={};Object.defineProperty(oR,"__esModule",{value:!0}),oR.SQLString=void 0;const Lxt=et,Pce=Tu;class Ixt extends Lxt.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter($xt)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof Pce.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}oR.SQLString=Ixt;function $xt(t){return t instanceof Pce.SourceQueryElement}var uR={};Object.defineProperty(uR,"__esModule",{value:!0}),uR.SourceDesc=void 0;const Bxt=et;class kxt extends Bxt.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}uR.SourceDesc=kxt;var aR={};Object.defineProperty(aR,"__esModule",{value:!0}),aR.isSourceProperty=void 0;const Mxt=qa,Pxt=Yc,Uxt=I2,jxt=Jc,qxt=$2,Hxt=B2,Qxt=k2,zxt=Kc,Wxt=ys;function Gxt(t){return t instanceof Mxt.Filter||t instanceof Wxt.JoinStatement||t instanceof Pxt.DeclareFields||t instanceof Uxt.FieldListEdit||t instanceof jxt.Renames||t instanceof qxt.PrimaryKey||t instanceof zxt.ObjectAnnotation||t instanceof Hxt.Views||t instanceof Qxt.TimezoneStatement}aR.isSourceProperty=Gxt;var lR={};Object.defineProperty(lR,"__esModule",{value:!0}),lR.isFieldCollectionMember=void 0;const Vxt=wn,Uce=_t;function Yxt(t){return t instanceof Uce.FieldReference||t instanceof Uce.WildcardFieldReference||t instanceof Vxt.AtomicFieldDeclaration}lR.isFieldCollectionMember=Yxt;var cR={};Object.defineProperty(cR,"__esModule",{value:!0}),cR.isQueryElement=void 0;const Kxt=M2,Jxt=P2,Xxt=CE,Zxt=SE;function edt(t){return t instanceof Kxt.QueryArrow||t instanceof Jxt.QueryRefine||t instanceof Xxt.QueryReference||t instanceof Zxt.QueryRaw}cR.isQueryElement=edt;var jce={};Object.defineProperty(jce,"__esModule",{value:!0});var fR={};Object.defineProperty(fR,"__esModule",{value:!0}),fR.isQueryProperty=void 0;function tdt(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}fR.isQueryProperty=tdt;var xR={};Object.defineProperty(xR,"__esModule",{value:!0}),xR.isQueryExtendProperty=void 0;const ndt=UE,rdt=ys,idt=jE;function sdt(t){return t instanceof ndt.Dimensions||t instanceof idt.Measures||t instanceof rdt.JoinStatement}xR.isQueryExtendProperty=sdt;var dR={};Object.defineProperty(dR,"__esModule",{value:!0}),dR.isFieldPropStatement=void 0;const odt=tf,udt=qa,adt=nf,ldt=G2;function cdt(t){return t instanceof udt.Filter||t instanceof adt.Limit||t instanceof ldt.PartitionBy||t instanceof odt.FunctionOrdering}dR.isFieldPropStatement=cdt,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(uE,t),r(O2,t),r(F2,t),r(Ro,t),r(cE,t),r(Tu,t),r(V4,t),r(Y4,t),r(X4,t),r(gE,t),r(Z4,t),r(eT,t),r(bu,t),r(I2,t),r($2,t),r(Jc,t),r(B2,t),r(k2,t),r(nT,t),r(H2,t),r(iT,t),r(Q2,t),r(tf,t),r(sT,t),r(E0,t),r(oT,t),r(W2,t),r(uT,t),r(aT,t),r(lT,t),r(y0,t),r(cT,t),r(fT,t),r(dT,t),r(FE,t),r(DE,t),r(bd,t),r(pT,t),r(mT,t),r(yT,t),r(AT,t),r(_T,t),r(vT,t),r(CT,t),r(sf,t),r(bT,t),r(TT,t),r(RT,t),r(DT,t),r(OT,t),r(FT,t),r(wT,t),r(LT,t),r(BT,t),r(Fr,t),r(PT,t),r(G2,t),r(Y2,t),r(J2,t),r(jT,t),r(Dd,t),r(ef,t),r(qT,t),r(wE,t),r(uf,t),r(IE,t),r(HT,t),r(QT,t),r(zT,t),r(P2,t),r(M2,t),r(af,t),r(WT,t),r(GT,t),r(VT,t),r(YT,t),r(wn,t),r(_t,t),r(nR,t),r(rR,t),r(Yc,t),r(UE,t),r(IE,t),r(qa,t),r(PE,t),r(kE,t),r(ys,t),r(aE,t),r(nf,t),r(jE,t),r(uE,t),r(iR,t),r(Od,t),r(sR,t),r(BE,t),r(ME,t),r(U2,t),r(Sd,t),r(bE,t),r(ff,t),r(oR,t),r(Kc,t),r(Ru,t),r(uR,t),r(aR,t),r(ht,t),r(lR,t),r(rf,t),r(et,t),r(cR,t),r(jce,t),r(fR,t),r(xR,t),r(dR,t)}(j4);var hR={},fdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),xdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ddt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fdt(e,t,r);return xdt(e,t),e};Object.defineProperty(hR,"__esModule",{value:!0}),hR.MalloyToAST=void 0;const qce=ig,hdt=qd,oe=ddt(j4),Mk=T2,Hce=xr,pdt=j4,Xn=Pn,pR=tt,mdt=$o,Qce=zn,gdt=iE;class zce extends oe.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Pk extends oe.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const ydt=[];class Edt extends hdt.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of ydt){const o=mdt.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,Mk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,Qce.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new Hce.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,Mk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,Mk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Pk||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new oe.FieldName((0,Xn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new oe.ModelEntryReference((0,Xn.getId)(e)),e.id())}defaultResult(){return new oe.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new Hce.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new oe.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof oe.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Xn.getPlainString)(e);for(const s of i)s instanceof qce.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of(0,Xn.getStringParts)(e))i instanceof qce.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new oe.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>oe.isDocStatementOrDocStatementList(i)&&i,"statement");return new oe.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new oe.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=(0,Xn.getId)(e.parameterNameDef());let i,s;const o=e.legalParamType();if(o){const l=o.malloyType();if(l){const f=this.getMalloyType(l);(0,gdt.isFilterable)(f)?s=f:this.contextError(o,"parameter-illegal-default-type",`Unknown filter type ${f}`)}const c=o.FILTER()?"filter expression":o.text.toLowerCase();if(!(0,pR.isParameterType)(c))return this.contextError(o,"parameter-illegal-default-type",`Unknown parameter type ${c}`),null;i=c}const u=e.fieldExpr();let a;if(u){const l=new oe.ConstantExpression(this.getFieldExpr(u));a=this.astAt(l,u)}return this.astAt(new oe.HasParameter({name:r,type:i,default:a,filterType:s}),e)}getSourceParameters(e){if(e===void 0)return[];this.inExperiment("parameters",e);function r(i){return i!==null}return e.sourceParameter().map(i=>this.getSourceParameter(i)).filter(r)}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new oe.DefineSource((0,Xn.getId)(e.sourceNameDef()),r instanceof oe.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>oe.isSourceProperty(s)&&s,"source property");return new oe.SourceDesc(r)}visitExploreTable(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new oe.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new oe.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Xn.getShortString)(u));const a=new oe.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof oe.Join&&(i.push(u),u instanceof oe.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof oe.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new oe.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof oe.Join&&(s.push(u),u instanceof oe.ExpressionJoin&&(u.joinType="one"));const o=new oe.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof oe.Join&&(s.push(u),u instanceof oe.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new oe.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof oe.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new oe.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new oe.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new oe.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,pR.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new oe.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Xn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),oe.DimensionFieldDeclaration),s=new oe.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),oe.MeasureFieldDeclaration),s=new oe.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(oe.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new oe.ExtendBlock(r);return this.astAt(s,e)}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new oe.RenameField((0,Xn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new oe.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new oe.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new oe.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),s}visitDefExplorePrimaryKey(e){const r=new oe.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new oe.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new oe.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),oe.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new oe.SQExtend(r,new oe.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new oe.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>oe.isQueryProperty(i)&&i,"query statement");return new oe.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof oe.FieldReference||s instanceof oe.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new oe.Aggregate(this.getQueryItems(e.queryFieldList(),oe.AggregateFieldDeclaration,oe.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new oe.GroupBy(this.getQueryItems(e.queryFieldList(),oe.GroupByFieldDeclaration,oe.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new oe.Calculate(this.getQueryItems(e.queryFieldList(),oe.CalculateFieldDeclaration,oe.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),oe.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new oe.ExprGranularTime(new oe.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new oe.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,oe.ProjectFieldDeclaration,oe.ProjectFieldReference));return this.astAt(new oe.ProjectStatement(r),e)}visitProjectStatement(e){const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,oe.ProjectFieldReference):void 0,o=this.astAt(new oe.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Xn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new oe.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,oe.IndexFieldReference);return i.STAR()?this.astAt(new oe.WildcardFieldReference(o),e):this.astAt(o,e)});return new oe.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new oe.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new oe.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new oe.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new oe.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new oe.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new oe.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new oe.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new oe.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new oe.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Xn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof oe.SourceQueryElement){const o=new oe.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new oe.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new oe.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof oe.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Xn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new oe.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Xn.getId)(e.exploreQueryNameDef()),i=new oe.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new oe.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new oe.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new oe.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new oe.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new oe.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new oe.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new oe.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(oe.isComparison(r))return this.astAt(new oe.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new oe.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new oe.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
|
|
1556
1556
|
`){const o=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing ${o}${r[0]}${o} before end-of-line`)}const s=new oe.ExprString(r.slice(1,-1));return this.astAt(s,e)}visitExprRegex(e){const r=e.HACKY_REGEX().text;return new oe.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new oe.ExprNow}visitExprNumber(e){return new oe.ExprNumber(e.text)}visitExprFieldPath(e){const r=new oe.ExprIdReference(this.getFieldPath(e.fieldPath(),oe.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new oe.ExprNULL}visitExprExpr(e){return new oe.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new oe.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1)),s=e.PLUS()?"+":"-";return new oe.ExprAddSub(r,s,i)}visitExprMulDiv(e){const r=e.STAR()?"*":e.SLASH()?"/":"%";return new oe.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const r=e.compareOp().text,i=this.getFieldExpr(e.fieldExpr(0)),s=this.getFieldExpr(e.fieldExpr(1));if(oe.isEquality(r)){const o=this.rangeFromContext(e);return s instanceof oe.ExprNULL&&(r==="="?this.warnWithReplacement("sql-is-null","Use 'is null' to check for NULL instead of '= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is null`):r==="!="&&this.warnWithReplacement("sql-is-not-null","Use 'is not null' to check for NULL instead of '!= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is not null`)),this.astAt(new oe.ExprEquality(i,r,s),e)}else if(oe.isComparison(r))return this.astAt(new oe.ExprCompare(i,r,s),e);throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprUngroup(e){const r=e.fieldName().map(s=>this.getFieldName(s)),i=e.ungroup().text.toLowerCase();return this.astAt(new oe.ExprUngroup(i==="all"?i:"exclude",this.getFieldExpr(e.fieldExpr()),r),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const r=e.fieldPath(),i=this.getFieldPath(r,oe.ExpressionFieldReference),s=r&&i?this.astAt(i,r):void 0,o=e.aggregate().text.toLowerCase(),u=e.fieldExpr();if(e.aggregate().COUNT())return u&&this.contextError(u,"count-expression-with-locality","Expression illegal inside path.count()"),new oe.ExprCount(s);const a=u?this.getFieldExpr(u):void 0;if(o==="min"||o==="max")if(a)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o));else{const l=this.astAt(new oe.ExprIdReference(i),r);return o==="min"?new oe.ExprMin(l):new oe.ExprMax(l)}else{if(o==="avg")return new oe.ExprAvg(a,s);if(o==="sum")return new oe.ExprSum(a,s);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${o}`)}return new oe.ExprNULL}visitExprPathlessAggregate(e){const r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0,s=void 0,o=e.aggregate().text.toLowerCase();if(o==="count")return this.astAt(i?new oe.ExprCountDistinct(i):new oe.ExprCount,e);if(o==="min"){if(i)return new oe.ExprMin(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else if(o==="max"){if(i)return new oe.ExprMax(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else{if(i===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(o)),new oe.ExprNULL;const u=e.SOURCE_KW()!==void 0;if(o==="avg")return new oe.ExprAvg(i,s,u);if(o==="sum")return new oe.ExprSum(i,s,u)}return new oe.ExprNULL}visitExprApply(e){return new oe.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new oe.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new oe.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyType(e){const r=e.text;if((0,pR.isCastType)(r))return r;throw this.internalError(e,`unknown type '${r}'`)}getMalloyOrSQLType(e){const r=e.malloyType();if(r)return this.getMalloyType(r);const i=e.string();if(i)return{raw:this.getPlainStringFrom({string:()=>i})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new oe.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new oe.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new oe.Timeframe(e.text)}visitExprForRange(e){const r=this.getFieldExpr(e._startAt),i=this.getFieldExpr(e._duration),s=this.visitTimeframe(e.timeframe());return new oe.ForRange(r,i,s)}visitExprAggFunc(e){const r=e.argumentList(),i=r?this.allFieldExpressions(r.fieldExpr()):[],s=(0,Xn.getId)(e),o=e.fieldPath(),u=o?this.getFieldPath(o,oe.ExpressionFieldReference):void 0,a=o&&u?this.astAt(u,o):void 0;return oe.ExprTimeExtract.extractor(s)?this.astAt(new oe.ExprTimeExtract(s,i),e):this.astAt(new oe.ExprFunc(s,i,!1,void 0,a),e)}visitExprFunc(e){var r,i;const s=e.argumentList(),o=s?this.allFieldExpressions(s.fieldExpr()):[],u=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text;let l;a&&((0,pR.isCastType)(a)?l=a:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${a}'`),l=void 0));let c=(0,Xn.getOptionalId)(e)||((i=e.timeframe())===null||i===void 0?void 0:i.text);return c===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),c="FUNCTION_NAME_ERROR"),oe.ExprTimeExtract.extractor(c)?this.astAt(new oe.ExprTimeExtract(c,o),e):this.astAt(new oe.ExprFunc(c,o,u,l),e)}visitExprDuration(e){return new oe.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const r=e._valueExpr,i=r?this.getFieldExpr(r):void 0,s=e.caseWhen(),o=s.map(l=>new oe.CaseWhen(this.getFieldExpr(l._condition),this.getFieldExpr(l._result))),u=e._caseElse,a=u?this.getFieldExpr(u):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.rangeFromContext(e),`${[...r?[`${this.getSourceCode(r)} ?`]:[],...s.map(l=>`pick ${this.getSourceCode(l._result)} when ${this.getSourceCode(l._condition)}`),u?`else ${u.text}`:"else null"].join(" ")}`),new oe.Case(i,o,a)}visitPickStatement(e){const r=e.pick().map(i=>{let s;return i._pickValue&&(s=this.getFieldExpr(i._pickValue)),new oe.PickWhen(s,this.getFieldExpr(i._pickWhen))});return e.ELSE()?new oe.Pick(r,this.getFieldExpr(e._pickElse)):new oe.Pick(r)}visitExprFieldProps(e){const r=this.only(e.fieldProperties().fieldPropertyStatement().map(i=>this.visit(i)),i=>oe.isFieldPropStatement(i)&&i,"field property statement");return new oe.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new oe.PartitionBy(e.id().map(r=>this.astAt(new oe.PartitionByFieldReference([this.astAt(new oe.FieldName((0,Xn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,oe.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,oe.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,oe.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,oe.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,oe.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,oe.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,oe.LiteralYear.parse)}visitImportStatement(e){const r=this.getPlainStringFrom(e.importURL()),i=this.astAt(new oe.ImportStatement(r,this.parseInfo.importBaseURL),e),s=e.importSelect();if(s)for(const o of s.importItem()){const u=o.id(),a=u[1]?this.astAt(new oe.ImportSourceName((0,Xn.idToStr)(u[1])),u[1]):void 0;i.push(this.astAt(new oe.ImportSelect((0,Xn.idToStr)(u[0]),a),u[0]))}return i}visitDebugExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const r=e.sampleSpec().INTEGER_LITERAL();if(r)return new oe.SampleProperty({rows:this.getNumber(r)});const i=e.sampleSpec().PERCENT_LITERAL();if(i)return new oe.SampleProperty({percent:this.getNumber(i)});const s=e.sampleSpec().TRUE()!==void 0;return new oe.SampleProperty({enable:s})}visitDocAnnotations(e){const r=e.DOC_ANNOTATION().map(s=>({text:s.text,at:this.getLocation(e)})),i=new oe.ModelAnnotation(r);return this.compilerFlags=i.getCompilerFlags(this.compilerFlags,this.msgLog),i}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new Pk(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new Pk(e.text)}visitDefExploreAnnotation(e){const r=this.getNotes(e);return new oe.ObjectAnnotation(r)}getSQArgument(e){const r=e.argumentId(),i=r?this.astAt(new oe.PartitionByFieldReference([this.astAt(new oe.FieldName((0,Xn.idToStr)(r.id())),r)]),r):void 0;return this.astAt(new oe.Argument({id:i,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(r=>this.getSQArgument(r))}visitSQID(e){const r=this.getModelEntryName(e),i=this.getSQArguments(e.sourceArguments());return this.astAt(new oe.SQReference(r,i),e.id())}getSqExpr(e){const r=this.visit(e);return r instanceof oe.SourceQueryElement?r:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${r.elementType}'`),new zce)}visitSQExtendedSource(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new oe.SQExtend(r,this.getSourceExtensions(e.exploreProperties()),s);return this.astAt(o,e)}getIncludeItems(e){return this.inExperiment("access_modifiers",e),e.includeItem().map(r=>this.getIncludeItem(r)).filter(Qce.isNotUndefined)}getIncludeItem(e){var r;const i=e.tags(),s=i?this.getNotes(i):[],o=e.includeExceptList();if(o){i&&s.length>0&&this.contextError(i,"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const u=this.getExcludeList(o);return this.astAt(new oe.IncludeExceptItem(u),e)}else{const u=e.includeList();if(u===void 0){this.contextError((r=e.orphanedAnnotation())!==null&&r!==void 0?r:e,"orphaned-object-annotation","This tag is not attached to anything",{severity:"warn"});return}const a=this.getAccessLabelProp(e.accessLabelProp()),l=this.getIncludeList(u),c=this.astAt(new oe.IncludeAccessItem(a,l),e);return c.extendNote({blockNotes:s}),c}}getIncludeList(e){const r=e.includeField();if(r===void 0)throw this.internalError(e,"Expected a field name list");return r.map(i=>this.getIncludeListItem(i))}getExcludeList(e){return e.includeExceptListItem().map(r=>{r.tags().ANNOTATION().length>0&&this.contextError(r.tags(),"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const i=r.fieldName();if(i)return this.astAt(new oe.AccessModifierFieldReference([this.astAt(this.getFieldName(i),r)]),i);const s=r.collectionWildCard();if(s)return this.astAt(this.visitCollectionWildCard(s),s);throw this.internalError(r,"Expected a field name or wildcard")})}getIncludeListItem(e){const r=e.collectionWildCard(),i=r?this.visitCollectionWildCard(r):void 0,s=e._as?e._as.text:void 0,o=e.tags(),u=o?this.getNotes(o):[],a=e.isDefine(),l=a?this.getIsNotes(a):[],c=[...u,...l],f=e._name?this.astAt(new oe.AccessModifierFieldReference([this.astAt(this.getFieldName(e._name),e._name)]),e._name):void 0,x=f??i;if(x===void 0)throw this.internalError(e,"Expected a field name or wildcard");const h=this.astAt(new oe.IncludeListItem(x,s),e);return h.extendNote({notes:c}),h}visitSQParens(e){const r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQCompose(e){const r=e.sqExpr().map(i=>this.getSqExpr(i));return this.inExperiment("composite_sources",e),this.astAt(new oe.SQCompose(r),e)}visitSQArrow(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new oe.SQArrow(r,this.getVExpr(i));return this.astAt(s,e)}getVExpr(e){const r=this.visit(e);if(r instanceof oe.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new oe.ReferenceView(this.getFieldPath(e.fieldPath(),oe.ViewOrScalarFieldReference))}visitSegOps(e){return new oe.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new oe.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new oe.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new oe.SQRefine(r,this.getVExpr(i));return this.astAt(s,e)}visitSQTable(e){const r=this.visit(e.exploreTable());if(r instanceof pdt.TableSource){const i=new oe.SQSource(r);return this.astAt(i,e)}return new zce}visitSQSQL(e){const r=new oe.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new oe.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const r=new oe.ExprIdReference(this.getFieldPath(e.fieldPath(),oe.ExpressionFieldReference));return this.astAt(new oe.RecordElement({path:r}),e)}visitRecordExpr(e){const r=this.getFieldExpr(e.fieldExpr()),i=e.recordKey(),s=i?{key:(0,Xn.getId)(i),value:r}:{value:r};return this.astAt(new oe.RecordElement(s),e)}visitExprLiteralRecord(e){const r=this.only(e.recordElement().map(i=>this.astAt(this.visit(i),i)),i=>i instanceof oe.RecordElement&&i,"a legal record property description");return new oe.RecordLiteral(r)}visitExprArrayLiteral(e){const r=e.fieldExpr().map(s=>this.getFieldExpr(s)),i=new oe.ArrayLiteral(r);return this.astAt(i,e)}visitExprWarnLike(e){let r="~";const i=e.fieldExpr(0),s=e.fieldExpr(1),o=this.rangeFromContext(e);return e.NOT()?(r="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",o,`${this.getSourceCode(i)} !~ ${this.getSourceCode(s)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",o,`${this.getSourceCode(i)} ~ ${this.getSourceCode(s)}`),this.astAt(new oe.ExprCompare(this.getFieldExpr(i),r,this.getFieldExpr(s)),e)}visitExprNullCheck(e){const r=e.fieldExpr();return this.astAt(new oe.ExprIsNull(this.getFieldExpr(r),e.NOT()?"!=":"="),e)}visitExprWarnIn(e){const r=this.getFieldExpr(e.fieldExpr()),i=!!e.NOT(),s=e.fieldExprList().fieldExpr(),o=this.astAt(new oe.ExprLegacyIn(r,i,s.map(u=>this.getFieldExpr(u))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${i?" NOT":""} IN (a,b,c)`,this.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${i?"!=":"="} (${s.map(u=>this.getSourceCode(u)).join(" | ")})`),o}visitTickFilterString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
|
|
1557
1557
|
`){const u=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing $${u}${r[0]}${u} before end-of-line`)}const s=r.slice(1,-1),o=new oe.ExprFilterExpression(s);return this.astAt(o,e)}visitTripFilterString(e){const i=e.text.slice(1).trimStart().slice(3,-3),s=new oe.ExprFilterExpression(i);return this.astAt(s,e)}}hR.MalloyToAST=Edt;var mR={};Object.defineProperty(mR,"__esModule",{value:!0}),mR.Zone=void 0;class Adt{constructor(){this.location={},this.zone=new Map}get(e){const r=this.zone.get(e);if((r==null?void 0:r.status)==="present")return r.value}getEntry(e){const r=this.zone.get(e);return r?r.firstReference||!this.location[e]?r:{...r,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,r){this.zone.set(e,{status:"present",value:r})}reference(e,r){const i=this.zone.get(e);(i==null?void 0:i.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){const e=[];for(const[r,i]of this.zone)i.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(const[i,s]of Object.entries(e))s!==void 0&&this.define(i,s);if(r)for(const[i,s]of Object.entries(r))this.zone.set(i,{status:"error",message:s})}}mR.Zone=Adt;var gR={};Object.defineProperty(gR,"__esModule",{value:!0}),gR.walkForDocumentSymbols=void 0;const _dt=T0,vdt=Pn;class Cdt{constructor(e,r,i,s){this.translator=e,this.tokens=r,this.scopes=i,this.symbols=s}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){const r=this.translator.rangeFromContext(e);this.scopes.push({range:r,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){const r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){const r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},i=this.peekScope();i&&i.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const r=e.queryName();if(r)return r.id().text;let i,s=!1;const o={enterVArrow(a){a.vExpr().enterRule(o)},enterVSeg(a){a.segExpr().enterRule(u)}},u={enterSegField(a){const l=a.fieldPath().fieldName();s||(i??(i=l[l.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(o)},enterSegRefine(a){a._lhs.enterRule(u)},enterSegOps(){i=void 0,s=!0}};return e.vExpr().enterRule(o),i}handleNestEntry(e){const r=this.getNestDefName(e);if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},s=this.peekScope();return s&&s.children.push(i),i}enterNestDef(e){const r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterQueryFieldEntry(e){var r;const i=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(i===void 0)return;const s={range:this.translator.rangeFromContext(e),name:i.text,type:"field",children:[]},o=this.peekScope();o&&o.children.push(s)}enterExploreRenameDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const r={range:this.translator.rangeFromContext(e),name:e.joinFrom().joinNameDef().id().text,type:"join",children:[]},i=this.peekScope();i&&i.children.push(r)}enterImportStatement(e){const r=(0,vdt.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const r=this.peekScope();if(r)for(const i of e.importItem()){const s={range:this.translator.rangeFromContext(e),name:i.text,type:"import_item",children:[]};r.children.push(s)}}}function Sdt(t,e,r){const i=new Cdt(t,e,[],[]),s=i;return _dt.ParseTreeWalker.DEFAULT.walk(s,r),i.symbols}gR.walkForDocumentSymbols=Sdt;var yR={};Object.defineProperty(yR,"__esModule",{value:!0}),yR.walkForDocumentCompletions=void 0;const bdt=T0,Tdt=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],Rdt=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],Ddt=["source","explore","query","sql"];class Odt{constructor(e,r,i){this.tokens=e,this.completions=r,this.position=i}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){const{start:r,end:i}=e,s=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,o=this.position.line<i.line||this.position.line===i.line&&this.position.character<=i.character;return s&&o}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.exploreStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Tdt)this.completions.push({type:"explore_property",text:`${i}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.queryStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Rdt)this.completions.push({type:"query_property",text:`${i}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.malloyStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Ddt)this.completions.push({type:"model_property",text:`${i}: `})}}}function Fdt(t,e,r){const i=new Odt(t,[],r),s=i;return bdt.ParseTreeWalker.DEFAULT.walk(s,e),i.completions}yR.walkForDocumentCompletions=Fdt;var ER={};Object.defineProperty(ER,"__esModule",{value:!0}),ER.walkForDocumentHelpContext=void 0;const wdt=o6;class Ndt extends wdt.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let r=this.defaultResult();if(this.inRange(this.rangeOf(e))){r={type:this.type,token:e.start.text};const i=e.childCount;for(let s=0;s<i;s++){const u=e.getChild(s).accept(this);u&&(r=this.aggregateResult(r,u))}}return r}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,r){return r}}function Ldt(t,e){return new Ndt(e).visit(t)}ER.walkForDocumentHelpContext=Ldt;var qE={};Object.defineProperty(qE,"__esModule",{value:!0}),qE.ReferenceList=void 0;const Idt=zn;class $dt{constructor(e,r=[]){this.sourceURL=e,this.references=r}findIndexBefore(e){let r=0,i=this.references.length;for(;r<i;){const s=Math.floor((r+i)/2),o=this.references[s].location.range.end;o.line<e.line||o.line===e.line&&o.character<e.character?r=s+1:i=s}return r}add(e){if(e.location.url!==this.sourceURL)return;const r=this.findIndexBefore(e.location.range.end);r<this.references.length&&this.isPositionEqual(e,this.references[r])||this.references.splice(r,0,e)}isPositionEqual(e,r){const i=e.location.range,s=r.location.range;return i.start.line===s.start.line&&i.start.character===s.start.character&&i.end.line===s.end.line&&i.end.character===s.end.character}find(e){const r=this.findIndexBefore(e);if(r===this.references.length)return;const i=this.references[r];if((0,Idt.locationContainsPosition)(i.location,e))return i}toArray(){return[...this.references]}}qE.ReferenceList=$dt;var AR={};Object.defineProperty(AR,"__esModule",{value:!0}),AR.isNeedResponse=void 0;function Bdt(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}AR.isNeedResponse=Bdt;var _R={};Object.defineProperty(_R,"__esModule",{value:!0}),_R.walkForModelAnnotation=void 0;const kdt=T0;class Mdt{constructor(e,r,i){this.translator=e,this.tokens=r,this.parseInfo=i,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.translator.rangeFromContext(e)}}enterDocAnnotations(e){const r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}}function Pdt(t,e,r){const i=new Mdt(t,e,r),s=i;return kdt.ParseTreeWalker.DEFAULT.walk(s,r.root),i.annotation}_R.walkForModelAnnotation=Pdt;var vR={};Object.defineProperty(vR,"__esModule",{value:!0}),vR.walkForTablePath=void 0;const Wce=Pn,Udt=T0;class jdt{constructor(e,r){this.translator=e,this.tokens=r,this.pathInfos=[]}enterExploreTable(e){const r=(0,Wce.getId)(e.connectionId()),[i,s]=(0,Wce.getPlainString)(e.tablePath(),!0);i!==void 0&&this.pathInfos.push({connectionId:r,tablePath:i,range:this.translator.rangeFromContext(e)})}}function qdt(t,e,r){const i=new jdt(t,e),s=i;return Udt.ParseTreeWalker.DEFAULT.walk(s,r.root),i.pathInfos}vR.walkForTablePath=qdt;var HE={},CR={},Hdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Qdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hdt(e,t,r);return Qdt(e,t),e};Object.defineProperty(CR,"__esModule",{value:!0}),CR.MalloyLexer=void 0;const Wdt=ph(),Gdt=xl(),Vdt=j1(),Ydt=Ts,Gce=zdt(Cn);class ue extends Gdt.Lexer{get vocabulary(){return ue.VOCABULARY}constructor(e){super(e),this._interp=new Vdt.LexerATNSimulator(ue._ATN,this)}get grammarFileName(){return"MalloyLexer.g4"}get ruleNames(){return ue.ruleNames}get serializedATN(){return ue._serializedATN}get channelNames(){return ue.channelNames}get modeNames(){return ue.modeNames}static get _ATN(){return ue.__ATN||(ue.__ATN=new Wdt.ATNDeserializer().deserialize(Gce.toCharArray(ue._serializedATN))),ue.__ATN}}CR.MalloyLexer=ue,ue.ACCEPT=1,ue.AGGREGATE=2,ue.CALCULATE=3,ue.CALCULATION=4,ue.CONNECTION=5,ue.DECLARE=6,ue.DIMENSION=7,ue.EXCEPT=8,ue.EXTENDQ=9,ue.GROUP_BY=10,ue.HAVING=11,ue.INDEX=12,ue.INTERNAL=13,ue.JOIN_CROSS=14,ue.JOIN_ONE=15,ue.JOIN_MANY=16,ue.LIMIT=17,ue.MEASURE=18,ue.NEST=19,ue.ORDER_BY=20,ue.PARTITION_BY=21,ue.PRIMARY_KEY=22,ue.PRIVATE=23,ue.PROJECT=24,ue.PUBLIC=25,ue.QUERY=26,ue.RENAME=27,ue.RUN=28,ue.SAMPLE=29,ue.SELECT=30,ue.SOURCE=31,ue.TOP=32,ue.WHERE=33,ue.VIEW=34,ue.TIMEZONE=35,ue.ALL=36,ue.AND=37,ue.AS=38,ue.ASC=39,ue.AVG=40,ue.BOOLEAN=41,ue.BY=42,ue.CASE=43,ue.CAST=44,ue.CONDITION=45,ue.COUNT=46,ue.COMPOSE=47,ue.DATE=48,ue.DAY=49,ue.DESC=50,ue.DISTINCT=51,ue.ELSE=52,ue.END=53,ue.EXCLUDE=54,ue.EXTEND=55,ue.FALSE=56,ue.FILTER=57,ue.FULL=58,ue.FOR=59,ue.FROM=60,ue.HAS=61,ue.HOUR=62,ue.IMPORT=63,ue.INCLUDE=64,ue.INNER=65,ue.IS=66,ue.IN=67,ue.INTERNAL_KW=68,ue.JSON=69,ue.LAST=70,ue.LEFT=71,ue.LIKE=72,ue.MAX=73,ue.MIN=74,ue.MINUTE=75,ue.MONTH=76,ue.NOT=77,ue.NOW=78,ue.NULL=79,ue.NUMBER=80,ue.ON=81,ue.OR=82,ue.PICK=83,ue.PRIVATE_KW=84,ue.PUBLIC_KW=85,ue.QUARTER=86,ue.RIGHT=87,ue.SECOND=88,ue.STRING=89,ue.SOURCE_KW=90,ue.SUM=91,ue.SQL=92,ue.TABLE=93,ue.THEN=94,ue.THIS=95,ue.TIMESTAMP=96,ue.TO=97,ue.TRUE=98,ue.TURTLE=99,ue.WEEK=100,ue.WHEN=101,ue.WITH=102,ue.YEAR=103,ue.UNGROUPED=104,ue.HACKY_REGEX=105,ue.RAW_SQ=106,ue.RAW_DQ=107,ue.SQ3_FILTER=108,ue.SQ_FILTER=109,ue.DQ3_FILTER=110,ue.DQ_FILTER=111,ue.BQ3_FILTER=112,ue.BQ_FILTER=113,ue.SQ_STRING=114,ue.DQ_STRING=115,ue.BQ_STRING=116,ue.DOC_ANNOTATION=117,ue.ANNOTATION=118,ue.AMPER=119,ue.ARROW=120,ue.FAT_ARROW=121,ue.OPAREN=122,ue.CPAREN=123,ue.OBRACK=124,ue.CBRACK=125,ue.OCURLY=126,ue.CCURLY=127,ue.DOUBLECOLON=128,ue.TRIPLECOLON=129,ue.EXCLAM=130,ue.COLON=131,ue.COMMA=132,ue.DOT=133,ue.LT=134,ue.GT=135,ue.EQ=136,ue.NE=137,ue.LTE=138,ue.GTE=139,ue.PLUS=140,ue.MINUS=141,ue.STAR=142,ue.STARSTAR=143,ue.SLASH=144,ue.BAR=145,ue.SEMI=146,ue.NOT_MATCH=147,ue.MATCH=148,ue.PERCENT=149,ue.DOUBLE_QMARK=150,ue.QMARK=151,ue.LITERAL_TIMESTAMP=152,ue.LITERAL_HOUR=153,ue.LITERAL_DAY=154,ue.LITERAL_QUARTER=155,ue.LITERAL_MONTH=156,ue.LITERAL_WEEK=157,ue.LITERAL_YEAR=158,ue.IDENTIFIER=159,ue.PERCENT_LITERAL=160,ue.NUMERIC_LITERAL=161,ue.INTEGER_LITERAL=162,ue.BLOCK_COMMENT=163,ue.COMMENT_TO_EOL=164,ue.WHITE_SPACE=165,ue.SQL_BEGIN=166,ue.UNWATED_CHARS_TRAILING_NUMBERS=167,ue.UNEXPECTED_CHAR=168,ue.OPEN_CODE=169,ue.SQL_END=170,ue.SQL_MODE=1,ue.channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"],ue.modeNames=["DEFAULT_MODE","SQL_MODE"],ue.ruleNames=["SPACE_CHAR","ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","SQ","BQ","DQ","SQ3","DQ3","BQ3","RAW_CHAR","RAW3_CHAR","F_PREFIX","S_PREFIX","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","HEX","UNICODE","SAFE_NON_QUOTE","ESCAPED","STR_CHAR","SQ_STRING","DQ_STRING","BQ_STRING","F_TO_EOL","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","F_YEAR","F_DD","F_TZ","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","EXPONENT","NUMERIC_LITERAL","INTEGER_LITERAL","ID_CHAR","DIGIT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","SQL_CHAR","OPEN_CODE","SQL_END"],ue._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`],ue._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FILTER","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],ue.VOCABULARY=new Ydt.VocabularyImpl(ue._LITERAL_NAMES,ue._SYMBOLIC_NAMES,[]),ue._serializedATNSegments=4,ue._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬ފ\b\b \x07 \x07\b \b
|
|
1558
1558
|
|