@malloydata/render 0.0.276 → 0.0.277

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.
@@ -114672,7 +114672,7 @@ ${r}}`, i;
114672
114672
  else
114673
114673
  return;
114674
114674
  }
114675
- return i;
114675
+ return i.deleted ? void 0 : i;
114676
114676
  }
114677
114677
  has(...e) {
114678
114678
  return this.find(e) !== void 0;
@@ -150252,7 +150252,7 @@ Sp.malloyToQuery = Tdt;
150252
150252
  var we = {}, ED = {};
150253
150253
  Object.defineProperty(ED, "__esModule", { value: !0 });
150254
150254
  ED.MALLOY_VERSION = void 0;
150255
- ED.MALLOY_VERSION = "0.0.276";
150255
+ ED.MALLOY_VERSION = "0.0.277";
150256
150256
  Object.defineProperty(we, "__esModule", { value: !0 });
150257
150257
  we.InMemoryModelCache = we.CacheManager = we.CSVWriter = we.JSONWriter = we.DataWriter = we.DataRecord = we.DataArray = we.Result = we.ExploreMaterializer = we.PreparedResultMaterializer = we.QueryMaterializer = we.ModelMaterializer = we.SingleConnectionRuntime = we.ConnectionRuntime = we.Runtime = we.ExploreField = we.JoinRelationship = we.QueryField = we.Query = we.StringField = we.UnsupportedField = we.JSONField = we.BooleanField = we.NumberField = we.TimestampField = we.DateField = we.TimestampTimeframe = we.DateTimeframe = we.AtomicField = we.AtomicFieldType = we.Explore = we.SourceRelationship = we.FixedConnectionMap = we.InMemoryURLReader = we.EmptyURLReader = we.PreparedResult = we.DocumentCompletion = we.DocumentSymbol = we.DocumentPosition = we.DocumentRange = we.DocumentTablePath = we.Parse = we.PreparedQuery = we.Model = we.MalloyError = we.Malloy = void 0;
150258
150258
  const _Y = ST, Kr = qi, vY = tE, DO = y2, Rdt = ED, Ddt = E2, Ln = si, Odt = $l, Fdt = Gn, wdt = DE, CY = "internal://internal.malloy";
@@ -737,7 +737,7 @@ ${r} `)}
737
737
  ${r} ]`),this.properties)for(const s in this.properties){const o=At.tagFrom(this.properties[s]);i+=`
738
738
  ${r} ${s}: ${o.peek(e+2)}`}return i+=`
