@malloydata/render 0.0.263-dev250414184158 → 0.0.263-dev250414204152

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.
@@ -124944,40 +124944,46 @@ class fT {
124944
124944
  };
124945
124945
  }
124946
124946
  addDefaultRowLimit(e, r) {
124947
+ const i = { query: e, addedDefaultRowLimit: void 0 };
124947
124948
  if (r === void 0)
124948
- return e;
124949
- const i = e.pipeline[e.pipeline.length - 1];
124950
- return i.type === "raw" || i.limit !== void 0 ? e : {
124951
- ...e,
124952
- pipeline: [
124953
- ...e.pipeline.slice(0, -1),
124954
- {
124955
- ...i,
124956
- limit: r
124957
- }
124958
- ]
124949
+ return i;
124950
+ const s = e.pipeline[e.pipeline.length - 1];
124951
+ return s.type === "raw" || s.limit !== void 0 ? i : {
124952
+ query: {
124953
+ ...e,
124954
+ pipeline: [
124955
+ ...e.pipeline.slice(0, -1),
124956
+ {
124957
+ ...s,
124958
+ limit: r
124959
+ }
124960
+ ]
124961
+ },
124962
+ addedDefaultRowLimit: r
124959
124963
  };
124960
124964
  }
124961
124965
  compileQuery(e, r, i = !0) {
124962
124966
  var s, o;
124963
- e = this.addDefaultRowLimit(e, r == null ? void 0 : r.defaultRowLimit);
124964
- const a = this.loadQuery(e, void 0, r, i, !1), l = (s = e.compositeResolvedSourceDef) !== null && s !== void 0 ? s : e.structRef, c = typeof l == "string" ? l : l.as || l.name;
124965
- return i && this.dialect.hasFinalStage && (a.lastStageName = a.stageWriter.addStage(
124967
+ const u = this.addDefaultRowLimit(e, r == null ? void 0 : r.defaultRowLimit);
124968
+ e = u.query;
124969
+ 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;
124970
+ return i && this.dialect.hasFinalStage && (c.lastStageName = c.stageWriter.addStage(
124966
124971
  // note this will be broken on duckDB waiting on a real fix.
124967
- this.dialect.sqlFinalStage(a.lastStageName, [])
124972
+ this.dialect.sqlFinalStage(c.lastStageName, [])
124968
124973
  )), {
124969
- lastStageName: a.lastStageName,
124970
- malloy: a.malloy,
124971
- sql: a.stageWriter.generateSQLStages(),
124972
- dependenciesToMaterialize: a.stageWriter.dependenciesToMaterialize,
124974
+ lastStageName: c.lastStageName,
124975
+ malloy: c.malloy,
124976
+ sql: c.stageWriter.generateSQLStages(),
124977
+ dependenciesToMaterialize: c.stageWriter.dependenciesToMaterialize,
124973
124978
  materialization: (0, UC.shouldMaterialize)(e.annotation) ? (0, UC.buildQueryMaterializationSpec)((o = e.location) === null || o === void 0 ? void 0 : o.url, e.name, r == null ? void 0 : r.materializedTablePrefix) : void 0,
124974
- structs: a.structs,
124975
- sourceExplore: c,
124979
+ structs: c.structs,
124980
+ sourceExplore: x,
124976
124981
  sourceFilters: e.filterList,
124977
124982
  queryName: e.name,
124978
- connectionName: a.connectionName,
124983
+ connectionName: c.connectionName,
124979
124984
  annotation: e.annotation,
124980
- queryTimezone: a.structs[0].queryTimezone
124985
+ queryTimezone: c.structs[0].queryTimezone,
124986
+ defaultRowLimitAdded: a
124981
124987
  };
124982
124988
  }
124983
124989
  async searchIndex(e, r, i, s = 1e3, o = void 0) {
@@ -152005,6 +152011,11 @@ DE.MALLOY_INTERFACE_TYPES = {
152005
152011
  optional: !1,
152006
152012
  array: !1
152007
152013
  },
152014
+ default_row_limit: {
152015
+ type: "number",
152016
+ optional: !0,
152017
+ array: !1
152018
+ },
152008
152019
  compiler_needs: {
152009
152020
  type: "CompilerNeeds",
152010
152021
  optional: !0,
@@ -152021,6 +152032,11 @@ DE.MALLOY_INTERFACE_TYPES = {
152021
152032
  optional: !0,
152022
152033
  array: !1
152023
152034
  },
152035
+ default_row_limit_added: {
152036
+ type: "number",
152037
+ optional: !0,
152038
+ array: !1
152039
+ },
152024
152040
  logs: {
152025
152041
  type: "LogMessage",
152026
152042
  array: !0,
@@ -152969,6 +152985,11 @@ DE.MALLOY_INTERFACE_TYPES = {
152969
152985
  optional: !1,
152970
152986
  array: !1
152971
152987
  },
152988
+ default_row_limit: {
152989
+ type: "number",
152990
+ optional: !0,
152991
+ array: !1
152992
+ },
152972
152993
  compiler_needs: {
152973
152994
  type: "CompilerNeeds",
152974
152995
  optional: !0,
@@ -152985,6 +153006,11 @@ DE.MALLOY_INTERFACE_TYPES = {
152985
153006
  optional: !0,
152986
153007
  array: !1
152987
153008
  },
153009
+ default_row_limit_added: {
153010
+ type: "number",
153011
+ optional: !0,
153012
+ array: !1
153013
+ },
152988
153014
  logs: {
152989
153015
  type: "LogMessage",
152990
153016
  array: !0,
@@ -154612,7 +154638,10 @@ function Gxe(t) {
154612
154638
  contents: i
154613
154639
  },
154614
154640
  ...(r = s.files) !== null && r !== void 0 ? r : []
154615
- ], y6(o, s, t.model_url);
154641
+ ], {
154642
+ ...y6(o, s, t.model_url),
154643
+ defaultRowLimit: t.default_row_limit
154644
+ };
154616
154645
  }
154617
154646
  Xt.newCompileQueryState = Gxe;
154618
154647
  function Vxe(t) {
@@ -154634,7 +154663,9 @@ function Vxe(t) {
154634
154663
  };
154635
154664
  const u = o.length - 1, a = r.modelDef.queryList[u], l = r.model.anonymous_queries[u].schema, c = (e = r.model.anonymous_queries[u].annotations) !== null && e !== void 0 ? e : [];
154636
154665
  try {
154637
- const x = new kxe.QueryModel(r.modelDef).compileQuery(a), h = (0, Rdt.annotationToTaglines)(r.modelDef.annotation).map((p) => ({
154666
+ const x = new kxe.QueryModel(r.modelDef).compileQuery(a, {
154667
+ defaultRowLimit: t.defaultRowLimit
154668
+ }), h = (0, Rdt.annotationToTaglines)(r.modelDef.annotation).map((p) => ({
154638
154669
  value: p
154639
154670
  }));
154640
154671
  return c.push({
@@ -154649,7 +154680,8 @@ function Vxe(t) {
154649
154680
  annotations: c.length > 0 ? c : void 0,
154650
154681
  model_annotations: h.length > 0 ? h : void 0,
154651
154682
  query_timezone: x.queryTimezone
154652
- }
154683
+ },
154684
+ default_row_limit_added: x.defaultRowLimitAdded
154653
154685
  };
154654
154686
  } catch (f) {
154655
154687
  return {
@@ -1134,7 +1134,7 @@ FROM ${r}
1134
1134
  FROM ${p}
1135
1135
  `),this.resultStage}}class OXe extends cs{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,Be.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 FXe extends cs{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=yae(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 fs&&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 DXe({...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}
1136
1136
  `).join(` UNION ALL
1137
- `)),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 fs extends s${constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new Wl(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}class Wl{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,Be.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,uXe.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,lXe.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Be.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,Be.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,Tn.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,Be.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,Be.getIdentifier)(r);if(r.type==="turtle")this.addFieldToNameMap(i,cs.makeQuery(r,this,void 0,!1));else if((0,Be.isAtomic)(r)||(0,Be.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 AXe({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=fXe((0,Be.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,Be.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlChildReference(e,r){let i=this.getSQLIdentifier();r&&(0,Be.isAtomic)(this.structDef)&&(0,Be.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,Be.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Be.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,Be.getIdentifier)(this.structDef),void 0):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Be.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,Be.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 fs&&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 fs(e,void 0,this,this.prepareResultOptions);case"string":return new mXe(e,this,r);case"date":return new u$(e,this,r);case"timestamp":return new a$(e,this,r);case"number":return new gXe(e,this,r);case"boolean":return new o$(e,this,r);case"json":return new yXe(e,this,r);case"sql native":return new EXe(e,this,r);case"turtle":return cs.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,P4.shouldMaterialize)(this.structDef.query.annotation)?e.addMaterializedQuery((0,Be.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,Be.getIdentifier)(this.structDef)}' type '${this.structDef.type}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Be.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 fs?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 fs)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 fs){const s={...i.fieldDef,annotation:r};return new fs(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(Wp(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 fs)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,Be.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[]),{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}class q4{constructor(e,r){this.eventStream=r,this.dialect=new aXe.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,Be.isSourceDef)(r))i=new Wl(r,void 0,{model:this},{}),this.structs.set((0,Be.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 Wl(o.structDef,r,(s=o.parent)!==null&&s!==void 0?s:{model:this},i):o}return new Wl(e,r,{model:this},i)}loadQuery(e,r,i,s=!1,o=!1){var u;const a="";r||(r=new Gp(!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=cs.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,Be.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){if(r===void 0)return e;const i=e.pipeline[e.pipeline.length-1];return i.type==="raw"||i.limit!==void 0?e:{...e,pipeline:[...e.pipeline.slice(0,-1),{...i,limit:r}]}}compileQuery(e,r,i=!0){var s,o;e=this.addDefaultRowLimit(e,r==null?void 0:r.defaultRowLimit);const a=this.loadQuery(e,void 0,r,i,!1),l=(s=e.compositeResolvedSourceDef)!==null&&s!==void 0?s:e.structRef,c=typeof l=="string"?l:l.as||l.name;return i&&this.dialect.hasFinalStage&&(a.lastStageName=a.stageWriter.addStage(this.dialect.sqlFinalStage(a.lastStageName,[]))),{lastStageName:a.lastStageName,malloy:a.malloy,sql:a.stageWriter.generateSQLStages(),dependenciesToMaterialize:a.stageWriter.dependenciesToMaterialize,materialization:(0,P4.shouldMaterialize)(e.annotation)?(0,P4.buildQueryMaterializationSpec)((o=e.location)===null||o===void 0?void 0:o.url,e.name,r==null?void 0:r.materializedTablePrefix):void 0,structs:a.structs,sourceExplore:c,sourceFilters:e.filterList,queryName:e.name,connectionName:a.connectionName,annotation:e.annotation,queryTimezone:a.structs[0].queryTimezone}}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)yo(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
1137
+ `)),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 fs extends s${constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new Wl(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}class Wl{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,Be.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,uXe.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,lXe.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Be.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,Be.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,Tn.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,Be.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,Be.getIdentifier)(r);if(r.type==="turtle")this.addFieldToNameMap(i,cs.makeQuery(r,this,void 0,!1));else if((0,Be.isAtomic)(r)||(0,Be.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 AXe({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=fXe((0,Be.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,Be.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlChildReference(e,r){let i=this.getSQLIdentifier();r&&(0,Be.isAtomic)(this.structDef)&&(0,Be.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,Be.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Be.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,Be.getIdentifier)(this.structDef),void 0):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Be.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,Be.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 fs&&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 fs(e,void 0,this,this.prepareResultOptions);case"string":return new mXe(e,this,r);case"date":return new u$(e,this,r);case"timestamp":return new a$(e,this,r);case"number":return new gXe(e,this,r);case"boolean":return new o$(e,this,r);case"json":return new yXe(e,this,r);case"sql native":return new EXe(e,this,r);case"turtle":return cs.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,P4.shouldMaterialize)(this.structDef.query.annotation)?e.addMaterializedQuery((0,Be.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,Be.getIdentifier)(this.structDef)}' type '${this.structDef.type}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Be.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 fs?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 fs)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 fs){const s={...i.fieldDef,annotation:r};return new fs(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(Wp(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 fs)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,Be.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[]),{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}class q4{constructor(e,r){this.eventStream=r,this.dialect=new aXe.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,Be.isSourceDef)(r))i=new Wl(r,void 0,{model:this},{}),this.structs.set((0,Be.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 Wl(o.structDef,r,(s=o.parent)!==null&&s!==void 0?s:{model:this},i):o}return new Wl(e,r,{model:this},i)}loadQuery(e,r,i,s=!1,o=!1){var u;const a="";r||(r=new Gp(!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=cs.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,Be.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,P4.shouldMaterialize)(e.annotation)?(0,P4.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)yo(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
1138
1138
  ${c},
1139
1139
  ${f},
1140
1140
  ${x},
@@ -1485,8 +1485,8 @@ ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(LR(S))throw new Error("In o
1485
1485
  `)}}this.stream.write(`
1486
1486
  ]
1487
1487
  `),this.stream.close()}}we.JSONWriter=pxt;class mxt extends tP{constructor(){super(...arguments),this.columnSeparator=",",this.rowSeparator=`
1488
- `,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(e){const r=e.includes(this.quoteCharacter),i=e.includes(this.columnSeparator),s=e.includes(this.rowSeparator),o=i||r||s;return r&&(e=e.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),o&&(e=this.quoteCharacter+e+this.quoteCharacter),e}stringify(e){return e===null?this.emptyCell:e instanceof Date?e.toISOString():typeof e=="boolean"||typeof e=="number"?JSON.stringify(e):`${e}`}getColWeight(e){let r=e;Array.isArray(e)&&(r=e[0]);let i=0;for(const s in r){i=i+1;const o=r[s];if(Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u}}return i}getHeaderRow(e){const r=[];let i=0;for(const s in e){r.push(this.escape(s));const o=e[s];if(i++,Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u;for(let a=0;a<u;a++)r.push(this.emptyCell)}}return{rows:[r.join(this.columnSeparator)],length:1,width:i}}mergeMatrices(e){const r=Math.max(...e.map(o=>o.length)),i=e.reduce((o,u)=>o+u.width,0),s=[];for(let o=0;o<r;o++){const u=[];for(const a of e)if(o<a.length)u.push(a.rows[o]);else{const l=Array(a.width).fill(this.emptyCell);u.push(...l)}s.push(u.join(this.columnSeparator))}return{rows:s,length:r,width:i}}getChildMatrix(e){if(Array.isArray(e)){if(e.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const r=[],i=this.getHeaderRow(e[0]);r.push(...i.rows);const s=i.width;let o=1;for(const u of e){const a=this.getRowMatrix(u);o=o+a.length,r.push(...a.rows)}return{rows:r,length:o,width:s}}getRowMatrix(e){const r=[];for(const i in e){const s=e[i];if(Array.isArray(s)){const o=this.getChildMatrix(s);r.push(o)}else{const o={rows:[this.stringify(s)],length:1,width:1};r.push(o)}}return this.mergeMatrices(r)}async process(e){let r=!1;for await(const i of e){if(!r&&this.includeHeader){const o=this.getHeaderRow(i.toObject());this.stream.write(o.rows[0]),this.stream.write(this.rowSeparator),r=!0}const s=this.getRowMatrix(i.toObject());for(const o of s.rows)this.stream.write(o),this.stream.write(this.rowSeparator)}this.stream.close()}}we.CSVWriter=mxt;class gxt{constructor(e){this.modelCache=e,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(e,r){const i=this.modelDependencies.get(r);if(i===void 0)return;const s=[r,...wR(i)],o={};for(const a of s){const l=this.modelInvalidationKeys.get(a);if(l==null)return;o[a]=l}for(const a of s)if(await nP(e,new URL(a))!==o[a])return;const u=await this.modelCache.getModel(new URL(r));if(u!==void 0){for(const a of s)if(u.invalidationKeys[a]!==o[a])return;return{modelDef:u.modelDef,invalidationKeys:o}}}async setCachedModelDef(e,r){this.modelDependencies.set(e,r.modelDef.dependencies);const i={};for(const o of[e,...wR(r.modelDef.dependencies)]){if(r.invalidationKeys[o]===null)return!1;if(r.invalidationKeys[o]===void 0)throw new Error(`Missing invalidation key for dependency ${o}`);this.modelInvalidationKeys.set(o,r.invalidationKeys[o]),i[o]=r.invalidationKeys[o]}return!!await this.modelCache.setModel(new URL(e),{modelDef:r.modelDef,invalidationKeys:i})}}we.CacheManager=gxt;function wR(t){return[...Object.keys(t),...Object.values(t).map(wR).flat()]}class yxt{constructor(){this.models=new Map}async getModel(e){return Promise.resolve(this.models.get(e.toString()))}async setModel(e,r){return this.models.set(e.toString(),r),Promise.resolve(!0)}}we.InMemoryModelCache=yxt;function vxe(t){return(0,axt.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}async function NR(t,e){const r=await t.readURL(e),{contents:i,invalidationKey:s}=typeof r=="string"?{contents:r,invalidationKey:void 0}:r;return{contents:i,invalidationKey:LR(e.toString())?null:s??vxe(i)}}async function nP(t,e){return LR(e.toString())?null:t.getInvalidationKey!==void 0?await t.getInvalidationKey(e):(await NR(t,e)).invalidationKey}function LR(t){return t.startsWith("internal://")}var IR={};Object.defineProperty(IR,"__esModule",{value:!0}),IR.toAsyncGenerator=void 0;async function*Ext(t){let e=!1;function r(s){let o;const u=new Promise(a=>{o=a});return s(a=>{o({done:!0,isError:!0,error:a})},a=>{o({done:!1,value:a,isError:!1,next:new Promise(l=>{o=l})})},()=>{o({done:!0,isError:!1})}),u}let i=r(t);for(;!e;){const s=await i;if(s.done){if(e=!0,s.isError)throw s.error;break}else i=s.next,yield s.value}}IR.toAsyncGenerator=Ext;var Cxe={},Wc={},rP={},vE={};Object.defineProperty(vE,"__esModule",{value:!0}),vE.MALLOY_INTERFACE_TYPES=void 0,vE.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{field_reference:{type:"Reference",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var BR={},$R={},kR={};Object.defineProperty(kR,"__esModule",{value:!0}),kR.RESERVED_WORDS=void 0,kR.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty($R,"__esModule",{value:!0}),$R.maybeQuoteIdentifier=void 0;const Axt=kR;function _xt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=Axt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function vxt(t){const e=t.split(".");for(let r=0;r<e.length;r++)_xt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}$R.maybeQuoteIdentifier=vxt,Object.defineProperty(BR,"__esModule",{value:!0}),BR.queryToMalloy=void 0;const CE=$R;function Cxt(t,{tabWidth:e}={tabWidth:2}){const r=Dxt(t);return bxt(r,{tabWidth:e})}BR.queryToMalloy=Cxt;const iP=Symbol("indent"),yu=Symbol("newline"),sP=Symbol("outdent"),Sxt=Symbol("optional_newline_indent");function bxt(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===yu)r+=`
1489
- `,s=!0;else if(o===sP)i--;else if(o===iP)i++;else{if(o===Sxt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function MR(t,e,r,i){var s;if(e.includes(yu))return[t,yu,iP,...e,yu,sP,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function Txt(t){return{contents:t,quoteCharacter:'"'}}function Rxt(t){var e,r;switch(t.kind){case"filter_expression_literal":return[Dxe(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=Txt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[bxe(Sxe(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day")];case"timestamp_literal":return[bxe(Sxe(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second")]}}function Sxe(t){return new Date(t)}function yn(t,e){return t.toString().padStart(e,"0")}function bxe(t,e){switch(e){case"year":return`@${yn(t.getUTCFullYear(),4)}`;case"quarter":{const r=yn(t.getUTCFullYear(),4),i=Math.floor(t.getUTCMonth()/3)+1;return`@${r}-Q${i}`}case"month":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2);return`@${r}-${i}`}case"week":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@WK${r}-${i}-${s}`}case"day":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@${r}-${i}-${s}`}case"hour":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2);return`@${r}-${i}-${s} ${o}`}case"minute":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2);return`@${r}-${i}-${s} ${o}:${u}`}case"second":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2),a=yn(t.getUTCSeconds(),2);return`@${r}-${i}-${s} ${o}:${u}:${a}`}default:throw new Error("Unknown timeframe.")}}function Vc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,CE.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,CE.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,CE.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Rxt(o.value)),s<t.parameters.length-1&&i.push(",",yu)}r.push(...MR("(",i,")",{spaces:!1}))}return r}function Dxt(t){const e=[];return e.push(...I2(t.annotations)),e.push("run: "),e.push(...oP(t.definition)),e}function Oxt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Vc(t));break}case"refinement":e.push(...oP(t));break}return e}function oP(t){const e=[];switch(t.kind){case"arrow":{e.push(...Oxt(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"query_reference":{e.push(...Vc(t));break}case"refinement":{const r=oP(t.base);t.base.kind==="arrow"?e.push(...MR("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...xd(t.refinement));break}}return e}function xd(t){const e=[];switch(t.kind){case"arrow":{e.push(...xd(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"view_reference":{e.push(...Vc(t));break}case"refinement":{e.push(...xd(t.base)),e.push(" + "),e.push(...xd(t.refinement));break}case"segment":{e.push(...Fxt(t));break}}return e}function Fxt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...wxt(o)),e&&i<t.operations.length-1&&r.push(yu)}return MR("{",r,"}")}function wxt(t){switch(t[0].kind){case"aggregate":return Bxt(t);case"group_by":return Ixt(t);case"order_by":return $xt(t);case"nest":return Mxt(t);case"limit":return qxt(t);case"where":return Rxe(t);case"having":return Hxt(t)}}function L2(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(yu));s?i.push(yu,iP):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(yu)}return s&&i.push(sP),i}function Nxt(t){const e=[];return e.push(...Lxt(t.expression)),e}function mht(t){return t}function Lxt(t){switch(t.kind){case"field_reference":return Vc(t);case"time_truncation":return[...Vc(t.field_reference),".",t.truncation];case"filtered_field":return[...Vc(t.field_reference),...MR(" {",Rxe(t.where),"}")]}}function Txe(t,e=!1){const r=[];return e||r.push(...I2(t.field.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Nxt(t.field)),r}function Ixt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("group_by",t.map(i=>Txe(i,r)))),e}function Bxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("aggregate",t.map(i=>Txe(i,r)))),e}function $xt(t){return L2("order_by",t.map(kxt),",")}function kxt(t){const e=[];return e.push(...Vc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function Mxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].view.annotations)),e.push(...L2("nest",t.map(i=>Pxt(i,r)))),e}function Pxt(t,e=!1){const r=[];return e||r.push(...I2(t.view.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Uxt(t.view)),r}function Uxt(t){return xd(t.definition)}function jxt(t){return[`limit: ${t.limit}`]}function qxt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(yu),e.push(...jxt(t[r]));return e}function Rxe(t){return L2("where",t.map(Oxe),",")}function Hxt(t){return L2("having",t.map(Oxe),",")}const Qxt=["`","'",'"'];function Dxe(t){let e,r;for(const i of Qxt){const s=zxt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function zxt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function Oxe(t){switch(t.filter.kind){case"filter_string":return[...Vc(t.filter.field_reference)," ~ ",Dxe(t.filter.filter)]}}function I2(t){return t?t.flatMap(Gxt):[]}function Gxt(t){return[t.value.trim(),yu]}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.convertToThrift=Ma.convertFromThrift=Ma.unnestUnions=Ma.nestUnions=void 0;const Wxt=vE;function uP(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(uP);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=uP(t[i]);return r===void 0?e:{[r]:e}}}Ma.nestUnions=uP;function PR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>PR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=PR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=PR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}Ma.unnestUnions=PR;function UR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=B2(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>UR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=UR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=UR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}Ma.convertFromThrift=UR;function B2(t){const e=Wxt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function jR(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=B2(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>jR(r,e));{const r=B2(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=B2(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=jR(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=jR(t[s],o.type)}return i}}}}Ma.convertToThrift=jR,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.queryToMalloy=void 0,r(vE,t);var i=BR;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}});var s=Ma;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",field_reference:{name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(rP);var nn={},Vxt=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]}),Yxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kxt=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)&&Vxt(e,t,r);return Yxt(e,t),e};Object.defineProperty(nn,"__esModule",{value:!0}),nn.statedCompileQuery=nn.newCompileQueryState=nn.hasErrors=nn.compileSource=nn.compileModel=nn._statedCompileModel=nn.statedCompileSource=nn.statedCompileModel=nn.newCompileSourceState=nn.newCompileModelState=nn.updateCompileModelState=nn.compileQuery=void 0;const Jxt=Kxt(rP),Xxt=H4,Fxe=Pi,Zxt=La,wxe=Yl,edt=ui,Nxe=Zo,dd=mE;function Lxe(t,e){return`${t}:${e}`}function tdt(t,e){return{type:"sql_select",selectStr:t.sql,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:(0,wxe.sqlKey)(t.connection_name,t.sql)}}function ndt(t,e){return{type:"table",tablePath:t.name,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:Lxe(t.connection_name,t.name)}}function rdt(t){if(t!==void 0)return t==="decimal"?"float":"integer"}function Ixe(t){switch(t.kind){case"string_type":return{type:"string"};case"number_type":return{type:"number",numberType:rdt(t.subtype)};case"boolean_type":return{type:"boolean"};case"timestamp_type":return{type:"timestamp",timeframe:t.timeframe};case"date_type":return{type:"date",timeframe:t.timeframe};case"sql_native_type":return{type:"sql native",rawType:t.sql_type};case"json_type":return{type:"json"};case"array_type":{if(t.element_type.kind==="record_type")return{type:"array",elementTypeDef:{type:"record_element"},fields:t.element_type.fields.map(aP)};{const e=Ixe(t.element_type);if(e.type==="record")throw new Error("Arrays of records should be a repeated record type");return{type:"array",elementTypeDef:e}}}case"record_type":return{type:"record",fields:t.fields.map(aP)}}}function aP(t){var e;const r=Ixe(t.type);return{...(0,Fxe.mkFieldDef)(r,t.name),annotation:t.annotations&&t.annotations.length?{notes:(e=t.annotations)===null||e===void 0?void 0:e.map(i=>({text:i.value,at:{url:"~internal~",range:dd.DEFAULT_LOG_RANGE}}))}:void 0}}function idt(t){if(t.kind!=="dimension")throw new Error("Table schemas must only have dimension fields");return aP(t)}function Bxe(t){const e=[];for(const r of t.fields)e.push(idt(r));return e}function $xe(t){var e,r,i,s,o,u;const a={urls:{},tables:{},compileSQL:{},translations:{}};if(t){for(const l of(e=t.files)!==null&&e!==void 0?e:[])l.contents!==void 0&&(a.urls[l.url]=l.contents);for(const l of(r=t.table_schemas)!==null&&r!==void 0?r:[]){const c=(i=t.connections)===null||i===void 0?void 0:i.find(f=>f.name===l.connection_name);c&&l.schema&&c.dialect&&(a.tables[Lxe(l.connection_name,l.name)]=ndt(l,c.dialect))}for(const l of(s=t.sql_schemas)!==null&&s!==void 0?s:[]){const c=(o=t.connections)===null||o===void 0?void 0:o.find(f=>f.name===l.connection_name);c&&c.dialect&&(a.compileSQL[(0,wxe.sqlKey)(l.connection_name,l.sql)]=tdt(l,c.dialect))}for(const l of(u=t.translations)!==null&&u!==void 0?u:[])if(l.compiled_model_json){const c=JSON.parse(l.compiled_model_json);a.translations[l.url]=c}}return a}function kxe(t,e,r){var i,s,o;const u={},a=new Set;if(t!==void 0&&(u.sql_schemas=[{sql:t.selectStr,connection_name:t.connection}],a.add(t.connection)),e!==void 0)for(const l of e)(i=u.files)!==null&&i!==void 0||(u.files=[]),u.files.push({url:l});if(r!==void 0)for(const l in r){const c=r[l],f=(s=c.connectionName)!==null&&s!==void 0?s:"__default__";(o=u.table_schemas)!==null&&o!==void 0||(u.table_schemas=[]),u.table_schemas.push({name:c.tablePath,connection_name:f}),a.add(f)}return a.size>0&&(u.connections=Array.from(a).map(l=>({name:l}))),u}function sdt(t,e){return e??(e=qxe(t)),Hxe(e)}nn.compileQuery=sdt;function odt(t,e){function r(s,o){var u,a,l,c;s.translator.update(o),s.extending&&r(s.extending,o),s.hasSource||(s.hasSource=((a=(u=e==null?void 0:e.files)===null||u===void 0?void 0:u.some(f=>f.url===s.translator.sourceURL))!==null&&a!==void 0?a:!1)||((c=(l=e==null?void 0:e.translations)===null||l===void 0?void 0:l.some(f=>f.url===s.translator.sourceURL))!==null&&c!==void 0?c:!1))}const i=$xe(e);r(t,i)}nn.updateCompileModelState=odt;function qR(t,e,r){var i,s,o,u;const a=new Xxt.MalloyTranslator(t,null,$xe(e)),l=((s=(i=e==null?void 0:e.files)===null||i===void 0?void 0:i.some(c=>c.url===t))!==null&&s!==void 0?s:!1)||((u=(o=e==null?void 0:e.translations)===null||o===void 0?void 0:o.some(c=>c.url===t))!==null&&u!==void 0?u:!1);return r?{extending:qR(r,e),translator:a,done:!1,hasSource:l}:{translator:a,done:!1,hasSource:l}}function Mxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileModelState=Mxe;function Pxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileSourceState=Pxe;function Uxe(t){return udt(SE(t),t.translator.sourceURL)}nn.statedCompileModel=Uxe;function jxe(t,e){return cdt(SE(t),e,t.translator.sourceURL)}nn.statedCompileSource=jxe;function SE(t){let e;if(t.extending){if(!t.extending.done){const i=SE(t.extending);if(!t.extending.done)return i}e=t.extending.translator.modelDef}if(!t.hasSource)return{compilerNeeds:kxe(void 0,[t.translator.sourceURL],void 0)};const r=t.translator.translate(e);if(r.final){if(t.done=!0,r.modelDef)return{model:(0,Zxt.modelDefToModelInfo)(r.modelDef),modelDef:r.modelDef};if(r.problems===void 0||r.problems.length===0)throw new Error("No problems found, but no model either");return{logs:r.problems}}else return{compilerNeeds:kxe(r.compileSQL,r.urls,r.tables),logs:r.problems}}nn._statedCompileModel=SE;function udt(t,e){const r=t.logs?(0,dd.mapLogs)(t.logs,e):void 0;if(t.compilerNeeds)return{compiler_needs:t.compilerNeeds,logs:r};{let i;return t.modelDef&&(i=[{url:e,compiled_model_json:JSON.stringify(t.modelDef)}]),{model:t.model,logs:r,translations:i}}}function adt(t,e){return e??(e=Mxe(t)),Uxe(e)}nn.compileModel=adt;function ldt(t){const e=Pxe(t);return jxe(e,t.name)}nn.compileSource=ldt;function cdt(t,e,r){const i=t.logs?(0,dd.mapLogs)(t.logs,r):void 0;if(t.model){const s=t.model.entries.find(o=>o.name===e);return s===void 0?{logs:[...i??[],{url:r,severity:"error",message:`Model does not contain a source named ${e}`,range:dd.DEFAULT_LOG_RANGE}]}:{source:s,logs:i}}else return{compiler_needs:t.compilerNeeds,logs:i}}function fdt(t){var e;return(e=t==null?void 0:t.some(r=>r.severity==="error"))!==null&&e!==void 0?e:!1}nn.hasErrors=fdt;function qxe(t){var e,r;const i=Jxt.queryToMalloy(t.query),s={...(e=t.compiler_needs)!==null&&e!==void 0?e:{}},o="internal://query.malloy";return s.files=[{url:o,contents:i},...(r=s.files)!==null&&r!==void 0?r:[]],qR(o,s,t.model_url)}nn.newCompileQueryState=qxe;function Hxe(t){var e;const r=SE(t),i=t.translator.sourceURL,s=r.logs?(0,dd.mapLogs)(r.logs,i):void 0;if(r.model){const o=r.modelDef.queryList;if(o.length===0)return{logs:[...s??[],{url:i,severity:"error",message:"Internal error: No queries found",range:dd.DEFAULT_LOG_RANGE}]};const u=o.length-1,a=r.modelDef.queryList[u],l=r.model.anonymous_queries[u].schema,c=(e=r.model.anonymous_queries[u].annotations)!==null&&e!==void 0?e:[];try{const x=new Fxe.QueryModel(r.modelDef).compileQuery(a),h=(0,edt.annotationToTaglines)(r.modelDef.annotation).map(p=>({value:p}));return c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore).toString()}),x.queryName&&c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["query_name"],x.queryName).toString()}),{result:{sql:x.sql,schema:l,connection_name:x.connectionName,annotations:c.length>0?c:void 0,model_annotations:h.length>0?h:void 0,query_timezone:x.queryTimezone}}}catch(f){return{logs:[...s??[],{url:i,severity:"error",message:`Internal compiler error: ${f.message}`,range:dd.DEFAULT_LOG_RANGE}]}}}else return{compiler_needs:r.compilerNeeds,logs:s}}nn.statedCompileQuery=Hxe;var xdt=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]}),ddt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qxe=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)&&xdt(e,t,r);return ddt(e,t),e};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.compileQuery=Wc.compileSource=Wc.compileModel=void 0;const hdt=Qxe(rP),Pa=Qxe(nn),pdt=Pp;function mdt(t,e){return t.type==="compile_model"?e.type!=="compile_model"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL:t.type==="compile_source"?e.type!=="compile_source"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL&&t.name===e.name:e.type!=="compile_query"?!1:t.modelURL===e.modelURL&&t.queryString===e.queryString}class gdt{constructor(){this.sessions=new Map}purgeExpired(e){const r=new Date;for(const i of this.sessions.values())i.sessionId!==(e==null?void 0:e.except)&&i.expires&&i.expires<r&&this.sessions.delete(i.sessionId)}findSession(e,r){const i=this.sessions.get(e);if(i&&mdt(i.sessionInfo,r))return i}getExpires(e){return e instanceof Date?e:new Date(Date.now()+e.seconds*1e3)}newSessionId(){let e;do e=(0,pdt.v4)();while(this.sessions.has(e));return e}newCompileModelSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileModelState(e);return{type:"compile_model",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileSourceSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileSourceState(e);return{type:"compile_source",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileQuerySession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileQueryState(e);return{type:"compile_query",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}findCompileModelSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_model")return i}killSession(e){this.sessions.delete(e)}hasErrors(e){return Pa.hasErrors(e)}compileModel(e,r){const i={type:"compile_model",modelURL:e.model_url,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileModelSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileModelSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileModel(s.state);return(o.model||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileSourceSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_source")return i}compileSource(e,r){const i={type:"compile_source",modelURL:e.model_url,name:e.name,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileSourceSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileSourceSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileSource(s.state,e.name);return(o.source||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileQuerySession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_query")return i}compileQuery(e,r){const i=hdt.queryToMalloy(e.query),s={type:"compile_query",modelURL:e.model_url,queryString:i,query:e.query};let o=(r==null?void 0:r.session_id)&&this.findCompileQuerySession(r.session_id,s);this.purgeExpired({except:r==null?void 0:r.session_id}),o?(r!=null&&r.ttl&&(o.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(o.state,e.compiler_needs)):(o=this.newCompileQuerySession(e,s,r),this.sessions.set(o.sessionId,o));const u=Pa.statedCompileQuery(o.state);return(u.result||this.hasErrors(u.logs))&&this.killSession(o.sessionId),{...u,session_id:o.sessionId}}}const lP=new gdt;function ydt(t,e){return lP.compileModel(t,e)}Wc.compileModel=ydt;function Edt(t,e){return lP.compileSource(t,e)}Wc.compileSource=Edt;function Adt(t,e){return lP.compileQuery(t,e)}Wc.compileQuery=Adt;var Yc={},_dt=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]}),vdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cdt=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)&&_dt(e,t,r);return vdt(e,t),e};Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.compileQuery=Yc.compileSource=Yc.compileModel=void 0;const cP=Cdt(nn);function Sdt(t){return cP.compileModel(t)}Yc.compileModel=Sdt;function bdt(t){return cP.compileSource(t)}Yc.compileSource=bdt;function Tdt(t){return cP.compileQuery(t)}Yc.compileQuery=Tdt;var Ua={},Rdt=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]}),Ddt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Odt=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)&&Rdt(e,t,r);return Ddt(e,t),e};Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.runQuery=Ua.compileQuery=Ua.compileSource=Ua.compileModel=void 0;const vo=Odt(nn),zxe=mE;async function fP(t,e){var r,i,s,o,u,a,l,c,f;if(t===void 0)throw new Error("Expected compiler to have needs because it didn't return a result");const x={};if(t.connections)for(const h of t.connections){const p=await e.connections.lookupConnection(h.name);(r=x.connections)!==null&&r!==void 0||(x.connections=[]),x.connections.push({...h,dialect:p.dialectName})}if(t.files)for(const h of t.files){const p=await e.urls.readURL(new URL(h.url));(i=x.files)!==null&&i!==void 0||(x.files=[]),typeof p=="string"?x.files.push({...h,contents:p}):x.files.push({...h,contents:p.contents,invalidation_key:(s=p.invalidationKey)===null||s===void 0?void 0:s.toString()})}if(t.table_schemas){const h={};for(const p of t.table_schemas)(o=h[c=p.connection_name])!==null&&o!==void 0||(h[c]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.name),y=await Promise.all(g.map(async E=>({name:E,schema:await m.fetchSchemaForTable(E)})));(u=x.table_schemas)!==null&&u!==void 0||(x.table_schemas=[]);for(const E of y)x.table_schemas.push({connection_name:p,name:E.name,schema:E.schema})}}if(t.sql_schemas){const h={};for(const p of t.sql_schemas)(a=h[f=p.connection_name])!==null&&a!==void 0||(h[f]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.sql),y=await Promise.all(g.map(async E=>({sql:E,schema:await m.fetchSchemaForSQLQuery(E)})));(l=x.sql_schemas)!==null&&l!==void 0||(x.sql_schemas=[]);for(const E of y)x.sql_schemas.push({connection_name:p,sql:E.sql,schema:E.schema})}}return x}async function Fdt(t,e){const r=vo.newCompileModelState(t);for(;;){const i=vo.statedCompileModel(r);if(i.model||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileModel=Fdt;async function wdt(t,e){const r=vo.newCompileSourceState(t);for(;;){const i=vo.statedCompileSource(r,t.name);if(i.source||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileSource=wdt;async function Gxe(t,e){const r=vo.newCompileQueryState(t);for(;;){const i=vo.statedCompileQuery(r);if(i.result||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileQuery=Gxe;async function Ndt(t,e){var r,i;const s=await Gxe(t,e);if(s.result===void 0)return s;const o=t.model_url;if(s.result.sql===void 0)return{logs:[...(r=s.logs)!==null&&r!==void 0?r:[],{url:o,severity:"error",message:"Internal error: Compiler did not generate SQL",range:zxe.DEFAULT_LOG_RANGE}]};try{const a=await(await e.connections.lookupConnection(s.result.connection_name)).runSQL(s.result.sql,s.result.schema);return{...s,result:{...s.result,data:a}}}catch(u){return{...s,logs:[...(i=s.logs)!==null&&i!==void 0?i:[],{url:o,severity:"error",message:`Error running SQL: ${u.message}`,range:zxe.DEFAULT_LOG_RANGE}]}}}Ua.runQuery=Ndt;var Wxe={};Object.defineProperty(Wxe,"__esModule",{value:!0}),function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u},s=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.util=t.asynchronous=t.stateless=t.sessioned=void 0,t.sessioned=i(Wc),t.stateless=i(Yc),t.asynchronous=i(Ua),s(Wxe,t),t.util=i(mE)}(Cxe),function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,g,y)}:function(h,p,m,g){g===void 0&&(g=m),h[g]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p};Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyURLReader=t.SingleConnectionRuntime=t.ConnectionRuntime=t.AtomicFieldType=t.Runtime=t.Malloy=t.Model=t.MalloyTranslator=t.malloyToQuery=t.composeSQLExpr=t.indent=t.expressionIsUngroupedAggregate=t.expressionIsScalar=t.expressionIsCalculation=t.expressionIsAnalytic=t.expressionIsAggregate=t.mkFieldDef=t.mkArrayDef=t.isBasicArray=t.isRepeatedRecord=t.isSamplingRows=t.isSamplingPercent=t.isSamplingEnable=t.isJoinedSource=t.isJoined=t.isBasicAtomic=t.Segment=t.isSourceDef=t.TinyParser=t.Dialect=t.spread=t.literal=t.variadicParam=t.param=t.makeParam=t.sql=t.maxScalar=t.minAggregate=t.anyExprType=t.minScalar=t.overload=t.qtz=t.arg=t.registerDialect=t.MySQLDialect=t.SnowflakeDialect=t.PostgresDialect=t.TrinoDialect=t.StandardSQLDialect=t.DuckDBDialect=void 0,t.annotationToTaglines=t.annotationToTag=t.sqlKey=t.API=t.modelDefToModelInfo=t.toAsyncGenerator=t.CacheManager=t.InMemoryModelCache=t.Explore=t.DataWriter=t.Parse=t.JSONWriter=t.CSVWriter=t.QueryMaterializer=t.Result=t.PreparedResult=t.TimestampTimeframe=t.DateTimeframe=t.SourceRelationship=t.JoinRelationship=t.MalloyError=t.FixedConnectionMap=t.InMemoryURLReader=void 0;var s=kp;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}}),Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return s.StandardSQLDialect}}),Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return s.TrinoDialect}}),Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}}),Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return s.SnowflakeDialect}}),Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return s.MySQLDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return s.registerDialect}}),Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return s.arg}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return s.qtz}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return s.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return s.minScalar}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return s.anyExprType}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return s.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return s.maxScalar}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return s.sql}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return s.makeParam}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return s.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return s.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return s.literal}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return s.spread}}),Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return s.Dialect}}),Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return s.TinyParser}});var o=Pi;Object.defineProperty(t,"isSourceDef",{enumerable:!0,get:function(){return o.isSourceDef}}),Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return o.Segment}}),Object.defineProperty(t,"isBasicAtomic",{enumerable:!0,get:function(){return o.isBasicAtomic}}),Object.defineProperty(t,"isJoined",{enumerable:!0,get:function(){return o.isJoined}}),Object.defineProperty(t,"isJoinedSource",{enumerable:!0,get:function(){return o.isJoinedSource}}),Object.defineProperty(t,"isSamplingEnable",{enumerable:!0,get:function(){return o.isSamplingEnable}}),Object.defineProperty(t,"isSamplingPercent",{enumerable:!0,get:function(){return o.isSamplingPercent}}),Object.defineProperty(t,"isSamplingRows",{enumerable:!0,get:function(){return o.isSamplingRows}}),Object.defineProperty(t,"isRepeatedRecord",{enumerable:!0,get:function(){return o.isRepeatedRecord}}),Object.defineProperty(t,"isBasicArray",{enumerable:!0,get:function(){return o.isBasicArray}}),Object.defineProperty(t,"mkArrayDef",{enumerable:!0,get:function(){return o.mkArrayDef}}),Object.defineProperty(t,"mkFieldDef",{enumerable:!0,get:function(){return o.mkFieldDef}}),Object.defineProperty(t,"expressionIsAggregate",{enumerable:!0,get:function(){return o.expressionIsAggregate}}),Object.defineProperty(t,"expressionIsAnalytic",{enumerable:!0,get:function(){return o.expressionIsAnalytic}}),Object.defineProperty(t,"expressionIsCalculation",{enumerable:!0,get:function(){return o.expressionIsCalculation}}),Object.defineProperty(t,"expressionIsScalar",{enumerable:!0,get:function(){return o.expressionIsScalar}}),Object.defineProperty(t,"expressionIsUngroupedAggregate",{enumerable:!0,get:function(){return o.expressionIsUngroupedAggregate}}),Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return o.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return o.composeSQLExpr}});var u=H4;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return u.malloyToQuery}}),Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return u.MalloyTranslator}});var a=we;Object.defineProperty(t,"Model",{enumerable:!0,get:function(){return a.Model}}),Object.defineProperty(t,"Malloy",{enumerable:!0,get:function(){return a.Malloy}}),Object.defineProperty(t,"Runtime",{enumerable:!0,get:function(){return a.Runtime}}),Object.defineProperty(t,"AtomicFieldType",{enumerable:!0,get:function(){return a.AtomicFieldType}}),Object.defineProperty(t,"ConnectionRuntime",{enumerable:!0,get:function(){return a.ConnectionRuntime}}),Object.defineProperty(t,"SingleConnectionRuntime",{enumerable:!0,get:function(){return a.SingleConnectionRuntime}}),Object.defineProperty(t,"EmptyURLReader",{enumerable:!0,get:function(){return a.EmptyURLReader}}),Object.defineProperty(t,"InMemoryURLReader",{enumerable:!0,get:function(){return a.InMemoryURLReader}}),Object.defineProperty(t,"FixedConnectionMap",{enumerable:!0,get:function(){return a.FixedConnectionMap}}),Object.defineProperty(t,"MalloyError",{enumerable:!0,get:function(){return a.MalloyError}}),Object.defineProperty(t,"JoinRelationship",{enumerable:!0,get:function(){return a.JoinRelationship}}),Object.defineProperty(t,"SourceRelationship",{enumerable:!0,get:function(){return a.SourceRelationship}}),Object.defineProperty(t,"DateTimeframe",{enumerable:!0,get:function(){return a.DateTimeframe}}),Object.defineProperty(t,"TimestampTimeframe",{enumerable:!0,get:function(){return a.TimestampTimeframe}}),Object.defineProperty(t,"PreparedResult",{enumerable:!0,get:function(){return a.PreparedResult}}),Object.defineProperty(t,"Result",{enumerable:!0,get:function(){return a.Result}}),Object.defineProperty(t,"QueryMaterializer",{enumerable:!0,get:function(){return a.QueryMaterializer}}),Object.defineProperty(t,"CSVWriter",{enumerable:!0,get:function(){return a.CSVWriter}}),Object.defineProperty(t,"JSONWriter",{enumerable:!0,get:function(){return a.JSONWriter}}),Object.defineProperty(t,"Parse",{enumerable:!0,get:function(){return a.Parse}}),Object.defineProperty(t,"DataWriter",{enumerable:!0,get:function(){return a.DataWriter}}),Object.defineProperty(t,"Explore",{enumerable:!0,get:function(){return a.Explore}}),Object.defineProperty(t,"InMemoryModelCache",{enumerable:!0,get:function(){return a.InMemoryModelCache}}),Object.defineProperty(t,"CacheManager",{enumerable:!0,get:function(){return a.CacheManager}});var l=IR;Object.defineProperty(t,"toAsyncGenerator",{enumerable:!0,get:function(){return l.toAsyncGenerator}});var c=La;Object.defineProperty(t,"modelDefToModelInfo",{enumerable:!0,get:function(){return c.modelDefToModelInfo}}),t.API=i(Cxe);var f=Yl;Object.defineProperty(t,"sqlKey",{enumerable:!0,get:function(){return f.sqlKey}});var x=ui;Object.defineProperty(t,"annotationToTag",{enumerable:!0,get:function(){return x.annotationToTag}}),Object.defineProperty(t,"annotationToTaglines",{enumerable:!0,get:function(){return x.annotationToTaglines}})}(vB);class Ldt{constructor(e){this.document=e}async render(e,r){var l;let i;if(e&&(e instanceof vB.Result||"modelDef"in e)?i=vB.API.util.wrapResult(e):i=e,!r4(i.model_annotations,"## ").has("renderer_legacy"))if(!!((l=this.document.defaultView)!=null&&l.customElements.get("malloy-render"))){const f=this.document.createElement("malloy-render");f.malloyResult=i;const x=r.nextRendererOptions??{};for(const[h,p]of Object.entries(x))f[h]=p;return f}else console.warn("Tried to use the new Malloy renderer, but the malloy-render component was not found. Falling back to the legacy renderer.");const u=xue(i),a=Yxe(u.field,this.document,r,{size:"large"},u.field.queryTimezone,u.field.tag);try{return await a.render(u)}catch(c){return c instanceof Error?Gs(this.document,c):Gs(this.document,"Internal error - Exception not an Error object.")}}}class Idt{constructor(e){this.document=e}async render(e){const r=new mP(this.document);try{return await r.render(e)}catch(i){return i instanceof Error?Gs(this.document,i):Gs(this.document,"Internal error - Exception not an Error object.")}}}const Vxe={shape_map:"shape_map",point_map:"point_map",bar_chart:"bar_chart",image:"image",json:"json",segment_map:"segment_map",dashboard:"dashboard",line_chart:"line_chart",scatter_chart:"scatter_chart",url:"url",list:"list",list_detail:"list_detail",sparkline:"sparkline",sparkline_area:"sparkline",sparkline_column:"sparkline",sparkline_bar:"sparkline"};function Bdt(t,e){const r=e[t.name],{name:i}=t;for(const s in Vxe)if(i.endsWith(`_${s}`)){const o=i.slice(0,i.length-s.length-1);return $dt(s,o,Vxe,r)}return r}function $dt(t,e,r,i){var s;return i?(i.renderer??(i.renderer=r[t]),i.data??(i.data={}),(s=i.data).label??(s.label=e)):i={renderer:r[t],data:{label:e}},i}function HR(t){if(t.isRecordOrRepeatedRecord())return t;throw new Error(`${t.name} does not contain fields and cannot be rendered this way`)}function Yxe(t,e,r,i,s,o){const u=Bdt(t,r.dataStyles);r.dataStyles[t.name]=u;const a=new jL().create(u,o,e,i,r,t,s);if(a)return a;if((u==null?void 0:u.renderer)==="dashboard"||o.has("dashboard"))return QR(AB,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list"||o.has("list"))return QR(Eue,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list_detail"||o.has("list_detail"))return QR(mYe,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="table"||o.has("table")||t.isRecordOrRepeatedRecord())return QR(Z2,e,HR(t),r,o);throw new Error(`Could not find a proper renderer for field ${t.name}`)}function QR(t,e,r,i,s){const o=wE.make(t,e,r,i,s),u={};return r.fields.forEach(a=>{u[a.name]=Yxe(a,e,i,o.defaultStylesForChildren,a.root().queryTimezone,a.tag)}),o.childRenderers=u,o}async function kdt(t){const e=await Kxe(t);try{await navigator.clipboard.writeText(e)}catch(r){console.error("Failed to copy text: ",r)}}async function Kxe(t){let e="";const r=t.tableConfig??{},i=Object.assign({disableVirtualization:!0},r);t.tableConfig=i;const s=t.dashboardConfig??{},o=Object.assign({disableVirtualization:!0},s);if(t.dashboardConfig=o,await Mdt(1e3),t.shadowRoot){let u="";for(const a of[...t.shadowRoot.adoptedStyleSheets]){for(let c=0;c<a.cssRules.length;c++){const f=a.cssRules.item(c);f&&(u+=`
1488
+ `,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(e){const r=e.includes(this.quoteCharacter),i=e.includes(this.columnSeparator),s=e.includes(this.rowSeparator),o=i||r||s;return r&&(e=e.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),o&&(e=this.quoteCharacter+e+this.quoteCharacter),e}stringify(e){return e===null?this.emptyCell:e instanceof Date?e.toISOString():typeof e=="boolean"||typeof e=="number"?JSON.stringify(e):`${e}`}getColWeight(e){let r=e;Array.isArray(e)&&(r=e[0]);let i=0;for(const s in r){i=i+1;const o=r[s];if(Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u}}return i}getHeaderRow(e){const r=[];let i=0;for(const s in e){r.push(this.escape(s));const o=e[s];if(i++,Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u;for(let a=0;a<u;a++)r.push(this.emptyCell)}}return{rows:[r.join(this.columnSeparator)],length:1,width:i}}mergeMatrices(e){const r=Math.max(...e.map(o=>o.length)),i=e.reduce((o,u)=>o+u.width,0),s=[];for(let o=0;o<r;o++){const u=[];for(const a of e)if(o<a.length)u.push(a.rows[o]);else{const l=Array(a.width).fill(this.emptyCell);u.push(...l)}s.push(u.join(this.columnSeparator))}return{rows:s,length:r,width:i}}getChildMatrix(e){if(Array.isArray(e)){if(e.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const r=[],i=this.getHeaderRow(e[0]);r.push(...i.rows);const s=i.width;let o=1;for(const u of e){const a=this.getRowMatrix(u);o=o+a.length,r.push(...a.rows)}return{rows:r,length:o,width:s}}getRowMatrix(e){const r=[];for(const i in e){const s=e[i];if(Array.isArray(s)){const o=this.getChildMatrix(s);r.push(o)}else{const o={rows:[this.stringify(s)],length:1,width:1};r.push(o)}}return this.mergeMatrices(r)}async process(e){let r=!1;for await(const i of e){if(!r&&this.includeHeader){const o=this.getHeaderRow(i.toObject());this.stream.write(o.rows[0]),this.stream.write(this.rowSeparator),r=!0}const s=this.getRowMatrix(i.toObject());for(const o of s.rows)this.stream.write(o),this.stream.write(this.rowSeparator)}this.stream.close()}}we.CSVWriter=mxt;class gxt{constructor(e){this.modelCache=e,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(e,r){const i=this.modelDependencies.get(r);if(i===void 0)return;const s=[r,...wR(i)],o={};for(const a of s){const l=this.modelInvalidationKeys.get(a);if(l==null)return;o[a]=l}for(const a of s)if(await nP(e,new URL(a))!==o[a])return;const u=await this.modelCache.getModel(new URL(r));if(u!==void 0){for(const a of s)if(u.invalidationKeys[a]!==o[a])return;return{modelDef:u.modelDef,invalidationKeys:o}}}async setCachedModelDef(e,r){this.modelDependencies.set(e,r.modelDef.dependencies);const i={};for(const o of[e,...wR(r.modelDef.dependencies)]){if(r.invalidationKeys[o]===null)return!1;if(r.invalidationKeys[o]===void 0)throw new Error(`Missing invalidation key for dependency ${o}`);this.modelInvalidationKeys.set(o,r.invalidationKeys[o]),i[o]=r.invalidationKeys[o]}return!!await this.modelCache.setModel(new URL(e),{modelDef:r.modelDef,invalidationKeys:i})}}we.CacheManager=gxt;function wR(t){return[...Object.keys(t),...Object.values(t).map(wR).flat()]}class yxt{constructor(){this.models=new Map}async getModel(e){return Promise.resolve(this.models.get(e.toString()))}async setModel(e,r){return this.models.set(e.toString(),r),Promise.resolve(!0)}}we.InMemoryModelCache=yxt;function vxe(t){return(0,axt.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}async function NR(t,e){const r=await t.readURL(e),{contents:i,invalidationKey:s}=typeof r=="string"?{contents:r,invalidationKey:void 0}:r;return{contents:i,invalidationKey:LR(e.toString())?null:s??vxe(i)}}async function nP(t,e){return LR(e.toString())?null:t.getInvalidationKey!==void 0?await t.getInvalidationKey(e):(await NR(t,e)).invalidationKey}function LR(t){return t.startsWith("internal://")}var IR={};Object.defineProperty(IR,"__esModule",{value:!0}),IR.toAsyncGenerator=void 0;async function*Ext(t){let e=!1;function r(s){let o;const u=new Promise(a=>{o=a});return s(a=>{o({done:!0,isError:!0,error:a})},a=>{o({done:!1,value:a,isError:!1,next:new Promise(l=>{o=l})})},()=>{o({done:!0,isError:!1})}),u}let i=r(t);for(;!e;){const s=await i;if(s.done){if(e=!0,s.isError)throw s.error;break}else i=s.next,yield s.value}}IR.toAsyncGenerator=Ext;var Cxe={},Wc={},rP={},vE={};Object.defineProperty(vE,"__esModule",{value:!0}),vE.MALLOY_INTERFACE_TYPES=void 0,vE.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{field_reference:{type:"Reference",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var BR={},$R={},kR={};Object.defineProperty(kR,"__esModule",{value:!0}),kR.RESERVED_WORDS=void 0,kR.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty($R,"__esModule",{value:!0}),$R.maybeQuoteIdentifier=void 0;const Axt=kR;function _xt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=Axt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function vxt(t){const e=t.split(".");for(let r=0;r<e.length;r++)_xt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}$R.maybeQuoteIdentifier=vxt,Object.defineProperty(BR,"__esModule",{value:!0}),BR.queryToMalloy=void 0;const CE=$R;function Cxt(t,{tabWidth:e}={tabWidth:2}){const r=Dxt(t);return bxt(r,{tabWidth:e})}BR.queryToMalloy=Cxt;const iP=Symbol("indent"),yu=Symbol("newline"),sP=Symbol("outdent"),Sxt=Symbol("optional_newline_indent");function bxt(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===yu)r+=`
1489
+ `,s=!0;else if(o===sP)i--;else if(o===iP)i++;else{if(o===Sxt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function MR(t,e,r,i){var s;if(e.includes(yu))return[t,yu,iP,...e,yu,sP,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function Txt(t){return{contents:t,quoteCharacter:'"'}}function Rxt(t){var e,r;switch(t.kind){case"filter_expression_literal":return[Dxe(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=Txt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[bxe(Sxe(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day")];case"timestamp_literal":return[bxe(Sxe(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second")]}}function Sxe(t){return new Date(t)}function yn(t,e){return t.toString().padStart(e,"0")}function bxe(t,e){switch(e){case"year":return`@${yn(t.getUTCFullYear(),4)}`;case"quarter":{const r=yn(t.getUTCFullYear(),4),i=Math.floor(t.getUTCMonth()/3)+1;return`@${r}-Q${i}`}case"month":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2);return`@${r}-${i}`}case"week":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@WK${r}-${i}-${s}`}case"day":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@${r}-${i}-${s}`}case"hour":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2);return`@${r}-${i}-${s} ${o}`}case"minute":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2);return`@${r}-${i}-${s} ${o}:${u}`}case"second":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2),a=yn(t.getUTCSeconds(),2);return`@${r}-${i}-${s} ${o}:${u}:${a}`}default:throw new Error("Unknown timeframe.")}}function Vc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,CE.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,CE.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,CE.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Rxt(o.value)),s<t.parameters.length-1&&i.push(",",yu)}r.push(...MR("(",i,")",{spaces:!1}))}return r}function Dxt(t){const e=[];return e.push(...I2(t.annotations)),e.push("run: "),e.push(...oP(t.definition)),e}function Oxt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Vc(t));break}case"refinement":e.push(...oP(t));break}return e}function oP(t){const e=[];switch(t.kind){case"arrow":{e.push(...Oxt(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"query_reference":{e.push(...Vc(t));break}case"refinement":{const r=oP(t.base);t.base.kind==="arrow"?e.push(...MR("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...xd(t.refinement));break}}return e}function xd(t){const e=[];switch(t.kind){case"arrow":{e.push(...xd(t.source)),e.push(" -> "),e.push(...xd(t.view));break}case"view_reference":{e.push(...Vc(t));break}case"refinement":{e.push(...xd(t.base)),e.push(" + "),e.push(...xd(t.refinement));break}case"segment":{e.push(...Fxt(t));break}}return e}function Fxt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...wxt(o)),e&&i<t.operations.length-1&&r.push(yu)}return MR("{",r,"}")}function wxt(t){switch(t[0].kind){case"aggregate":return Bxt(t);case"group_by":return Ixt(t);case"order_by":return $xt(t);case"nest":return Mxt(t);case"limit":return qxt(t);case"where":return Rxe(t);case"having":return Hxt(t)}}function L2(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(yu));s?i.push(yu,iP):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(yu)}return s&&i.push(sP),i}function Nxt(t){const e=[];return e.push(...Lxt(t.expression)),e}function mht(t){return t}function Lxt(t){switch(t.kind){case"field_reference":return Vc(t);case"time_truncation":return[...Vc(t.field_reference),".",t.truncation];case"filtered_field":return[...Vc(t.field_reference),...MR(" {",Rxe(t.where),"}")]}}function Txe(t,e=!1){const r=[];return e||r.push(...I2(t.field.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Nxt(t.field)),r}function Ixt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("group_by",t.map(i=>Txe(i,r)))),e}function Bxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].field.annotations)),e.push(...L2("aggregate",t.map(i=>Txe(i,r)))),e}function $xt(t){return L2("order_by",t.map(kxt),",")}function kxt(t){const e=[];return e.push(...Vc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function Mxt(t){const e=[],r=t.length===1;return r&&e.push(...I2(t[0].view.annotations)),e.push(...L2("nest",t.map(i=>Pxt(i,r)))),e}function Pxt(t,e=!1){const r=[];return e||r.push(...I2(t.view.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Uxt(t.view)),r}function Uxt(t){return xd(t.definition)}function jxt(t){return[`limit: ${t.limit}`]}function qxt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(yu),e.push(...jxt(t[r]));return e}function Rxe(t){return L2("where",t.map(Oxe),",")}function Hxt(t){return L2("having",t.map(Oxe),",")}const Qxt=["`","'",'"'];function Dxe(t){let e,r;for(const i of Qxt){const s=zxt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function zxt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function Oxe(t){switch(t.filter.kind){case"filter_string":return[...Vc(t.filter.field_reference)," ~ ",Dxe(t.filter.filter)]}}function I2(t){return t?t.flatMap(Gxt):[]}function Gxt(t){return[t.value.trim(),yu]}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.convertToThrift=Ma.convertFromThrift=Ma.unnestUnions=Ma.nestUnions=void 0;const Wxt=vE;function uP(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(uP);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=uP(t[i]);return r===void 0?e:{[r]:e}}}Ma.nestUnions=uP;function PR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>PR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=PR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=PR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}Ma.unnestUnions=PR;function UR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=B2(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>UR(r,e));{const r=B2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=UR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=UR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}Ma.convertFromThrift=UR;function B2(t){const e=Wxt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function jR(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=B2(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>jR(r,e));{const r=B2(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=B2(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=jR(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=jR(t[s],o.type)}return i}}}}Ma.convertToThrift=jR,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.queryToMalloy=void 0,r(vE,t);var i=BR;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}});var s=Ma;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",field_reference:{name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(rP);var nn={},Vxt=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]}),Yxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kxt=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)&&Vxt(e,t,r);return Yxt(e,t),e};Object.defineProperty(nn,"__esModule",{value:!0}),nn.statedCompileQuery=nn.newCompileQueryState=nn.hasErrors=nn.compileSource=nn.compileModel=nn._statedCompileModel=nn.statedCompileSource=nn.statedCompileModel=nn.newCompileSourceState=nn.newCompileModelState=nn.updateCompileModelState=nn.compileQuery=void 0;const Jxt=Kxt(rP),Xxt=H4,Fxe=Pi,Zxt=La,wxe=Yl,edt=ui,Nxe=Zo,dd=mE;function Lxe(t,e){return`${t}:${e}`}function tdt(t,e){return{type:"sql_select",selectStr:t.sql,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:(0,wxe.sqlKey)(t.connection_name,t.sql)}}function ndt(t,e){return{type:"table",tablePath:t.name,connection:t.connection_name,dialect:e,fields:t.schema?Bxe(t.schema):[],name:Lxe(t.connection_name,t.name)}}function rdt(t){if(t!==void 0)return t==="decimal"?"float":"integer"}function Ixe(t){switch(t.kind){case"string_type":return{type:"string"};case"number_type":return{type:"number",numberType:rdt(t.subtype)};case"boolean_type":return{type:"boolean"};case"timestamp_type":return{type:"timestamp",timeframe:t.timeframe};case"date_type":return{type:"date",timeframe:t.timeframe};case"sql_native_type":return{type:"sql native",rawType:t.sql_type};case"json_type":return{type:"json"};case"array_type":{if(t.element_type.kind==="record_type")return{type:"array",elementTypeDef:{type:"record_element"},fields:t.element_type.fields.map(aP)};{const e=Ixe(t.element_type);if(e.type==="record")throw new Error("Arrays of records should be a repeated record type");return{type:"array",elementTypeDef:e}}}case"record_type":return{type:"record",fields:t.fields.map(aP)}}}function aP(t){var e;const r=Ixe(t.type);return{...(0,Fxe.mkFieldDef)(r,t.name),annotation:t.annotations&&t.annotations.length?{notes:(e=t.annotations)===null||e===void 0?void 0:e.map(i=>({text:i.value,at:{url:"~internal~",range:dd.DEFAULT_LOG_RANGE}}))}:void 0}}function idt(t){if(t.kind!=="dimension")throw new Error("Table schemas must only have dimension fields");return aP(t)}function Bxe(t){const e=[];for(const r of t.fields)e.push(idt(r));return e}function $xe(t){var e,r,i,s,o,u;const a={urls:{},tables:{},compileSQL:{},translations:{}};if(t){for(const l of(e=t.files)!==null&&e!==void 0?e:[])l.contents!==void 0&&(a.urls[l.url]=l.contents);for(const l of(r=t.table_schemas)!==null&&r!==void 0?r:[]){const c=(i=t.connections)===null||i===void 0?void 0:i.find(f=>f.name===l.connection_name);c&&l.schema&&c.dialect&&(a.tables[Lxe(l.connection_name,l.name)]=ndt(l,c.dialect))}for(const l of(s=t.sql_schemas)!==null&&s!==void 0?s:[]){const c=(o=t.connections)===null||o===void 0?void 0:o.find(f=>f.name===l.connection_name);c&&c.dialect&&(a.compileSQL[(0,wxe.sqlKey)(l.connection_name,l.sql)]=tdt(l,c.dialect))}for(const l of(u=t.translations)!==null&&u!==void 0?u:[])if(l.compiled_model_json){const c=JSON.parse(l.compiled_model_json);a.translations[l.url]=c}}return a}function kxe(t,e,r){var i,s,o;const u={},a=new Set;if(t!==void 0&&(u.sql_schemas=[{sql:t.selectStr,connection_name:t.connection}],a.add(t.connection)),e!==void 0)for(const l of e)(i=u.files)!==null&&i!==void 0||(u.files=[]),u.files.push({url:l});if(r!==void 0)for(const l in r){const c=r[l],f=(s=c.connectionName)!==null&&s!==void 0?s:"__default__";(o=u.table_schemas)!==null&&o!==void 0||(u.table_schemas=[]),u.table_schemas.push({name:c.tablePath,connection_name:f}),a.add(f)}return a.size>0&&(u.connections=Array.from(a).map(l=>({name:l}))),u}function sdt(t,e){return e??(e=qxe(t)),Hxe(e)}nn.compileQuery=sdt;function odt(t,e){function r(s,o){var u,a,l,c;s.translator.update(o),s.extending&&r(s.extending,o),s.hasSource||(s.hasSource=((a=(u=e==null?void 0:e.files)===null||u===void 0?void 0:u.some(f=>f.url===s.translator.sourceURL))!==null&&a!==void 0?a:!1)||((c=(l=e==null?void 0:e.translations)===null||l===void 0?void 0:l.some(f=>f.url===s.translator.sourceURL))!==null&&c!==void 0?c:!1))}const i=$xe(e);r(t,i)}nn.updateCompileModelState=odt;function qR(t,e,r){var i,s,o,u;const a=new Xxt.MalloyTranslator(t,null,$xe(e)),l=((s=(i=e==null?void 0:e.files)===null||i===void 0?void 0:i.some(c=>c.url===t))!==null&&s!==void 0?s:!1)||((u=(o=e==null?void 0:e.translations)===null||o===void 0?void 0:o.some(c=>c.url===t))!==null&&u!==void 0?u:!1);return r?{extending:qR(r,e),translator:a,done:!1,hasSource:l}:{translator:a,done:!1,hasSource:l}}function Mxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileModelState=Mxe;function Pxe(t){return qR(t.model_url,t.compiler_needs,t.extend_model_url)}nn.newCompileSourceState=Pxe;function Uxe(t){return udt(SE(t),t.translator.sourceURL)}nn.statedCompileModel=Uxe;function jxe(t,e){return cdt(SE(t),e,t.translator.sourceURL)}nn.statedCompileSource=jxe;function SE(t){let e;if(t.extending){if(!t.extending.done){const i=SE(t.extending);if(!t.extending.done)return i}e=t.extending.translator.modelDef}if(!t.hasSource)return{compilerNeeds:kxe(void 0,[t.translator.sourceURL],void 0)};const r=t.translator.translate(e);if(r.final){if(t.done=!0,r.modelDef)return{model:(0,Zxt.modelDefToModelInfo)(r.modelDef),modelDef:r.modelDef};if(r.problems===void 0||r.problems.length===0)throw new Error("No problems found, but no model either");return{logs:r.problems}}else return{compilerNeeds:kxe(r.compileSQL,r.urls,r.tables),logs:r.problems}}nn._statedCompileModel=SE;function udt(t,e){const r=t.logs?(0,dd.mapLogs)(t.logs,e):void 0;if(t.compilerNeeds)return{compiler_needs:t.compilerNeeds,logs:r};{let i;return t.modelDef&&(i=[{url:e,compiled_model_json:JSON.stringify(t.modelDef)}]),{model:t.model,logs:r,translations:i}}}function adt(t,e){return e??(e=Mxe(t)),Uxe(e)}nn.compileModel=adt;function ldt(t){const e=Pxe(t);return jxe(e,t.name)}nn.compileSource=ldt;function cdt(t,e,r){const i=t.logs?(0,dd.mapLogs)(t.logs,r):void 0;if(t.model){const s=t.model.entries.find(o=>o.name===e);return s===void 0?{logs:[...i??[],{url:r,severity:"error",message:`Model does not contain a source named ${e}`,range:dd.DEFAULT_LOG_RANGE}]}:{source:s,logs:i}}else return{compiler_needs:t.compilerNeeds,logs:i}}function fdt(t){var e;return(e=t==null?void 0:t.some(r=>r.severity==="error"))!==null&&e!==void 0?e:!1}nn.hasErrors=fdt;function qxe(t){var e,r;const i=Jxt.queryToMalloy(t.query),s={...(e=t.compiler_needs)!==null&&e!==void 0?e:{}},o="internal://query.malloy";return s.files=[{url:o,contents:i},...(r=s.files)!==null&&r!==void 0?r:[]],{...qR(o,s,t.model_url),defaultRowLimit:t.default_row_limit}}nn.newCompileQueryState=qxe;function Hxe(t){var e;const r=SE(t),i=t.translator.sourceURL,s=r.logs?(0,dd.mapLogs)(r.logs,i):void 0;if(r.model){const o=r.modelDef.queryList;if(o.length===0)return{logs:[...s??[],{url:i,severity:"error",message:"Internal error: No queries found",range:dd.DEFAULT_LOG_RANGE}]};const u=o.length-1,a=r.modelDef.queryList[u],l=r.model.anonymous_queries[u].schema,c=(e=r.model.anonymous_queries[u].annotations)!==null&&e!==void 0?e:[];try{const x=new Fxe.QueryModel(r.modelDef).compileQuery(a,{defaultRowLimit:t.defaultRowLimit}),h=(0,edt.annotationToTaglines)(r.modelDef.annotation).map(p=>({value:p}));return c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore).toString()}),x.queryName&&c.push({value:Nxe.Tag.withPrefix("#(malloy) ").set(["query_name"],x.queryName).toString()}),{result:{sql:x.sql,schema:l,connection_name:x.connectionName,annotations:c.length>0?c:void 0,model_annotations:h.length>0?h:void 0,query_timezone:x.queryTimezone},default_row_limit_added:x.defaultRowLimitAdded}}catch(f){return{logs:[...s??[],{url:i,severity:"error",message:`Internal compiler error: ${f.message}`,range:dd.DEFAULT_LOG_RANGE}]}}}else return{compiler_needs:r.compilerNeeds,logs:s}}nn.statedCompileQuery=Hxe;var xdt=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]}),ddt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qxe=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)&&xdt(e,t,r);return ddt(e,t),e};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.compileQuery=Wc.compileSource=Wc.compileModel=void 0;const hdt=Qxe(rP),Pa=Qxe(nn),pdt=Pp;function mdt(t,e){return t.type==="compile_model"?e.type!=="compile_model"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL:t.type==="compile_source"?e.type!=="compile_source"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL&&t.name===e.name:e.type!=="compile_query"?!1:t.modelURL===e.modelURL&&t.queryString===e.queryString}class gdt{constructor(){this.sessions=new Map}purgeExpired(e){const r=new Date;for(const i of this.sessions.values())i.sessionId!==(e==null?void 0:e.except)&&i.expires&&i.expires<r&&this.sessions.delete(i.sessionId)}findSession(e,r){const i=this.sessions.get(e);if(i&&mdt(i.sessionInfo,r))return i}getExpires(e){return e instanceof Date?e:new Date(Date.now()+e.seconds*1e3)}newSessionId(){let e;do e=(0,pdt.v4)();while(this.sessions.has(e));return e}newCompileModelSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileModelState(e);return{type:"compile_model",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileSourceSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileSourceState(e);return{type:"compile_source",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileQuerySession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileQueryState(e);return{type:"compile_query",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}findCompileModelSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_model")return i}killSession(e){this.sessions.delete(e)}hasErrors(e){return Pa.hasErrors(e)}compileModel(e,r){const i={type:"compile_model",modelURL:e.model_url,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileModelSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileModelSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileModel(s.state);return(o.model||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileSourceSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_source")return i}compileSource(e,r){const i={type:"compile_source",modelURL:e.model_url,name:e.name,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileSourceSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileSourceSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileSource(s.state,e.name);return(o.source||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileQuerySession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_query")return i}compileQuery(e,r){const i=hdt.queryToMalloy(e.query),s={type:"compile_query",modelURL:e.model_url,queryString:i,query:e.query};let o=(r==null?void 0:r.session_id)&&this.findCompileQuerySession(r.session_id,s);this.purgeExpired({except:r==null?void 0:r.session_id}),o?(r!=null&&r.ttl&&(o.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(o.state,e.compiler_needs)):(o=this.newCompileQuerySession(e,s,r),this.sessions.set(o.sessionId,o));const u=Pa.statedCompileQuery(o.state);return(u.result||this.hasErrors(u.logs))&&this.killSession(o.sessionId),{...u,session_id:o.sessionId}}}const lP=new gdt;function ydt(t,e){return lP.compileModel(t,e)}Wc.compileModel=ydt;function Edt(t,e){return lP.compileSource(t,e)}Wc.compileSource=Edt;function Adt(t,e){return lP.compileQuery(t,e)}Wc.compileQuery=Adt;var Yc={},_dt=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]}),vdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cdt=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)&&_dt(e,t,r);return vdt(e,t),e};Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.compileQuery=Yc.compileSource=Yc.compileModel=void 0;const cP=Cdt(nn);function Sdt(t){return cP.compileModel(t)}Yc.compileModel=Sdt;function bdt(t){return cP.compileSource(t)}Yc.compileSource=bdt;function Tdt(t){return cP.compileQuery(t)}Yc.compileQuery=Tdt;var Ua={},Rdt=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]}),Ddt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Odt=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)&&Rdt(e,t,r);return Ddt(e,t),e};Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.runQuery=Ua.compileQuery=Ua.compileSource=Ua.compileModel=void 0;const vo=Odt(nn),zxe=mE;async function fP(t,e){var r,i,s,o,u,a,l,c,f;if(t===void 0)throw new Error("Expected compiler to have needs because it didn't return a result");const x={};if(t.connections)for(const h of t.connections){const p=await e.connections.lookupConnection(h.name);(r=x.connections)!==null&&r!==void 0||(x.connections=[]),x.connections.push({...h,dialect:p.dialectName})}if(t.files)for(const h of t.files){const p=await e.urls.readURL(new URL(h.url));(i=x.files)!==null&&i!==void 0||(x.files=[]),typeof p=="string"?x.files.push({...h,contents:p}):x.files.push({...h,contents:p.contents,invalidation_key:(s=p.invalidationKey)===null||s===void 0?void 0:s.toString()})}if(t.table_schemas){const h={};for(const p of t.table_schemas)(o=h[c=p.connection_name])!==null&&o!==void 0||(h[c]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.name),y=await Promise.all(g.map(async E=>({name:E,schema:await m.fetchSchemaForTable(E)})));(u=x.table_schemas)!==null&&u!==void 0||(x.table_schemas=[]);for(const E of y)x.table_schemas.push({connection_name:p,name:E.name,schema:E.schema})}}if(t.sql_schemas){const h={};for(const p of t.sql_schemas)(a=h[f=p.connection_name])!==null&&a!==void 0||(h[f]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),g=h[p].map(E=>E.sql),y=await Promise.all(g.map(async E=>({sql:E,schema:await m.fetchSchemaForSQLQuery(E)})));(l=x.sql_schemas)!==null&&l!==void 0||(x.sql_schemas=[]);for(const E of y)x.sql_schemas.push({connection_name:p,sql:E.sql,schema:E.schema})}}return x}async function Fdt(t,e){const r=vo.newCompileModelState(t);for(;;){const i=vo.statedCompileModel(r);if(i.model||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileModel=Fdt;async function wdt(t,e){const r=vo.newCompileSourceState(t);for(;;){const i=vo.statedCompileSource(r,t.name);if(i.source||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileSource=wdt;async function Gxe(t,e){const r=vo.newCompileQueryState(t);for(;;){const i=vo.statedCompileQuery(r);if(i.result||vo.hasErrors(i.logs))return i;const s=await fP(i.compiler_needs,e);vo.updateCompileModelState(r,s)}}Ua.compileQuery=Gxe;async function Ndt(t,e){var r,i;const s=await Gxe(t,e);if(s.result===void 0)return s;const o=t.model_url;if(s.result.sql===void 0)return{logs:[...(r=s.logs)!==null&&r!==void 0?r:[],{url:o,severity:"error",message:"Internal error: Compiler did not generate SQL",range:zxe.DEFAULT_LOG_RANGE}]};try{const a=await(await e.connections.lookupConnection(s.result.connection_name)).runSQL(s.result.sql,s.result.schema);return{...s,result:{...s.result,data:a}}}catch(u){return{...s,logs:[...(i=s.logs)!==null&&i!==void 0?i:[],{url:o,severity:"error",message:`Error running SQL: ${u.message}`,range:zxe.DEFAULT_LOG_RANGE}]}}}Ua.runQuery=Ndt;var Wxe={};Object.defineProperty(Wxe,"__esModule",{value:!0}),function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u},s=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.util=t.asynchronous=t.stateless=t.sessioned=void 0,t.sessioned=i(Wc),t.stateless=i(Yc),t.asynchronous=i(Ua),s(Wxe,t),t.util=i(mE)}(Cxe),function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,g,y)}:function(h,p,m,g){g===void 0&&(g=m),h[g]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p};Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyURLReader=t.SingleConnectionRuntime=t.ConnectionRuntime=t.AtomicFieldType=t.Runtime=t.Malloy=t.Model=t.MalloyTranslator=t.malloyToQuery=t.composeSQLExpr=t.indent=t.expressionIsUngroupedAggregate=t.expressionIsScalar=t.expressionIsCalculation=t.expressionIsAnalytic=t.expressionIsAggregate=t.mkFieldDef=t.mkArrayDef=t.isBasicArray=t.isRepeatedRecord=t.isSamplingRows=t.isSamplingPercent=t.isSamplingEnable=t.isJoinedSource=t.isJoined=t.isBasicAtomic=t.Segment=t.isSourceDef=t.TinyParser=t.Dialect=t.spread=t.literal=t.variadicParam=t.param=t.makeParam=t.sql=t.maxScalar=t.minAggregate=t.anyExprType=t.minScalar=t.overload=t.qtz=t.arg=t.registerDialect=t.MySQLDialect=t.SnowflakeDialect=t.PostgresDialect=t.TrinoDialect=t.StandardSQLDialect=t.DuckDBDialect=void 0,t.annotationToTaglines=t.annotationToTag=t.sqlKey=t.API=t.modelDefToModelInfo=t.toAsyncGenerator=t.CacheManager=t.InMemoryModelCache=t.Explore=t.DataWriter=t.Parse=t.JSONWriter=t.CSVWriter=t.QueryMaterializer=t.Result=t.PreparedResult=t.TimestampTimeframe=t.DateTimeframe=t.SourceRelationship=t.JoinRelationship=t.MalloyError=t.FixedConnectionMap=t.InMemoryURLReader=void 0;var s=kp;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}}),Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return s.StandardSQLDialect}}),Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return s.TrinoDialect}}),Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}}),Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return s.SnowflakeDialect}}),Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return s.MySQLDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return s.registerDialect}}),Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return s.arg}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return s.qtz}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return s.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return s.minScalar}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return s.anyExprType}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return s.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return s.maxScalar}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return s.sql}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return s.makeParam}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return s.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return s.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return s.literal}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return s.spread}}),Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return s.Dialect}}),Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return s.TinyParser}});var o=Pi;Object.defineProperty(t,"isSourceDef",{enumerable:!0,get:function(){return o.isSourceDef}}),Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return o.Segment}}),Object.defineProperty(t,"isBasicAtomic",{enumerable:!0,get:function(){return o.isBasicAtomic}}),Object.defineProperty(t,"isJoined",{enumerable:!0,get:function(){return o.isJoined}}),Object.defineProperty(t,"isJoinedSource",{enumerable:!0,get:function(){return o.isJoinedSource}}),Object.defineProperty(t,"isSamplingEnable",{enumerable:!0,get:function(){return o.isSamplingEnable}}),Object.defineProperty(t,"isSamplingPercent",{enumerable:!0,get:function(){return o.isSamplingPercent}}),Object.defineProperty(t,"isSamplingRows",{enumerable:!0,get:function(){return o.isSamplingRows}}),Object.defineProperty(t,"isRepeatedRecord",{enumerable:!0,get:function(){return o.isRepeatedRecord}}),Object.defineProperty(t,"isBasicArray",{enumerable:!0,get:function(){return o.isBasicArray}}),Object.defineProperty(t,"mkArrayDef",{enumerable:!0,get:function(){return o.mkArrayDef}}),Object.defineProperty(t,"mkFieldDef",{enumerable:!0,get:function(){return o.mkFieldDef}}),Object.defineProperty(t,"expressionIsAggregate",{enumerable:!0,get:function(){return o.expressionIsAggregate}}),Object.defineProperty(t,"expressionIsAnalytic",{enumerable:!0,get:function(){return o.expressionIsAnalytic}}),Object.defineProperty(t,"expressionIsCalculation",{enumerable:!0,get:function(){return o.expressionIsCalculation}}),Object.defineProperty(t,"expressionIsScalar",{enumerable:!0,get:function(){return o.expressionIsScalar}}),Object.defineProperty(t,"expressionIsUngroupedAggregate",{enumerable:!0,get:function(){return o.expressionIsUngroupedAggregate}}),Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return o.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return o.composeSQLExpr}});var u=H4;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return u.malloyToQuery}}),Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return u.MalloyTranslator}});var a=we;Object.defineProperty(t,"Model",{enumerable:!0,get:function(){return a.Model}}),Object.defineProperty(t,"Malloy",{enumerable:!0,get:function(){return a.Malloy}}),Object.defineProperty(t,"Runtime",{enumerable:!0,get:function(){return a.Runtime}}),Object.defineProperty(t,"AtomicFieldType",{enumerable:!0,get:function(){return a.AtomicFieldType}}),Object.defineProperty(t,"ConnectionRuntime",{enumerable:!0,get:function(){return a.ConnectionRuntime}}),Object.defineProperty(t,"SingleConnectionRuntime",{enumerable:!0,get:function(){return a.SingleConnectionRuntime}}),Object.defineProperty(t,"EmptyURLReader",{enumerable:!0,get:function(){return a.EmptyURLReader}}),Object.defineProperty(t,"InMemoryURLReader",{enumerable:!0,get:function(){return a.InMemoryURLReader}}),Object.defineProperty(t,"FixedConnectionMap",{enumerable:!0,get:function(){return a.FixedConnectionMap}}),Object.defineProperty(t,"MalloyError",{enumerable:!0,get:function(){return a.MalloyError}}),Object.defineProperty(t,"JoinRelationship",{enumerable:!0,get:function(){return a.JoinRelationship}}),Object.defineProperty(t,"SourceRelationship",{enumerable:!0,get:function(){return a.SourceRelationship}}),Object.defineProperty(t,"DateTimeframe",{enumerable:!0,get:function(){return a.DateTimeframe}}),Object.defineProperty(t,"TimestampTimeframe",{enumerable:!0,get:function(){return a.TimestampTimeframe}}),Object.defineProperty(t,"PreparedResult",{enumerable:!0,get:function(){return a.PreparedResult}}),Object.defineProperty(t,"Result",{enumerable:!0,get:function(){return a.Result}}),Object.defineProperty(t,"QueryMaterializer",{enumerable:!0,get:function(){return a.QueryMaterializer}}),Object.defineProperty(t,"CSVWriter",{enumerable:!0,get:function(){return a.CSVWriter}}),Object.defineProperty(t,"JSONWriter",{enumerable:!0,get:function(){return a.JSONWriter}}),Object.defineProperty(t,"Parse",{enumerable:!0,get:function(){return a.Parse}}),Object.defineProperty(t,"DataWriter",{enumerable:!0,get:function(){return a.DataWriter}}),Object.defineProperty(t,"Explore",{enumerable:!0,get:function(){return a.Explore}}),Object.defineProperty(t,"InMemoryModelCache",{enumerable:!0,get:function(){return a.InMemoryModelCache}}),Object.defineProperty(t,"CacheManager",{enumerable:!0,get:function(){return a.CacheManager}});var l=IR;Object.defineProperty(t,"toAsyncGenerator",{enumerable:!0,get:function(){return l.toAsyncGenerator}});var c=La;Object.defineProperty(t,"modelDefToModelInfo",{enumerable:!0,get:function(){return c.modelDefToModelInfo}}),t.API=i(Cxe);var f=Yl;Object.defineProperty(t,"sqlKey",{enumerable:!0,get:function(){return f.sqlKey}});var x=ui;Object.defineProperty(t,"annotationToTag",{enumerable:!0,get:function(){return x.annotationToTag}}),Object.defineProperty(t,"annotationToTaglines",{enumerable:!0,get:function(){return x.annotationToTaglines}})}(vB);class Ldt{constructor(e){this.document=e}async render(e,r){var l;let i;if(e&&(e instanceof vB.Result||"modelDef"in e)?i=vB.API.util.wrapResult(e):i=e,!r4(i.model_annotations,"## ").has("renderer_legacy"))if(!!((l=this.document.defaultView)!=null&&l.customElements.get("malloy-render"))){const f=this.document.createElement("malloy-render");f.malloyResult=i;const x=r.nextRendererOptions??{};for(const[h,p]of Object.entries(x))f[h]=p;return f}else console.warn("Tried to use the new Malloy renderer, but the malloy-render component was not found. Falling back to the legacy renderer.");const u=xue(i),a=Yxe(u.field,this.document,r,{size:"large"},u.field.queryTimezone,u.field.tag);try{return await a.render(u)}catch(c){return c instanceof Error?Gs(this.document,c):Gs(this.document,"Internal error - Exception not an Error object.")}}}class Idt{constructor(e){this.document=e}async render(e){const r=new mP(this.document);try{return await r.render(e)}catch(i){return i instanceof Error?Gs(this.document,i):Gs(this.document,"Internal error - Exception not an Error object.")}}}const Vxe={shape_map:"shape_map",point_map:"point_map",bar_chart:"bar_chart",image:"image",json:"json",segment_map:"segment_map",dashboard:"dashboard",line_chart:"line_chart",scatter_chart:"scatter_chart",url:"url",list:"list",list_detail:"list_detail",sparkline:"sparkline",sparkline_area:"sparkline",sparkline_column:"sparkline",sparkline_bar:"sparkline"};function Bdt(t,e){const r=e[t.name],{name:i}=t;for(const s in Vxe)if(i.endsWith(`_${s}`)){const o=i.slice(0,i.length-s.length-1);return $dt(s,o,Vxe,r)}return r}function $dt(t,e,r,i){var s;return i?(i.renderer??(i.renderer=r[t]),i.data??(i.data={}),(s=i.data).label??(s.label=e)):i={renderer:r[t],data:{label:e}},i}function HR(t){if(t.isRecordOrRepeatedRecord())return t;throw new Error(`${t.name} does not contain fields and cannot be rendered this way`)}function Yxe(t,e,r,i,s,o){const u=Bdt(t,r.dataStyles);r.dataStyles[t.name]=u;const a=new jL().create(u,o,e,i,r,t,s);if(a)return a;if((u==null?void 0:u.renderer)==="dashboard"||o.has("dashboard"))return QR(AB,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list"||o.has("list"))return QR(Eue,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="list_detail"||o.has("list_detail"))return QR(mYe,e,HR(t),r,o);if((u==null?void 0:u.renderer)==="table"||o.has("table")||t.isRecordOrRepeatedRecord())return QR(Z2,e,HR(t),r,o);throw new Error(`Could not find a proper renderer for field ${t.name}`)}function QR(t,e,r,i,s){const o=wE.make(t,e,r,i,s),u={};return r.fields.forEach(a=>{u[a.name]=Yxe(a,e,i,o.defaultStylesForChildren,a.root().queryTimezone,a.tag)}),o.childRenderers=u,o}async function kdt(t){const e=await Kxe(t);try{await navigator.clipboard.writeText(e)}catch(r){console.error("Failed to copy text: ",r)}}async function Kxe(t){let e="";const r=t.tableConfig??{},i=Object.assign({disableVirtualization:!0},r);t.tableConfig=i;const s=t.dashboardConfig??{},o=Object.assign({disableVirtualization:!0},s);if(t.dashboardConfig=o,await Mdt(1e3),t.shadowRoot){let u="";for(const a of[...t.shadowRoot.adoptedStyleSheets]){for(let c=0;c<a.cssRules.length;c++){const f=a.cssRules.item(c);f&&(u+=`
1490
1490
  `+f.cssText)}u=u.replaceAll(":host",".malloy_html_host");const l=t.getAttribute("style");e=`
1491
1491
  <div>
1492
1492
  <style>