@malloydata/render 0.0.218-dev241120182108 → 0.0.218-dev241120184958

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.
@@ -52207,7 +52207,7 @@ ${i}` : e = i;
52207
52207
  const i = this.parseStep.sourceInfo.lines.length - 1;
52208
52208
  for (let s = e.line - 1; s <= i; s++) {
52209
52209
  const o = this.parseStep.sourceInfo.at[s];
52210
- if (n.stopIndex >= o.begin && n.stopIndex <= o.end)
52210
+ if (n.stopIndex >= o.begin && n.stopIndex < o.end)
52211
52211
  return {
52212
52212
  start: r,
52213
52213
  end: {
@@ -1327,7 +1327,7 @@ QUERY: ${(0,Qq.inspect)(n,{breakLength:72,depth:1/0})}`)}return Gq.ErrorFactory.
1327
1327
  | ${l}`,u>0&&(i=i+`
1328
1328
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1329
1329
  `+i,n=s),e!==""?e=`${e}
1330
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,MTe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,VTe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}nu.MalloyTranslation=I7;class GQ extends I7{constructor(e,n){super(e),this.root=n}}nu.MalloyChildTranslator=GQ;class u6e extends I7{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new L7.Zone,this.importZone=new L7.Zone,this.sqlQueryZone=new L7.Zone,this.root=this,this.logger=new F7.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,F7.makeLogMessage)(e,n,{severity:"error",...r})),e}}nu.MalloyTranslator=u6e;class WQ{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,F7.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}nu.MalloyParserErrorHandler=WQ;var jd={};Object.defineProperty(jd,"__esModule",{value:!0}),jd.exploreQueryWalkerBuilder=jd.ExploreQueryWalker=void 0;const a6e=Al;class VQ{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}jd.ExploreQueryWalker=VQ;function l6e(t,e){const n=new VQ(t),r=n;return a6e.ParseTreeWalker.DEFAULT.walk(r,e),n}jd.exploreQueryWalkerBuilder=l6e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=nu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=jd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(eR);var Oe={},$v={};Object.defineProperty($v,"__esModule",{value:!0}),$v.MALLOY_VERSION=void 0,$v.MALLOY_VERSION="0.0.218",Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.PreparedResultMaterializer=Oe.QueryMaterializer=Oe.ModelMaterializer=Oe.SingleConnectionRuntime=Oe.ConnectionRuntime=Oe.Runtime=Oe.ExploreField=Oe.JoinRelationship=Oe.QueryField=Oe.Query=Oe.StringField=Oe.UnsupportedField=Oe.JSONField=Oe.BooleanField=Oe.NumberField=Oe.TimestampField=Oe.DateField=Oe.TimestampTimeframe=Oe.DateTimeframe=Oe.AtomicField=Oe.AtomicFieldType=Oe.Explore=Oe.SourceRelationship=Oe.FixedConnectionMap=Oe.InMemoryURLReader=Oe.EmptyURLReader=Oe.PreparedResult=Oe.DocumentCompletion=Oe.DocumentSymbol=Oe.DocumentPosition=Oe.DocumentRange=Oe.DocumentTablePath=Oe.Parse=Oe.PreparedQuery=Oe.Model=Oe.MalloyError=Oe.Malloy=void 0;const c6e=eR,pr=Es,YQ=nQ,vn=Uo,$7=gx,f6e=$v;class Fn{static get version(){return f6e.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new c6e.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new KQ(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Fn._parse(r,e,i,s);if(n===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 n.readURL(e).then(o=>Fn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,d;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new ug(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new ug(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(d=g.fromSources)!==null&&d!==void 0?d:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new JQ(`Error(s) compiling model:
1330
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,MTe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,VTe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}nu.MalloyTranslation=I7;class GQ extends I7{constructor(e,n){super(e),this.root=n}}nu.MalloyChildTranslator=GQ;class u6e extends I7{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new L7.Zone,this.importZone=new L7.Zone,this.sqlQueryZone=new L7.Zone,this.root=this,this.logger=new F7.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,F7.makeLogMessage)(e,n,{severity:"error",...r})),e}}nu.MalloyTranslator=u6e;class WQ{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,F7.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}nu.MalloyParserErrorHandler=WQ;var jd={};Object.defineProperty(jd,"__esModule",{value:!0}),jd.exploreQueryWalkerBuilder=jd.ExploreQueryWalker=void 0;const a6e=Al;class VQ{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}jd.ExploreQueryWalker=VQ;function l6e(t,e){const n=new VQ(t),r=n;return a6e.ParseTreeWalker.DEFAULT.walk(r,e),n}jd.exploreQueryWalkerBuilder=l6e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=nu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=jd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(eR);var Oe={},$v={};Object.defineProperty($v,"__esModule",{value:!0}),$v.MALLOY_VERSION=void 0,$v.MALLOY_VERSION="0.0.218",Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.PreparedResultMaterializer=Oe.QueryMaterializer=Oe.ModelMaterializer=Oe.SingleConnectionRuntime=Oe.ConnectionRuntime=Oe.Runtime=Oe.ExploreField=Oe.JoinRelationship=Oe.QueryField=Oe.Query=Oe.StringField=Oe.UnsupportedField=Oe.JSONField=Oe.BooleanField=Oe.NumberField=Oe.TimestampField=Oe.DateField=Oe.TimestampTimeframe=Oe.DateTimeframe=Oe.AtomicField=Oe.AtomicFieldType=Oe.Explore=Oe.SourceRelationship=Oe.FixedConnectionMap=Oe.InMemoryURLReader=Oe.EmptyURLReader=Oe.PreparedResult=Oe.DocumentCompletion=Oe.DocumentSymbol=Oe.DocumentPosition=Oe.DocumentRange=Oe.DocumentTablePath=Oe.Parse=Oe.PreparedQuery=Oe.Model=Oe.MalloyError=Oe.Malloy=void 0;const c6e=eR,pr=Es,YQ=nQ,vn=Uo,$7=gx,f6e=$v;class Fn{static get version(){return f6e.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new c6e.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new KQ(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Fn._parse(r,e,i,s);if(n===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 n.readURL(e).then(o=>Fn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,d;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new ug(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new ug(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(d=g.fromSources)!==null&&d!==void 0?d:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new JQ(`Error(s) compiling model:
1331
1331
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const A=await e.readURL(new URL(E)),_={[E]:A};m.update({urls:_})}catch(A){m.update({errors:{urls:{[E]:A.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const A in g.tables){const{connectionName:_,tablePath:v}=g.tables[A],C=E.get(_);C===void 0?E.set(_,{[A]:v}):C[A]=v}for(const[A,_]of E)try{const v=await n.lookupConnection(A),{schemas:C,errors:S}=await Fn.safelyFetchTableSchema(v,_,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:C,errors:{tables:S}})}catch(v){const C={},S={};for(const b in _)S[b]=v.toString();m.update({tables:C,errors:{tables:S}})}}if(g.compileSQL){const E=g.compileSQL,A=E.connection;try{const _=await n.lookupConnection(A),v=Fn.compileSQLBlock(_.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),C=await _.fetchSchemaForSQLStruct(v,{refreshTimestamp:p,modelAnnotation:y});C.error&&m.update({errors:{compileSQL:{[v.name]:C.error}}}),C.structDef&&m.update({compileSQL:{[v.name]:C.structDef}})}catch(_){const v={};v[E.name]=_.toString(),m.update({errors:{compileSQL:v}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,pr.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new pr.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new fg({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new fg({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new es(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new nf(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=Fn;class JQ extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=JQ;let ug=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return vn.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return vn.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new Ud(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new Ud(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Ud(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,pr.isSourceDef)(n))return new es(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(pr.isSourceDef).map(e=>new es(e))}get namedQueries(){const e=n=>n.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}};Oe.Model=ug;class Ud{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=vn.Tag.annotationToTag(this._modelDef.annotation).tag;return e=vn.Tag.addModelScope(e,n),vn.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return vn.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new pr.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new ag({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,pr.isSourceDef)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Ud;class KQ{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new Bv(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new XQ(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new ZQ(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=KQ;class XQ{constructor(e){this._range=qd.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}}Oe.DocumentTablePath=XQ;class qd{constructor(e,n){this._start=e,this._end=n}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 qd(new B7(e.start.line,e.start.character),new B7(e.end.line,e.end.character))}}Oe.DocumentRange=qd;class B7{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Oe.DocumentPosition=B7;class Bv{constructor(e){this._range=qd.fromJSON(e.range),this._lensRange=e.lensRange?qd.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new Bv(n))}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}}Oe.DocumentSymbol=Bv;class ZQ{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=ZQ;class ag{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new ag(e,n)}tagParse(e){const n=vn.Tag.annotationToTag(this.modelDef.annotation).tag;return e=vn.Tag.addModelScope(e,n),vn.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return vn.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return vn.Tag.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],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new es(n,this.sourceExplore)}catch{return new es(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,pr.isSourceDef)(n))return new es(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=ag;class eG{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=eG;class x6e{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Oe.InMemoryURLReader=x6e;class lg{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 lg(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=lg;var tG;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(tG||(Oe.SourceRelationship=tG={}));class k7{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof es}isQuery(){return this instanceof z7}}class es extends k7{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,pr.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return vn.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return vn.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=vn.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Ud(r,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new ug(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,pr.isJoined)(r))return[i,new Q7(r,this,s)];if(r.type==="turtle")return[i,new z7(r,this,s)];if(r.type==="string")return[i,new H7(r,this,s)];if(r.type==="number")return[i,new kv(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new kv({...r,type:"number"},this,s)]:[i,new P7(r,this,s)];if(r.type==="timestamp")return[i,new M7(r,this,s)];if(r.type==="boolean")return[i,new j7(r,this,s)];if(r.type==="json")return[i,new U7(r,this,s)];if(r.type==="sql native")return[i,new q7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}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 Q7}get filters(){var e;return(0,pr.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.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,pr.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?es.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?es.fromJSON(e.sourceExplore):void 0;return new es(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=es;var fu;(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"})(fu||(Oe.AtomicFieldType=fu={}));class n0 extends k7{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return fu.String;case"boolean":return fu.Boolean;case"date":return fu.Date;case"timestamp":return fu.Timestamp;case"number":return fu.Number;case"json":return fu.Json;case"sql native":return fu.NativeUnsupported;case"error":return fu.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=vn.Tag.addModelScope(e,this.parent.modelTag),vn.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return vn.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,pr.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,pr.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,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 H7}isNumber(){return this instanceof kv}isDate(){return this instanceof P7}isBoolean(){return this instanceof j7}isJSON(){return this instanceof U7}isTimestamp(){return this instanceof M7}isUnsupported(){return this instanceof q7}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Oe.AtomicField=n0;var tf;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(tf||(Oe.DateTimeframe=tf={}));var xu;(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"})(xu||(Oe.TimestampTimeframe=xu={}));class P7 extends n0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return tf.Day;case"week":return tf.Week;case"month":return tf.Month;case"quarter":return tf.Quarter;case"year":return tf.Year}}}Oe.DateField=P7;class M7 extends n0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return xu.Day;case"week":return xu.Week;case"month":return xu.Month;case"quarter":return xu.Quarter;case"year":return xu.Year;case"second":return xu.Second;case"hour":return xu.Hour;case"minute":return xu.Minute}}}Oe.TimestampField=M7;class kv extends n0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=kv;class j7 extends n0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=j7;class U7 extends n0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=U7;class q7 extends n0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=q7;class H7 extends n0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=H7;class nG extends k7{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Oe.Query=nG;class z7 extends nG{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=vn.Tag.addModelScope(e,this.parent.modelTag),vn.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return vn.Tag.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}}Oe.QueryField=z7;var Hd;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Hd||(Oe.JoinRelationship=Hd={}));class Q7 extends es{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,pr.isJoined)(this.structDef))switch(this.structDef.join){case"one":return Hd.OneToOne;case"many":case"cross":return Hd.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===Hd.OneToOne}get isArray(){return this.joinRelationship!==Hd.OneToOne}tagParse(e){return e=vn.Tag.addModelScope(e,this._parentExplore.modelTag),vn.Tag.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]:[]}}Oe.ExploreField=Q7;class G7{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&(pG(s)?n=s:m6e(s)?r=s:gG(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new eG),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new cg(this,async()=>{const s=e instanceof URL?await Fn.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):Fn.parse({source:e,eventStream:this.eventStream,options:n});return Fn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new cg(this,async()=>new ug(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}Oe.Runtime=G7;class d6e extends G7{constructor(e,n){if(n===void 0){const r=e;super(lg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,lg.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=d6e;class h6e extends G7{constructor(...e){let n,r,i;for(const s of e)pG(s)&&(n=s),y6e(s)&&(r=s),gG(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,$7.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,$7.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,$7.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=h6e;class Pv{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new rG(this.runtime,e,n)}makeExploreMaterializer(e,n){return new sG(this.runtime,e,n)}makePreparedResultMaterializer(e){return new iG(this.runtime,e)}}class cg extends Pv{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await Fn.parse({url:e,urlReader:s,options:n}):Fn.parse({source:e,options:n}),a=await this.getModel();return(await Fn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new cg(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await Fn.parse({url:e,urlReader:r,options:n}):Fn.parse({source:e,options:n}),o=await this.getModel();return await Fn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new pr.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,pr.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,pr.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1332
1332
  run: ${e}
1333
1333
  -> ${o}
@@ -53366,7 +53366,7 @@ ${i}` : e = i;
53366
53366
  const i = this.parseStep.sourceInfo.lines.length - 1;
53367
53367
  for (let s = e.line - 1; s <= i; s++) {
53368
53368
  const o = this.parseStep.sourceInfo.at[s];
53369
- if (n.stopIndex >= o.begin && n.stopIndex <= o.end)
53369
+ if (n.stopIndex >= o.begin && n.stopIndex < o.end)
53370
53370
  return {
53371
53371
  start: r,
53372
53372
  end: {
@@ -1327,7 +1327,7 @@ QUERY: ${(0,Uz.inspect)(n,{breakLength:72,depth:1/0})}`)}return qz.ErrorFactory.
1327
1327
  | ${l}`,u>0&&(i=i+`
1328
1328
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1329
1329
  `+i,n=s),e!==""?e=`${e}
1330
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,IOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,zOe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}yu.MalloyTranslation=DD;class UG extends DD{constructor(e,n){super(e),this.root=n}}yu.MalloyChildTranslator=UG;class nRe extends DD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new RD.Zone,this.importZone=new RD.Zone,this.sqlQueryZone=new RD.Zone,this.root=this,this.logger=new OD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,OD.makeLogMessage)(e,n,{severity:"error",...r})),e}}yu.MalloyTranslator=nRe;class qG{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,OD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}yu.MalloyParserErrorHandler=qG;var gh={};Object.defineProperty(gh,"__esModule",{value:!0}),gh.exploreQueryWalkerBuilder=gh.ExploreQueryWalker=void 0;const rRe=ql;class zG{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}gh.ExploreQueryWalker=zG;function iRe(t,e){const n=new zG(t),r=n;return rRe.ParseTreeWalker.DEFAULT.walk(r,e),n}gh.exploreQueryWalkerBuilder=iRe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=yu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=gh;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(YO);var we={},IS={};Object.defineProperty(IS,"__esModule",{value:!0}),IS.MALLOY_VERSION=void 0,IS.MALLOY_VERSION="0.0.218",Object.defineProperty(we,"__esModule",{value:!0}),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 sRe=YO,Ar=Rs,HG=Fi,Cn=ru,wD=Gx,oRe=IS;class Bn{static get version(){return oRe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new sRe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new GG(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Bn._parse(r,e,i,s);if(n===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 n.readURL(e).then(o=>Bn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,d;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new Yg(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new Yg(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(d=g.fromSources)!==null&&d!==void 0?d:[]],v=>m.referenceAt(v),v=>m.importAt(v))}else{const y=g.problems||[],E=m.prettyErrors();throw new QG(`Error(s) compiling model:
1330
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,IOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,zOe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}yu.MalloyTranslation=DD;class UG extends DD{constructor(e,n){super(e),this.root=n}}yu.MalloyChildTranslator=UG;class nRe extends DD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new RD.Zone,this.importZone=new RD.Zone,this.sqlQueryZone=new RD.Zone,this.root=this,this.logger=new OD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,OD.makeLogMessage)(e,n,{severity:"error",...r})),e}}yu.MalloyTranslator=nRe;class qG{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,OD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}yu.MalloyParserErrorHandler=qG;var gh={};Object.defineProperty(gh,"__esModule",{value:!0}),gh.exploreQueryWalkerBuilder=gh.ExploreQueryWalker=void 0;const rRe=ql;class zG{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}gh.ExploreQueryWalker=zG;function iRe(t,e){const n=new zG(t),r=n;return rRe.ParseTreeWalker.DEFAULT.walk(r,e),n}gh.exploreQueryWalkerBuilder=iRe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=yu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=gh;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(YO);var we={},IS={};Object.defineProperty(IS,"__esModule",{value:!0}),IS.MALLOY_VERSION=void 0,IS.MALLOY_VERSION="0.0.218",Object.defineProperty(we,"__esModule",{value:!0}),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 sRe=YO,Ar=Rs,HG=Fi,Cn=ru,wD=Gx,oRe=IS;class Bn{static get version(){return oRe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new sRe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new GG(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Bn._parse(r,e,i,s);if(n===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 n.readURL(e).then(o=>Bn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,d;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new Yg(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new Yg(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(d=g.fromSources)!==null&&d!==void 0?d:[]],v=>m.referenceAt(v),v=>m.importAt(v))}else{const y=g.problems||[],E=m.prettyErrors();throw new QG(`Error(s) compiling model:
1331
1331
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const v=await e.readURL(new URL(E)),A={[E]:v};m.update({urls:A})}catch(v){m.update({errors:{urls:{[E]:v.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const v in g.tables){const{connectionName:A,tablePath:_}=g.tables[v],S=E.get(A);S===void 0?E.set(A,{[v]:_}):S[v]=_}for(const[v,A]of E)try{const _=await n.lookupConnection(v),{schemas:S,errors:b}=await Bn.safelyFetchTableSchema(_,A,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:S,errors:{tables:b}})}catch(_){const S={},b={};for(const C in A)b[C]=_.toString();m.update({tables:S,errors:{tables:b}})}}if(g.compileSQL){const E=g.compileSQL,v=E.connection;try{const A=await n.lookupConnection(v),_=Bn.compileSQLBlock(A.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),S=await A.fetchSchemaForSQLStruct(_,{refreshTimestamp:p,modelAnnotation:y});S.error&&m.update({errors:{compileSQL:{[_.name]:S.error}}}),S.structDef&&m.update({compileSQL:{[_.name]:S.structDef}})}catch(A){const _={};_[E.name]=A.toString(),m.update({errors:{compileSQL:_}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,Ar.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new Ar.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new Zg({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new Zg({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new ls(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new Tf(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}we.Malloy=Bn;class QG extends Error{constructor(e,n=[]){super(e),this.problems=n}}we.MalloyError=QG;let Yg=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return Cn.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new mh(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new mh(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new mh(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,Ar.isSourceDef)(n))return new ls(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(Ar.isSourceDef).map(e=>new ls(e))}get namedQueries(){const e=n=>n.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=Yg;class mh{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Cn.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new Ar.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new Kg({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,Ar.isSourceDef)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=mh;class GG{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new $S(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new WG(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new VG(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=GG;class WG{constructor(e){this._range=yh.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=WG;class yh{constructor(e,n){this._start=e,this._end=n}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 yh(new ND(e.start.line,e.start.character),new ND(e.end.line,e.end.character))}}we.DocumentRange=yh;class ND{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=ND;class $S{constructor(e){this._range=yh.fromJSON(e.range),this._lensRange=e.lensRange?yh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new $S(n))}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=$S;class VG{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=VG;class Kg{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new Kg(e,n)}tagParse(e){const n=Cn.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Cn.Tag.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],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new ls(n,this.sourceExplore)}catch{return new ls(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,Ar.isSourceDef)(n))return new ls(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=Kg;class YG{async readURL(e){throw new Error("No files.")}}we.EmptyURLReader=YG;class uRe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}we.InMemoryURLReader=uRe;class Xg{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 Xg(new Map(e.map(n=>[n.name,n])))}}we.FixedConnectionMap=Xg;var KG;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(KG||(we.SourceRelationship=KG={}));class FD{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ls}isQuery(){return this instanceof PD}}class ls extends FD{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,Ar.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return Cn.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Cn.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new mh(r,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Yg(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,Ar.isJoined)(r))return[i,new jD(r,this,s)];if(r.type==="turtle")return[i,new PD(r,this,s)];if(r.type==="string")return[i,new MD(r,this,s)];if(r.type==="number")return[i,new BS(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new BS({...r,type:"number"},this,s)]:[i,new LD(r,this,s)];if(r.type==="timestamp")return[i,new ID(r,this,s)];if(r.type==="boolean")return[i,new $D(r,this,s)];if(r.type==="json")return[i,new BD(r,this,s)];if(r.type==="sql native")return[i,new kD(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}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 jD}get filters(){var e;return(0,Ar.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.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,Ar.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ls.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ls.fromJSON(e.sourceExplore):void 0;return new ls(e._structDef,n,r)}get location(){return this.structDef.location}}we.Explore=ls;var Ou;(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"})(Ou||(we.AtomicFieldType=Ou={}));class b0 extends FD{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return Ou.String;case"boolean":return Ou.Boolean;case"date":return Ou.Date;case"timestamp":return Ou.Timestamp;case"number":return Ou.Number;case"json":return Ou.Json;case"sql native":return Ou.NativeUnsupported;case"error":return Ou.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=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,Ar.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,Ar.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,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 MD}isNumber(){return this instanceof BS}isDate(){return this instanceof LD}isBoolean(){return this instanceof $D}isJSON(){return this instanceof BD}isTimestamp(){return this instanceof ID}isUnsupported(){return this instanceof kD}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=b0;var Cf;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Cf||(we.DateTimeframe=Cf={}));var Ru;(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"})(Ru||(we.TimestampTimeframe=Ru={}));class LD extends b0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Cf.Day;case"week":return Cf.Week;case"month":return Cf.Month;case"quarter":return Cf.Quarter;case"year":return Cf.Year}}}we.DateField=LD;class ID extends b0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ru.Day;case"week":return Ru.Week;case"month":return Ru.Month;case"quarter":return Ru.Quarter;case"year":return Ru.Year;case"second":return Ru.Second;case"hour":return Ru.Hour;case"minute":return Ru.Minute}}}we.TimestampField=ID;class BS extends b0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}we.NumberField=BS;class $D extends b0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}we.BooleanField=$D;class BD extends b0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}we.JSONField=BD;class kD extends b0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=kD;class MD extends b0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}we.StringField=MD;class XG extends FD{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=XG;class PD extends XG{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Cn.Tag.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=PD;var Eh;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Eh||(we.JoinRelationship=Eh={}));class jD extends ls{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,Ar.isJoined)(this.structDef))switch(this.structDef.join){case"one":return Eh.OneToOne;case"many":case"cross":return Eh.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===Eh.OneToOne}get isArray(){return this.joinRelationship!==Eh.OneToOne}tagParse(e){return e=Cn.Tag.addModelScope(e,this._parentExplore.modelTag),Cn.Tag.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=jD;class UD{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&(cW(s)?n=s:xRe(s)?r=s:fW(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new YG),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Jg(this,async()=>{const s=e instanceof URL?await Bn.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):Bn.parse({source:e,eventStream:this.eventStream,options:n});return Bn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new Jg(this,async()=>new Yg(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}we.Runtime=UD;class aRe extends UD{constructor(e,n){if(n===void 0){const r=e;super(Xg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Xg.fromArray(r)),this.rawConnections=r}}}we.ConnectionRuntime=aRe;class lRe extends UD{constructor(...e){let n,r,i;for(const s of e)cW(s)&&(n=s),dRe(s)&&(r=s),fW(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,wD.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,wD.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,wD.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=lRe;class kS{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new JG(this.runtime,e,n)}makeExploreMaterializer(e,n){return new eW(this.runtime,e,n)}makePreparedResultMaterializer(e){return new ZG(this.runtime,e)}}class Jg extends kS{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await Bn.parse({url:e,urlReader:s,options:n}):Bn.parse({source:e,options:n}),a=await this.getModel();return(await Bn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Jg(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await Bn.parse({url:e,urlReader:r,options:n}):Bn.parse({source:e,options:n}),o=await this.getModel();return await Bn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new Ar.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,Ar.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,Ar.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1332
1332
  run: ${e}
1333
1333
  -> ${o}
@@ -53366,7 +53366,7 @@ ${i}` : e = i;
53366
53366
  const i = this.parseStep.sourceInfo.lines.length - 1;
53367
53367
  for (let s = e.line - 1; s <= i; s++) {
53368
53368
  const o = this.parseStep.sourceInfo.at[s];
53369
- if (n.stopIndex >= o.begin && n.stopIndex <= o.end)
53369
+ if (n.stopIndex >= o.begin && n.stopIndex < o.end)
53370
53370
  return {
53371
53371
  start: r,
53372
53372
  end: {
@@ -1327,7 +1327,7 @@ QUERY: ${(0,jz.inspect)(n,{breakLength:72,depth:1/0})}`)}return Uz.ErrorFactory.
1327
1327
  | ${l}`,u>0&&(i=i+`
1328
1328
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1329
1329
  `+i,n=s),e!==""?e=`${e}
1330
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,IOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,zOe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}yu.MalloyTranslation=RD;class jG extends RD{constructor(e,n){super(e),this.root=n}}yu.MalloyChildTranslator=jG;class nRe extends RD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new OD.Zone,this.importZone=new OD.Zone,this.sqlQueryZone=new OD.Zone,this.root=this,this.logger=new TD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,TD.makeLogMessage)(e,n,{severity:"error",...r})),e}}yu.MalloyTranslator=nRe;class UG{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,TD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}yu.MalloyParserErrorHandler=UG;var gh={};Object.defineProperty(gh,"__esModule",{value:!0}),gh.exploreQueryWalkerBuilder=gh.ExploreQueryWalker=void 0;const rRe=ql;class qG{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}gh.ExploreQueryWalker=qG;function iRe(t,e){const n=new qG(t),r=n;return rRe.ParseTreeWalker.DEFAULT.walk(r,e),n}gh.exploreQueryWalkerBuilder=iRe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=yu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=gh;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(VO);var we={},LS={};Object.defineProperty(LS,"__esModule",{value:!0}),LS.MALLOY_VERSION=void 0,LS.MALLOY_VERSION="0.0.218",Object.defineProperty(we,"__esModule",{value:!0}),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 sRe=VO,Ar=Rs,zG=Fi,Cn=ru,DD=Gx,oRe=LS;class Bn{static get version(){return oRe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new sRe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new QG(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Bn._parse(r,e,i,s);if(n===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 n.readURL(e).then(o=>Bn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,d;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new Wg(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new Wg(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(d=g.fromSources)!==null&&d!==void 0?d:[]],v=>m.referenceAt(v),v=>m.importAt(v))}else{const y=g.problems||[],E=m.prettyErrors();throw new HG(`Error(s) compiling model:
1330
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,IOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,zOe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}yu.MalloyTranslation=RD;class jG extends RD{constructor(e,n){super(e),this.root=n}}yu.MalloyChildTranslator=jG;class nRe extends RD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new OD.Zone,this.importZone=new OD.Zone,this.sqlQueryZone=new OD.Zone,this.root=this,this.logger=new TD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,TD.makeLogMessage)(e,n,{severity:"error",...r})),e}}yu.MalloyTranslator=nRe;class UG{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,TD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}yu.MalloyParserErrorHandler=UG;var gh={};Object.defineProperty(gh,"__esModule",{value:!0}),gh.exploreQueryWalkerBuilder=gh.ExploreQueryWalker=void 0;const rRe=ql;class qG{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}gh.ExploreQueryWalker=qG;function iRe(t,e){const n=new qG(t),r=n;return rRe.ParseTreeWalker.DEFAULT.walk(r,e),n}gh.exploreQueryWalkerBuilder=iRe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=yu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=gh;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(VO);var we={},LS={};Object.defineProperty(LS,"__esModule",{value:!0}),LS.MALLOY_VERSION=void 0,LS.MALLOY_VERSION="0.0.218",Object.defineProperty(we,"__esModule",{value:!0}),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 sRe=VO,Ar=Rs,zG=Fi,Cn=ru,DD=Gx,oRe=LS;class Bn{static get version(){return oRe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new sRe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new QG(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Bn._parse(r,e,i,s);if(n===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 n.readURL(e).then(o=>Bn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,d;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new Wg(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new Wg(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(d=g.fromSources)!==null&&d!==void 0?d:[]],v=>m.referenceAt(v),v=>m.importAt(v))}else{const y=g.problems||[],E=m.prettyErrors();throw new HG(`Error(s) compiling model:
1331
1331
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const v=await e.readURL(new URL(E)),A={[E]:v};m.update({urls:A})}catch(v){m.update({errors:{urls:{[E]:v.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const v in g.tables){const{connectionName:A,tablePath:_}=g.tables[v],S=E.get(A);S===void 0?E.set(A,{[v]:_}):S[v]=_}for(const[v,A]of E)try{const _=await n.lookupConnection(v),{schemas:S,errors:b}=await Bn.safelyFetchTableSchema(_,A,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:S,errors:{tables:b}})}catch(_){const S={},b={};for(const C in A)b[C]=_.toString();m.update({tables:S,errors:{tables:b}})}}if(g.compileSQL){const E=g.compileSQL,v=E.connection;try{const A=await n.lookupConnection(v),_=Bn.compileSQLBlock(A.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),S=await A.fetchSchemaForSQLStruct(_,{refreshTimestamp:p,modelAnnotation:y});S.error&&m.update({errors:{compileSQL:{[_.name]:S.error}}}),S.structDef&&m.update({compileSQL:{[_.name]:S.structDef}})}catch(A){const _={};_[E.name]=A.toString(),m.update({errors:{compileSQL:_}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,Ar.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new Ar.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new Xg({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new Xg({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new ls(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new Tf(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}we.Malloy=Bn;class HG extends Error{constructor(e,n=[]){super(e),this.problems=n}}we.MalloyError=HG;let Wg=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return Cn.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new mh(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new mh(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new mh(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,Ar.isSourceDef)(n))return new ls(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(Ar.isSourceDef).map(e=>new ls(e))}get namedQueries(){const e=n=>n.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=Wg;class mh{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Cn.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new Ar.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new Vg({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,Ar.isSourceDef)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=mh;class QG{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new IS(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new GG(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new WG(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=QG;class GG{constructor(e){this._range=yh.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=GG;class yh{constructor(e,n){this._start=e,this._end=n}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 yh(new wD(e.start.line,e.start.character),new wD(e.end.line,e.end.character))}}we.DocumentRange=yh;class wD{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=wD;class IS{constructor(e){this._range=yh.fromJSON(e.range),this._lensRange=e.lensRange?yh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new IS(n))}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=IS;class WG{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=WG;class Vg{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new Vg(e,n)}tagParse(e){const n=Cn.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Cn.Tag.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],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new ls(n,this.sourceExplore)}catch{return new ls(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,Ar.isSourceDef)(n))return new ls(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=Vg;class VG{async readURL(e){throw new Error("No files.")}}we.EmptyURLReader=VG;class uRe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}we.InMemoryURLReader=uRe;class Yg{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 Yg(new Map(e.map(n=>[n.name,n])))}}we.FixedConnectionMap=Yg;var YG;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(YG||(we.SourceRelationship=YG={}));class ND{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ls}isQuery(){return this instanceof MD}}class ls extends ND{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,Ar.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return Cn.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Cn.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new mh(r,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Wg(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,Ar.isJoined)(r))return[i,new PD(r,this,s)];if(r.type==="turtle")return[i,new MD(r,this,s)];if(r.type==="string")return[i,new kD(r,this,s)];if(r.type==="number")return[i,new $S(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new $S({...r,type:"number"},this,s)]:[i,new FD(r,this,s)];if(r.type==="timestamp")return[i,new LD(r,this,s)];if(r.type==="boolean")return[i,new ID(r,this,s)];if(r.type==="json")return[i,new $D(r,this,s)];if(r.type==="sql native")return[i,new BD(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}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 PD}get filters(){var e;return(0,Ar.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.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,Ar.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ls.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ls.fromJSON(e.sourceExplore):void 0;return new ls(e._structDef,n,r)}get location(){return this.structDef.location}}we.Explore=ls;var Ou;(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"})(Ou||(we.AtomicFieldType=Ou={}));class b0 extends ND{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return Ou.String;case"boolean":return Ou.Boolean;case"date":return Ou.Date;case"timestamp":return Ou.Timestamp;case"number":return Ou.Number;case"json":return Ou.Json;case"sql native":return Ou.NativeUnsupported;case"error":return Ou.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=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,Ar.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,Ar.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,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 kD}isNumber(){return this instanceof $S}isDate(){return this instanceof FD}isBoolean(){return this instanceof ID}isJSON(){return this instanceof $D}isTimestamp(){return this instanceof LD}isUnsupported(){return this instanceof BD}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=b0;var Cf;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Cf||(we.DateTimeframe=Cf={}));var Ru;(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"})(Ru||(we.TimestampTimeframe=Ru={}));class FD extends b0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Cf.Day;case"week":return Cf.Week;case"month":return Cf.Month;case"quarter":return Cf.Quarter;case"year":return Cf.Year}}}we.DateField=FD;class LD extends b0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ru.Day;case"week":return Ru.Week;case"month":return Ru.Month;case"quarter":return Ru.Quarter;case"year":return Ru.Year;case"second":return Ru.Second;case"hour":return Ru.Hour;case"minute":return Ru.Minute}}}we.TimestampField=LD;class $S extends b0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}we.NumberField=$S;class ID extends b0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}we.BooleanField=ID;class $D extends b0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}we.JSONField=$D;class BD extends b0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=BD;class kD extends b0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}we.StringField=kD;class KG extends ND{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=KG;class MD extends KG{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Cn.Tag.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=MD;var Eh;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Eh||(we.JoinRelationship=Eh={}));class PD extends ls{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,Ar.isJoined)(this.structDef))switch(this.structDef.join){case"one":return Eh.OneToOne;case"many":case"cross":return Eh.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===Eh.OneToOne}get isArray(){return this.joinRelationship!==Eh.OneToOne}tagParse(e){return e=Cn.Tag.addModelScope(e,this._parentExplore.modelTag),Cn.Tag.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=PD;class jD{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&(lW(s)?n=s:xRe(s)?r=s:cW(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new VG),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Kg(this,async()=>{const s=e instanceof URL?await Bn.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):Bn.parse({source:e,eventStream:this.eventStream,options:n});return Bn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new Kg(this,async()=>new Wg(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}we.Runtime=jD;class aRe extends jD{constructor(e,n){if(n===void 0){const r=e;super(Yg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Yg.fromArray(r)),this.rawConnections=r}}}we.ConnectionRuntime=aRe;class lRe extends jD{constructor(...e){let n,r,i;for(const s of e)lW(s)&&(n=s),dRe(s)&&(r=s),cW(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,DD.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,DD.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,DD.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=lRe;class BS{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new XG(this.runtime,e,n)}makeExploreMaterializer(e,n){return new ZG(this.runtime,e,n)}makePreparedResultMaterializer(e){return new JG(this.runtime,e)}}class Kg extends BS{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await Bn.parse({url:e,urlReader:s,options:n}):Bn.parse({source:e,options:n}),a=await this.getModel();return(await Bn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Kg(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await Bn.parse({url:e,urlReader:r,options:n}):Bn.parse({source:e,options:n}),o=await this.getModel();return await Bn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new Ar.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,Ar.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,Ar.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1332
1332
  run: ${e}
1333
1333
  -> ${o}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.218-dev241120182108",
3
+ "version": "0.0.218-dev241120184958",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "build-types": "tsc --build --declaration --emitDeclarationOnly"
31
31
  },
32
32
  "dependencies": {
33
- "@malloydata/malloy": "^0.0.218-dev241120182108",
33
+ "@malloydata/malloy": "^0.0.218-dev241120184958",
34
34
  "@tanstack/solid-virtual": "^3.10.4",
35
35
  "component-register": "^0.8.6",
36
36
  "lodash": "^4.17.20",