739
739
  ${r}}`,i}static fromTagLine(e,r=0,i,...s){return wue(e,i,s,r)}static fromTagLines(e,r,...i){const s=[];let o=r;for(let u=0;u<e.length;u++){const a=e[u],l=wue(a,o,i,u);o=l.tag,s.push(...l.log)}return{tag:o,log:s}}constructor(e={}){e.eq&&(this.eq=e.eq),e.properties&&(this.properties=e.properties),e.deleted&&(this.deleted=e.deleted),e.prefix&&(this.prefix=e.prefix)}static withPrefix(e){return new At({prefix:e})}tag(...e){return this.find(e)}text(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(typeof i=="string")return i}numeric(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(typeof i=="string"){const s=Number.parseFloat(i);if(!Number.isNaN(s))return s}}bare(...e){const r=this.find(e);if(r!==void 0)return r.properties===void 0||Object.entries(r.properties).length===0}get dict(){const e={};if(this.properties)for(const r in this.properties)e[r]=At.tagFrom(this.properties[r]);return e}array(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(!(i===void 0||typeof i=="string"))return i.map(s=>typeof s=="string"?new At({eq:s}):At.tagFrom(s))}textArray(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(!(i===void 0||typeof i=="string"))return i.reduce((s,o)=>typeof o.eq=="string"?s.concat(o.eq):s,[])}numericArray(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(!(i===void 0||typeof i=="string"))return i.reduce((s,o)=>{if(typeof o.eq=="string"){const u=Number.parseFloat(o.eq);if(!Number.isNaN(u))return s.concat(u)}return s},[])}getProperties(){return this.properties===void 0&&(this.properties={}),this.properties}clone(){return new At(structuredClone(this))}static escapeString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}static escapeProp(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static quoteAndEscape(e,r=!1){return e.match(/^[0-9A-Za-z_]+$/)?e:r?`\`${At.escapeProp(e)}\``:`"${At.escapeString(e)}"`}toString(){var e;let r=(e=this.prefix)!==null&&e!==void 0?e:"# ";function i(u){var a;const l=Object.keys((a=u.properties)!==null&&a!==void 0?a:{});for(let c=0;c<l.length;c++)o(l[c],u.properties[l[c]]),c<l.length-1&&(r+=" ")}function s(u,a=!1){if(u.eq!==void 0)if(a||(r+=" = "),Array.isArray(u.eq)){r+="[";for(let l=0;l<u.eq.length;l++)s(u.eq[l],!0),l!==u.eq.length-1&&(r+=", ");r+="]"}else r+=At.quoteAndEscape(`${u.eq}`);if(u.properties){const l=Object.keys(u.properties);!a&&l.length===1&&!l.some(c=>{var f;return((f=u.properties)!==null&&f!==void 0?f:{})[c].deleted})&&u.eq===void 0?(r+=".",i(u)):((!a||u.eq!==void 0)&&(r+=" "),r+="{ ",i(u),r+=" }")}}function o(u,a){if(a.deleted){r+=`-${At.quoteAndEscape(u,!0)}`;return}r+=At.quoteAndEscape(u,!0),s(a)}return i(this),r+=`
740
- `,r}find(e){var r;let i=At.tagFrom(this);for(const s of e)if(typeof s=="number"){if(i.eq===void 0||!Array.isArray(i.eq)||i.eq.length<=s)return;i=At.tagFrom(i.eq[s])}else{const o=(r=i.properties)!==null&&r!==void 0?r:{};if(s in o)i=At.tagFrom(o[s]);else return}return i}has(...e){return this.find(e)!==void 0}set(e,r=null){const i=At.tagFrom(this);let s=i;for(const o of e)if(typeof o=="number"){if(s.eq===void 0||!Array.isArray(s.eq))s.eq=Array.from({length:o+1}).map(u=>({}));else if(s.eq.length<=o){const u=s.eq,a=Array.from({length:o+1}).map((l,c)=>c<u.length?u[c]:{});s.eq=a}s=s.eq[o]}else{const u=s.properties;u===void 0?(s.properties={[o]:{}},s=s.properties[o]):o in u?(s=u[o],s.deleted&&(s.deleted=!1)):(u[o]={},s=u[o])}return r===null?s.eq=void 0:typeof r=="string"?s.eq=r:typeof r=="number"?s.eq=r.toString():Array.isArray(r)&&(s.eq=r.map(o=>({eq:typeof o=="string"?o:o.toString()}))),i}delete(...e){return this.remove(e,!1)}unset(...e){return this.remove(e,!0)}remove(e,r=!1){var i;const s=At.tagFrom(this);let o=s;for(const a of e.slice(0,e.length-1))if(typeof a=="number"){if(o.eq===void 0||!Array.isArray(o.eq)){if(!r)return s;o.eq=Array.from({length:a}).map(l=>({}))}else if(o.eq.length<=a){if(!r)return s;const l=o.eq,c=Array.from({length:a}).map((f,x)=>x<l.length?l[x]:{});o.eq=c}o=o.eq[a]}else{const l=o.properties;if(l===void 0){if(!r)return s;o.properties={[a]:{}},o=o.properties[a]}else if(a in l)o=l[a];else{if(!r)return s;l[a]={},o=l[a]}}const u=e[e.length-1];return typeof u=="string"?o.properties&&u in o.properties?delete o.properties[u]:r&&((i=o.properties)!==null&&i!==void 0||(o.properties={}),o.properties[u]={deleted:!0}):Array.isArray(o.eq)&&o.eq.splice(u,1),s}}zS.Tag=At,At.ids=new Map,At.nextTagId=1e3;class AYe{constructor(e){this.line=e,this.log=[]}syntaxError(e,r,i,s,o,u){const a={code:"tag-parse-syntax-error",message:o,line:this.line,offset:s};this.log.push(a)}semanticError(e,r,i){const s={code:r,message:i,line:this.line,offset:e.start.charPositionInLine};this.log.push(s)}}function Sy(t){const e=t.buildOn;return e instanceof At?e:new At}function x4(t,e){var r,i;let s=t.getProperties();for(const o of e.slice(0,e.length-1)){let u;s[o]===void 0?(u=new At({}),s[o]=u):((r=(i=s[o]).properties)!==null&&r!==void 0||(i.properties={}),u=At.tagFrom(s[o])),s=u.getProperties()}return[e[e.length-1],s]}function Fue(t){return t.SQ_STRING()||t.DQ_STRING()?(0,Oue.parseString)(t.text,t.text[0]):t.text}function wue(t,e,r,i){if(t[0]==="#"){const h=t.indexOf(" ");h>0?t=t.slice(h):t=""}const s=Due.CharStreams.fromString(t),o=new yYe.MalloyTagLexer(s),u=new Due.CommonTokenStream(o),a=new AYe(i),l=new EYe.MalloyTagParser(u);l.removeErrorListeners(),l.addErrorListener(a);const c=l.tagLine();return{tag:new _Ye(r,a).tagLineToTag(c,e),log:a.log}}class _Ye extends gYe.AbstractParseTreeVisitor{constructor(e=[],r){super(),this.scopes=[],this.msgLog=r,this.scopes.unshift(...e)}defaultResult(){return new At}visitString(e){return new At({eq:Fue(e)})}getPropName(e){return e.identifier().map(r=>r.BARE_STRING()?r.text:(0,Oue.parseString)(r.text,r.text[0]))}getTags(e,r){for(const i of e)i.buildOn=r,this.visit(i);return r}tagLineToTag(e,r){return r=(r==null?void 0:r.clone())||new At({}),this.scopes.unshift(r),this.getTags(e.tagSpec(),r),r}visitTagLine(e){throw new Error("INTERNAL: ERROR: Call tagLineToTag, not vistTagLine")}visitProperties(e){return this.getTags(e.tagSpec(),Sy(e))}visitArrayValue(e){return new At({eq:this.getArray(e)})}getArray(e){return e.arrayElement().map(r=>this.visit(r))}visitArrayElement(e){const r=e.properties(),i=r?this.visitProperties(r):void 0,s=e.string();let o=s?Fue(s):void 0;const u=e.arrayValue();if(u&&(o=this.getArray(u)),i)return o!==void 0&&(i.eq=o),i;const a=e.reference();return a?this.visitReference(a):new At({eq:o})}visitReference(e){const r=this.getPropName(e.propName());for(const i of this.scopes)if(i.has(r[0])){const s=i.tag(...r);if(s)return s.clone();break}return this.msgLog.semanticError(e,"tag-property-not-found",`Reference to undefined property ${r.join(".")}`),this.defaultResult()}visitTagEq(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i),u=this.visit(e.eqValue()),a=e.properties();if(a)if(a.DOTTY()===void 0){const l=this.visitProperties(a).dict;o[s]={...u,properties:l}}else o[s]={...o[s],...u};else o[s]=u;return r}visitTagReplaceProperties(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i),u=e.properties(),a=this.visitProperties(u);return e.DOTTY()===void 0?o[s]={properties:a.dict}:o[s].properties=a.dict,r}visitTagUpdateProperties(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i),u=e.properties();u.buildOn=At.tagFrom(o[s]);const a=this.visitProperties(u),l=o[s]||new At({}),c={...l.properties,...a.dict};return o[s]={...l,properties:c},r}visitTagDef(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i);return e.MINUS()?o[s]={deleted:!0}:o[s]=new At({}),r}visitTagEmpty(e){const r=e.buildOn;return r.properties={},r}}(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.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)},s=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};Object.defineProperty(t,"__esModule",{value:!0}),t.ParseUtil=void 0,i(zS,t),t.ParseUtil=s(Cy)})(tu);const vYe="∅";function d4(t,e="# "){var i;const r=((i=t==null?void 0:t.map(s=>s.value))==null?void 0:i.filter(s=>s.startsWith(e)))??[];return tu.Tag.fromTagLines(r).tag??new tu.Tag}Bt.Nanoseconds,Bt.Microseconds,Bt.Milliseconds,Bt.Seconds,Bt.Minutes,Bt.Hours,Bt.Days,Bt.Nanoseconds,Bt.Microseconds,Bt.Milliseconds,Bt.Seconds,Bt.Minutes,Bt.Hours,Bt.Days,Number.MAX_VALUE;function by(t,e=2){return`${"0".repeat(e-1)}${t}`.slice(-e)}function v$(t,e,r){const i=t.getUTCFullYear(),s=by(t.getUTCMonth()+1),o=by(t.getUTCDate()),u=by(t.getUTCHours()),a=by(t.getUTCMinutes()),l=by(t.getUTCSeconds()),c=`${u}:${a}:${l}`,f=`${i}-${s}-${o}`;switch(r){case"minute":return`${f} ${u}:${a}`;case"hour":return`${f} ${u}`;case"day":return`${f}`;case"week":return`${f}-WK`;case"month":return`${i}-${s}`;case"quarter":return`${i}-Q${Math.floor(t.getUTCMonth()/3)+1}`;case"year":return t.getUTCFullYear().toString();default:return e?f:`${f} ${c}`}}function CYe(t){return`'${t.replace(/(['\\])/g,"\\$1")}'`}function SYe(t){return t.isNull()?"null":t.isString()?CYe(t.value):t.isNumber()||t.isBoolean()?t.value.toString():t.isTime()?"@"+v$(t.value,t.isDate(),t.field.timeframe):"invalid_drill_literal()"}function Nue(t){const e=[];for(const a of t.schema.fields)a.kind==="dimension"&&e.push(a);const i=d4(t.annotations,"#(malloy) ").text("query_name")??"root",s=new Lue({name:i,type:{kind:"array_type",element_type:{kind:"record_type",fields:e}},annotations:t.annotations},{modelTag:d4(t.model_annotations,"## "),queryTimezone:t.query_timezone}),o=t.data.kind==="record_cell"?{kind:"array_cell",array_value:[t.data]}:t.data;return new kYe(o,s)}function bYe(t){return t.type.kind==="array_type"}function TYe(t){return t.type.kind==="array_type"&&t.type.element_type.kind==="record_type"}function RYe(t){return t.type.kind==="record_type"}function DYe(t){return t.type.kind==="number_type"}function OYe(t){return t.type.kind==="date_type"}function FYe(t){return t.type.kind==="json_type"}function wYe(t){return t.type.kind==="string_type"}function NYe(t){return t.type.kind==="timestamp_type"}function LYe(t){return t.type.kind==="boolean_type"}function IYe(t){return t.type.kind==="sql_native_type"}const Mp={from(t,e){if(TYe(t))return new Up(t,e);if(bYe(t))return new Pp(t,e);if(RYe(t))return new Ty(t,e);if(LYe(t))return new A4(t,e);if(FYe(t))return new E4(t,e);if(OYe(t))return new p4(t,e);if(NYe(t))return new m4(t,e);if(wYe(t))return new g4(t,e);if(DYe(t))return new h4(t,e);if(IYe(t))return new y4(t,e);throw new Error(`Unknown field type ${t.type.kind}`)},isNestField(t){return t instanceof Up||t instanceof Pp||t instanceof Ty},pathFromString(t){return JSON.parse(t)},pathToString(t){return JSON.stringify(t)}};function C$(t,e="# "){return d4(t.annotations,e)}const $Ye=["link","image","cell","list","list_detail","bar_chart","line_chart","dashboard","scatter_chart","shape_map","segment_map"];function BYe(t,e,r){const i=C$(t),s=Object.keys(i.properties??{}).reverse();for(const u of s)if($Ye.includes(u))return["list","list_detail"].includes(u)?"list":["bar_chart","line_chart"].includes(u)?"chart":u;return t.type.kind==="record_type"&&(e==null?void 0:e.renderAs)==="chart"?"none":t.type.kind==="array_type"||t.type.kind==="record_type"?"table":"cell"}class Gl{constructor(e,r){this.field=e,this.parent=r,this.valueSet=new Set,this.tag=C$(this.field),this.metadataTag=C$(this.field,"#(malloy) "),this.path=r?r.isArray()?[...r.path]:[...r.path,e.name]:[],this.renderAs=BYe(e,r)}isRoot(){return this.path.length===0}root(){if(this.parent)return this.parent.root();if(this instanceof Lue)return this;throw new Error("Root field was not an instance of RootField")}get sourceName(){return this.metadataTag.text("source_name")??"__source__"}get name(){return this.field.name}fieldAt(e){return typeof e=="string"?this.fieldAtPath(Mp.pathFromString(e)):this.fieldAtPath(e)}getParentRecord(e){let r=this.asField();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}get key(){return Mp.pathToString(this.path)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error(`${this.constructor.name} cannot contain fields`)}registerNullValue(){this.valueSet.add(vYe)}get drillFilters(){return this.metadataTag.textArray("drill_filters")??[]}get referenceId(){return this.metadataTag.text("reference_id")}escapeIdentifier(e){return e.replace(/\\/g,"\\\\").replace("`","\\`")}identifierCode(){return this.name.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?this.name:`\`${this.escapeIdentifier(this.name)}\``}drillExpression(){return this.metadataTag.text("drill_expression")??this.identifierCode()}wasDimension(){return!this.wasCalculation()}wasCalculation(){return this.metadataTag.has("calculation")}isHidden(){return this.tag.has("hidden")}get minNumber(){}get maxNumber(){}get maxString(){}asField(){if(this instanceof Pp||this instanceof Up||this instanceof Ty||this instanceof h4||this instanceof p4||this instanceof E4||this instanceof g4||this instanceof m4||this instanceof A4||this instanceof y4)return this;throw new Error("Not a field")}isArray(){return this instanceof Pp}isRepeatedRecord(){return this instanceof Up}isRecord(){return this instanceof Ty}isNumber(){return this instanceof h4}isBoolean(){return this instanceof A4}isString(){return this instanceof g4}isRecordOrRepeatedRecord(){return this.isRecord()||this.isRepeatedRecord()}isDate(){return this instanceof p4}isTimestamp(){return this instanceof m4}isTime(){return this.isDate()||this.isTimestamp()}isSQLNative(){return this instanceof y4}isJSON(){return this instanceof E4}isBasic(){return!this.isNest()}isNest(){return this.isArray()||this.isRecord()||this.isRepeatedRecord()}getLocationInParent(){var e;return((e=this.parent)==null?void 0:e.fields.findIndex(r=>r===this))??-1}isLastChild(){const e=this.parent;return e===void 0||this.getLocationInParent()===e.fields.length}isFirstChild(){return this.getLocationInParent()===0}pathTo(e){const r=this.path,i=e.path,s=r.length;let o=0;for(;r[o];){if(r[o]!==i[o])throw new Error("Tried to get path from parent field to child field, but parent field is not a parent of child field.");o++}return Mp.pathToString(i.slice(s))}}class Pp extends Gl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this.eachField=Mp.from({name:"each",type:this.field.type.element_type},this),this.fields=[this.eachField]}}class Up extends Pp{constructor(e,r){super(e,r),this.field=e,this.maxRecordCount=0,this._fieldsWithOrder=void 0;const i=this.eachField;if(!i.isRecord())throw new Error("Expected eachField of repeatedRecord to be a record");this.fields=i.fields}fieldAtPath(e){return e.length===0?this.asField():this.eachField.fieldAtPath(e)}registerRecordCount(e){this.maxRecordCount=Math.max(e,this.maxRecordCount)}registerValueSetSize(e,r){this.maxUniqueFieldValueCounts.set(e,Math.max(this.maxUniqueFieldValueCounts.get(e)??0,r))}get fieldsWithOrder(){var e;if(!this._fieldsWithOrder){const r=this.metadataTag.tag("ordered_by"),i=(r&&((e=r.array())==null?void 0:e.map(o=>{const u=Object.keys(o.properties??{})[0],a=o.text(u);return{field:this.fieldAt(u),dir:a}})))??[],s=new Set(i.map(o=>o.field.name));this._fieldsWithOrder=[...i,...this.fields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._fieldsWithOrder}}class Lue extends Up{constructor(e,r){super(e,void 0),this.field=e,this.modelTag=r.modelTag,this.queryTimezone=r.queryTimezone}}class Ty extends Gl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this._fieldsWithOrder=void 0,this.fields=e.type.fields.map(i=>Mp.from(i,this)),this.fieldsByName=Object.fromEntries(this.fields.map(i=>[i.name,i]))}fieldAtPath(e){if(e.length===0)return this.asField();{const[r,...i]=e,s=this.fieldsByName[r];if(s===void 0)throw new Error(`No such field ${r} in ${this.path}`);return s.fieldAtPath(i)}}get fieldsWithOrder(){return this._fieldsWithOrder===void 0&&(this._fieldsWithOrder=[...this.fields.map(e=>({field:e,dir:"asc"}))]),this._fieldsWithOrder}}let h4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const r=e.toString();(this._maxString===void 0||r.length>this._maxString.length)&&(this._maxString=r)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error("NumberField cannot contain fields")}get minNumber(){return this.min}get maxNumber(){return this.max}get maxString(){return this._maxString}},p4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=v$(e,!0,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}get minNumber(){return this.min!==void 0?Number(this.min):void 0}get maxNumber(){return this.max!==void 0?Number(this.max):void 0}},m4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=v$(e,!1,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}},g4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e),(this._maxString===void 0||e.length>this._maxString.length)&&(this._maxString=e)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}};class y4 extends Gl{constructor(e,r){super(e,r),this.field=e}}let E4=class extends Gl{constructor(e,r){super(e,r),this.field=e}},A4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this._maxString=void 0}get maxString(){return this._maxString}registerValue(e){this.valueSet.add(e);const r=String(e);(this._maxString===void 0||this._maxString.length<r.length)&&(this._maxString=r)}};const Iue={from(t,e,r){switch(t.kind){case"array_cell":{if(e instanceof Up)return new v4(t,e,r);if(e instanceof Pp)return new _4(t,e,r);throw new Error("Expected record data to be associated with record field")}case"record_cell":{if(e instanceof Ty)return new S$(t,e,r);throw new Error("Expected record data to be associated with record field")}case"null_cell":return new b$(t,e,r);case"number_cell":{if(e instanceof h4)return new T$(t,e,r);throw new Error("Expected number data to be associated with number field")}case"date_cell":{if(e instanceof p4)return new R$(t,e,r);throw new Error("Expected date data to be associated with date field")}case"json_cell":{if(e instanceof E4)return new O$(t,e,r);throw new Error("Expected JSON data to be associated with JSON field")}case"string_cell":{if(e instanceof g4)return new F$(t,e,r);throw new Error("Expected string data to be associated with string field")}case"timestamp_cell":{if(e instanceof m4)return new D$(t,e,r);throw new Error("Expected timestamp data to be associated with timestamp field")}case"boolean_cell":{if(e instanceof A4)return new w$(t,e,r);throw new Error("Expected boolean data to be associated with boolean field")}case"sql_native_cell":{if(e instanceof y4)return new $ue(t,e,r);throw new Error("Expected sql_native data to be associated with sql_native field")}}}};class va{constructor(e,r,i){this.cell=e,this.field=r,this.parent=i}isNull(){return this instanceof b$}isArray(){return this instanceof _4}isRecord(){return this instanceof S$}isRepeatedRecord(){return this instanceof v4}isRecordOrRepeatedRecord(){return this.isRepeatedRecord()||this.isRecord()}isNest(){return this.isRepeatedRecord()||this.isRecord()||this.isArray()}isNumber(){return this instanceof T$}isDate(){return this instanceof R$}isTime(){return this.isDate()||this.isTimestamp()}isJSON(){return this instanceof O$}isString(){return this instanceof F$}isTimestamp(){return this instanceof D$}isBoolean(){return this instanceof w$}asCell(){if(this instanceof _4||this instanceof v4||this instanceof S$||this instanceof T$||this instanceof R$||this instanceof O$||this instanceof F$||this instanceof D$||this instanceof w$||this instanceof b$||this instanceof $ue)return this;throw new Error("Not a cell")}root(){return this.parent?this.parent.root():this.asCell()}getPathInfo(e){const r=e.split("/"),i=r.filter(o=>o==="..").length+1,s=r.filter(o=>o!==".."&&o!=="");return{levelsUp:i,pathSegments:s}}getParentRecord(e){let r=this.asCell();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}getRelativeCell(e){try{const{levelsUp:r,pathSegments:i}=this.getPathInfo(e);return this.getParentRecord(r).cellAtPath(i)}catch{return}}cellAt(e){return typeof e=="string"?this.cellAtPath(Mp.pathFromString(e)):this.cellAtPath(e)}cellAtPath(e){if(e.length===0)return this.asCell();throw new Error(`${this.constructor.name} cannot contain columns`)}compareTo(e){return 0}getDrillValues(){let e=this.asCell();const r=[];for(;e&&(e&&e.isArray()&&(r.unshift(...e.field.drillFilters.map(i=>({where:i}))),e=e.parent),e!==void 0);){if(e&&e.isRecord()){const i=e,s=e.field.fields.filter(o=>o.isBasic()&&o.wasDimension());r.unshift(...s.map(o=>({field:o,value:i.column(o.name)})))}e=e.parent}return r}getDrillExpressions(){return this.getDrillValues().map(r=>{if("where"in r)return r.where;const i=SYe(r.value);return`${r.field.drillExpression()} = ${i}`})}getDrillEntries(){const e=this.getDrillValues(),r=[];for(const i of e)"where"in i?r.push(i):(i.value.isNull()||i.value.isTime()||i.value.isString()||i.value.isNumber()||i.value.isBoolean())&&r.push({field:i.field,value:i.value.value});return r}getDrillQuery(){const e=this.getDrillExpressions();let r=`run: ${this.field.root().sourceName} ->`;return e.length>0&&(r+=` {
740
+ `,r}find(e){var r;let i=At.tagFrom(this);for(const s of e)if(typeof s=="number"){if(i.eq===void 0||!Array.isArray(i.eq)||i.eq.length<=s)return;i=At.tagFrom(i.eq[s])}else{const o=(r=i.properties)!==null&&r!==void 0?r:{};if(s in o)i=At.tagFrom(o[s]);else return}return i.deleted?void 0:i}has(...e){return this.find(e)!==void 0}set(e,r=null){const i=At.tagFrom(this);let s=i;for(const o of e)if(typeof o=="number"){if(s.eq===void 0||!Array.isArray(s.eq))s.eq=Array.from({length:o+1}).map(u=>({}));else if(s.eq.length<=o){const u=s.eq,a=Array.from({length:o+1}).map((l,c)=>c<u.length?u[c]:{});s.eq=a}s=s.eq[o]}else{const u=s.properties;u===void 0?(s.properties={[o]:{}},s=s.properties[o]):o in u?(s=u[o],s.deleted&&(s.deleted=!1)):(u[o]={},s=u[o])}return r===null?s.eq=void 0:typeof r=="string"?s.eq=r:typeof r=="number"?s.eq=r.toString():Array.isArray(r)&&(s.eq=r.map(o=>({eq:typeof o=="string"?o:o.toString()}))),i}delete(...e){return this.remove(e,!1)}unset(...e){return this.remove(e,!0)}remove(e,r=!1){var i;const s=At.tagFrom(this);let o=s;for(const a of e.slice(0,e.length-1))if(typeof a=="number"){if(o.eq===void 0||!Array.isArray(o.eq)){if(!r)return s;o.eq=Array.from({length:a}).map(l=>({}))}else if(o.eq.length<=a){if(!r)return s;const l=o.eq,c=Array.from({length:a}).map((f,x)=>x<l.length?l[x]:{});o.eq=c}o=o.eq[a]}else{const l=o.properties;if(l===void 0){if(!r)return s;o.properties={[a]:{}},o=o.properties[a]}else if(a in l)o=l[a];else{if(!r)return s;l[a]={},o=l[a]}}const u=e[e.length-1];return typeof u=="string"?o.properties&&u in o.properties?delete o.properties[u]:r&&((i=o.properties)!==null&&i!==void 0||(o.properties={}),o.properties[u]={deleted:!0}):Array.isArray(o.eq)&&o.eq.splice(u,1),s}}zS.Tag=At,At.ids=new Map,At.nextTagId=1e3;class AYe{constructor(e){this.line=e,this.log=[]}syntaxError(e,r,i,s,o,u){const a={code:"tag-parse-syntax-error",message:o,line:this.line,offset:s};this.log.push(a)}semanticError(e,r,i){const s={code:r,message:i,line:this.line,offset:e.start.charPositionInLine};this.log.push(s)}}function Sy(t){const e=t.buildOn;return e instanceof At?e:new At}function x4(t,e){var r,i;let s=t.getProperties();for(const o of e.slice(0,e.length-1)){let u;s[o]===void 0?(u=new At({}),s[o]=u):((r=(i=s[o]).properties)!==null&&r!==void 0||(i.properties={}),u=At.tagFrom(s[o])),s=u.getProperties()}return[e[e.length-1],s]}function Fue(t){return t.SQ_STRING()||t.DQ_STRING()?(0,Oue.parseString)(t.text,t.text[0]):t.text}function wue(t,e,r,i){if(t[0]==="#"){const h=t.indexOf(" ");h>0?t=t.slice(h):t=""}const s=Due.CharStreams.fromString(t),o=new yYe.MalloyTagLexer(s),u=new Due.CommonTokenStream(o),a=new AYe(i),l=new EYe.MalloyTagParser(u);l.removeErrorListeners(),l.addErrorListener(a);const c=l.tagLine();return{tag:new _Ye(r,a).tagLineToTag(c,e),log:a.log}}class _Ye extends gYe.AbstractParseTreeVisitor{constructor(e=[],r){super(),this.scopes=[],this.msgLog=r,this.scopes.unshift(...e)}defaultResult(){return new At}visitString(e){return new At({eq:Fue(e)})}getPropName(e){return e.identifier().map(r=>r.BARE_STRING()?r.text:(0,Oue.parseString)(r.text,r.text[0]))}getTags(e,r){for(const i of e)i.buildOn=r,this.visit(i);return r}tagLineToTag(e,r){return r=(r==null?void 0:r.clone())||new At({}),this.scopes.unshift(r),this.getTags(e.tagSpec(),r),r}visitTagLine(e){throw new Error("INTERNAL: ERROR: Call tagLineToTag, not vistTagLine")}visitProperties(e){return this.getTags(e.tagSpec(),Sy(e))}visitArrayValue(e){return new At({eq:this.getArray(e)})}getArray(e){return e.arrayElement().map(r=>this.visit(r))}visitArrayElement(e){const r=e.properties(),i=r?this.visitProperties(r):void 0,s=e.string();let o=s?Fue(s):void 0;const u=e.arrayValue();if(u&&(o=this.getArray(u)),i)return o!==void 0&&(i.eq=o),i;const a=e.reference();return a?this.visitReference(a):new At({eq:o})}visitReference(e){const r=this.getPropName(e.propName());for(const i of this.scopes)if(i.has(r[0])){const s=i.tag(...r);if(s)return s.clone();break}return this.msgLog.semanticError(e,"tag-property-not-found",`Reference to undefined property ${r.join(".")}`),this.defaultResult()}visitTagEq(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i),u=this.visit(e.eqValue()),a=e.properties();if(a)if(a.DOTTY()===void 0){const l=this.visitProperties(a).dict;o[s]={...u,properties:l}}else o[s]={...o[s],...u};else o[s]=u;return r}visitTagReplaceProperties(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i),u=e.properties(),a=this.visitProperties(u);return e.DOTTY()===void 0?o[s]={properties:a.dict}:o[s].properties=a.dict,r}visitTagUpdateProperties(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i),u=e.properties();u.buildOn=At.tagFrom(o[s]);const a=this.visitProperties(u),l=o[s]||new At({}),c={...l.properties,...a.dict};return o[s]={...l,properties:c},r}visitTagDef(e){const r=Sy(e),i=this.getPropName(e.propName()),[s,o]=x4(r,i);return e.MINUS()?o[s]={deleted:!0}:o[s]=new At({}),r}visitTagEmpty(e){const r=e.buildOn;return r.properties={},r}}(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.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)},s=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};Object.defineProperty(t,"__esModule",{value:!0}),t.ParseUtil=void 0,i(zS,t),t.ParseUtil=s(Cy)})(tu);const vYe="∅";function d4(t,e="# "){var i;const r=((i=t==null?void 0:t.map(s=>s.value))==null?void 0:i.filter(s=>s.startsWith(e)))??[];return tu.Tag.fromTagLines(r).tag??new tu.Tag}Bt.Nanoseconds,Bt.Microseconds,Bt.Milliseconds,Bt.Seconds,Bt.Minutes,Bt.Hours,Bt.Days,Bt.Nanoseconds,Bt.Microseconds,Bt.Milliseconds,Bt.Seconds,Bt.Minutes,Bt.Hours,Bt.Days,Number.MAX_VALUE;function by(t,e=2){return`${"0".repeat(e-1)}${t}`.slice(-e)}function v$(t,e,r){const i=t.getUTCFullYear(),s=by(t.getUTCMonth()+1),o=by(t.getUTCDate()),u=by(t.getUTCHours()),a=by(t.getUTCMinutes()),l=by(t.getUTCSeconds()),c=`${u}:${a}:${l}`,f=`${i}-${s}-${o}`;switch(r){case"minute":return`${f} ${u}:${a}`;case"hour":return`${f} ${u}`;case"day":return`${f}`;case"week":return`${f}-WK`;case"month":return`${i}-${s}`;case"quarter":return`${i}-Q${Math.floor(t.getUTCMonth()/3)+1}`;case"year":return t.getUTCFullYear().toString();default:return e?f:`${f} ${c}`}}function CYe(t){return`'${t.replace(/(['\\])/g,"\\$1")}'`}function SYe(t){return t.isNull()?"null":t.isString()?CYe(t.value):t.isNumber()||t.isBoolean()?t.value.toString():t.isTime()?"@"+v$(t.value,t.isDate(),t.field.timeframe):"invalid_drill_literal()"}function Nue(t){const e=[];for(const a of t.schema.fields)a.kind==="dimension"&&e.push(a);const i=d4(t.annotations,"#(malloy) ").text("query_name")??"root",s=new Lue({name:i,type:{kind:"array_type",element_type:{kind:"record_type",fields:e}},annotations:t.annotations},{modelTag:d4(t.model_annotations,"## "),queryTimezone:t.query_timezone}),o=t.data.kind==="record_cell"?{kind:"array_cell",array_value:[t.data]}:t.data;return new kYe(o,s)}function bYe(t){return t.type.kind==="array_type"}function TYe(t){return t.type.kind==="array_type"&&t.type.element_type.kind==="record_type"}function RYe(t){return t.type.kind==="record_type"}function DYe(t){return t.type.kind==="number_type"}function OYe(t){return t.type.kind==="date_type"}function FYe(t){return t.type.kind==="json_type"}function wYe(t){return t.type.kind==="string_type"}function NYe(t){return t.type.kind==="timestamp_type"}function LYe(t){return t.type.kind==="boolean_type"}function IYe(t){return t.type.kind==="sql_native_type"}const Mp={from(t,e){if(TYe(t))return new Up(t,e);if(bYe(t))return new Pp(t,e);if(RYe(t))return new Ty(t,e);if(LYe(t))return new A4(t,e);if(FYe(t))return new E4(t,e);if(OYe(t))return new p4(t,e);if(NYe(t))return new m4(t,e);if(wYe(t))return new g4(t,e);if(DYe(t))return new h4(t,e);if(IYe(t))return new y4(t,e);throw new Error(`Unknown field type ${t.type.kind}`)},isNestField(t){return t instanceof Up||t instanceof Pp||t instanceof Ty},pathFromString(t){return JSON.parse(t)},pathToString(t){return JSON.stringify(t)}};function C$(t,e="# "){return d4(t.annotations,e)}const $Ye=["link","image","cell","list","list_detail","bar_chart","line_chart","dashboard","scatter_chart","shape_map","segment_map"];function BYe(t,e,r){const i=C$(t),s=Object.keys(i.properties??{}).reverse();for(const u of s)if($Ye.includes(u))return["list","list_detail"].includes(u)?"list":["bar_chart","line_chart"].includes(u)?"chart":u;return t.type.kind==="record_type"&&(e==null?void 0:e.renderAs)==="chart"?"none":t.type.kind==="array_type"||t.type.kind==="record_type"?"table":"cell"}class Gl{constructor(e,r){this.field=e,this.parent=r,this.valueSet=new Set,this.tag=C$(this.field),this.metadataTag=C$(this.field,"#(malloy) "),this.path=r?r.isArray()?[...r.path]:[...r.path,e.name]:[],this.renderAs=BYe(e,r)}isRoot(){return this.path.length===0}root(){if(this.parent)return this.parent.root();if(this instanceof Lue)return this;throw new Error("Root field was not an instance of RootField")}get sourceName(){return this.metadataTag.text("source_name")??"__source__"}get name(){return this.field.name}fieldAt(e){return typeof e=="string"?this.fieldAtPath(Mp.pathFromString(e)):this.fieldAtPath(e)}getParentRecord(e){let r=this.asField();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}get key(){return Mp.pathToString(this.path)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error(`${this.constructor.name} cannot contain fields`)}registerNullValue(){this.valueSet.add(vYe)}get drillFilters(){return this.metadataTag.textArray("drill_filters")??[]}get referenceId(){return this.metadataTag.text("reference_id")}escapeIdentifier(e){return e.replace(/\\/g,"\\\\").replace("`","\\`")}identifierCode(){return this.name.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?this.name:`\`${this.escapeIdentifier(this.name)}\``}drillExpression(){return this.metadataTag.text("drill_expression")??this.identifierCode()}wasDimension(){return!this.wasCalculation()}wasCalculation(){return this.metadataTag.has("calculation")}isHidden(){return this.tag.has("hidden")}get minNumber(){}get maxNumber(){}get maxString(){}asField(){if(this instanceof Pp||this instanceof Up||this instanceof Ty||this instanceof h4||this instanceof p4||this instanceof E4||this instanceof g4||this instanceof m4||this instanceof A4||this instanceof y4)return this;throw new Error("Not a field")}isArray(){return this instanceof Pp}isRepeatedRecord(){return this instanceof Up}isRecord(){return this instanceof Ty}isNumber(){return this instanceof h4}isBoolean(){return this instanceof A4}isString(){return this instanceof g4}isRecordOrRepeatedRecord(){return this.isRecord()||this.isRepeatedRecord()}isDate(){return this instanceof p4}isTimestamp(){return this instanceof m4}isTime(){return this.isDate()||this.isTimestamp()}isSQLNative(){return this instanceof y4}isJSON(){return this instanceof E4}isBasic(){return!this.isNest()}isNest(){return this.isArray()||this.isRecord()||this.isRepeatedRecord()}getLocationInParent(){var e;return((e=this.parent)==null?void 0:e.fields.findIndex(r=>r===this))??-1}isLastChild(){const e=this.parent;return e===void 0||this.getLocationInParent()===e.fields.length}isFirstChild(){return this.getLocationInParent()===0}pathTo(e){const r=this.path,i=e.path,s=r.length;let o=0;for(;r[o];){if(r[o]!==i[o])throw new Error("Tried to get path from parent field to child field, but parent field is not a parent of child field.");o++}return Mp.pathToString(i.slice(s))}}class Pp extends Gl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this.eachField=Mp.from({name:"each",type:this.field.type.element_type},this),this.fields=[this.eachField]}}class Up extends Pp{constructor(e,r){super(e,r),this.field=e,this.maxRecordCount=0,this._fieldsWithOrder=void 0;const i=this.eachField;if(!i.isRecord())throw new Error("Expected eachField of repeatedRecord to be a record");this.fields=i.fields}fieldAtPath(e){return e.length===0?this.asField():this.eachField.fieldAtPath(e)}registerRecordCount(e){this.maxRecordCount=Math.max(e,this.maxRecordCount)}registerValueSetSize(e,r){this.maxUniqueFieldValueCounts.set(e,Math.max(this.maxUniqueFieldValueCounts.get(e)??0,r))}get fieldsWithOrder(){var e;if(!this._fieldsWithOrder){const r=this.metadataTag.tag("ordered_by"),i=(r&&((e=r.array())==null?void 0:e.map(o=>{const u=Object.keys(o.properties??{})[0],a=o.text(u);return{field:this.fieldAt(u),dir:a}})))??[],s=new Set(i.map(o=>o.field.name));this._fieldsWithOrder=[...i,...this.fields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._fieldsWithOrder}}class Lue extends Up{constructor(e,r){super(e,void 0),this.field=e,this.modelTag=r.modelTag,this.queryTimezone=r.queryTimezone}}class Ty extends Gl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this._fieldsWithOrder=void 0,this.fields=e.type.fields.map(i=>Mp.from(i,this)),this.fieldsByName=Object.fromEntries(this.fields.map(i=>[i.name,i]))}fieldAtPath(e){if(e.length===0)return this.asField();{const[r,...i]=e,s=this.fieldsByName[r];if(s===void 0)throw new Error(`No such field ${r} in ${this.path}`);return s.fieldAtPath(i)}}get fieldsWithOrder(){return this._fieldsWithOrder===void 0&&(this._fieldsWithOrder=[...this.fields.map(e=>({field:e,dir:"asc"}))]),this._fieldsWithOrder}}let h4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const r=e.toString();(this._maxString===void 0||r.length>this._maxString.length)&&(this._maxString=r)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error("NumberField cannot contain fields")}get minNumber(){return this.min}get maxNumber(){return this.max}get maxString(){return this._maxString}},p4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=v$(e,!0,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}get minNumber(){return this.min!==void 0?Number(this.min):void 0}get maxNumber(){return this.max!==void 0?Number(this.max):void 0}},m4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=v$(e,!1,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}},g4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e),(this._maxString===void 0||e.length>this._maxString.length)&&(this._maxString=e)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}};class y4 extends Gl{constructor(e,r){super(e,r),this.field=e}}let E4=class extends Gl{constructor(e,r){super(e,r),this.field=e}},A4=class extends Gl{constructor(e,r){super(e,r),this.field=e,this._maxString=void 0}get maxString(){return this._maxString}registerValue(e){this.valueSet.add(e);const r=String(e);(this._maxString===void 0||this._maxString.length<r.length)&&(this._maxString=r)}};const Iue={from(t,e,r){switch(t.kind){case"array_cell":{if(e instanceof Up)return new v4(t,e,r);if(e instanceof Pp)return new _4(t,e,r);throw new Error("Expected record data to be associated with record field")}case"record_cell":{if(e instanceof Ty)return new S$(t,e,r);throw new Error("Expected record data to be associated with record field")}case"null_cell":return new b$(t,e,r);case"number_cell":{if(e instanceof h4)return new T$(t,e,r);throw new Error("Expected number data to be associated with number field")}case"date_cell":{if(e instanceof p4)return new R$(t,e,r);throw new Error("Expected date data to be associated with date field")}case"json_cell":{if(e instanceof E4)return new O$(t,e,r);throw new Error("Expected JSON data to be associated with JSON field")}case"string_cell":{if(e instanceof g4)return new F$(t,e,r);throw new Error("Expected string data to be associated with string field")}case"timestamp_cell":{if(e instanceof m4)return new D$(t,e,r);throw new Error("Expected timestamp data to be associated with timestamp field")}case"boolean_cell":{if(e instanceof A4)return new w$(t,e,r);throw new Error("Expected boolean data to be associated with boolean field")}case"sql_native_cell":{if(e instanceof y4)return new $ue(t,e,r);throw new Error("Expected sql_native data to be associated with sql_native field")}}}};class va{constructor(e,r,i){this.cell=e,this.field=r,this.parent=i}isNull(){return this instanceof b$}isArray(){return this instanceof _4}isRecord(){return this instanceof S$}isRepeatedRecord(){return this instanceof v4}isRecordOrRepeatedRecord(){return this.isRepeatedRecord()||this.isRecord()}isNest(){return this.isRepeatedRecord()||this.isRecord()||this.isArray()}isNumber(){return this instanceof T$}isDate(){return this instanceof R$}isTime(){return this.isDate()||this.isTimestamp()}isJSON(){return this instanceof O$}isString(){return this instanceof F$}isTimestamp(){return this instanceof D$}isBoolean(){return this instanceof w$}asCell(){if(this instanceof _4||this instanceof v4||this instanceof S$||this instanceof T$||this instanceof R$||this instanceof O$||this instanceof F$||this instanceof D$||this instanceof w$||this instanceof b$||this instanceof $ue)return this;throw new Error("Not a cell")}root(){return this.parent?this.parent.root():this.asCell()}getPathInfo(e){const r=e.split("/"),i=r.filter(o=>o==="..").length+1,s=r.filter(o=>o!==".."&&o!=="");return{levelsUp:i,pathSegments:s}}getParentRecord(e){let r=this.asCell();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}getRelativeCell(e){try{const{levelsUp:r,pathSegments:i}=this.getPathInfo(e);return this.getParentRecord(r).cellAtPath(i)}catch{return}}cellAt(e){return typeof e=="string"?this.cellAtPath(Mp.pathFromString(e)):this.cellAtPath(e)}cellAtPath(e){if(e.length===0)return this.asCell();throw new Error(`${this.constructor.name} cannot contain columns`)}compareTo(e){return 0}getDrillValues(){let e=this.asCell();const r=[];for(;e&&(e&&e.isArray()&&(r.unshift(...e.field.drillFilters.map(i=>({where:i}))),e=e.parent),e!==void 0);){if(e&&e.isRecord()){const i=e,s=e.field.fields.filter(o=>o.isBasic()&&o.wasDimension());r.unshift(...s.map(o=>({field:o,value:i.column(o.name)})))}e=e.parent}return r}getDrillExpressions(){return this.getDrillValues().map(r=>{if("where"in r)return r.where;const i=SYe(r.value);return`${r.field.drillExpression()} = ${i}`})}getDrillEntries(){const e=this.getDrillValues(),r=[];for(const i of e)"where"in i?r.push(i):(i.value.isNull()||i.value.isTime()||i.value.isString()||i.value.isNumber()||i.value.isBoolean())&&r.push({field:i.field,value:i.value.value});return r}getDrillQuery(){const e=this.getDrillExpressions();let r=`run: ${this.field.root().sourceName} ->`;return e.length>0&&(r+=` {
741
741
  where:
742
742
  ${e.map(i=>` ${i}`).join(`,
743
743
  `)}
@@ -1470,7 +1470,7 @@ yzz{{||}}~~Ӂ
1470
1470
  | ${c}`,a>0&&(s=s+`
1471
1471
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1472
1472
  `+s,r=o),e!==""?e=`${e}
1473
- ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,gxt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,eP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,eP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=tP;class vxe extends tP{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=vxe;class Mxt extends tP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new ZM.Zone,this.importZone=new ZM.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new ZM.Zone,this.root=this,this.logger=new _xe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,_xe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=Mxt;function Cxe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Cxe(t[e])).flat()]}var L2={};Object.defineProperty(L2,"__esModule",{value:!0}),L2.exploreQueryWalkerBuilder=L2.ExploreQueryWalker=void 0;const Pxt=ac;class Sxe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}L2.ExploreQueryWalker=Sxe;function Uxt(t,e){const r=new Sxe(t),i=r;return Pxt.ParseTreeWalker.DEFAULT.walk(i,e),r}L2.exploreQueryWalkerBuilder=Uxt;var I2={},TE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const $a=Mi,nP=Ls,rP=si,bxe=tu;function jxt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,$a.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,$a.isAtomic)(a)?{name:u,type:$R(a),default_value:Txe(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Txe(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:$2(i,i.fields)},parameters:s,annotations:iP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,nP.getResultStructDefForQuery)(t,i),o=iP(i),u=s.resultMetadata?IR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:$2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,nP.getResultStructDefForQuery)(t,r),s=iP(r),o=i.resultMetadata?IR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:$2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=jxt;function Txe(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function iP(t){return(0,rP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function $2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,rP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,$a.isTurtle)(u)){const x=(0,nP.getResultStructDefForView)(t,u),h=x.resultMetadata?IR(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:$2(x,x.fields)}};o.push(m)}else if((0,$a.isAtomic)(u)){const x=(0,$a.expressionIsAggregate)(u.expressionType),h=(0,$a.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?Rxe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:$R(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,$a.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:$2(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ia.convertFieldInfos=$2;function Rxe(t,e){const r=bxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Hxt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function qxt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Hxt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${qxt(t)}\``}function IR(t,e){var r,i;const s=bxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=IR;function $R(t){if((0,$a.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Qxt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:zxt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,$a.isRepeatedRecord)(t))return{kind:"array_type",element_type:Dxe(t)};if(t.type==="record")return Dxe(t);if(t.type==="array")return{kind:"array_type",element_type:$R(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Dxe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Rxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,rP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,$a.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:$R(e)};throw new Error("Expected record type to not have a table as its child")})}}function Qxt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function zxt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function apt(t){return t}function lpt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=tu,r=si,i=Ia,s=Ny;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(y,E){const A=[];for(const _ of E.schema.fields){const v=y[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const g={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(TE);var Gxt=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]}),Wxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vxt=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)&&Gxt(e,t,r);return Wxt(e,t),e};Object.defineProperty(I2,"__esModule",{value:!0}),I2.malloyToQuery=I2.MalloyToQuery=void 0;const Yxt=ep,Dn=Vxt(w),Oxe=Xp,RE=In,Kxt=Ke,Jxt=yE,Fxe=Vn,Xxt=TE,sP="Malloy query documents";class wxe extends Yxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Fxe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Oxe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${sP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${sP} may only have one run statement`);return i===void 0?(this.illegal(e,`${sP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,RE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Dn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Dn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Dn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Dn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Dn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Dn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Dn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Dn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Dn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Dn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Dn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Dn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Dn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,RE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Dn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,RE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Dn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Dn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,RE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Kxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,RE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Dn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Dn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Dn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Dn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Dn.ExprFieldPathContext&&i instanceof Dn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Dn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}I2.MalloyToQuery=wxe;function Zxt(t){const e=(0,Fxe.getSourceInfo)(t),r=new Oxe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Jxt.runMalloyParser)(t,i,e,r),u=new wxe(s,r).visit(s.root),a=(0,Xxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}I2.malloyToQuery=Zxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=L2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=I2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Z4);var we={},BR={};Object.defineProperty(BR,"__esModule",{value:!0}),BR.MALLOY_VERSION=void 0,BR.MALLOY_VERSION="0.0.276",Object.defineProperty(we,"__esModule",{value:!0}),we.InMemoryModelCache=we.CacheManager=we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const Nxe=Z4,ai=Mi,Lxe=Ny,oP=jp,edt=BR,tdt=Hp,$n=si,ndt=Kl,rdt=Vn,idt=gE,Ixe="internal://internal.malloy";let r0=class wD{static get version(){return edt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(Ixe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Nxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Bxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return wD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return QR(r,e).then(({contents:u,invalidationKey:a})=>wD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(Ixe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new B2(C.modelDef,[],[e.toString(),...HR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await EP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await QR(s,e);A[v]=b,r=C}else{const C=await EP(s,e);A[v]=C}_=new Nxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new B2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new B2(S,C.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=C.fromSources)!==null&&y!==void 0?y:[]])}else{const b=C.problems||[],S=_.prettyErrors();throw new $xe(`Error(s) compiling model:
1473
+ ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,gxt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,eP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,eP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=tP;class vxe extends tP{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=vxe;class Mxt extends tP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new ZM.Zone,this.importZone=new ZM.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new ZM.Zone,this.root=this,this.logger=new _xe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,_xe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=Mxt;function Cxe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Cxe(t[e])).flat()]}var L2={};Object.defineProperty(L2,"__esModule",{value:!0}),L2.exploreQueryWalkerBuilder=L2.ExploreQueryWalker=void 0;const Pxt=ac;class Sxe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}L2.ExploreQueryWalker=Sxe;function Uxt(t,e){const r=new Sxe(t),i=r;return Pxt.ParseTreeWalker.DEFAULT.walk(i,e),r}L2.exploreQueryWalkerBuilder=Uxt;var I2={},TE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const $a=Mi,nP=Ls,rP=si,bxe=tu;function jxt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,$a.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,$a.isAtomic)(a)?{name:u,type:$R(a),default_value:Txe(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Txe(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:$2(i,i.fields)},parameters:s,annotations:iP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,nP.getResultStructDefForQuery)(t,i),o=iP(i),u=s.resultMetadata?IR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:$2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,nP.getResultStructDefForQuery)(t,r),s=iP(r),o=i.resultMetadata?IR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:$2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=jxt;function Txe(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function iP(t){return(0,rP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function $2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,rP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,$a.isTurtle)(u)){const x=(0,nP.getResultStructDefForView)(t,u),h=x.resultMetadata?IR(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:$2(x,x.fields)}};o.push(m)}else if((0,$a.isAtomic)(u)){const x=(0,$a.expressionIsAggregate)(u.expressionType),h=(0,$a.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?Rxe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:$R(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,$a.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:$2(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ia.convertFieldInfos=$2;function Rxe(t,e){const r=bxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Hxt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function qxt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Hxt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${qxt(t)}\``}function IR(t,e){var r,i;const s=bxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=IR;function $R(t){if((0,$a.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Qxt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:zxt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,$a.isRepeatedRecord)(t))return{kind:"array_type",element_type:Dxe(t)};if(t.type==="record")return Dxe(t);if(t.type==="array")return{kind:"array_type",element_type:$R(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Dxe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Rxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,rP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,$a.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:$R(e)};throw new Error("Expected record type to not have a table as its child")})}}function Qxt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function zxt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function apt(t){return t}function lpt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=tu,r=si,i=Ia,s=Ny;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(y,E){const A=[];for(const _ of E.schema.fields){const v=y[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const g={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(TE);var Gxt=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]}),Wxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vxt=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)&&Gxt(e,t,r);return Wxt(e,t),e};Object.defineProperty(I2,"__esModule",{value:!0}),I2.malloyToQuery=I2.MalloyToQuery=void 0;const Yxt=ep,Dn=Vxt(w),Oxe=Xp,RE=In,Kxt=Ke,Jxt=yE,Fxe=Vn,Xxt=TE,sP="Malloy query documents";class wxe extends Yxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Fxe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Oxe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${sP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${sP} may only have one run statement`);return i===void 0?(this.illegal(e,`${sP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,RE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Dn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Dn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Dn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Dn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Dn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Dn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Dn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Dn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Dn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Dn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Dn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Dn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Dn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,RE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Dn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,RE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Dn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Dn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,RE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Kxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,RE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Dn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Dn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Dn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Dn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Dn.ExprFieldPathContext&&i instanceof Dn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Dn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}I2.MalloyToQuery=wxe;function Zxt(t){const e=(0,Fxe.getSourceInfo)(t),r=new Oxe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Jxt.runMalloyParser)(t,i,e,r),u=new wxe(s,r).visit(s.root),a=(0,Xxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}I2.malloyToQuery=Zxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=L2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=I2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Z4);var we={},BR={};Object.defineProperty(BR,"__esModule",{value:!0}),BR.MALLOY_VERSION=void 0,BR.MALLOY_VERSION="0.0.277",Object.defineProperty(we,"__esModule",{value:!0}),we.InMemoryModelCache=we.CacheManager=we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const Nxe=Z4,ai=Mi,Lxe=Ny,oP=jp,edt=BR,tdt=Hp,$n=si,ndt=Kl,rdt=Vn,idt=gE,Ixe="internal://internal.malloy";let r0=class wD{static get version(){return edt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(Ixe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Nxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Bxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return wD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return QR(r,e).then(({contents:u,invalidationKey:a})=>wD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(Ixe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new B2(C.modelDef,[],[e.toString(),...HR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await EP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await QR(s,e);A[v]=b,r=C}else{const C=await EP(s,e);A[v]=C}_=new Nxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new B2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new B2(S,C.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=C.fromSources)!==null&&y!==void 0?y:[]])}else{const b=C.problems||[],S=_.prettyErrors();throw new $xe(`Error(s) compiling model:
1474
1474
  ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(zR(S))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,S);if(D){for(const k in D.invalidationKeys)A[k]=D.invalidationKeys[k];_.update({translations:{[S]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await QR(s,new URL(S)),I={[S]:R};A[S]=O,_.update({urls:I})}catch(R){_.update({errors:{urls:{[S]:R.message}}})}const{modelAnnotation:b}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const S=new Map;for(const R in C.tables){const{connectionName:O,tablePath:I}=C.tables[R],D=S.get(O);D===void 0?S.set(O,{[R]:I}):D[R]=I}for(const[R,O]of S)try{const I=await o.lookupConnection(R),{schemas:D,errors:k}=await wD.safelyFetchTableSchema(I,O,{refreshTimestamp:E,modelAnnotation:b});_.update({tables:D,errors:{tables:k}})}catch(I){const D={},k={};for(const U in O)k[U]=I.toString();_.update({tables:D,errors:{tables:k}})}}if(C.compileSQL){const S=C.compileSQL,R=S.connection,O=(0,ndt.sqlKey)(S.connection,S.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(S,{refreshTimestamp:E,modelAnnotation:b});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch(I){const D={};D[O]=I.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new FE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new FE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Us(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new pd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};we.Malloy=r0;class $xe extends Error{constructor(e,r=[]){super(e),this.problems=r}}we.MalloyError=$xe;class B2{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new idt.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,$n.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,rdt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new k2(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new k2(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new k2(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,ai.isSourceDef)(r))return new Us(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(ai.isSourceDef).map(e=>new Us(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}we.Model=B2;class k2{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,$n.annotationToTag)(this._modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new ai.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new DE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,ai.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=k2;class Bxe{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new kR(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new kxe(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new Mxe(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=Bxe;class kxe{constructor(e){this._range=M2.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}we.DocumentTablePath=kxe;class M2{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new M2(new uP(e.start.line,e.start.character),new uP(e.end.line,e.end.character))}}we.DocumentRange=M2;class uP{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=uP;class kR{constructor(e){this._range=M2.fromJSON(e.range),this._lensRange=e.lensRange?M2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new kR(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}we.DocumentSymbol=kR;class Mxe{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=Mxe;class DE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new DE(e,r)}tagParse(e){const r=(0,$n.annotationToTag)(this.modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,$n.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Us(r,this.sourceExplore)}catch{return new Us(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,ai.isSourceDef)(r))return new Us(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=DE;class Pxe{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}we.EmptyURLReader=Pxe;class sdt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return zR(e.toString())?null:ede(r)}}we.InMemoryURLReader=sdt;class MR{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new MR(new Map(e.map(r=>[r.name,r])))}}we.FixedConnectionMap=MR;var Uxe;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(Uxe||(we.SourceRelationship=Uxe={}));class aP{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Us}isQuery(){return this instanceof pP}}class Us extends aP{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,ai.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,$n.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,$n.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new k2(i,this.modelDef,[],e)}get modelDef(){if(!(0,ai.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new B2(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,ai.isJoined)(i))return[s,new mP(i,this,o)];if(i.type==="turtle")return[s,new pP(i,this,o)];if(i.type==="string")return[s,new hP(i,this,o)];if(i.type==="number")return[s,new PR(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new PR({...i,type:"number"},this,o)]:[s,new lP(i,this,o)];if(i.type==="timestamp")return[s,new cP(i,this,o)];if(i.type==="boolean")return[s,new fP(i,this,o)];if(i.type==="json")return[s,new xP(i,this,o)];if(i.type==="sql native")return[s,new dP(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof mP}get filters(){var e;return(0,ai.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,ai.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Us.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Us.fromJSON(e.sourceExplore):void 0;return new Us(e._structDef,r,i)}get location(){return this.structDef.location}}we.Explore=Us;var Ba;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ba||(we.AtomicFieldType=Ba={}));class Vc extends aP{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ba.String;case"boolean":return Ba.Boolean;case"date":return Ba.Date;case"timestamp":return Ba.Timestamp;case"number":return Ba.Number;case"json":return Ba.Json;case"sql native":return Ba.NativeUnsupported;case"error":return Ba.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,ai.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,ai.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof hP}isNumber(){return this instanceof PR}isDate(){return this instanceof lP}isBoolean(){return this instanceof fP}isJSON(){return this instanceof xP}isTimestamp(){return this instanceof cP}isUnsupported(){return this instanceof dP}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=Vc;var hd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(hd||(we.DateTimeframe=hd={}));var ka;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(ka||(we.TimestampTimeframe=ka={}));class lP extends Vc{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return hd.Day;case"week":return hd.Week;case"month":return hd.Month;case"quarter":return hd.Quarter;case"year":return hd.Year}}}we.DateField=lP;class cP extends Vc{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return ka.Day;case"week":return ka.Week;case"month":return ka.Month;case"quarter":return ka.Quarter;case"year":return ka.Year;case"second":return ka.Second;case"hour":return ka.Hour;case"minute":return ka.Minute}}}we.TimestampField=cP;class PR extends Vc{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}we.NumberField=PR;class fP extends Vc{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}we.BooleanField=fP;class xP extends Vc{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}we.JSONField=xP;class dP extends Vc{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=dP;class hP extends Vc{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}we.StringField=hP;class jxe extends aP{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=jxe;class pP extends jxe{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}we.QueryField=pP;var P2;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(P2||(we.JoinRelationship=P2={}));class mP extends Us{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,ai.isJoined)(this.structDef))switch(this.structDef.join){case"one":return P2.OneToOne;case"many":case"cross":return P2.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===P2.OneToOne}get isArray(){return this.joinRelationship!==P2.OneToOne}tagParse(e){return e=(0,$n.addModelScope)(e,this._parentExplore.modelTag),(0,$n.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}we.ExploreField=mP;class gP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new Pxe),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new OE(this,async()=>r0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new OE(this,async()=>new B2(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}we.Runtime=gP;class odt extends gP{constructor({urlReader:e,connections:r}){super({connections:MR.fromArray(r),urlReader:e}),this.rawConnections=r}}we.ConnectionRuntime=odt;class udt extends gP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,oP.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,oP.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,oP.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=udt;class UR{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new qxe(this.runtime,e,r)}makeExploreMaterializer(e,r){return new Qxe(this.runtime,e,r)}makePreparedResultMaterializer(e){return new Hxe(this.runtime,e)}}class OE extends UR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await r0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new OE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await r0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new ai.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,ai.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,ai.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1475
1475
  run: ${e}
1476
1476
  -> ${u}
@@ -19925,7 +19925,7 @@ ${r}}`, i;
19925
19925
  else
19926
19926
  return;
19927
19927
  }
19928
- return i;
19928
+ return i.deleted ? void 0 : i;
19929
19929
  }
19930
19930
  has(...e) {
19931
19931
  return this.find(e) !== void 0;
@@ -154142,7 +154142,7 @@ n2.malloyToQuery = C2t;
154142
154142
  var $e = {}, GD = {};
154143
154143
  Object.defineProperty(GD, "__esModule", { value: !0 });
154144
154144
  GD.MALLOY_VERSION = void 0;
154145
- GD.MALLOY_VERSION = "0.0.276";
154145
+ GD.MALLOY_VERSION = "0.0.277";
154146
154146
  Object.defineProperty($e, "__esModule", { value: !0 });
154147
154147
  $e.InMemoryModelCache = $e.CacheManager = $e.CSVWriter = $e.JSONWriter = $e.DataWriter = $e.DataRecord = $e.DataArray = $e.Result = $e.ExploreMaterializer = $e.PreparedResultMaterializer = $e.QueryMaterializer = $e.ModelMaterializer = $e.SingleConnectionRuntime = $e.ConnectionRuntime = $e.Runtime = $e.ExploreField = $e.JoinRelationship = $e.QueryField = $e.Query = $e.StringField = $e.UnsupportedField = $e.JSONField = $e.BooleanField = $e.NumberField = $e.TimestampField = $e.DateField = $e.TimestampTimeframe = $e.DateTimeframe = $e.AtomicField = $e.AtomicFieldType = $e.Explore = $e.SourceRelationship = $e.FixedConnectionMap = $e.InMemoryURLReader = $e.EmptyURLReader = $e.PreparedResult = $e.DocumentCompletion = $e.DocumentSymbol = $e.DocumentPosition = $e.DocumentRange = $e.DocumentTablePath = $e.Parse = $e.PreparedQuery = $e.Model = $e.MalloyError = $e.Malloy = void 0;
154148
154148
  const eK = JT, ri = Ki, tK = zr, ow = J2, b2t = GD, T2t = X2, kn = di, R2t = n0, D2t = Kn, O2t = uv, nK = "internal://internal.malloy";