@malloydata/render 0.0.193-dev241001144416 → 0.0.193-dev241001152900

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.
@@ -50477,6 +50477,9 @@ class qm {
50477
50477
  get dependenciesToMaterialize() {
50478
50478
  return this.inner.dependenciesToMaterialize;
50479
50479
  }
50480
+ get materialization() {
50481
+ return this.inner.materialization;
50482
+ }
50480
50483
  /**
50481
50484
  * @return The `Explore` representing the data that will be returned by running this query.
50482
50485
  */
@@ -1303,7 +1303,7 @@ QUERY: ${(0,Pge.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...GU.ErrorFact
1303
1303
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1304
1304
  `+i,n=s),e!==""?e=`${e}
1305
1305
  ${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];(u.type==="struct"||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,Q_e.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))}}Jo.MalloyTranslation=GO;class PH extends GO{constructor(e,n){super(e),this.root=n}}Jo.MalloyChildTranslator=PH;class iCe extends GO{constructor(e,n=null,r=null){super(e,n),this.schemaZone=new QO.Zone,this.importZone=new QO.Zone,this.sqlQueryZone=new QO.Zone,this.logger=new HO.BaseMessageLogger,this.root=this,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,HO.makeLogMessage)(e,n,{severity:"error",...r})),e}}Jo.MalloyTranslator=iCe;class jH{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,HO.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}})}}Jo.MalloyParserErrorHandler=jH;var Rd={};Object.defineProperty(Rd,"__esModule",{value:!0}),Rd.exploreQueryWalkerBuilder=Rd.ExploreQueryWalker=void 0;const sCe=ul;class UH{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}}Rd.ExploreQueryWalker=UH;function oCe(t,e){const n=new UH(t),r=n;return sCe.ParseTreeWalker.DEFAULT.walk(r,e),n}Rd.exploreQueryWalkerBuilder=oCe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=Jo;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Rd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(b6);var Oe={};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.SQLBlockMaterializer=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 uCe=b6,ql=Bo,qH=Kz,vn=$o,WO=cx;class sn{static get version(){return"0.0.1"}static get log(){return sn._log||console}static setLogger(e){sn._log=e}static _parse(e,n,r){n===void 0&&(n=new URL("internal://internal.malloy"));let i=n;r!=null&&r.importBaseURL&&(i=r==null?void 0:r.importBaseURL);const s=new uCe.MalloyTranslator(n.toString(),i.toString(),{urls:{[n.toString()]:e}});return r!=null&&r.testEnvironment&&(s.allDialectsEnabled=!0),new HH(s)}static parse({url:e,urlReader:n,source:r,options:i}){if(r!==void 0)return sn._parse(r,e,i);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(s=>sn._parse(s,e,i))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,replaceMaterializedReferences:u}){var a,l,c,f;let x;s&&(x=typeof s=="number"?s:Date.now());const h=r._translator;for(;;){const p=h.translate(i==null?void 0:i._modelDef);if(p.final){if(p.translated)return new W1(p.translated.modelDef,p.translated.queryList,p.translated.sqlBlocks,p.problems||[],[...(a=i==null?void 0:i.fromSources)!==null&&a!==void 0?a:[],...(l=p.fromSources)!==null&&l!==void 0?l:[]],m=>h.referenceAt(m),m=>h.importAt(m));if(o){const m={name:"modelDidNotCompile",exports:[],contents:{}},g=(i==null?void 0:i._modelDef)||m;return new W1(g,[],[],p.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=p.fromSources)!==null&&f!==void 0?f:[]],y=>h.referenceAt(y),y=>h.importAt(y))}else{const m=p.problems||[],g=h.prettyErrors();throw new zH(`Error(s) compiling model:
1306
- ${g}`,m)}}else{if(p.urls)for(const g of p.urls)try{if(g.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const y=await e.readURL(new URL(g)),E={[g]:y};h.update({urls:E})}catch(y){h.update({errors:{urls:{[g]:y.message}}})}const{modelAnnotation:m}=h.modelAnnotation(i==null?void 0:i._modelDef);if(p.tables){const g=new Map;for(const y in p.tables){const{connectionName:E,tablePath:A}=p.tables[y],v=g.get(E);v===void 0?g.set(E,{[y]:A}):v[y]=A}for(const[y,E]of g)try{const A=await n.lookupConnection(y),{schemas:v,errors:_}=await A.fetchSchemaForTables(E,{refreshTimestamp:x,modelAnnotation:m});h.update({tables:v,errors:{tables:_}})}catch(A){const v={},_={};for(const S in E)_[S]=A.toString();h.update({tables:v,errors:{tables:_}})}}if(p.compileSQL){const g=p.compileSQL,y=g.connection;try{const E=await n.lookupConnection(y),A=sn.compileSQLBlock(p.partialModel,g,{replaceMaterializedReferences:u}),v=await E.fetchSchemaForSQLBlock(A,{refreshTimestamp:x,modelAnnotation:m});v.error&&h.update({errors:{compileSQL:{[A.name]:v.error}}}),v.structDef&&(0,ql.isSQLBlockStruct)(v.structDef)&&h.update({compileSQL:{[A.name]:v.structDef}})}catch(E){const A={};A[g.name]=E.toString(),h.update({errors:{compileSQL:A}})}}}}}static compileSQLBlock(e,n,r){let i,s="",o=!1;for(const l of n.select)if((0,ql.isSQLFragment)(l))s+=l.sql,o=l.sql.match(/\(\s*$/)!==null;else{if(!i){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new ql.QueryModel(e)}const c=i.compileQuery(l,r,!1).sql;s+=o?c:`(${c})`,o=!1}const{name:u,connection:a}=n;return{type:"sqlBlock",name:u,connection:a,selectStr:s}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new K1({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new K1({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.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}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.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(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new Zi(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new Xc(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=sn;class zH extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=zH;let W1=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}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 Od(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 Od(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Od(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new Zi(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new Zi(n))}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=W1;class Od{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 ql.QueryModel(this._modelDef).compileQuery(this._query,e);return new V1({...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(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Od;class HH{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new av(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new QH(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new GH(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=HH;class QH{constructor(e){this._range=Dd.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=QH;class Dd{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 Dd(new VO(e.start.line,e.start.character),new VO(e.end.line,e.end.character))}}Oe.DocumentRange=Dd;class VO{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=VO;class av{constructor(e){this._range=Dd.fromJSON(e.range),this._lensRange=e.lensRange?Dd.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new av(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=av;class GH{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=GH;class V1{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 V1(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 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 Zi(n,this.sourceExplore)}catch{return new Zi(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new Zi(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=V1;class WH{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=WH;class aCe{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=aCe;class Y1{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 Y1(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=Y1;var zl;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(zl||(Oe.SourceRelationship=zl={}));class YO{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 Zi}isQuery(){return this instanceof n7}}class Zi extends YO{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,ql.FieldIsIntrinsic)(this._structDef)}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={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Od(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new W1(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(r.type==="struct")return[i,new r7(r,this,s)];if(r.type==="turtle")return[i,new n7(r,this,s)];if(r.type==="string")return[i,new t7(r,this,s)];if(r.type==="number")return[i,new lv(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new lv({...r,type:"number"},this,s)]:[i,new XO(r,this,s)];if(r.type==="timestamp")return[i,new JO(r,this,s)];if(r.type==="boolean")return[i,new KO(r,this,s)];if(r.type==="json")return[i,new ZO(r,this,s)];if(r.type==="sql native")return[i,new e7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return zl.Many;case"one":return zl.One;case"cross":return zl.Cross;case"inline":return zl.Inline;case"nested":return zl.Nested;case"basetable":return zl.BaseTable}}hasParentExplore(){return this instanceof r7}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}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?Zi.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?Zi.fromJSON(e.sourceExplore):void 0;return new Zi(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=Zi;var uu;(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"})(uu||(Oe.AtomicFieldType=uu={}));class Hl extends YO{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 uu.String;case"boolean":return uu.Boolean;case"date":return uu.Date;case"timestamp":return uu.Timestamp;case"number":return uu.Number;case"json":return uu.Json;case"sql native":return uu.NativeUnsupported;case"error":return uu.Error}}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,ql.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,ql.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}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 t7}isNumber(){return this instanceof lv}isDate(){return this instanceof XO}isBoolean(){return this instanceof KO}isJSON(){return this instanceof ZO}isTimestamp(){return this instanceof JO}isUnsupported(){return this instanceof e7}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=Hl;var Yc;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Yc||(Oe.DateTimeframe=Yc={}));var au;(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"})(au||(Oe.TimestampTimeframe=au={}));class XO extends Hl{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 Yc.Day;case"week":return Yc.Week;case"month":return Yc.Month;case"quarter":return Yc.Quarter;case"year":return Yc.Year}}}Oe.DateField=XO;class JO extends Hl{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 au.Day;case"week":return au.Week;case"month":return au.Month;case"quarter":return au.Quarter;case"year":return au.Year;case"second":return au.Second;case"hour":return au.Hour;case"minute":return au.Minute}}}Oe.TimestampField=JO;class lv extends Hl{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=lv;class KO extends Hl{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=KO;class ZO extends Hl{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=ZO;class e7 extends Hl{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=e7;class t7 extends Hl{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=t7;class VH extends YO{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=VH;class n7 extends VH{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=n7;var Ql;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Ql||(Oe.JoinRelationship=Ql={}));class r7 extends Zi{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return Ql.OneToMany;case"many":case"cross":return Ql.ManyToOne;case"inline":return Ql.OneToOne;case"nested":return Ql.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===Ql.OneToOne}get isArray(){return this.joinRelationship!==Ql.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=r7;class i7{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)dCe(i)?n=i:hCe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new WH),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new J1(this,async()=>{const s=e instanceof URL?await sn.parse({url:e,urlReader:this.urlReader,options:n}):sn.parse({source:e,options:n});return sn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences})},n)}_loadModelFromModelDef(e,n){return new J1(this,async()=>new W1(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)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}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()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Oe.Runtime=i7;class lCe extends i7{constructor(e,n){if(n===void 0){const r=e;super(Y1.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Y1.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=lCe;class cCe extends i7{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,WO.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,WO.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,WO.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=cCe;class X1{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 YH(this.runtime,e,n)}makeExploreMaterializer(e,n){return new KH(this.runtime,e,n)}makePreparedResultMaterializer(e){return new XH(this.runtime,e)}makeSQLBlockMaterializer(e){return new JH(this.runtime,e)}}class J1 extends X1{constructor(e,n,r){var i;super(e,n),this.runtime=e,this.replaceMaterializedReferences=(i=r==null?void 0:r.replaceMaterializedReferences)!==null&&i!==void 0?i:!1}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{replaceMaterializedReferences:this.replaceMaterializedReferences,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{var s;const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const a=e instanceof URL?await sn.parse({url:e,urlReader:o,options:n}):sn.parse({source:e,options:n}),l=await this.getModel();return(await sn.compile({urlReader:o,connections:u,parse:a,model:l,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:(s=n==null?void 0:n.replaceMaterializedReferences)!==null&&s!==void 0?s:this.replaceMaterializedReferences})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new J1(this.runtime,async()=>{var r;const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?await sn.parse({url:e,urlReader:i,options:n}):sn.parse({source:e,options:n}),u=await this.getModel();return await sn.compile({urlReader:i,connections:s,parse:o,model:u,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,replaceMaterializedReferences:(r=n==null?void 0:n.replaceMaterializedReferences)!==null&&r!==void 0?r:this.replaceMaterializedReferences})},n)}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new ql.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1306
+ ${g}`,m)}}else{if(p.urls)for(const g of p.urls)try{if(g.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const y=await e.readURL(new URL(g)),E={[g]:y};h.update({urls:E})}catch(y){h.update({errors:{urls:{[g]:y.message}}})}const{modelAnnotation:m}=h.modelAnnotation(i==null?void 0:i._modelDef);if(p.tables){const g=new Map;for(const y in p.tables){const{connectionName:E,tablePath:A}=p.tables[y],v=g.get(E);v===void 0?g.set(E,{[y]:A}):v[y]=A}for(const[y,E]of g)try{const A=await n.lookupConnection(y),{schemas:v,errors:_}=await A.fetchSchemaForTables(E,{refreshTimestamp:x,modelAnnotation:m});h.update({tables:v,errors:{tables:_}})}catch(A){const v={},_={};for(const S in E)_[S]=A.toString();h.update({tables:v,errors:{tables:_}})}}if(p.compileSQL){const g=p.compileSQL,y=g.connection;try{const E=await n.lookupConnection(y),A=sn.compileSQLBlock(p.partialModel,g,{replaceMaterializedReferences:u}),v=await E.fetchSchemaForSQLBlock(A,{refreshTimestamp:x,modelAnnotation:m});v.error&&h.update({errors:{compileSQL:{[A.name]:v.error}}}),v.structDef&&(0,ql.isSQLBlockStruct)(v.structDef)&&h.update({compileSQL:{[A.name]:v.structDef}})}catch(E){const A={};A[g.name]=E.toString(),h.update({errors:{compileSQL:A}})}}}}}static compileSQLBlock(e,n,r){let i,s="",o=!1;for(const l of n.select)if((0,ql.isSQLFragment)(l))s+=l.sql,o=l.sql.match(/\(\s*$/)!==null;else{if(!i){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new ql.QueryModel(e)}const c=i.compileQuery(l,r,!1).sql;s+=o?c:`(${c})`,o=!1}const{name:u,connection:a}=n;return{type:"sqlBlock",name:u,connection:a,selectStr:s}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new K1({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new K1({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.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}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.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(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new Zi(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new Xc(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=sn;class zH extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=zH;let W1=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}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 Od(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 Od(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Od(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new Zi(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new Zi(n))}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=W1;class Od{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 ql.QueryModel(this._modelDef).compileQuery(this._query,e);return new V1({...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(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Od;class HH{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new av(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new QH(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new GH(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=HH;class QH{constructor(e){this._range=Dd.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=QH;class Dd{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 Dd(new VO(e.start.line,e.start.character),new VO(e.end.line,e.end.character))}}Oe.DocumentRange=Dd;class VO{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=VO;class av{constructor(e){this._range=Dd.fromJSON(e.range),this._lensRange=e.lensRange?Dd.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new av(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=av;class GH{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=GH;class V1{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 V1(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 Zi(n,this.sourceExplore)}catch{return new Zi(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new Zi(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=V1;class WH{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=WH;class aCe{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=aCe;class Y1{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 Y1(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=Y1;var zl;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(zl||(Oe.SourceRelationship=zl={}));class YO{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 Zi}isQuery(){return this instanceof n7}}class Zi extends YO{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,ql.FieldIsIntrinsic)(this._structDef)}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={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Od(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new W1(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(r.type==="struct")return[i,new r7(r,this,s)];if(r.type==="turtle")return[i,new n7(r,this,s)];if(r.type==="string")return[i,new t7(r,this,s)];if(r.type==="number")return[i,new lv(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new lv({...r,type:"number"},this,s)]:[i,new XO(r,this,s)];if(r.type==="timestamp")return[i,new JO(r,this,s)];if(r.type==="boolean")return[i,new KO(r,this,s)];if(r.type==="json")return[i,new ZO(r,this,s)];if(r.type==="sql native")return[i,new e7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return zl.Many;case"one":return zl.One;case"cross":return zl.Cross;case"inline":return zl.Inline;case"nested":return zl.Nested;case"basetable":return zl.BaseTable}}hasParentExplore(){return this instanceof r7}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}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?Zi.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?Zi.fromJSON(e.sourceExplore):void 0;return new Zi(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=Zi;var uu;(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"})(uu||(Oe.AtomicFieldType=uu={}));class Hl extends YO{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 uu.String;case"boolean":return uu.Boolean;case"date":return uu.Date;case"timestamp":return uu.Timestamp;case"number":return uu.Number;case"json":return uu.Json;case"sql native":return uu.NativeUnsupported;case"error":return uu.Error}}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,ql.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,ql.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}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 t7}isNumber(){return this instanceof lv}isDate(){return this instanceof XO}isBoolean(){return this instanceof KO}isJSON(){return this instanceof ZO}isTimestamp(){return this instanceof JO}isUnsupported(){return this instanceof e7}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=Hl;var Yc;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Yc||(Oe.DateTimeframe=Yc={}));var au;(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"})(au||(Oe.TimestampTimeframe=au={}));class XO extends Hl{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 Yc.Day;case"week":return Yc.Week;case"month":return Yc.Month;case"quarter":return Yc.Quarter;case"year":return Yc.Year}}}Oe.DateField=XO;class JO extends Hl{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 au.Day;case"week":return au.Week;case"month":return au.Month;case"quarter":return au.Quarter;case"year":return au.Year;case"second":return au.Second;case"hour":return au.Hour;case"minute":return au.Minute}}}Oe.TimestampField=JO;class lv extends Hl{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=lv;class KO extends Hl{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=KO;class ZO extends Hl{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=ZO;class e7 extends Hl{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=e7;class t7 extends Hl{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=t7;class VH extends YO{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=VH;class n7 extends VH{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=n7;var Ql;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Ql||(Oe.JoinRelationship=Ql={}));class r7 extends Zi{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return Ql.OneToMany;case"many":case"cross":return Ql.ManyToOne;case"inline":return Ql.OneToOne;case"nested":return Ql.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===Ql.OneToOne}get isArray(){return this.joinRelationship!==Ql.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=r7;class i7{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)dCe(i)?n=i:hCe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new WH),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new J1(this,async()=>{const s=e instanceof URL?await sn.parse({url:e,urlReader:this.urlReader,options:n}):sn.parse({source:e,options:n});return sn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences})},n)}_loadModelFromModelDef(e,n){return new J1(this,async()=>new W1(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)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}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()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Oe.Runtime=i7;class lCe extends i7{constructor(e,n){if(n===void 0){const r=e;super(Y1.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Y1.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=lCe;class cCe extends i7{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,WO.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,WO.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,WO.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=cCe;class X1{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 YH(this.runtime,e,n)}makeExploreMaterializer(e,n){return new KH(this.runtime,e,n)}makePreparedResultMaterializer(e){return new XH(this.runtime,e)}makeSQLBlockMaterializer(e){return new JH(this.runtime,e)}}class J1 extends X1{constructor(e,n,r){var i;super(e,n),this.runtime=e,this.replaceMaterializedReferences=(i=r==null?void 0:r.replaceMaterializedReferences)!==null&&i!==void 0?i:!1}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{replaceMaterializedReferences:this.replaceMaterializedReferences,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{var s;const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const a=e instanceof URL?await sn.parse({url:e,urlReader:o,options:n}):sn.parse({source:e,options:n}),l=await this.getModel();return(await sn.compile({urlReader:o,connections:u,parse:a,model:l,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:(s=n==null?void 0:n.replaceMaterializedReferences)!==null&&s!==void 0?s:this.replaceMaterializedReferences})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new J1(this.runtime,async()=>{var r;const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?await sn.parse({url:e,urlReader:i,options:n}):sn.parse({source:e,options:n}),u=await this.getModel();return await sn.compile({urlReader:i,connections:s,parse:o,model:u,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,replaceMaterializedReferences:(r=n==null?void 0:n.replaceMaterializedReferences)!==null&&r!==void 0?r:this.replaceMaterializedReferences})},n)}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new ql.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1307
1307
  run: ${e}
1308
1308
  -> ${o}
1309
1309
  -> {
@@ -51642,6 +51642,9 @@ class C3 {
51642
51642
  get dependenciesToMaterialize() {
51643
51643
  return this.inner.dependenciesToMaterialize;
51644
51644
  }
51645
+ get materialization() {
51646
+ return this.inner.materialization;
51647
+ }
51645
51648
  /**
51646
51649
  * @return The `Explore` representing the data that will be returned by running this query.
51647
51650
  */
@@ -1303,7 +1303,7 @@ QUERY: ${(0,C3e.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...Iq.ErrorFact
1303
1303
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1304
1304
  `+i,n=s),e!==""?e=`${e}
1305
1305
  ${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];(u.type==="struct"||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,Fbe.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))}}au.MalloyTranslation=F7;class TQ extends F7{constructor(e,n){super(e),this.root=n}}au.MalloyChildTranslator=TQ;class Qbe extends F7{constructor(e,n=null,r=null){super(e,n),this.schemaZone=new N7.Zone,this.importZone=new N7.Zone,this.sqlQueryZone=new N7.Zone,this.logger=new w7.BaseMessageLogger,this.root=this,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,w7.makeLogMessage)(e,n,{severity:"error",...r})),e}}au.MalloyTranslator=Qbe;class RQ{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,w7.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}})}}au.MalloyParserErrorHandler=RQ;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.exploreQueryWalkerBuilder=Jd.ExploreQueryWalker=void 0;const Gbe=bl;class OQ{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=OQ;function Wbe(t,e){const n=new OQ(t),r=n;return Gbe.ParseTreeWalker.DEFAULT.walk(r,e),n}Jd.exploreQueryWalkerBuilder=Wbe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=au;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}})}(fR);var Oe={};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.SQLBlockMaterializer=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 Vbe=fR,o0=Go,DQ=wi,_n=Wo,L7=Bx;class an{static get version(){return"0.0.1"}static get log(){return an._log||console}static setLogger(e){an._log=e}static _parse(e,n,r){n===void 0&&(n=new URL("internal://internal.malloy"));let i=n;r!=null&&r.importBaseURL&&(i=r==null?void 0:r.importBaseURL);const s=new Vbe.MalloyTranslator(n.toString(),i.toString(),{urls:{[n.toString()]:e}});return r!=null&&r.testEnvironment&&(s.allDialectsEnabled=!0),new NQ(s)}static parse({url:e,urlReader:n,source:r,options:i}){if(r!==void 0)return an._parse(r,e,i);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(s=>an._parse(s,e,i))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,replaceMaterializedReferences:u}){var a,l,c,f;let x;s&&(x=typeof s=="number"?s:Date.now());const h=r._translator;for(;;){const p=h.translate(i==null?void 0:i._modelDef);if(p.final){if(p.translated)return new Og(p.translated.modelDef,p.translated.queryList,p.translated.sqlBlocks,p.problems||[],[...(a=i==null?void 0:i.fromSources)!==null&&a!==void 0?a:[],...(l=p.fromSources)!==null&&l!==void 0?l:[]],m=>h.referenceAt(m),m=>h.importAt(m));if(o){const m={name:"modelDidNotCompile",exports:[],contents:{}},g=(i==null?void 0:i._modelDef)||m;return new Og(g,[],[],p.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=p.fromSources)!==null&&f!==void 0?f:[]],y=>h.referenceAt(y),y=>h.importAt(y))}else{const m=p.problems||[],g=h.prettyErrors();throw new wQ(`Error(s) compiling model:
1306
- ${g}`,m)}}else{if(p.urls)for(const g of p.urls)try{if(g.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const y=await e.readURL(new URL(g)),E={[g]:y};h.update({urls:E})}catch(y){h.update({errors:{urls:{[g]:y.message}}})}const{modelAnnotation:m}=h.modelAnnotation(i==null?void 0:i._modelDef);if(p.tables){const g=new Map;for(const y in p.tables){const{connectionName:E,tablePath:A}=p.tables[y],v=g.get(E);v===void 0?g.set(E,{[y]:A}):v[y]=A}for(const[y,E]of g)try{const A=await n.lookupConnection(y),{schemas:v,errors:_}=await A.fetchSchemaForTables(E,{refreshTimestamp:x,modelAnnotation:m});h.update({tables:v,errors:{tables:_}})}catch(A){const v={},_={};for(const S in E)_[S]=A.toString();h.update({tables:v,errors:{tables:_}})}}if(p.compileSQL){const g=p.compileSQL,y=g.connection;try{const E=await n.lookupConnection(y),A=an.compileSQLBlock(p.partialModel,g,{replaceMaterializedReferences:u}),v=await E.fetchSchemaForSQLBlock(A,{refreshTimestamp:x,modelAnnotation:m});v.error&&h.update({errors:{compileSQL:{[A.name]:v.error}}}),v.structDef&&(0,o0.isSQLBlockStruct)(v.structDef)&&h.update({compileSQL:{[A.name]:v.structDef}})}catch(E){const A={};A[g.name]=E.toString(),h.update({errors:{compileSQL:A}})}}}}}static compileSQLBlock(e,n,r){let i,s="",o=!1;for(const l of n.select)if((0,o0.isSQLFragment)(l))s+=l.sql,o=l.sql.match(/\(\s*$/)!==null;else{if(!i){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new o0.QueryModel(e)}const c=i.compileQuery(l,r,!1).sql;s+=o?c:`(${c})`,o=!1}const{name:u,connection:a}=n;return{type:"sqlBlock",name:u,connection:a,selectStr:s}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new Lg({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new Lg({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.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}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.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(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new ss(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new hf(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=an;class wQ extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=wQ;let Og=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return _n.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return _n.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 Zd(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 Zd(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Zd(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new ss(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new ss(n))}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=Og;class Zd{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=_n.Tag.annotationToTag(this._modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new o0.QueryModel(this._modelDef).compileQuery(this._query,e);return new Dg({...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(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Zd;class NQ{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new JS(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new FQ(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new LQ(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=NQ;class FQ{constructor(e){this._range=eh.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=FQ;class eh{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 eh(new I7(e.start.line,e.start.character),new I7(e.end.line,e.end.character))}}Oe.DocumentRange=eh;class I7{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=I7;class JS{constructor(e){this._range=eh.fromJSON(e.range),this._lensRange=e.lensRange?eh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new JS(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=JS;class LQ{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=LQ;class Dg{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 Dg(e,n)}tagParse(e){const n=_n.Tag.annotationToTag(this.modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return _n.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 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 ss(n,this.sourceExplore)}catch{return new ss(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new ss(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=Dg;class IQ{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=IQ;class Ybe{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=Ybe;class wg{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 wg(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=wg;var u0;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(u0||(Oe.SourceRelationship=u0={}));class B7{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 ss}isQuery(){return this instanceof q7}}class ss extends B7{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,o0.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return _n.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=_n.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Zd(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Og(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(r.type==="struct")return[i,new z7(r,this,s)];if(r.type==="turtle")return[i,new q7(r,this,s)];if(r.type==="string")return[i,new U7(r,this,s)];if(r.type==="number")return[i,new ZS(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new ZS({...r,type:"number"},this,s)]:[i,new $7(r,this,s)];if(r.type==="timestamp")return[i,new k7(r,this,s)];if(r.type==="boolean")return[i,new M7(r,this,s)];if(r.type==="json")return[i,new P7(r,this,s)];if(r.type==="sql native")return[i,new j7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return u0.Many;case"one":return u0.One;case"cross":return u0.Cross;case"inline":return u0.Inline;case"nested":return u0.Nested;case"basetable":return u0.BaseTable}}hasParentExplore(){return this instanceof z7}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}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?ss.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ss.fromJSON(e.sourceExplore):void 0;return new ss(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=ss;var yu;(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"})(yu||(Oe.AtomicFieldType=yu={}));class a0 extends B7{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 yu.String;case"boolean":return yu.Boolean;case"date":return yu.Date;case"timestamp":return yu.Timestamp;case"number":return yu.Number;case"json":return yu.Json;case"sql native":return yu.NativeUnsupported;case"error":return yu.Error}}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,o0.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,o0.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}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 U7}isNumber(){return this instanceof ZS}isDate(){return this instanceof $7}isBoolean(){return this instanceof M7}isJSON(){return this instanceof P7}isTimestamp(){return this instanceof k7}isUnsupported(){return this instanceof j7}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=a0;var df;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(df||(Oe.DateTimeframe=df={}));var Eu;(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"})(Eu||(Oe.TimestampTimeframe=Eu={}));class $7 extends a0{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 df.Day;case"week":return df.Week;case"month":return df.Month;case"quarter":return df.Quarter;case"year":return df.Year}}}Oe.DateField=$7;class k7 extends a0{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 Eu.Day;case"week":return Eu.Week;case"month":return Eu.Month;case"quarter":return Eu.Quarter;case"year":return Eu.Year;case"second":return Eu.Second;case"hour":return Eu.Hour;case"minute":return Eu.Minute}}}Oe.TimestampField=k7;class ZS extends a0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=ZS;class M7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=M7;class P7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=P7;class j7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=j7;class U7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=U7;class BQ extends B7{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=BQ;class q7 extends BQ{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return _n.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=q7;var l0;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(l0||(Oe.JoinRelationship=l0={}));class z7 extends ss{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return l0.OneToMany;case"many":case"cross":return l0.ManyToOne;case"inline":return l0.OneToOne;case"nested":return l0.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===l0.OneToOne}get isArray(){return this.joinRelationship!==l0.OneToOne}tagParse(e){return e=_n.Tag.addModelScope(e,this._parentExplore.modelTag),_n.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=z7;class H7{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)eTe(i)?n=i:tTe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new IQ),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Fg(this,async()=>{const s=e instanceof URL?await an.parse({url:e,urlReader:this.urlReader,options:n}):an.parse({source:e,options:n});return an.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences})},n)}_loadModelFromModelDef(e,n){return new Fg(this,async()=>new Og(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)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}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()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Oe.Runtime=H7;class Xbe extends H7{constructor(e,n){if(n===void 0){const r=e;super(wg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,wg.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=Xbe;class Kbe extends H7{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,L7.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,L7.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,L7.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=Kbe;class Ng{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 $Q(this.runtime,e,n)}makeExploreMaterializer(e,n){return new PQ(this.runtime,e,n)}makePreparedResultMaterializer(e){return new kQ(this.runtime,e)}makeSQLBlockMaterializer(e){return new MQ(this.runtime,e)}}class Fg extends Ng{constructor(e,n,r){var i;super(e,n),this.runtime=e,this.replaceMaterializedReferences=(i=r==null?void 0:r.replaceMaterializedReferences)!==null&&i!==void 0?i:!1}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{replaceMaterializedReferences:this.replaceMaterializedReferences,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{var s;const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const a=e instanceof URL?await an.parse({url:e,urlReader:o,options:n}):an.parse({source:e,options:n}),l=await this.getModel();return(await an.compile({urlReader:o,connections:u,parse:a,model:l,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:(s=n==null?void 0:n.replaceMaterializedReferences)!==null&&s!==void 0?s:this.replaceMaterializedReferences})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Fg(this.runtime,async()=>{var r;const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?await an.parse({url:e,urlReader:i,options:n}):an.parse({source:e,options:n}),u=await this.getModel();return await an.compile({urlReader:i,connections:s,parse:o,model:u,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,replaceMaterializedReferences:(r=n==null?void 0:n.replaceMaterializedReferences)!==null&&r!==void 0?r:this.replaceMaterializedReferences})},n)}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new o0.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1306
+ ${g}`,m)}}else{if(p.urls)for(const g of p.urls)try{if(g.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const y=await e.readURL(new URL(g)),E={[g]:y};h.update({urls:E})}catch(y){h.update({errors:{urls:{[g]:y.message}}})}const{modelAnnotation:m}=h.modelAnnotation(i==null?void 0:i._modelDef);if(p.tables){const g=new Map;for(const y in p.tables){const{connectionName:E,tablePath:A}=p.tables[y],v=g.get(E);v===void 0?g.set(E,{[y]:A}):v[y]=A}for(const[y,E]of g)try{const A=await n.lookupConnection(y),{schemas:v,errors:_}=await A.fetchSchemaForTables(E,{refreshTimestamp:x,modelAnnotation:m});h.update({tables:v,errors:{tables:_}})}catch(A){const v={},_={};for(const S in E)_[S]=A.toString();h.update({tables:v,errors:{tables:_}})}}if(p.compileSQL){const g=p.compileSQL,y=g.connection;try{const E=await n.lookupConnection(y),A=an.compileSQLBlock(p.partialModel,g,{replaceMaterializedReferences:u}),v=await E.fetchSchemaForSQLBlock(A,{refreshTimestamp:x,modelAnnotation:m});v.error&&h.update({errors:{compileSQL:{[A.name]:v.error}}}),v.structDef&&(0,o0.isSQLBlockStruct)(v.structDef)&&h.update({compileSQL:{[A.name]:v.structDef}})}catch(E){const A={};A[g.name]=E.toString(),h.update({errors:{compileSQL:A}})}}}}}static compileSQLBlock(e,n,r){let i,s="",o=!1;for(const l of n.select)if((0,o0.isSQLFragment)(l))s+=l.sql,o=l.sql.match(/\(\s*$/)!==null;else{if(!i){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new o0.QueryModel(e)}const c=i.compileQuery(l,r,!1).sql;s+=o?c:`(${c})`,o=!1}const{name:u,connection:a}=n;return{type:"sqlBlock",name:u,connection:a,selectStr:s}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new Lg({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new Lg({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.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}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.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(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new ss(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new hf(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=an;class wQ extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=wQ;let Og=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return _n.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return _n.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 Zd(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 Zd(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Zd(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new ss(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new ss(n))}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=Og;class Zd{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=_n.Tag.annotationToTag(this._modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new o0.QueryModel(this._modelDef).compileQuery(this._query,e);return new Dg({...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(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Zd;class NQ{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new JS(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new FQ(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new LQ(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=NQ;class FQ{constructor(e){this._range=eh.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=FQ;class eh{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 eh(new I7(e.start.line,e.start.character),new I7(e.end.line,e.end.character))}}Oe.DocumentRange=eh;class I7{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=I7;class JS{constructor(e){this._range=eh.fromJSON(e.range),this._lensRange=e.lensRange?eh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new JS(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=JS;class LQ{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=LQ;class Dg{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 Dg(e,n)}tagParse(e){const n=_n.Tag.annotationToTag(this.modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return _n.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 ss(n,this.sourceExplore)}catch{return new ss(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new ss(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=Dg;class IQ{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=IQ;class Ybe{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=Ybe;class wg{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 wg(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=wg;var u0;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(u0||(Oe.SourceRelationship=u0={}));class B7{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 ss}isQuery(){return this instanceof q7}}class ss extends B7{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,o0.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return _n.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=_n.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Zd(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Og(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(r.type==="struct")return[i,new z7(r,this,s)];if(r.type==="turtle")return[i,new q7(r,this,s)];if(r.type==="string")return[i,new U7(r,this,s)];if(r.type==="number")return[i,new ZS(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new ZS({...r,type:"number"},this,s)]:[i,new $7(r,this,s)];if(r.type==="timestamp")return[i,new k7(r,this,s)];if(r.type==="boolean")return[i,new M7(r,this,s)];if(r.type==="json")return[i,new P7(r,this,s)];if(r.type==="sql native")return[i,new j7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return u0.Many;case"one":return u0.One;case"cross":return u0.Cross;case"inline":return u0.Inline;case"nested":return u0.Nested;case"basetable":return u0.BaseTable}}hasParentExplore(){return this instanceof z7}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}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?ss.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ss.fromJSON(e.sourceExplore):void 0;return new ss(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=ss;var yu;(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"})(yu||(Oe.AtomicFieldType=yu={}));class a0 extends B7{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 yu.String;case"boolean":return yu.Boolean;case"date":return yu.Date;case"timestamp":return yu.Timestamp;case"number":return yu.Number;case"json":return yu.Json;case"sql native":return yu.NativeUnsupported;case"error":return yu.Error}}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,o0.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,o0.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}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 U7}isNumber(){return this instanceof ZS}isDate(){return this instanceof $7}isBoolean(){return this instanceof M7}isJSON(){return this instanceof P7}isTimestamp(){return this instanceof k7}isUnsupported(){return this instanceof j7}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=a0;var df;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(df||(Oe.DateTimeframe=df={}));var Eu;(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"})(Eu||(Oe.TimestampTimeframe=Eu={}));class $7 extends a0{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 df.Day;case"week":return df.Week;case"month":return df.Month;case"quarter":return df.Quarter;case"year":return df.Year}}}Oe.DateField=$7;class k7 extends a0{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 Eu.Day;case"week":return Eu.Week;case"month":return Eu.Month;case"quarter":return Eu.Quarter;case"year":return Eu.Year;case"second":return Eu.Second;case"hour":return Eu.Hour;case"minute":return Eu.Minute}}}Oe.TimestampField=k7;class ZS extends a0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=ZS;class M7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=M7;class P7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=P7;class j7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=j7;class U7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=U7;class BQ extends B7{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=BQ;class q7 extends BQ{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return _n.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=q7;var l0;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(l0||(Oe.JoinRelationship=l0={}));class z7 extends ss{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return l0.OneToMany;case"many":case"cross":return l0.ManyToOne;case"inline":return l0.OneToOne;case"nested":return l0.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===l0.OneToOne}get isArray(){return this.joinRelationship!==l0.OneToOne}tagParse(e){return e=_n.Tag.addModelScope(e,this._parentExplore.modelTag),_n.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=z7;class H7{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)eTe(i)?n=i:tTe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new IQ),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Fg(this,async()=>{const s=e instanceof URL?await an.parse({url:e,urlReader:this.urlReader,options:n}):an.parse({source:e,options:n});return an.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences})},n)}_loadModelFromModelDef(e,n){return new Fg(this,async()=>new Og(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)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}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()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Oe.Runtime=H7;class Xbe extends H7{constructor(e,n){if(n===void 0){const r=e;super(wg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,wg.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=Xbe;class Kbe extends H7{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,L7.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,L7.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,L7.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=Kbe;class Ng{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 $Q(this.runtime,e,n)}makeExploreMaterializer(e,n){return new PQ(this.runtime,e,n)}makePreparedResultMaterializer(e){return new kQ(this.runtime,e)}makeSQLBlockMaterializer(e){return new MQ(this.runtime,e)}}class Fg extends Ng{constructor(e,n,r){var i;super(e,n),this.runtime=e,this.replaceMaterializedReferences=(i=r==null?void 0:r.replaceMaterializedReferences)!==null&&i!==void 0?i:!1}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{replaceMaterializedReferences:this.replaceMaterializedReferences,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{var s;const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const a=e instanceof URL?await an.parse({url:e,urlReader:o,options:n}):an.parse({source:e,options:n}),l=await this.getModel();return(await an.compile({urlReader:o,connections:u,parse:a,model:l,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:(s=n==null?void 0:n.replaceMaterializedReferences)!==null&&s!==void 0?s:this.replaceMaterializedReferences})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Fg(this.runtime,async()=>{var r;const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?await an.parse({url:e,urlReader:i,options:n}):an.parse({source:e,options:n}),u=await this.getModel();return await an.compile({urlReader:i,connections:s,parse:o,model:u,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,replaceMaterializedReferences:(r=n==null?void 0:n.replaceMaterializedReferences)!==null&&r!==void 0?r:this.replaceMaterializedReferences})},n)}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new o0.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1307
1307
  run: ${e}
1308
1308
  -> ${o}
1309
1309
  -> {
@@ -51642,6 +51642,9 @@ class C3 {
51642
51642
  get dependenciesToMaterialize() {
51643
51643
  return this.inner.dependenciesToMaterialize;
51644
51644
  }
51645
+ get materialization() {
51646
+ return this.inner.materialization;
51647
+ }
51645
51648
  /**
51646
51649
  * @return The `Explore` representing the data that will be returned by running this query.
51647
51650
  */
@@ -1303,7 +1303,7 @@ QUERY: ${(0,C3e.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...Lq.ErrorFact
1303
1303
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1304
1304
  `+i,n=s),e!==""?e=`${e}
1305
1305
  ${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];(u.type==="struct"||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,Fbe.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))}}au.MalloyTranslation=N7;class bQ extends N7{constructor(e,n){super(e),this.root=n}}au.MalloyChildTranslator=bQ;class Qbe extends N7{constructor(e,n=null,r=null){super(e,n),this.schemaZone=new w7.Zone,this.importZone=new w7.Zone,this.sqlQueryZone=new w7.Zone,this.logger=new D7.BaseMessageLogger,this.root=this,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,D7.makeLogMessage)(e,n,{severity:"error",...r})),e}}au.MalloyTranslator=Qbe;class TQ{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,D7.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}})}}au.MalloyParserErrorHandler=TQ;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.exploreQueryWalkerBuilder=Jd.ExploreQueryWalker=void 0;const Gbe=bl;class RQ{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=RQ;function Wbe(t,e){const n=new RQ(t),r=n;return Gbe.ParseTreeWalker.DEFAULT.walk(r,e),n}Jd.exploreQueryWalkerBuilder=Wbe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=au;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}})}(cR);var Oe={};Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.SQLBlockMaterializer=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 Vbe=cR,o0=Go,OQ=wi,_n=Wo,F7=Bx;class an{static get version(){return"0.0.1"}static get log(){return an._log||console}static setLogger(e){an._log=e}static _parse(e,n,r){n===void 0&&(n=new URL("internal://internal.malloy"));let i=n;r!=null&&r.importBaseURL&&(i=r==null?void 0:r.importBaseURL);const s=new Vbe.MalloyTranslator(n.toString(),i.toString(),{urls:{[n.toString()]:e}});return r!=null&&r.testEnvironment&&(s.allDialectsEnabled=!0),new wQ(s)}static parse({url:e,urlReader:n,source:r,options:i}){if(r!==void 0)return an._parse(r,e,i);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(s=>an._parse(s,e,i))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,replaceMaterializedReferences:u}){var a,l,c,f;let x;s&&(x=typeof s=="number"?s:Date.now());const h=r._translator;for(;;){const p=h.translate(i==null?void 0:i._modelDef);if(p.final){if(p.translated)return new Tg(p.translated.modelDef,p.translated.queryList,p.translated.sqlBlocks,p.problems||[],[...(a=i==null?void 0:i.fromSources)!==null&&a!==void 0?a:[],...(l=p.fromSources)!==null&&l!==void 0?l:[]],m=>h.referenceAt(m),m=>h.importAt(m));if(o){const m={name:"modelDidNotCompile",exports:[],contents:{}},g=(i==null?void 0:i._modelDef)||m;return new Tg(g,[],[],p.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=p.fromSources)!==null&&f!==void 0?f:[]],y=>h.referenceAt(y),y=>h.importAt(y))}else{const m=p.problems||[],g=h.prettyErrors();throw new DQ(`Error(s) compiling model:
1306
- ${g}`,m)}}else{if(p.urls)for(const g of p.urls)try{if(g.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const y=await e.readURL(new URL(g)),E={[g]:y};h.update({urls:E})}catch(y){h.update({errors:{urls:{[g]:y.message}}})}const{modelAnnotation:m}=h.modelAnnotation(i==null?void 0:i._modelDef);if(p.tables){const g=new Map;for(const y in p.tables){const{connectionName:E,tablePath:A}=p.tables[y],v=g.get(E);v===void 0?g.set(E,{[y]:A}):v[y]=A}for(const[y,E]of g)try{const A=await n.lookupConnection(y),{schemas:v,errors:_}=await A.fetchSchemaForTables(E,{refreshTimestamp:x,modelAnnotation:m});h.update({tables:v,errors:{tables:_}})}catch(A){const v={},_={};for(const S in E)_[S]=A.toString();h.update({tables:v,errors:{tables:_}})}}if(p.compileSQL){const g=p.compileSQL,y=g.connection;try{const E=await n.lookupConnection(y),A=an.compileSQLBlock(p.partialModel,g,{replaceMaterializedReferences:u}),v=await E.fetchSchemaForSQLBlock(A,{refreshTimestamp:x,modelAnnotation:m});v.error&&h.update({errors:{compileSQL:{[A.name]:v.error}}}),v.structDef&&(0,o0.isSQLBlockStruct)(v.structDef)&&h.update({compileSQL:{[A.name]:v.structDef}})}catch(E){const A={};A[g.name]=E.toString(),h.update({errors:{compileSQL:A}})}}}}}static compileSQLBlock(e,n,r){let i,s="",o=!1;for(const l of n.select)if((0,o0.isSQLFragment)(l))s+=l.sql,o=l.sql.match(/\(\s*$/)!==null;else{if(!i){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new o0.QueryModel(e)}const c=i.compileQuery(l,r,!1).sql;s+=o?c:`(${c})`,o=!1}const{name:u,connection:a}=n;return{type:"sqlBlock",name:u,connection:a,selectStr:s}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new Ng({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new Ng({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.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}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.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(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new ss(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new hf(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=an;class DQ extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=DQ;let Tg=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return _n.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return _n.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 Zd(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 Zd(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Zd(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new ss(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new ss(n))}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=Tg;class Zd{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=_n.Tag.annotationToTag(this._modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new o0.QueryModel(this._modelDef).compileQuery(this._query,e);return new Rg({...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(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Zd;class wQ{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new KS(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new NQ(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new FQ(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=wQ;class NQ{constructor(e){this._range=eh.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=NQ;class eh{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 eh(new L7(e.start.line,e.start.character),new L7(e.end.line,e.end.character))}}Oe.DocumentRange=eh;class L7{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=L7;class KS{constructor(e){this._range=eh.fromJSON(e.range),this._lensRange=e.lensRange?eh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new KS(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=KS;class FQ{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=FQ;class Rg{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 Rg(e,n)}tagParse(e){const n=_n.Tag.annotationToTag(this.modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return _n.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 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 ss(n,this.sourceExplore)}catch{return new ss(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new ss(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=Rg;class LQ{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=LQ;class Ybe{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=Ybe;class Og{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 Og(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=Og;var u0;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(u0||(Oe.SourceRelationship=u0={}));class I7{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 ss}isQuery(){return this instanceof U7}}class ss extends I7{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,o0.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return _n.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=_n.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Zd(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Tg(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(r.type==="struct")return[i,new q7(r,this,s)];if(r.type==="turtle")return[i,new U7(r,this,s)];if(r.type==="string")return[i,new j7(r,this,s)];if(r.type==="number")return[i,new JS(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new JS({...r,type:"number"},this,s)]:[i,new B7(r,this,s)];if(r.type==="timestamp")return[i,new $7(r,this,s)];if(r.type==="boolean")return[i,new k7(r,this,s)];if(r.type==="json")return[i,new M7(r,this,s)];if(r.type==="sql native")return[i,new P7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return u0.Many;case"one":return u0.One;case"cross":return u0.Cross;case"inline":return u0.Inline;case"nested":return u0.Nested;case"basetable":return u0.BaseTable}}hasParentExplore(){return this instanceof q7}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}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?ss.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ss.fromJSON(e.sourceExplore):void 0;return new ss(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=ss;var yu;(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"})(yu||(Oe.AtomicFieldType=yu={}));class a0 extends I7{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 yu.String;case"boolean":return yu.Boolean;case"date":return yu.Date;case"timestamp":return yu.Timestamp;case"number":return yu.Number;case"json":return yu.Json;case"sql native":return yu.NativeUnsupported;case"error":return yu.Error}}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,o0.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,o0.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}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 j7}isNumber(){return this instanceof JS}isDate(){return this instanceof B7}isBoolean(){return this instanceof k7}isJSON(){return this instanceof M7}isTimestamp(){return this instanceof $7}isUnsupported(){return this instanceof P7}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=a0;var df;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(df||(Oe.DateTimeframe=df={}));var Eu;(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"})(Eu||(Oe.TimestampTimeframe=Eu={}));class B7 extends a0{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 df.Day;case"week":return df.Week;case"month":return df.Month;case"quarter":return df.Quarter;case"year":return df.Year}}}Oe.DateField=B7;class $7 extends a0{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 Eu.Day;case"week":return Eu.Week;case"month":return Eu.Month;case"quarter":return Eu.Quarter;case"year":return Eu.Year;case"second":return Eu.Second;case"hour":return Eu.Hour;case"minute":return Eu.Minute}}}Oe.TimestampField=$7;class JS extends a0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=JS;class k7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=k7;class M7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=M7;class P7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=P7;class j7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=j7;class IQ extends I7{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=IQ;class U7 extends IQ{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return _n.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=U7;var l0;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(l0||(Oe.JoinRelationship=l0={}));class q7 extends ss{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return l0.OneToMany;case"many":case"cross":return l0.ManyToOne;case"inline":return l0.OneToOne;case"nested":return l0.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===l0.OneToOne}get isArray(){return this.joinRelationship!==l0.OneToOne}tagParse(e){return e=_n.Tag.addModelScope(e,this._parentExplore.modelTag),_n.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 z7{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)eTe(i)?n=i:tTe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new LQ),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new wg(this,async()=>{const s=e instanceof URL?await an.parse({url:e,urlReader:this.urlReader,options:n}):an.parse({source:e,options:n});return an.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences})},n)}_loadModelFromModelDef(e,n){return new wg(this,async()=>new Tg(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)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}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()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Oe.Runtime=z7;class Xbe extends z7{constructor(e,n){if(n===void 0){const r=e;super(Og.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Og.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=Xbe;class Kbe extends z7{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,F7.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,F7.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,F7.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=Kbe;class Dg{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 BQ(this.runtime,e,n)}makeExploreMaterializer(e,n){return new MQ(this.runtime,e,n)}makePreparedResultMaterializer(e){return new $Q(this.runtime,e)}makeSQLBlockMaterializer(e){return new kQ(this.runtime,e)}}class wg extends Dg{constructor(e,n,r){var i;super(e,n),this.runtime=e,this.replaceMaterializedReferences=(i=r==null?void 0:r.replaceMaterializedReferences)!==null&&i!==void 0?i:!1}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{replaceMaterializedReferences:this.replaceMaterializedReferences,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{var s;const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const a=e instanceof URL?await an.parse({url:e,urlReader:o,options:n}):an.parse({source:e,options:n}),l=await this.getModel();return(await an.compile({urlReader:o,connections:u,parse:a,model:l,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:(s=n==null?void 0:n.replaceMaterializedReferences)!==null&&s!==void 0?s:this.replaceMaterializedReferences})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new wg(this.runtime,async()=>{var r;const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?await an.parse({url:e,urlReader:i,options:n}):an.parse({source:e,options:n}),u=await this.getModel();return await an.compile({urlReader:i,connections:s,parse:o,model:u,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,replaceMaterializedReferences:(r=n==null?void 0:n.replaceMaterializedReferences)!==null&&r!==void 0?r:this.replaceMaterializedReferences})},n)}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new o0.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1306
+ ${g}`,m)}}else{if(p.urls)for(const g of p.urls)try{if(g.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const y=await e.readURL(new URL(g)),E={[g]:y};h.update({urls:E})}catch(y){h.update({errors:{urls:{[g]:y.message}}})}const{modelAnnotation:m}=h.modelAnnotation(i==null?void 0:i._modelDef);if(p.tables){const g=new Map;for(const y in p.tables){const{connectionName:E,tablePath:A}=p.tables[y],v=g.get(E);v===void 0?g.set(E,{[y]:A}):v[y]=A}for(const[y,E]of g)try{const A=await n.lookupConnection(y),{schemas:v,errors:_}=await A.fetchSchemaForTables(E,{refreshTimestamp:x,modelAnnotation:m});h.update({tables:v,errors:{tables:_}})}catch(A){const v={},_={};for(const S in E)_[S]=A.toString();h.update({tables:v,errors:{tables:_}})}}if(p.compileSQL){const g=p.compileSQL,y=g.connection;try{const E=await n.lookupConnection(y),A=an.compileSQLBlock(p.partialModel,g,{replaceMaterializedReferences:u}),v=await E.fetchSchemaForSQLBlock(A,{refreshTimestamp:x,modelAnnotation:m});v.error&&h.update({errors:{compileSQL:{[A.name]:v.error}}}),v.structDef&&(0,o0.isSQLBlockStruct)(v.structDef)&&h.update({compileSQL:{[A.name]:v.structDef}})}catch(E){const A={};A[g.name]=E.toString(),h.update({errors:{compileSQL:A}})}}}}}static compileSQLBlock(e,n,r){let i,s="",o=!1;for(const l of n.select)if((0,o0.isSQLFragment)(l))s+=l.sql,o=l.sql.match(/\(\s*$/)!==null;else{if(!i){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new o0.QueryModel(e)}const c=i.compileQuery(l,r,!1).sql;s+=o?c:`(${c})`,o=!1}const{name:u,connection:a}=n;return{type:"sqlBlock",name:u,connection:a,selectStr:s}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new Ng({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new Ng({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.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}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.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(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new ss(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new hf(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=an;class DQ extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=DQ;let Tg=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return _n.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return _n.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 Zd(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 Zd(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Zd(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new ss(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new ss(n))}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=Tg;class Zd{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=_n.Tag.annotationToTag(this._modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new o0.QueryModel(this._modelDef).compileQuery(this._query,e);return new Rg({...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(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Zd;class wQ{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new KS(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new NQ(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new FQ(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=wQ;class NQ{constructor(e){this._range=eh.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=NQ;class eh{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 eh(new L7(e.start.line,e.start.character),new L7(e.end.line,e.end.character))}}Oe.DocumentRange=eh;class L7{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=L7;class KS{constructor(e){this._range=eh.fromJSON(e.range),this._lensRange=e.lensRange?eh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new KS(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=KS;class FQ{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=FQ;class Rg{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 Rg(e,n)}tagParse(e){const n=_n.Tag.annotationToTag(this.modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return _n.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 ss(n,this.sourceExplore)}catch{return new ss(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new ss(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=Rg;class LQ{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=LQ;class Ybe{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=Ybe;class Og{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 Og(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=Og;var u0;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(u0||(Oe.SourceRelationship=u0={}));class I7{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 ss}isQuery(){return this instanceof U7}}class ss extends I7{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,o0.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return _n.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=_n.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Zd(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Tg(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(r.type==="struct")return[i,new q7(r,this,s)];if(r.type==="turtle")return[i,new U7(r,this,s)];if(r.type==="string")return[i,new j7(r,this,s)];if(r.type==="number")return[i,new JS(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new JS({...r,type:"number"},this,s)]:[i,new B7(r,this,s)];if(r.type==="timestamp")return[i,new $7(r,this,s)];if(r.type==="boolean")return[i,new k7(r,this,s)];if(r.type==="json")return[i,new M7(r,this,s)];if(r.type==="sql native")return[i,new P7(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return u0.Many;case"one":return u0.One;case"cross":return u0.Cross;case"inline":return u0.Inline;case"nested":return u0.Nested;case"basetable":return u0.BaseTable}}hasParentExplore(){return this instanceof q7}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}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?ss.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ss.fromJSON(e.sourceExplore):void 0;return new ss(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=ss;var yu;(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"})(yu||(Oe.AtomicFieldType=yu={}));class a0 extends I7{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 yu.String;case"boolean":return yu.Boolean;case"date":return yu.Date;case"timestamp":return yu.Timestamp;case"number":return yu.Number;case"json":return yu.Json;case"sql native":return yu.NativeUnsupported;case"error":return yu.Error}}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,o0.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,o0.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}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 j7}isNumber(){return this instanceof JS}isDate(){return this instanceof B7}isBoolean(){return this instanceof k7}isJSON(){return this instanceof M7}isTimestamp(){return this instanceof $7}isUnsupported(){return this instanceof P7}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=a0;var df;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(df||(Oe.DateTimeframe=df={}));var Eu;(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"})(Eu||(Oe.TimestampTimeframe=Eu={}));class B7 extends a0{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 df.Day;case"week":return df.Week;case"month":return df.Month;case"quarter":return df.Quarter;case"year":return df.Year}}}Oe.DateField=B7;class $7 extends a0{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 Eu.Day;case"week":return Eu.Week;case"month":return Eu.Month;case"quarter":return Eu.Quarter;case"year":return Eu.Year;case"second":return Eu.Second;case"hour":return Eu.Hour;case"minute":return Eu.Minute}}}Oe.TimestampField=$7;class JS extends a0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=JS;class k7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=k7;class M7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=M7;class P7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=P7;class j7 extends a0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=j7;class IQ extends I7{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=IQ;class U7 extends IQ{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return _n.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=U7;var l0;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(l0||(Oe.JoinRelationship=l0={}));class q7 extends ss{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return l0.OneToMany;case"many":case"cross":return l0.ManyToOne;case"inline":return l0.OneToOne;case"nested":return l0.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===l0.OneToOne}get isArray(){return this.joinRelationship!==l0.OneToOne}tagParse(e){return e=_n.Tag.addModelScope(e,this._parentExplore.modelTag),_n.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 z7{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)eTe(i)?n=i:tTe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new LQ),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new wg(this,async()=>{const s=e instanceof URL?await an.parse({url:e,urlReader:this.urlReader,options:n}):an.parse({source:e,options:n});return an.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences})},n)}_loadModelFromModelDef(e,n){return new wg(this,async()=>new Tg(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)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}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()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Oe.Runtime=z7;class Xbe extends z7{constructor(e,n){if(n===void 0){const r=e;super(Og.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Og.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=Xbe;class Kbe extends z7{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,F7.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,F7.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,F7.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=Kbe;class Dg{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 BQ(this.runtime,e,n)}makeExploreMaterializer(e,n){return new MQ(this.runtime,e,n)}makePreparedResultMaterializer(e){return new $Q(this.runtime,e)}makeSQLBlockMaterializer(e){return new kQ(this.runtime,e)}}class wg extends Dg{constructor(e,n,r){var i;super(e,n),this.runtime=e,this.replaceMaterializedReferences=(i=r==null?void 0:r.replaceMaterializedReferences)!==null&&i!==void 0?i:!1}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{replaceMaterializedReferences:this.replaceMaterializedReferences,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{replaceMaterializedReferences:this.replaceMaterializedReferences,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{var s;const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const a=e instanceof URL?await an.parse({url:e,urlReader:o,options:n}):an.parse({source:e,options:n}),l=await this.getModel();return(await an.compile({urlReader:o,connections:u,parse:a,model:l,refreshSchemaCache:r,noThrowOnError:i,replaceMaterializedReferences:(s=n==null?void 0:n.replaceMaterializedReferences)!==null&&s!==void 0?s:this.replaceMaterializedReferences})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new wg(this.runtime,async()=>{var r;const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?await an.parse({url:e,urlReader:i,options:n}):an.parse({source:e,options:n}),u=await this.getModel();return await an.compile({urlReader:i,connections:s,parse:o,model:u,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,replaceMaterializedReferences:(r=n==null?void 0:n.replaceMaterializedReferences)!==null&&r!==void 0?r:this.replaceMaterializedReferences})},n)}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new o0.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1307
1307
  run: ${e}
1308
1308
  -> ${o}
1309
1309
  -> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.193-dev241001144416",
3
+ "version": "0.0.193-dev241001152900",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -32,7 +32,7 @@
32
32
  "build-types": "tsc --build --declaration --emitDeclarationOnly"
33
33
  },
34
34
  "dependencies": {
35
- "@malloydata/malloy": "^0.0.193-dev241001144416",
35
+ "@malloydata/malloy": "^0.0.193-dev241001152900",
36
36
  "@tanstack/solid-virtual": "^3.10.4",
37
37
  "component-register": "^0.8.6",
38
38
  "lodash": "^4.17.20",