@malloydata/render 0.0.261 → 0.0.262-dev250414163813
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.
package/dist/module/index.mjs
CHANGED
|
@@ -149228,7 +149228,7 @@ Ap.malloyToQuery = Pxt;
|
|
|
149228
149228
|
var Fe = {}, aD = {};
|
|
149229
149229
|
Object.defineProperty(aD, "__esModule", { value: !0 });
|
|
149230
149230
|
aD.MALLOY_VERSION = void 0;
|
|
149231
|
-
aD.MALLOY_VERSION = "0.0.
|
|
149231
|
+
aD.MALLOY_VERSION = "0.0.262";
|
|
149232
149232
|
Object.defineProperty(Fe, "__esModule", { value: !0 });
|
|
149233
149233
|
Fe.InMemoryModelCache = Fe.CacheManager = Fe.CSVWriter = Fe.JSONWriter = Fe.DataWriter = Fe.DataRecord = Fe.DataArray = Fe.Result = Fe.ExploreMaterializer = Fe.PreparedResultMaterializer = Fe.QueryMaterializer = Fe.ModelMaterializer = Fe.SingleConnectionRuntime = Fe.ConnectionRuntime = Fe.Runtime = Fe.ExploreField = Fe.JoinRelationship = Fe.QueryField = Fe.Query = Fe.StringField = Fe.UnsupportedField = Fe.JSONField = Fe.BooleanField = Fe.NumberField = Fe.TimestampField = Fe.DateField = Fe.TimestampTimeframe = Fe.DateTimeframe = Fe.AtomicField = Fe.AtomicFieldType = Fe.Explore = Fe.SourceRelationship = Fe.FixedConnectionMap = Fe.InMemoryURLReader = Fe.EmptyURLReader = Fe.PreparedResult = Fe.DocumentCompletion = Fe.DocumentSymbol = Fe.DocumentPosition = Fe.DocumentRange = Fe.DocumentTablePath = Fe.Parse = Fe.PreparedQuery = Fe.Model = Fe.MalloyError = Fe.Malloy = void 0;
|
|
149234
149234
|
const nY = dT, Xr = ji, rY = zy, v7 = h2, Uxt = aD, jxt = p2, In = ui, qxt = $l, iY = "internal://internal.malloy";
|
|
@@ -152210,7 +152210,7 @@ DE.MALLOY_INTERFACE_TYPES = {
|
|
|
152210
152210
|
array: !1
|
|
152211
152211
|
},
|
|
152212
152212
|
where: {
|
|
152213
|
-
type: "
|
|
152213
|
+
type: "FilterOperation",
|
|
152214
152214
|
array: !0,
|
|
152215
152215
|
optional: !1
|
|
152216
152216
|
}
|
|
@@ -153151,17 +153151,6 @@ DE.MALLOY_INTERFACE_TYPES = {
|
|
|
153151
153151
|
optional: !1
|
|
153152
153152
|
}
|
|
153153
153153
|
}
|
|
153154
|
-
},
|
|
153155
|
-
Where: {
|
|
153156
|
-
type: "struct",
|
|
153157
|
-
name: "Where",
|
|
153158
|
-
fields: {
|
|
153159
|
-
filter: {
|
|
153160
|
-
type: "Filter",
|
|
153161
|
-
optional: !1,
|
|
153162
|
-
array: !1
|
|
153163
|
-
}
|
|
153164
|
-
}
|
|
153165
153154
|
}
|
|
153166
153155
|
};
|
|
153167
153156
|
var pD = {}, mD = {}, gD = {};
|
package/dist/module/index.umd.js
CHANGED
|
@@ -1465,7 +1465,7 @@ wxxyyzz{{||}}}Ҩ
|
|
|
1465
1465
|
| ${c}`,a>0&&(s=s+`
|
|
1466
1466
|
| ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
|
|
1467
1467
|
`+s,r=o),e!==""?e=`${e}
|
|
1468
|
-
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Oft.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,UM.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,UM.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=jM;class Kfe extends jM{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=Kfe;class Kft extends jM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new PM.Zone,this.importZone=new PM.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new PM.Zone,this.root=this,this.logger=new Yfe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Yfe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=Kft;function Jfe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Jfe(t[e])).flat()]}var D2={};Object.defineProperty(D2,"__esModule",{value:!0}),D2.exploreQueryWalkerBuilder=D2.ExploreQueryWalker=void 0;const Jft=ac;class Xfe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}D2.ExploreQueryWalker=Xfe;function Xft(t,e){const r=new Xfe(t),i=r;return Jft.ParseTreeWalker.DEFAULT.walk(i,e),r}D2.exploreQueryWalkerBuilder=Xft;var O2={},mE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const n0=Pi,qM=Is,HM=ui,Zfe=eu;function Zft(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,n0.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>({name:u,type:CR(a),default_value:ext(a.value)})):void 0,o={kind:"source",name:r,schema:{fields:F2(i,i.fields)},parameters:s,annotations:QM(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,qM.getResultStructDefForQuery)(t,i),o=QM(i),u=s.resultMetadata?vR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:F2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,qM.getResultStructDefForQuery)(t,r),s=QM(r),o=i.resultMetadata?vR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:F2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=Zft;function ext(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function QM(t){return(0,HM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function F2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,HM.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,n0.isTurtle)(u)){const x=(0,qM.getResultStructDefForView)(t,u),h=x.resultMetadata?vR(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:F2(x,x.fields)}};o.push(m)}else if((0,n0.isAtomic)(u)){const x=(0,n0.expressionIsAggregate)(u.expressionType),h=(0,n0.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?exe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],y={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:CR(u),annotations:m.length>0?m:void 0};o.push(y)}else if((0,n0.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:F2(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ia.convertFieldInfos=F2;function exe(t,e){const r=Zfe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:nxt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function txt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function nxt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${txt(t)}\``}function vR(t,e){var r,i;const s=Zfe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=vR;function CR(t){if((0,n0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!rxt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:ixt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,n0.isRepeatedRecord)(t))return{kind:"array_type",element_type:txe(t)};if(t.type==="record")return txe(t);if(t.type==="array")return{kind:"array_type",element_type:CR(t.elementTypeDef)}}throw new Error("Unexpected field type")}function txe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=exe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,HM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,n0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:CR(e)};throw new Error("Expected record type to not have a table as its child")})}}function rxt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function ixt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function _ht(t){return t}function vht(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=eu,r=ui,i=Ia,s=Ty;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(mE);var sxt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),oxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sxt(e,t,r);return oxt(e,t),e};Object.defineProperty(O2,"__esModule",{value:!0}),O2.malloyToQuery=O2.MalloyToQuery=void 0;const axt=Xh,On=uxt(w),nxe=Jp,gE=$n,lxt=Xe,cxt=aE,rxe=Vn,fxt=mE,zM="Malloy query documents";class ixe extends axt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,rxe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,nxe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${zM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${zM} may only have one run statement`);return i===void 0?(this.illegal(e,`${zM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,gE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof On.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof On.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof On.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof On.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof On.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof On.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof On.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof On.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof On.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof On.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof On.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof On.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof On.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,gE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof On.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,gE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof On.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof On.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,gE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,lxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,gE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof On.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof On.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof On.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof On.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof On.ExprFieldPathContext&&i instanceof On.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof On.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}O2.MalloyToQuery=ixe;function xxt(t){const e=(0,rxe.getSourceInfo)(t),r=new nxe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,cxt.runMalloyParser)(t,i,e,r),u=new ixe(s,r).visit(s.root),a=(0,fxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}O2.malloyToQuery=xxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=D2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=O2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Q4);var Fe={},SR={};Object.defineProperty(SR,"__esModule",{value:!0}),SR.MALLOY_VERSION=void 0,SR.MALLOY_VERSION="0.0.261",Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.InMemoryModelCache=Fe.CacheManager=Fe.CSVWriter=Fe.JSONWriter=Fe.DataWriter=Fe.DataRecord=Fe.DataArray=Fe.Result=Fe.ExploreMaterializer=Fe.PreparedResultMaterializer=Fe.QueryMaterializer=Fe.ModelMaterializer=Fe.SingleConnectionRuntime=Fe.ConnectionRuntime=Fe.Runtime=Fe.ExploreField=Fe.JoinRelationship=Fe.QueryField=Fe.Query=Fe.StringField=Fe.UnsupportedField=Fe.JSONField=Fe.BooleanField=Fe.NumberField=Fe.TimestampField=Fe.DateField=Fe.TimestampTimeframe=Fe.DateTimeframe=Fe.AtomicField=Fe.AtomicFieldType=Fe.Explore=Fe.SourceRelationship=Fe.FixedConnectionMap=Fe.InMemoryURLReader=Fe.EmptyURLReader=Fe.PreparedResult=Fe.DocumentCompletion=Fe.DocumentSymbol=Fe.DocumentPosition=Fe.DocumentRange=Fe.DocumentTablePath=Fe.Parse=Fe.PreparedQuery=Fe.Model=Fe.MalloyError=Fe.Malloy=void 0;const sxe=Q4,li=Pi,oxe=Ty,GM=Pp,dxt=SR,hxt=jp,Bn=ui,pxt=Yl,uxe="internal://internal.malloy";let r0=class AD{static get version(){return dxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(uxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new sxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new lxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return AD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return LR(r,e).then(({contents:u,invalidationKey:a})=>AD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(uxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new w2(C.modelDef,[],[e.toString(),...NR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await sP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:S}=await LR(s,e);A[v]=S,r=C}else{const C=await sP(s,e);A[v]=C}_=new sxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const S of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(S.url,{modelDef:S.modelDef,invalidationKeys:A}));return new w2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],S=>_.referenceAt(S),S=>_.importAt(S))}else if(l){const S={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},b=(u==null?void 0:u._modelDef)||S;return new w2(b,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const S=C.problems||[],b=_.prettyErrors();throw new axe(`Error(s) compiling model:
|
|
1468
|
+
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Oft.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,UM.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,UM.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=jM;class Kfe extends jM{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=Kfe;class Kft extends jM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new PM.Zone,this.importZone=new PM.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new PM.Zone,this.root=this,this.logger=new Yfe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Yfe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=Kft;function Jfe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Jfe(t[e])).flat()]}var D2={};Object.defineProperty(D2,"__esModule",{value:!0}),D2.exploreQueryWalkerBuilder=D2.ExploreQueryWalker=void 0;const Jft=ac;class Xfe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}D2.ExploreQueryWalker=Xfe;function Xft(t,e){const r=new Xfe(t),i=r;return Jft.ParseTreeWalker.DEFAULT.walk(i,e),r}D2.exploreQueryWalkerBuilder=Xft;var O2={},mE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const n0=Pi,qM=Is,HM=ui,Zfe=eu;function Zft(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,n0.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>({name:u,type:CR(a),default_value:ext(a.value)})):void 0,o={kind:"source",name:r,schema:{fields:F2(i,i.fields)},parameters:s,annotations:QM(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,qM.getResultStructDefForQuery)(t,i),o=QM(i),u=s.resultMetadata?vR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:F2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,qM.getResultStructDefForQuery)(t,r),s=QM(r),o=i.resultMetadata?vR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:F2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=Zft;function ext(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function QM(t){return(0,HM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function F2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,HM.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,n0.isTurtle)(u)){const x=(0,qM.getResultStructDefForView)(t,u),h=x.resultMetadata?vR(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:F2(x,x.fields)}};o.push(m)}else if((0,n0.isAtomic)(u)){const x=(0,n0.expressionIsAggregate)(u.expressionType),h=(0,n0.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?exe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],y={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:CR(u),annotations:m.length>0?m:void 0};o.push(y)}else if((0,n0.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:F2(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ia.convertFieldInfos=F2;function exe(t,e){const r=Zfe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:nxt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function txt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function nxt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${txt(t)}\``}function vR(t,e){var r,i;const s=Zfe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=vR;function CR(t){if((0,n0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!rxt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:ixt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,n0.isRepeatedRecord)(t))return{kind:"array_type",element_type:txe(t)};if(t.type==="record")return txe(t);if(t.type==="array")return{kind:"array_type",element_type:CR(t.elementTypeDef)}}throw new Error("Unexpected field type")}function txe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=exe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,HM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,n0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:CR(e)};throw new Error("Expected record type to not have a table as its child")})}}function rxt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function ixt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function _ht(t){return t}function vht(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=eu,r=ui,i=Ia,s=Ty;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(mE);var sxt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),oxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sxt(e,t,r);return oxt(e,t),e};Object.defineProperty(O2,"__esModule",{value:!0}),O2.malloyToQuery=O2.MalloyToQuery=void 0;const axt=Xh,On=uxt(w),nxe=Jp,gE=$n,lxt=Xe,cxt=aE,rxe=Vn,fxt=mE,zM="Malloy query documents";class ixe extends axt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,rxe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,nxe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${zM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${zM} may only have one run statement`);return i===void 0?(this.illegal(e,`${zM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,gE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof On.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof On.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof On.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof On.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof On.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof On.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof On.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof On.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof On.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof On.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof On.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof On.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof On.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,gE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof On.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,gE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof On.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof On.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,gE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,lxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,gE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof On.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof On.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof On.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof On.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof On.ExprFieldPathContext&&i instanceof On.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof On.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}O2.MalloyToQuery=ixe;function xxt(t){const e=(0,rxe.getSourceInfo)(t),r=new nxe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,cxt.runMalloyParser)(t,i,e,r),u=new ixe(s,r).visit(s.root),a=(0,fxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}O2.malloyToQuery=xxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=D2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=O2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Q4);var Fe={},SR={};Object.defineProperty(SR,"__esModule",{value:!0}),SR.MALLOY_VERSION=void 0,SR.MALLOY_VERSION="0.0.262",Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.InMemoryModelCache=Fe.CacheManager=Fe.CSVWriter=Fe.JSONWriter=Fe.DataWriter=Fe.DataRecord=Fe.DataArray=Fe.Result=Fe.ExploreMaterializer=Fe.PreparedResultMaterializer=Fe.QueryMaterializer=Fe.ModelMaterializer=Fe.SingleConnectionRuntime=Fe.ConnectionRuntime=Fe.Runtime=Fe.ExploreField=Fe.JoinRelationship=Fe.QueryField=Fe.Query=Fe.StringField=Fe.UnsupportedField=Fe.JSONField=Fe.BooleanField=Fe.NumberField=Fe.TimestampField=Fe.DateField=Fe.TimestampTimeframe=Fe.DateTimeframe=Fe.AtomicField=Fe.AtomicFieldType=Fe.Explore=Fe.SourceRelationship=Fe.FixedConnectionMap=Fe.InMemoryURLReader=Fe.EmptyURLReader=Fe.PreparedResult=Fe.DocumentCompletion=Fe.DocumentSymbol=Fe.DocumentPosition=Fe.DocumentRange=Fe.DocumentTablePath=Fe.Parse=Fe.PreparedQuery=Fe.Model=Fe.MalloyError=Fe.Malloy=void 0;const sxe=Q4,li=Pi,oxe=Ty,GM=Pp,dxt=SR,hxt=jp,Bn=ui,pxt=Yl,uxe="internal://internal.malloy";let r0=class AD{static get version(){return dxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(uxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new sxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new lxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return AD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return LR(r,e).then(({contents:u,invalidationKey:a})=>AD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(uxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new w2(C.modelDef,[],[e.toString(),...NR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await sP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:S}=await LR(s,e);A[v]=S,r=C}else{const C=await sP(s,e);A[v]=C}_=new sxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const S of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(S.url,{modelDef:S.modelDef,invalidationKeys:A}));return new w2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],S=>_.referenceAt(S),S=>_.importAt(S))}else if(l){const S={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},b=(u==null?void 0:u._modelDef)||S;return new w2(b,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const S=C.problems||[],b=_.prettyErrors();throw new axe(`Error(s) compiling model:
|
|
1469
1469
|
${b}`,S)}else{if(C.urls)for(const b of C.urls)try{if(IR(b))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,b);if(D){for(const B in D.invalidationKeys)A[B]=D.invalidationKeys[B];_.update({translations:{[b]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await LR(s,new URL(b)),$={[b]:R};A[b]=O,_.update({urls:$})}catch(R){_.update({errors:{urls:{[b]:R.message}}})}const{modelAnnotation:S}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const b=new Map;for(const R in C.tables){const{connectionName:O,tablePath:$}=C.tables[R],D=b.get(O);D===void 0?b.set(O,{[R]:$}):D[R]=$}for(const[R,O]of b)try{const $=await o.lookupConnection(R),{schemas:D,errors:B}=await AD.safelyFetchTableSchema($,O,{refreshTimestamp:E,modelAnnotation:S});_.update({tables:D,errors:{tables:B}})}catch($){const D={},B={};for(const q in O)B[q]=$.toString();_.update({tables:D,errors:{tables:B}})}}if(C.compileSQL){const b=C.compileSQL,R=b.connection,O=(0,pxt.sqlKey)(b.connection,b.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(b,{refreshTimestamp:E,modelAnnotation:S});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch($){const D={};D[O]=$.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new AE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new AE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Us(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new dd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};Fe.Malloy=r0;class axe extends Error{constructor(e,r=[]){super(e),this.problems=r}}Fe.MalloyError=axe;class w2{constructor(e,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return(0,Bn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new N2(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new N2(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new N2(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,li.isSourceDef)(r))return new Us(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(li.isSourceDef).map(e=>new Us(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}Fe.Model=w2;class N2{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Bn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Bn.addModelScope)(e,r),(0,Bn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new li.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new yE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,li.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}Fe.PreparedQuery=N2;class lxe{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new bR(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new cxe(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new fxe(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}Fe.Parse=lxe;class cxe{constructor(e){this._range=L2.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}}Fe.DocumentTablePath=cxe;class L2{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new L2(new WM(e.start.line,e.start.character),new WM(e.end.line,e.end.character))}}Fe.DocumentRange=L2;class WM{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Fe.DocumentPosition=WM;class bR{constructor(e){this._range=L2.fromJSON(e.range),this._lensRange=e.lensRange?L2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new bR(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}Fe.DocumentSymbol=bR;class fxe{constructor(e){this.type=e.type,this.text=e.text}}Fe.DocumentCompletion=fxe;class yE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new yE(e,r)}tagParse(e){const r=(0,Bn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Bn.addModelScope)(e,r),(0,Bn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Bn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Us(r,this.sourceExplore)}catch{return new Us(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,li.isSourceDef)(r))return new Us(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Fe.PreparedResult=yE;class xxe{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}Fe.EmptyURLReader=xxe;class mxt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return IR(e.toString())?null:Rxe(r)}}Fe.InMemoryURLReader=mxt;class TR{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new TR(new Map(e.map(r=>[r.name,r])))}}Fe.FixedConnectionMap=TR;var dxe;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(dxe||(Fe.SourceRelationship=dxe={}));class VM{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Us}isQuery(){return this instanceof tP}}class Us extends VM{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,li.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Bn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Bn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new N2(i,this.modelDef,[],e)}get modelDef(){if(!(0,li.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new w2(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,li.isJoined)(i))return[s,new nP(i,this,o)];if(i.type==="turtle")return[s,new tP(i,this,o)];if(i.type==="string")return[s,new eP(i,this,o)];if(i.type==="number")return[s,new RR(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new RR({...i,type:"number"},this,o)]:[s,new YM(i,this,o)];if(i.type==="timestamp")return[s,new KM(i,this,o)];if(i.type==="boolean")return[s,new JM(i,this,o)];if(i.type==="json")return[s,new XM(i,this,o)];if(i.type==="sql native")return[s,new ZM(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof nP}get filters(){var e;return(0,li.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,li.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Us.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Us.fromJSON(e.sourceExplore):void 0;return new Us(e._structDef,r,i)}get location(){return this.structDef.location}}Fe.Explore=Us;var $a;(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"})($a||(Fe.AtomicFieldType=$a={}));class Wc extends VM{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return $a.String;case"boolean":return $a.Boolean;case"date":return $a.Date;case"timestamp":return $a.Timestamp;case"number":return $a.Number;case"json":return $a.Json;case"sql native":return $a.NativeUnsupported;case"error":return $a.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Bn.addModelScope)(e,this.parent.modelTag),(0,Bn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,li.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,li.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof eP}isNumber(){return this instanceof RR}isDate(){return this instanceof YM}isBoolean(){return this instanceof JM}isJSON(){return this instanceof XM}isTimestamp(){return this instanceof KM}isUnsupported(){return this instanceof ZM}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Fe.AtomicField=Wc;var xd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(xd||(Fe.DateTimeframe=xd={}));var Ba;(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"})(Ba||(Fe.TimestampTimeframe=Ba={}));class YM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return xd.Day;case"week":return xd.Week;case"month":return xd.Month;case"quarter":return xd.Quarter;case"year":return xd.Year}}}Fe.DateField=YM;class KM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ba.Day;case"week":return Ba.Week;case"month":return Ba.Month;case"quarter":return Ba.Quarter;case"year":return Ba.Year;case"second":return Ba.Second;case"hour":return Ba.Hour;case"minute":return Ba.Minute}}}Fe.TimestampField=KM;class RR extends Wc{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}Fe.NumberField=RR;class JM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}Fe.BooleanField=JM;class XM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}Fe.JSONField=XM;class ZM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Fe.UnsupportedField=ZM;class eP extends Wc{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}Fe.StringField=eP;class hxe extends VM{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Fe.Query=hxe;class tP extends hxe{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Bn.addModelScope)(e,this.parent.modelTag),(0,Bn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Bn.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}}Fe.QueryField=tP;var I2;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(I2||(Fe.JoinRelationship=I2={}));class nP extends Us{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,li.isJoined)(this.structDef))switch(this.structDef.join){case"one":return I2.OneToOne;case"many":case"cross":return I2.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===I2.OneToOne}get isArray(){return this.joinRelationship!==I2.OneToOne}tagParse(e){return e=(0,Bn.addModelScope)(e,this._parentExplore.modelTag),(0,Bn.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]:[]}}Fe.ExploreField=nP;class rP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new xxe),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new EE(this,async()=>r0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new EE(this,async()=>new w2(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}Fe.Runtime=rP;class gxt extends rP{constructor({urlReader:e,connections:r}){super({connections:TR.fromArray(r),urlReader:e}),this.rawConnections=r}}Fe.ConnectionRuntime=gxt;class yxt extends rP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,GM.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,GM.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,GM.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Fe.SingleConnectionRuntime=yxt;class DR{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new pxe(this.runtime,e,r)}makeExploreMaterializer(e,r){return new gxe(this.runtime,e,r)}makePreparedResultMaterializer(e){return new mxe(this.runtime,e)}}class EE extends DR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await r0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new EE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await r0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new li.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,li.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,li.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
|
|
1470
1470
|
run: ${e}
|
|
1471
1471
|
-> ${u}
|
|
@@ -1487,7 +1487,7 @@ ${b}`,S)}else{if(C.urls)for(const b of C.urls)try{if(IR(b))throw new Error("In o
|
|
|
1487
1487
|
`)}}this.stream.write(`
|
|
1488
1488
|
]
|
|
1489
1489
|
`),this.stream.close()}}Fe.JSONWriter=_xt;class vxt extends iP{constructor(){super(...arguments),this.columnSeparator=",",this.rowSeparator=`
|
|
1490
|
-
`,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(e){const r=e.includes(this.quoteCharacter),i=e.includes(this.columnSeparator),s=e.includes(this.rowSeparator),o=i||r||s;return r&&(e=e.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),o&&(e=this.quoteCharacter+e+this.quoteCharacter),e}stringify(e){return e===null?this.emptyCell:e instanceof Date?e.toISOString():typeof e=="boolean"||typeof e=="number"?JSON.stringify(e):`${e}`}getColWeight(e){let r=e;Array.isArray(e)&&(r=e[0]);let i=0;for(const s in r){i=i+1;const o=r[s];if(Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u}}return i}getHeaderRow(e){const r=[];let i=0;for(const s in e){r.push(this.escape(s));const o=e[s];if(i++,Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u;for(let a=0;a<u;a++)r.push(this.emptyCell)}}return{rows:[r.join(this.columnSeparator)],length:1,width:i}}mergeMatrices(e){const r=Math.max(...e.map(o=>o.length)),i=e.reduce((o,u)=>o+u.width,0),s=[];for(let o=0;o<r;o++){const u=[];for(const a of e)if(o<a.length)u.push(a.rows[o]);else{const l=Array(a.width).fill(this.emptyCell);u.push(...l)}s.push(u.join(this.columnSeparator))}return{rows:s,length:r,width:i}}getChildMatrix(e){if(Array.isArray(e)){if(e.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const r=[],i=this.getHeaderRow(e[0]);r.push(...i.rows);const s=i.width;let o=1;for(const u of e){const a=this.getRowMatrix(u);o=o+a.length,r.push(...a.rows)}return{rows:r,length:o,width:s}}getRowMatrix(e){const r=[];for(const i in e){const s=e[i];if(Array.isArray(s)){const o=this.getChildMatrix(s);r.push(o)}else{const o={rows:[this.stringify(s)],length:1,width:1};r.push(o)}}return this.mergeMatrices(r)}async process(e){let r=!1;for await(const i of e){if(!r&&this.includeHeader){const o=this.getHeaderRow(i.toObject());this.stream.write(o.rows[0]),this.stream.write(this.rowSeparator),r=!0}const s=this.getRowMatrix(i.toObject());for(const o of s.rows)this.stream.write(o),this.stream.write(this.rowSeparator)}this.stream.close()}}Fe.CSVWriter=vxt;class Cxt{constructor(e){this.modelCache=e,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(e,r){const i=this.modelDependencies.get(r);if(i===void 0)return;const s=[r,...NR(i)],o={};for(const a of s){const l=this.modelInvalidationKeys.get(a);if(l==null)return;o[a]=l}for(const a of s)if(await sP(e,new URL(a))!==o[a])return;const u=await this.modelCache.getModel(new URL(r));if(u!==void 0){for(const a of s)if(u.invalidationKeys[a]!==o[a])return;return{modelDef:u.modelDef,invalidationKeys:o}}}async setCachedModelDef(e,r){this.modelDependencies.set(e,r.modelDef.dependencies);const i={};for(const o of[e,...NR(r.modelDef.dependencies)]){if(r.invalidationKeys[o]===null)return!1;if(r.invalidationKeys[o]===void 0)throw new Error(`Missing invalidation key for dependency ${o}`);this.modelInvalidationKeys.set(o,r.invalidationKeys[o]),i[o]=r.invalidationKeys[o]}return!!await this.modelCache.setModel(new URL(e),{modelDef:r.modelDef,invalidationKeys:i})}}Fe.CacheManager=Cxt;function NR(t){return[...Object.keys(t),...Object.values(t).map(NR).flat()]}class Sxt{constructor(){this.models=new Map}async getModel(e){return Promise.resolve(this.models.get(e.toString()))}async setModel(e,r){return this.models.set(e.toString(),r),Promise.resolve(!0)}}Fe.InMemoryModelCache=Sxt;function Rxe(t){return(0,hxt.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}async function LR(t,e){const r=await t.readURL(e),{contents:i,invalidationKey:s}=typeof r=="string"?{contents:r,invalidationKey:void 0}:r;return{contents:i,invalidationKey:IR(e.toString())?null:s??Rxe(i)}}async function sP(t,e){return IR(e.toString())?null:t.getInvalidationKey!==void 0?await t.getInvalidationKey(e):(await LR(t,e)).invalidationKey}function IR(t){return t.startsWith("internal://")}var $R={};Object.defineProperty($R,"__esModule",{value:!0}),$R.toAsyncGenerator=void 0;async function*bxt(t){let e=!1;function r(s){let o;const u=new Promise(a=>{o=a});return s(a=>{o({done:!0,isError:!0,error:a})},a=>{o({done:!1,value:a,isError:!1,next:new Promise(l=>{o=l})})},()=>{o({done:!0,isError:!1})}),u}let i=r(t);for(;!e;){const s=await i;if(s.done){if(e=!0,s.isError)throw s.error;break}else i=s.next,yield s.value}}$R.toAsyncGenerator=bxt;var Dxe={},Vc={},oP={},vE={};Object.defineProperty(vE,"__esModule",{value:!0}),vE.MALLOY_INTERFACE_TYPES=void 0,vE.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication"}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{field_reference:{type:"Reference",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"Where",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral"}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}},Where:{type:"struct",name:"Where",fields:{filter:{type:"Filter",optional:!1,array:!1}}}};var BR={},kR={},MR={};Object.defineProperty(MR,"__esModule",{value:!0}),MR.RESERVED_WORDS=void 0,MR.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty(kR,"__esModule",{value:!0}),kR.maybeQuoteIdentifier=void 0;const Txt=MR;function Rxt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=Txt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function Dxt(t){const e=t.split(".");for(let r=0;r<e.length;r++)Rxt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}kR.maybeQuoteIdentifier=Dxt,Object.defineProperty(BR,"__esModule",{value:!0}),BR.queryToMalloy=void 0;const CE=kR;function Oxt(t,{tabWidth:e}={tabWidth:2}){const r=Ixt(t);return wxt(r,{tabWidth:e})}BR.queryToMalloy=Oxt;const uP=Symbol("indent"),Eu=Symbol("newline"),aP=Symbol("outdent"),Fxt=Symbol("optional_newline_indent");function wxt(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===Eu)r+=`
|
|
1490
|
+
`,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(e){const r=e.includes(this.quoteCharacter),i=e.includes(this.columnSeparator),s=e.includes(this.rowSeparator),o=i||r||s;return r&&(e=e.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),o&&(e=this.quoteCharacter+e+this.quoteCharacter),e}stringify(e){return e===null?this.emptyCell:e instanceof Date?e.toISOString():typeof e=="boolean"||typeof e=="number"?JSON.stringify(e):`${e}`}getColWeight(e){let r=e;Array.isArray(e)&&(r=e[0]);let i=0;for(const s in r){i=i+1;const o=r[s];if(Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u}}return i}getHeaderRow(e){const r=[];let i=0;for(const s in e){r.push(this.escape(s));const o=e[s];if(i++,Array.isArray(o)){const u=this.getColWeight(o)-1;i=i+u;for(let a=0;a<u;a++)r.push(this.emptyCell)}}return{rows:[r.join(this.columnSeparator)],length:1,width:i}}mergeMatrices(e){const r=Math.max(...e.map(o=>o.length)),i=e.reduce((o,u)=>o+u.width,0),s=[];for(let o=0;o<r;o++){const u=[];for(const a of e)if(o<a.length)u.push(a.rows[o]);else{const l=Array(a.width).fill(this.emptyCell);u.push(...l)}s.push(u.join(this.columnSeparator))}return{rows:s,length:r,width:i}}getChildMatrix(e){if(Array.isArray(e)){if(e.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const r=[],i=this.getHeaderRow(e[0]);r.push(...i.rows);const s=i.width;let o=1;for(const u of e){const a=this.getRowMatrix(u);o=o+a.length,r.push(...a.rows)}return{rows:r,length:o,width:s}}getRowMatrix(e){const r=[];for(const i in e){const s=e[i];if(Array.isArray(s)){const o=this.getChildMatrix(s);r.push(o)}else{const o={rows:[this.stringify(s)],length:1,width:1};r.push(o)}}return this.mergeMatrices(r)}async process(e){let r=!1;for await(const i of e){if(!r&&this.includeHeader){const o=this.getHeaderRow(i.toObject());this.stream.write(o.rows[0]),this.stream.write(this.rowSeparator),r=!0}const s=this.getRowMatrix(i.toObject());for(const o of s.rows)this.stream.write(o),this.stream.write(this.rowSeparator)}this.stream.close()}}Fe.CSVWriter=vxt;class Cxt{constructor(e){this.modelCache=e,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(e,r){const i=this.modelDependencies.get(r);if(i===void 0)return;const s=[r,...NR(i)],o={};for(const a of s){const l=this.modelInvalidationKeys.get(a);if(l==null)return;o[a]=l}for(const a of s)if(await sP(e,new URL(a))!==o[a])return;const u=await this.modelCache.getModel(new URL(r));if(u!==void 0){for(const a of s)if(u.invalidationKeys[a]!==o[a])return;return{modelDef:u.modelDef,invalidationKeys:o}}}async setCachedModelDef(e,r){this.modelDependencies.set(e,r.modelDef.dependencies);const i={};for(const o of[e,...NR(r.modelDef.dependencies)]){if(r.invalidationKeys[o]===null)return!1;if(r.invalidationKeys[o]===void 0)throw new Error(`Missing invalidation key for dependency ${o}`);this.modelInvalidationKeys.set(o,r.invalidationKeys[o]),i[o]=r.invalidationKeys[o]}return!!await this.modelCache.setModel(new URL(e),{modelDef:r.modelDef,invalidationKeys:i})}}Fe.CacheManager=Cxt;function NR(t){return[...Object.keys(t),...Object.values(t).map(NR).flat()]}class Sxt{constructor(){this.models=new Map}async getModel(e){return Promise.resolve(this.models.get(e.toString()))}async setModel(e,r){return this.models.set(e.toString(),r),Promise.resolve(!0)}}Fe.InMemoryModelCache=Sxt;function Rxe(t){return(0,hxt.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}async function LR(t,e){const r=await t.readURL(e),{contents:i,invalidationKey:s}=typeof r=="string"?{contents:r,invalidationKey:void 0}:r;return{contents:i,invalidationKey:IR(e.toString())?null:s??Rxe(i)}}async function sP(t,e){return IR(e.toString())?null:t.getInvalidationKey!==void 0?await t.getInvalidationKey(e):(await LR(t,e)).invalidationKey}function IR(t){return t.startsWith("internal://")}var $R={};Object.defineProperty($R,"__esModule",{value:!0}),$R.toAsyncGenerator=void 0;async function*bxt(t){let e=!1;function r(s){let o;const u=new Promise(a=>{o=a});return s(a=>{o({done:!0,isError:!0,error:a})},a=>{o({done:!1,value:a,isError:!1,next:new Promise(l=>{o=l})})},()=>{o({done:!0,isError:!1})}),u}let i=r(t);for(;!e;){const s=await i;if(s.done){if(e=!0,s.isError)throw s.error;break}else i=s.next,yield s.value}}$R.toAsyncGenerator=bxt;var Dxe={},Vc={},oP={},vE={};Object.defineProperty(vE,"__esModule",{value:!0}),vE.MALLOY_INTERFACE_TYPES=void 0,vE.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication"}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{field_reference:{type:"Reference",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral"}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!1,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var BR={},kR={},MR={};Object.defineProperty(MR,"__esModule",{value:!0}),MR.RESERVED_WORDS=void 0,MR.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty(kR,"__esModule",{value:!0}),kR.maybeQuoteIdentifier=void 0;const Txt=MR;function Rxt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=Txt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function Dxt(t){const e=t.split(".");for(let r=0;r<e.length;r++)Rxt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}kR.maybeQuoteIdentifier=Dxt,Object.defineProperty(BR,"__esModule",{value:!0}),BR.queryToMalloy=void 0;const CE=kR;function Oxt(t,{tabWidth:e}={tabWidth:2}){const r=Ixt(t);return wxt(r,{tabWidth:e})}BR.queryToMalloy=Oxt;const uP=Symbol("indent"),Eu=Symbol("newline"),aP=Symbol("outdent"),Fxt=Symbol("optional_newline_indent");function wxt(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===Eu)r+=`
|
|
1491
1491
|
`,s=!0;else if(o===aP)i--;else if(o===uP)i++;else{if(o===Fxt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function PR(t,e,r,i){var s;if(e.includes(Eu))return[t,Eu,uP,...e,Eu,aP,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function Nxt(t){return{contents:t,quoteCharacter:'"'}}function Lxt(t){var e,r;switch(t.kind){case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=Nxt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[Fxe(Oxe(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day")];case"timestamp_literal":return[Fxe(Oxe(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second")]}}function Oxe(t){return new Date(t)}function yn(t,e){return t.toString().padStart(e,"0")}function Fxe(t,e){switch(e){case"year":return`@${yn(t.getUTCFullYear(),4)}`;case"quarter":{const r=yn(t.getUTCFullYear(),4),i=Math.floor(t.getUTCMonth()/3)+1;return`@${r}-Q${i}`}case"month":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2);return`@${r}-${i}`}case"week":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@WK${r}-${i}-${s}`}case"day":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2);return`@${r}-${i}-${s}`}case"hour":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2);return`@${r}-${i}-${s} ${o}`}case"minute":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2);return`@${r}-${i}-${s} ${o}:${u}`}case"second":{const r=yn(t.getUTCFullYear(),2),i=yn(t.getUTCMonth()+1,2),s=yn(t.getUTCDate(),2),o=yn(t.getUTCHours(),2),u=yn(t.getUTCMinutes(),2),a=yn(t.getUTCSeconds(),2);return`@${r}-${i}-${s} ${o}:${u}:${a}`}default:throw new Error("Unknown timeframe.")}}function Yc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,CE.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,CE.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,CE.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Lxt(o.value)),s<t.parameters.length-1&&i.push(",",Eu)}r.push(...PR("(",i,")",{spaces:!1}))}return r}function Ixt(t){const e=[];return e.push(...B2(t.annotations)),e.push("run: "),e.push(...lP(t.definition)),e}function $xt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Yc(t));break}case"refinement":e.push(...lP(t));break}return e}function lP(t){const e=[];switch(t.kind){case"arrow":{e.push(...$xt(t.source)),e.push(" -> "),e.push(...hd(t.view));break}case"query_reference":{e.push(...Yc(t));break}case"refinement":{const r=lP(t.base);t.base.kind==="arrow"?e.push(...PR("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...hd(t.refinement));break}}return e}function hd(t){const e=[];switch(t.kind){case"arrow":{e.push(...hd(t.source)),e.push(" -> "),e.push(...hd(t.view));break}case"view_reference":{e.push(...Yc(t));break}case"refinement":{e.push(...hd(t.base)),e.push(" + "),e.push(...hd(t.refinement));break}case"segment":{e.push(...Bxt(t));break}}return e}function Bxt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...kxt(o)),e&&i<t.operations.length-1&&r.push(Eu)}return PR("{",r,"}")}function kxt(t){switch(t[0].kind){case"aggregate":return jxt(t);case"group_by":return Uxt(t);case"order_by":return qxt(t);case"nest":return Qxt(t);case"limit":return Vxt(t);case"where":return Nxe(t);case"having":return Yxt(t)}}function $2(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(Eu));s?i.push(Eu,uP):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(Eu)}return s&&i.push(aP),i}function Mxt(t){const e=[];return e.push(...Pxt(t.expression)),e}function Cht(t){return t}function Pxt(t){switch(t.kind){case"field_reference":return Yc(t);case"time_truncation":return[...Yc(t.field_reference),".",t.truncation];case"filtered_field":return[...Yc(t.field_reference),...PR(" {",Nxe(t.where),"}")]}}function wxe(t,e=!1){const r=[];return e||r.push(...B2(t.field.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Mxt(t.field)),r}function Uxt(t){const e=[],r=t.length===1;return r&&e.push(...B2(t[0].field.annotations)),e.push(...$2("group_by",t.map(i=>wxe(i,r)))),e}function jxt(t){const e=[],r=t.length===1;return r&&e.push(...B2(t[0].field.annotations)),e.push(...$2("aggregate",t.map(i=>wxe(i,r)))),e}function qxt(t){return $2("order_by",t.map(Hxt),",")}function Hxt(t){const e=[];return e.push(...Yc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function Qxt(t){const e=[],r=t.length===1;return r&&e.push(...B2(t[0].view.annotations)),e.push(...$2("nest",t.map(i=>zxt(i,r)))),e}function zxt(t,e=!1){const r=[];return e||r.push(...B2(t.view.annotations)),t.name&&(r.push((0,CE.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Gxt(t.view)),r}function Gxt(t){return hd(t.definition)}function Wxt(t){return[`limit: ${t.limit}`]}function Vxt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(Eu),e.push(...Wxt(t[r]));return e}function Nxe(t){return $2("where",t.map(Lxe),",")}function Yxt(t){return $2("having",t.map(Lxe),",")}const Kxt=["`","'",'"'];function Jxt(t){let e,r;for(const i of Kxt){const s=Xxt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function Xxt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function Lxe(t){switch(t.filter.kind){case"filter_string":return[...Yc(t.filter.field_reference)," ~ ",Jxt(t.filter.filter)]}}function B2(t){return t?t.flatMap(Zxt):[]}function Zxt(t){return[t.value.trim(),Eu]}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.convertToThrift=Ma.convertFromThrift=Ma.unnestUnions=Ma.nestUnions=void 0;const edt=vE;function cP(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(cP);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=cP(t[i]);return r===void 0?e:{[r]:e}}}Ma.nestUnions=cP;function UR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>UR(r,e));{const r=k2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=UR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=UR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}Ma.unnestUnions=UR;function jR(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=k2(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>jR(r,e));{const r=k2(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=jR(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=jR(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}Ma.convertFromThrift=jR;function k2(t){const e=edt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function qR(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=k2(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>qR(r,e));{const r=k2(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=k2(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=qR(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=qR(t[s],o.type)}return i}}}}Ma.convertToThrift=qR,function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.queryToMalloy=void 0,r(vE,t);var i=BR;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}});var s=Ma;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",field_reference:{name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(oP);var tn={},tdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ndt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&tdt(e,t,r);return ndt(e,t),e};Object.defineProperty(tn,"__esModule",{value:!0}),tn.statedCompileQuery=tn.newCompileQueryState=tn.hasErrors=tn.compileSource=tn.compileModel=tn._statedCompileModel=tn.statedCompileSource=tn.statedCompileModel=tn.newCompileSourceState=tn.newCompileModelState=tn.updateCompileModelState=tn.compileQuery=void 0;const idt=rdt(oP),sdt=Q4,Ixe=Pi,odt=Ia,$xe=Yl,udt=ui,Bxe=eu,pd=mE;function kxe(t,e){return`${t}:${e}`}function adt(t,e){return{type:"sql_select",selectStr:t.sql,connection:t.connection_name,dialect:e,fields:t.schema?Pxe(t.schema):[],name:(0,$xe.sqlKey)(t.connection_name,t.sql)}}function ldt(t,e){return{type:"table",tablePath:t.name,connection:t.connection_name,dialect:e,fields:t.schema?Pxe(t.schema):[],name:kxe(t.connection_name,t.name)}}function cdt(t){if(t!==void 0)return t==="decimal"?"float":"integer"}function Mxe(t){switch(t.kind){case"string_type":return{type:"string"};case"number_type":return{type:"number",numberType:cdt(t.subtype)};case"boolean_type":return{type:"boolean"};case"timestamp_type":return{type:"timestamp",timeframe:t.timeframe};case"date_type":return{type:"date",timeframe:t.timeframe};case"sql_native_type":return{type:"sql native",rawType:t.sql_type};case"json_type":return{type:"json"};case"array_type":{if(t.element_type.kind==="record_type")return{type:"array",elementTypeDef:{type:"record_element"},fields:t.element_type.fields.map(fP)};{const e=Mxe(t.element_type);if(e.type==="record")throw new Error("Arrays of records should be a repeated record type");return{type:"array",elementTypeDef:e}}}case"record_type":return{type:"record",fields:t.fields.map(fP)}}}function fP(t){var e;const r=Mxe(t.type);return{...(0,Ixe.mkFieldDef)(r,t.name),annotation:t.annotations&&t.annotations.length?{notes:(e=t.annotations)===null||e===void 0?void 0:e.map(i=>({text:i.value,at:{url:"~internal~",range:pd.DEFAULT_LOG_RANGE}}))}:void 0}}function fdt(t){if(t.kind!=="dimension")throw new Error("Table schemas must only have dimension fields");return fP(t)}function Pxe(t){const e=[];for(const r of t.fields)e.push(fdt(r));return e}function Uxe(t){var e,r,i,s,o,u;const a={urls:{},tables:{},compileSQL:{},translations:{}};if(t){for(const l of(e=t.files)!==null&&e!==void 0?e:[])l.contents!==void 0&&(a.urls[l.url]=l.contents);for(const l of(r=t.table_schemas)!==null&&r!==void 0?r:[]){const c=(i=t.connections)===null||i===void 0?void 0:i.find(f=>f.name===l.connection_name);c&&l.schema&&c.dialect&&(a.tables[kxe(l.connection_name,l.name)]=ldt(l,c.dialect))}for(const l of(s=t.sql_schemas)!==null&&s!==void 0?s:[]){const c=(o=t.connections)===null||o===void 0?void 0:o.find(f=>f.name===l.connection_name);c&&c.dialect&&(a.compileSQL[(0,$xe.sqlKey)(l.connection_name,l.sql)]=adt(l,c.dialect))}for(const l of(u=t.translations)!==null&&u!==void 0?u:[])if(l.compiled_model_json){const c=JSON.parse(l.compiled_model_json);a.translations[l.url]=c}}return a}function jxe(t,e,r){var i,s,o;const u={},a=new Set;if(t!==void 0&&(u.sql_schemas=[{sql:t.selectStr,connection_name:t.connection}],a.add(t.connection)),e!==void 0)for(const l of e)(i=u.files)!==null&&i!==void 0||(u.files=[]),u.files.push({url:l});if(r!==void 0)for(const l in r){const c=r[l],f=(s=c.connectionName)!==null&&s!==void 0?s:"__default__";(o=u.table_schemas)!==null&&o!==void 0||(u.table_schemas=[]),u.table_schemas.push({name:c.tablePath,connection_name:f}),a.add(f)}return a.size>0&&(u.connections=Array.from(a).map(l=>({name:l}))),u}function xdt(t,e){return e??(e=Gxe(t)),Wxe(e)}tn.compileQuery=xdt;function ddt(t,e){function r(s,o){var u,a,l,c;s.translator.update(o),s.extending&&r(s.extending,o),s.hasSource||(s.hasSource=((a=(u=e==null?void 0:e.files)===null||u===void 0?void 0:u.some(f=>f.url===s.translator.sourceURL))!==null&&a!==void 0?a:!1)||((c=(l=e==null?void 0:e.translations)===null||l===void 0?void 0:l.some(f=>f.url===s.translator.sourceURL))!==null&&c!==void 0?c:!1))}const i=Uxe(e);r(t,i)}tn.updateCompileModelState=ddt;function HR(t,e,r){var i,s,o,u;const a=new sdt.MalloyTranslator(t,null,Uxe(e)),l=((s=(i=e==null?void 0:e.files)===null||i===void 0?void 0:i.some(c=>c.url===t))!==null&&s!==void 0?s:!1)||((u=(o=e==null?void 0:e.translations)===null||o===void 0?void 0:o.some(c=>c.url===t))!==null&&u!==void 0?u:!1);return r?{extending:HR(r,e),translator:a,done:!1,hasSource:l}:{translator:a,done:!1,hasSource:l}}function qxe(t){return HR(t.model_url,t.compiler_needs,t.extend_model_url)}tn.newCompileModelState=qxe;function Hxe(t){return HR(t.model_url,t.compiler_needs,t.extend_model_url)}tn.newCompileSourceState=Hxe;function Qxe(t){return hdt(SE(t),t.translator.sourceURL)}tn.statedCompileModel=Qxe;function zxe(t,e){return gdt(SE(t),e,t.translator.sourceURL)}tn.statedCompileSource=zxe;function SE(t){let e;if(t.extending){if(!t.extending.done){const i=SE(t.extending);if(!t.extending.done)return i}e=t.extending.translator.modelDef}if(!t.hasSource)return{compilerNeeds:jxe(void 0,[t.translator.sourceURL],void 0)};const r=t.translator.translate(e);if(r.final){if(t.done=!0,r.modelDef)return{model:(0,odt.modelDefToModelInfo)(r.modelDef),modelDef:r.modelDef};if(r.problems===void 0||r.problems.length===0)throw new Error("No problems found, but no model either");return{logs:r.problems}}else return{compilerNeeds:jxe(r.compileSQL,r.urls,r.tables),logs:r.problems}}tn._statedCompileModel=SE;function hdt(t,e){const r=t.logs?(0,pd.mapLogs)(t.logs,e):void 0;if(t.compilerNeeds)return{compiler_needs:t.compilerNeeds,logs:r};{let i;return t.modelDef&&(i=[{url:e,compiled_model_json:JSON.stringify(t.modelDef)}]),{model:t.model,logs:r,translations:i}}}function pdt(t,e){return e??(e=qxe(t)),Qxe(e)}tn.compileModel=pdt;function mdt(t){const e=Hxe(t);return zxe(e,t.name)}tn.compileSource=mdt;function gdt(t,e,r){const i=t.logs?(0,pd.mapLogs)(t.logs,r):void 0;if(t.model){const s=t.model.entries.find(o=>o.name===e);return s===void 0?{logs:[...i??[],{url:r,severity:"error",message:`Model does not contain a source named ${e}`,range:pd.DEFAULT_LOG_RANGE}]}:{source:s,logs:i}}else return{compiler_needs:t.compilerNeeds,logs:i}}function ydt(t){var e;return(e=t==null?void 0:t.some(r=>r.severity==="error"))!==null&&e!==void 0?e:!1}tn.hasErrors=ydt;function Gxe(t){var e,r;const i=idt.queryToMalloy(t.query),s={...(e=t.compiler_needs)!==null&&e!==void 0?e:{}},o="internal://query.malloy";return s.files=[{url:o,contents:i},...(r=s.files)!==null&&r!==void 0?r:[]],HR(o,s,t.model_url)}tn.newCompileQueryState=Gxe;function Wxe(t){var e;const r=SE(t),i=t.translator.sourceURL,s=r.logs?(0,pd.mapLogs)(r.logs,i):void 0;if(r.model){const o=r.modelDef.queryList;if(o.length===0)return{logs:[...s??[],{url:i,severity:"error",message:"Internal error: No queries found",range:pd.DEFAULT_LOG_RANGE}]};const u=o.length-1,a=r.modelDef.queryList[u],l=r.model.anonymous_queries[u].schema,c=(e=r.model.anonymous_queries[u].annotations)!==null&&e!==void 0?e:[];try{const x=new Ixe.QueryModel(r.modelDef).compileQuery(a),h=(0,udt.annotationToTaglines)(r.modelDef.annotation).map(p=>({value:p}));return c.push({value:Bxe.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore).toString()}),x.queryName&&c.push({value:Bxe.Tag.withPrefix("#(malloy) ").set(["query_name"],x.queryName).toString()}),{result:{sql:x.sql,schema:l,connection_name:x.connectionName,annotations:c.length>0?c:void 0,model_annotations:h.length>0?h:void 0,query_timezone:x.queryTimezone}}}catch(f){return{logs:[...s??[],{url:i,severity:"error",message:`Internal compiler error: ${f.message}`,range:pd.DEFAULT_LOG_RANGE}]}}}else return{compiler_needs:r.compilerNeeds,logs:s}}tn.statedCompileQuery=Wxe;var Edt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Adt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vxe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Edt(e,t,r);return Adt(e,t),e};Object.defineProperty(Vc,"__esModule",{value:!0}),Vc.compileQuery=Vc.compileSource=Vc.compileModel=void 0;const _dt=Vxe(oP),Pa=Vxe(tn),vdt=jp;function Cdt(t,e){return t.type==="compile_model"?e.type!=="compile_model"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL:t.type==="compile_source"?e.type!=="compile_source"?!1:t.modelURL===e.modelURL&&t.extendModelURL===e.extendModelURL&&t.name===e.name:e.type!=="compile_query"?!1:t.modelURL===e.modelURL&&t.queryString===e.queryString}class Sdt{constructor(){this.sessions=new Map}purgeExpired(e){const r=new Date;for(const i of this.sessions.values())i.sessionId!==(e==null?void 0:e.except)&&i.expires&&i.expires<r&&this.sessions.delete(i.sessionId)}findSession(e,r){const i=this.sessions.get(e);if(i&&Cdt(i.sessionInfo,r))return i}getExpires(e){return e instanceof Date?e:new Date(Date.now()+e.seconds*1e3)}newSessionId(){let e;do e=(0,vdt.v4)();while(this.sessions.has(e));return e}newCompileModelSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileModelState(e);return{type:"compile_model",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileSourceSession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileSourceState(e);return{type:"compile_source",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}newCompileQuerySession(e,r,i){const s=i!=null&&i.ttl?this.getExpires(i.ttl):void 0,o=Pa.newCompileQueryState(e);return{type:"compile_query",sessionInfo:r,state:o,expires:s,sessionId:this.newSessionId()}}findCompileModelSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_model")return i}killSession(e){this.sessions.delete(e)}hasErrors(e){return Pa.hasErrors(e)}compileModel(e,r){const i={type:"compile_model",modelURL:e.model_url,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileModelSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileModelSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileModel(s.state);return(o.model||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileSourceSession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_source")return i}compileSource(e,r){const i={type:"compile_source",modelURL:e.model_url,name:e.name,extendModelURL:e.extend_model_url};let s=(r==null?void 0:r.session_id)&&this.findCompileSourceSession(r.session_id,i);this.purgeExpired({except:r==null?void 0:r.session_id}),s?(r!=null&&r.ttl&&(s.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(s.state,e.compiler_needs)):(s=this.newCompileSourceSession(e,i,r),this.sessions.set(s.sessionId,s));const o=Pa.statedCompileSource(s.state,e.name);return(o.source||this.hasErrors(o.logs))&&this.killSession(s.sessionId),{...o,session_id:s.sessionId}}findCompileQuerySession(e,r){const i=this.findSession(e,r);if((i==null?void 0:i.type)==="compile_query")return i}compileQuery(e,r){const i=_dt.queryToMalloy(e.query),s={type:"compile_query",modelURL:e.model_url,queryString:i,query:e.query};let o=(r==null?void 0:r.session_id)&&this.findCompileQuerySession(r.session_id,s);this.purgeExpired({except:r==null?void 0:r.session_id}),o?(r!=null&&r.ttl&&(o.expires=this.getExpires(r.ttl)),Pa.updateCompileModelState(o.state,e.compiler_needs)):(o=this.newCompileQuerySession(e,s,r),this.sessions.set(o.sessionId,o));const u=Pa.statedCompileQuery(o.state);return(u.result||this.hasErrors(u.logs))&&this.killSession(o.sessionId),{...u,session_id:o.sessionId}}}const xP=new Sdt;function bdt(t,e){return xP.compileModel(t,e)}Vc.compileModel=bdt;function Tdt(t,e){return xP.compileSource(t,e)}Vc.compileSource=Tdt;function Rdt(t,e){return xP.compileQuery(t,e)}Vc.compileQuery=Rdt;var Kc={},Ddt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Odt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ddt(e,t,r);return Odt(e,t),e};Object.defineProperty(Kc,"__esModule",{value:!0}),Kc.compileQuery=Kc.compileSource=Kc.compileModel=void 0;const dP=Fdt(tn);function wdt(t){return dP.compileModel(t)}Kc.compileModel=wdt;function Ndt(t){return dP.compileSource(t)}Kc.compileSource=Ndt;function Ldt(t){return dP.compileQuery(t)}Kc.compileQuery=Ldt;var Ua={},Idt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),$dt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Bdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Idt(e,t,r);return $dt(e,t),e};Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.runQuery=Ua.compileQuery=Ua.compileSource=Ua.compileModel=void 0;const Co=Bdt(tn),Yxe=mE;async function hP(t,e){var r,i,s,o,u,a,l,c,f;if(t===void 0)throw new Error("Expected compiler to have needs because it didn't return a result");const x={};if(t.connections)for(const h of t.connections){const p=await e.connections.lookupConnection(h.name);(r=x.connections)!==null&&r!==void 0||(x.connections=[]),x.connections.push({...h,dialect:p.dialectName})}if(t.files)for(const h of t.files){const p=await e.urls.readURL(new URL(h.url));(i=x.files)!==null&&i!==void 0||(x.files=[]),typeof p=="string"?x.files.push({...h,contents:p}):x.files.push({...h,contents:p.contents,invalidation_key:(s=p.invalidationKey)===null||s===void 0?void 0:s.toString()})}if(t.table_schemas){const h={};for(const p of t.table_schemas)(o=h[c=p.connection_name])!==null&&o!==void 0||(h[c]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),y=h[p].map(E=>E.name),g=await Promise.all(y.map(async E=>({name:E,schema:await m.fetchSchemaForTable(E)})));(u=x.table_schemas)!==null&&u!==void 0||(x.table_schemas=[]);for(const E of g)x.table_schemas.push({connection_name:p,name:E.name,schema:E.schema})}}if(t.sql_schemas){const h={};for(const p of t.sql_schemas)(a=h[f=p.connection_name])!==null&&a!==void 0||(h[f]=[]),h[p.connection_name].push(p);for(const p in h){const m=await e.connections.lookupConnection(p),y=h[p].map(E=>E.sql),g=await Promise.all(y.map(async E=>({sql:E,schema:await m.fetchSchemaForSQLQuery(E)})));(l=x.sql_schemas)!==null&&l!==void 0||(x.sql_schemas=[]);for(const E of g)x.sql_schemas.push({connection_name:p,sql:E.sql,schema:E.schema})}}return x}async function kdt(t,e){const r=Co.newCompileModelState(t);for(;;){const i=Co.statedCompileModel(r);if(i.model||Co.hasErrors(i.logs))return i;const s=await hP(i.compiler_needs,e);Co.updateCompileModelState(r,s)}}Ua.compileModel=kdt;async function Mdt(t,e){const r=Co.newCompileSourceState(t);for(;;){const i=Co.statedCompileSource(r,t.name);if(i.source||Co.hasErrors(i.logs))return i;const s=await hP(i.compiler_needs,e);Co.updateCompileModelState(r,s)}}Ua.compileSource=Mdt;async function Kxe(t,e){const r=Co.newCompileQueryState(t);for(;;){const i=Co.statedCompileQuery(r);if(i.result||Co.hasErrors(i.logs))return i;const s=await hP(i.compiler_needs,e);Co.updateCompileModelState(r,s)}}Ua.compileQuery=Kxe;async function Pdt(t,e){var r,i;const s=await Kxe(t,e);if(s.result===void 0)return s;const o=t.model_url;if(s.result.sql===void 0)return{logs:[...(r=s.logs)!==null&&r!==void 0?r:[],{url:o,severity:"error",message:"Internal error: Compiler did not generate SQL",range:Yxe.DEFAULT_LOG_RANGE}]};try{const a=await(await e.connections.lookupConnection(s.result.connection_name)).runSQL(s.result.sql,s.result.schema);return{...s,result:{...s.result,data:a}}}catch(u){return{...s,logs:[...(i=s.logs)!==null&&i!==void 0?i:[],{url:o,severity:"error",message:`Error running SQL: ${u.message}`,range:Yxe.DEFAULT_LOG_RANGE}]}}}Ua.runQuery=Pdt;var Jxe={};Object.defineProperty(Jxe,"__esModule",{value:!0}),function(t){var e=T&&T.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u},s=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.util=t.asynchronous=t.stateless=t.sessioned=void 0,t.sessioned=i(Vc),t.stateless=i(Kc),t.asynchronous=i(Ua),s(Jxe,t),t.util=i(mE)}(Dxe),function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,y){y===void 0&&(y=m);var g=Object.getOwnPropertyDescriptor(p,m);(!g||("get"in g?!p.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,y,g)}:function(h,p,m,y){y===void 0&&(y=m),h[y]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p};Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyURLReader=t.SingleConnectionRuntime=t.ConnectionRuntime=t.AtomicFieldType=t.Runtime=t.Malloy=t.Model=t.MalloyTranslator=t.malloyToQuery=t.composeSQLExpr=t.indent=t.expressionIsUngroupedAggregate=t.expressionIsScalar=t.expressionIsCalculation=t.expressionIsAnalytic=t.expressionIsAggregate=t.mkFieldDef=t.mkArrayDef=t.isBasicArray=t.isRepeatedRecord=t.isSamplingRows=t.isSamplingPercent=t.isSamplingEnable=t.isJoinedSource=t.isJoined=t.isBasicAtomic=t.Segment=t.isSourceDef=t.TinyParser=t.Dialect=t.spread=t.literal=t.variadicParam=t.param=t.makeParam=t.sql=t.maxScalar=t.minAggregate=t.anyExprType=t.minScalar=t.overload=t.qtz=t.arg=t.registerDialect=t.MySQLDialect=t.SnowflakeDialect=t.PostgresDialect=t.TrinoDialect=t.StandardSQLDialect=t.DuckDBDialect=void 0,t.annotationToTaglines=t.annotationToTag=t.sqlKey=t.API=t.modelDefToModelInfo=t.toAsyncGenerator=t.CacheManager=t.InMemoryModelCache=t.Explore=t.DataWriter=t.Parse=t.JSONWriter=t.CSVWriter=t.QueryMaterializer=t.Result=t.PreparedResult=t.TimestampTimeframe=t.DateTimeframe=t.SourceRelationship=t.JoinRelationship=t.MalloyError=t.FixedConnectionMap=t.InMemoryURLReader=void 0;var s=Pp;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}}),Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return s.StandardSQLDialect}}),Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return s.TrinoDialect}}),Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}}),Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return s.SnowflakeDialect}}),Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return s.MySQLDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return s.registerDialect}}),Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return s.arg}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return s.qtz}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return s.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return s.minScalar}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return s.anyExprType}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return s.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return s.maxScalar}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return s.sql}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return s.makeParam}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return s.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return s.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return s.literal}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return s.spread}}),Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return s.Dialect}}),Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return s.TinyParser}});var o=Pi;Object.defineProperty(t,"isSourceDef",{enumerable:!0,get:function(){return o.isSourceDef}}),Object.defineProperty(t,"Segment",{enumerable:!0,get:function(){return o.Segment}}),Object.defineProperty(t,"isBasicAtomic",{enumerable:!0,get:function(){return o.isBasicAtomic}}),Object.defineProperty(t,"isJoined",{enumerable:!0,get:function(){return o.isJoined}}),Object.defineProperty(t,"isJoinedSource",{enumerable:!0,get:function(){return o.isJoinedSource}}),Object.defineProperty(t,"isSamplingEnable",{enumerable:!0,get:function(){return o.isSamplingEnable}}),Object.defineProperty(t,"isSamplingPercent",{enumerable:!0,get:function(){return o.isSamplingPercent}}),Object.defineProperty(t,"isSamplingRows",{enumerable:!0,get:function(){return o.isSamplingRows}}),Object.defineProperty(t,"isRepeatedRecord",{enumerable:!0,get:function(){return o.isRepeatedRecord}}),Object.defineProperty(t,"isBasicArray",{enumerable:!0,get:function(){return o.isBasicArray}}),Object.defineProperty(t,"mkArrayDef",{enumerable:!0,get:function(){return o.mkArrayDef}}),Object.defineProperty(t,"mkFieldDef",{enumerable:!0,get:function(){return o.mkFieldDef}}),Object.defineProperty(t,"expressionIsAggregate",{enumerable:!0,get:function(){return o.expressionIsAggregate}}),Object.defineProperty(t,"expressionIsAnalytic",{enumerable:!0,get:function(){return o.expressionIsAnalytic}}),Object.defineProperty(t,"expressionIsCalculation",{enumerable:!0,get:function(){return o.expressionIsCalculation}}),Object.defineProperty(t,"expressionIsScalar",{enumerable:!0,get:function(){return o.expressionIsScalar}}),Object.defineProperty(t,"expressionIsUngroupedAggregate",{enumerable:!0,get:function(){return o.expressionIsUngroupedAggregate}}),Object.defineProperty(t,"indent",{enumerable:!0,get:function(){return o.indent}}),Object.defineProperty(t,"composeSQLExpr",{enumerable:!0,get:function(){return o.composeSQLExpr}});var u=Q4;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return u.malloyToQuery}}),Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return u.MalloyTranslator}});var a=Fe;Object.defineProperty(t,"Model",{enumerable:!0,get:function(){return a.Model}}),Object.defineProperty(t,"Malloy",{enumerable:!0,get:function(){return a.Malloy}}),Object.defineProperty(t,"Runtime",{enumerable:!0,get:function(){return a.Runtime}}),Object.defineProperty(t,"AtomicFieldType",{enumerable:!0,get:function(){return a.AtomicFieldType}}),Object.defineProperty(t,"ConnectionRuntime",{enumerable:!0,get:function(){return a.ConnectionRuntime}}),Object.defineProperty(t,"SingleConnectionRuntime",{enumerable:!0,get:function(){return a.SingleConnectionRuntime}}),Object.defineProperty(t,"EmptyURLReader",{enumerable:!0,get:function(){return a.EmptyURLReader}}),Object.defineProperty(t,"InMemoryURLReader",{enumerable:!0,get:function(){return a.InMemoryURLReader}}),Object.defineProperty(t,"FixedConnectionMap",{enumerable:!0,get:function(){return a.FixedConnectionMap}}),Object.defineProperty(t,"MalloyError",{enumerable:!0,get:function(){return a.MalloyError}}),Object.defineProperty(t,"JoinRelationship",{enumerable:!0,get:function(){return a.JoinRelationship}}),Object.defineProperty(t,"SourceRelationship",{enumerable:!0,get:function(){return a.SourceRelationship}}),Object.defineProperty(t,"DateTimeframe",{enumerable:!0,get:function(){return a.DateTimeframe}}),Object.defineProperty(t,"TimestampTimeframe",{enumerable:!0,get:function(){return a.TimestampTimeframe}}),Object.defineProperty(t,"PreparedResult",{enumerable:!0,get:function(){return a.PreparedResult}}),Object.defineProperty(t,"Result",{enumerable:!0,get:function(){return a.Result}}),Object.defineProperty(t,"QueryMaterializer",{enumerable:!0,get:function(){return a.QueryMaterializer}}),Object.defineProperty(t,"CSVWriter",{enumerable:!0,get:function(){return a.CSVWriter}}),Object.defineProperty(t,"JSONWriter",{enumerable:!0,get:function(){return a.JSONWriter}}),Object.defineProperty(t,"Parse",{enumerable:!0,get:function(){return a.Parse}}),Object.defineProperty(t,"DataWriter",{enumerable:!0,get:function(){return a.DataWriter}}),Object.defineProperty(t,"Explore",{enumerable:!0,get:function(){return a.Explore}}),Object.defineProperty(t,"InMemoryModelCache",{enumerable:!0,get:function(){return a.InMemoryModelCache}}),Object.defineProperty(t,"CacheManager",{enumerable:!0,get:function(){return a.CacheManager}});var l=$R;Object.defineProperty(t,"toAsyncGenerator",{enumerable:!0,get:function(){return l.toAsyncGenerator}});var c=Ia;Object.defineProperty(t,"modelDefToModelInfo",{enumerable:!0,get:function(){return c.modelDefToModelInfo}}),t.API=i(Dxe);var f=Yl;Object.defineProperty(t,"sqlKey",{enumerable:!0,get:function(){return f.sqlKey}});var x=ui;Object.defineProperty(t,"annotationToTag",{enumerable:!0,get:function(){return x.annotationToTag}}),Object.defineProperty(t,"annotationToTaglines",{enumerable:!0,get:function(){return x.annotationToTaglines}})}(C$);class Udt{constructor(e){this.document=e}async render(e,r){var l;let i;if(e&&(e instanceof C$.Result||"modelDef"in e)?i=C$.API.util.wrapResult(e):i=e,!r4(i.model_annotations,"## ").has("renderer_legacy"))if(!!((l=this.document.defaultView)!=null&&l.customElements.get("malloy-render"))){const f=this.document.createElement("malloy-render");f.malloyResult=i;const x=r.nextRendererOptions??{};for(const[h,p]of Object.entries(x))f[h]=p;return f}else console.warn("Tried to use the new Malloy renderer, but the malloy-render component was not found. Falling back to the legacy renderer.");const u=pue(i),a=Zxe(u.field,this.document,r,{size:"large"},u.field.queryTimezone,u.field.tag);try{return await a.render(u)}catch(c){return c instanceof Error?Ws(this.document,c):Ws(this.document,"Internal error - Exception not an Error object.")}}}class jdt{constructor(e){this.document=e}async render(e){const r=new EP(this.document);try{return await r.render(e)}catch(i){return i instanceof Error?Ws(this.document,i):Ws(this.document,"Internal error - Exception not an Error object.")}}}const Xxe={shape_map:"shape_map",point_map:"point_map",bar_chart:"bar_chart",image:"image",json:"json",segment_map:"segment_map",dashboard:"dashboard",line_chart:"line_chart",scatter_chart:"scatter_chart",url:"url",list:"list",list_detail:"list_detail",sparkline:"sparkline",sparkline_area:"sparkline",sparkline_column:"sparkline",sparkline_bar:"sparkline"};function qdt(t,e){const r=e[t.name],{name:i}=t;for(const s in Xxe)if(i.endsWith(`_${s}`)){const o=i.slice(0,i.length-s.length-1);return Hdt(s,o,Xxe,r)}return r}function Hdt(t,e,r,i){var s;return i?(i.renderer??(i.renderer=r[t]),i.data??(i.data={}),(s=i.data).label??(s.label=e)):i={renderer:r[t],data:{label:e}},i}function QR(t){if(t.isRecordOrRepeatedRecord())return t;throw new Error(`${t.name} does not contain fields and cannot be rendered this way`)}function Zxe(t,e,r,i,s,o){const u=qdt(t,r.dataStyles);r.dataStyles[t.name]=u;const a=new qL().create(u,o,e,i,r,t,s);if(a)return a;if((u==null?void 0:u.renderer)==="dashboard"||o.has("dashboard"))return zR(_$,e,QR(t),r,o);if((u==null?void 0:u.renderer)==="list"||o.has("list"))return zR(vue,e,QR(t),r,o);if((u==null?void 0:u.renderer)==="list_detail"||o.has("list_detail"))return zR(AYe,e,QR(t),r,o);if((u==null?void 0:u.renderer)==="table"||o.has("table")||t.isRecordOrRepeatedRecord())return zR(t1,e,QR(t),r,o);throw new Error(`Could not find a proper renderer for field ${t.name}`)}function zR(t,e,r,i,s){const o=wE.make(t,e,r,i,s),u={};return r.fields.forEach(a=>{u[a.name]=Zxe(a,e,i,o.defaultStylesForChildren,a.root().queryTimezone,a.tag)}),o.childRenderers=u,o}async function Qdt(t){const e=await ede(t);try{await navigator.clipboard.writeText(e)}catch(r){console.error("Failed to copy text: ",r)}}async function ede(t){let e="";const r=t.tableConfig??{},i=Object.assign({disableVirtualization:!0},r);t.tableConfig=i;const s=t.dashboardConfig??{},o=Object.assign({disableVirtualization:!0},s);if(t.dashboardConfig=o,await zdt(1e3),t.shadowRoot){let u="";for(const a of[...t.shadowRoot.adoptedStyleSheets]){for(let c=0;c<a.cssRules.length;c++){const f=a.cssRules.item(c);f&&(u+=`
|
|
1492
1492
|
`+f.cssText)}u=u.replaceAll(":host",".malloy_html_host");const l=t.getAttribute("style");e=`
|
|
1493
1493
|
<div>
|
|
@@ -153040,7 +153040,7 @@ Xp.malloyToQuery = Lpt;
|
|
|
153040
153040
|
var Le = {}, $D = {};
|
|
153041
153041
|
Object.defineProperty($D, "__esModule", { value: !0 });
|
|
153042
153042
|
$D.MALLOY_VERSION = void 0;
|
|
153043
|
-
$D.MALLOY_VERSION = "0.0.
|
|
153043
|
+
$D.MALLOY_VERSION = "0.0.262";
|
|
153044
153044
|
Object.defineProperty(Le, "__esModule", { value: !0 });
|
|
153045
153045
|
Le.InMemoryModelCache = Le.CacheManager = Le.CSVWriter = Le.JSONWriter = Le.DataWriter = Le.DataRecord = Le.DataArray = Le.Result = Le.ExploreMaterializer = Le.PreparedResultMaterializer = Le.QueryMaterializer = Le.ModelMaterializer = Le.SingleConnectionRuntime = Le.ConnectionRuntime = Le.Runtime = Le.ExploreField = Le.JoinRelationship = Le.QueryField = Le.Query = Le.StringField = Le.UnsupportedField = Le.JSONField = Le.BooleanField = Le.NumberField = Le.TimestampField = Le.DateField = Le.TimestampTimeframe = Le.DateTimeframe = Le.AtomicField = Le.AtomicFieldType = Le.Explore = Le.SourceRelationship = Le.FixedConnectionMap = Le.InMemoryURLReader = Le.EmptyURLReader = Le.PreparedResult = Le.DocumentCompletion = Le.DocumentSymbol = Le.DocumentPosition = Le.DocumentRange = Le.DocumentTablePath = Le.Parse = Le.PreparedQuery = Le.Model = Le.MalloyError = Le.Malloy = void 0;
|
|
153046
153046
|
const LY = UT, si = Yi, IY = Wr, ew = G2, Ipt = $D, $pt = V2, Mn = pi, Bpt = n0, $Y = "internal://internal.malloy";
|
|
@@ -156022,7 +156022,7 @@ uA.MALLOY_INTERFACE_TYPES = {
|
|
|
156022
156022
|
array: !1
|
|
156023
156023
|
},
|
|
156024
156024
|
where: {
|
|
156025
|
-
type: "
|
|
156025
|
+
type: "FilterOperation",
|
|
156026
156026
|
array: !0,
|
|
156027
156027
|
optional: !1
|
|
156028
156028
|
}
|
|
@@ -156963,17 +156963,6 @@ uA.MALLOY_INTERFACE_TYPES = {
|
|
|
156963
156963
|
optional: !1
|
|
156964
156964
|
}
|
|
156965
156965
|
}
|
|
156966
|
-
},
|
|
156967
|
-
Where: {
|
|
156968
|
-
type: "struct",
|
|
156969
|
-
name: "Where",
|
|
156970
|
-
fields: {
|
|
156971
|
-
filter: {
|
|
156972
|
-
type: "Filter",
|
|
156973
|
-
optional: !1,
|
|
156974
|
-
array: !1
|
|
156975
|
-
}
|
|
156976
|
-
}
|
|
156977
156966
|
}
|
|
156978
156967
|
};
|
|
156979
156968
|
var qD = {}, HD = {}, zD = {};
|