@malloydata/render 0.0.153 → 0.0.154-dev240722014518

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.
@@ -1281,7 +1281,7 @@ ${r} ${s}: [`,o.length>0&&(i+=`
1281
1281
  `)+`
1282
1282
  ${r} `),i+="]")}return i}*walk(){for(const e of Object.keys(this.children)){const n=this.children[e];if(n instanceof Ku)yield n;else for(const r of n)yield r}}varInfo(){let e="";for(const[n,r]of Object.entries(this))n!=="elementType"&&(typeof r=="boolean"?e+=r?` ${n}`:` !${n}`:(typeof r=="string"||typeof r=="number")&&(e+=` ${n}=${r}`));return e}internalError(e){return this.log(`INTERNAL ERROR IN TRANSLATION: ${e}`),new Error(e)}needs(e){for(const n of this.walk()){const r=n.needs(e);if(r)return r}}inExperiment(e,n=!1){var r;const i=(r=this.translator())===null||r===void 0?void 0:r.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(n||this.log(`Experimental flag '${e}' is not set, feature not available`),!1)}}Ve.MalloyElement=Ku;class nEe extends Ku{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Ve.Unimplemented=nEe;class eD extends Ku{constructor(e){super(),this.name=e,this.elementType="modelEntryReference"}get refString(){return this.name}toString(){return this.refString}getNamed(){var e;return(e=this.modelEntry(this))===null||e===void 0?void 0:e.entry}}Ve.ModelEntryReference=eD;class rEe extends Ku{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Ve.ExperimentalExperiment=rEe;function lQ(t){return t.execute!==void 0}Ve.isDocStatement=lQ;function iEe(t){return t instanceof mm||lQ(t)}Ve.isDocStatementOrDocStatementList=iEe;class cQ extends Ku{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const n of this.elements){const r=n.needs(e);if(r)return r}}}Ve.ListOf=cQ;class mm extends cQ{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=aQ.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const n=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,aQ.isNoteable)(n)&&n.extendNote(this.note),this.noteCursor+=1),n instanceof mm){const r=n.executeList(e);if(r)return r}else{const r=n.needs(e);if(r)return r;n.execute(e)}this.execCursor+=1}}}Ve.DocStatementList=mm;const sEe="5a79a191-06bc-43cf-9b12-58741cd82970";function fQ(t){const e=t.inherits?fQ(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(n=>n.text)),t.notes&&e.push(...t.notes.map(n=>n.text)),e}function oEe(t){const e=fQ(t).join("");return(0,tEe.v5)(e,sEe)}class tD extends Ku{constructor(e){super(),this.elementType="document",this.globalNameSpace=new eEe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new Zye.Tag({}),this.modelAnnotationTodoList=[],this.statements=new mm(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],this.sqlBlocks=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[n,r]of Object.entries(e.contents)){const i=structuredClone(r);if(i.type==="struct"||i.type==="query"||i.type==="function"){const s=e.exports.includes(n);this.setEntry(n,{entry:i,exported:s})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),n=this.modelDef();if(e===void 0){for(const i of this.queryList)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation);for(const i of this.sqlBlocks)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation)}if(n.annotation)for(const i of this.modelAnnotationTodoList)i.modelAnnotation||(i.modelAnnotation=n.annotation);return{modelDef:n,queryList:this.queryList,sqlBlocks:this.sqlBlocks,needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=oEe(e),e}}modelDef(){const e={name:"",exports:[],contents:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const n in this.documentModel){const r=this.documentModel[n].entry;if(r.type==="struct"||r.type==="query"){this.documentModel[n].exported&&e.exports.push(n);const i=structuredClone(r);i.modelAnnotation===void 0&&e.annotation&&(i.modelAnnotation=e.annotation),e.contents[n]=i}}return e}defineSQL(e,n){const r={...e,as:`$${this.sqlBlocks.length}`,declaredSQLBlock:!0};if(n){if(this.getEntry(n))return!1;r.as=n,this.setEntry(n,{entry:r})}return this.sqlBlocks.push(r),!0}getEntry(e){var n;return(n=this.globalNameSpace.getEntry(e))!==null&&n!==void 0?n:this.documentModel[e]}setEntry(e,n){this.globalNameSpace.getEntry(e)!==void 0&&this.log(`Cannot redefine '${e}', which is in global namespace`),n.entry.type==="struct"&&this.checkExperimentalDialect(this,n.entry.dialect),this.documentModel[e]=n}checkExperimentalDialect(e,n){const r=this.translator();r&&r.firstReferenceToDialect(n)&&(0,Xye.getDialect)(n).experimental&&!r.experimentalDialectEnabled(n)&&e.log(`Requires compiler flag '##! experimental.dialect.${n}'`,"error")}}Ve.Document=tD;var B4={},t2={},Yr={},L0={};Object.defineProperty(L0,"__esModule",{value:!0}),L0.canMakeEntry=L0.SpaceEntry=void 0;class uEe{}L0.SpaceEntry=uEe;function aEe(t){return"makeEntry"in t}L0.canMakeEntry=aEe,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.SpaceField=void 0;const lEe=ne,cEe=L0;class fEe extends cEe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){const n={dataType:e.type,expressionType:"scalar",evalSpace:"input"};return(0,lEe.isFieldTypeDef)(e)&&e.expressionType&&(n.expressionType=e.expressionType),n.dataType==="unsupported"&&e.type==="unsupported"&&e.rawType&&(n.rawType=e.rawType),n}getQueryFieldDef(e){}fieldDef(){}}Yr.SpaceField=fEe,Object.defineProperty(t2,"__esModule",{value:!0}),t2.ViewField=void 0;const xEe=Yr;class dEe extends xEe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){return{dataType:"turtle",expressionType:"scalar",evalSpace:"input"}}}t2.ViewField=dEe,Object.defineProperty(B4,"__esModule",{value:!0}),B4.ASTViewField=void 0;const hEe=t2;class pEe extends hEe.ViewField{constructor(e,n,r){super(e),this.view=n,this.name=r}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.view.getFieldDef(this.inSpace)}}B4.ASTViewField=pEe,Object.defineProperty(xm,"__esModule",{value:!0}),xm.ViewFieldDeclaration=void 0;const gEe=Ve,mEe=Vr,yEe=Jh,EEe=B4;class AEe extends gEe.MalloyElement{constructor(e,n){super({view:n}),this.name=e,this.view=n,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=mEe.extendNoteMethod}makeEntry(e){const n=new EEe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,n)}getFieldDef(e){const{pipeline:n,annotation:r}=this.view.pipelineComp(e),i=(0,yEe.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}}xm.ViewFieldDeclaration=AEe;var Rn={};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.LegalRefinementStage=Rn.QueryClass=void 0;var xQ;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(xQ||(Rn.QueryClass=xQ={}));var dQ;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(dQ||(Rn.LegalRefinementStage=dQ={})),Object.defineProperty(fm,"__esModule",{value:!0}),fm.NestFieldDeclaration=void 0;const vEe=Jh,SEe=xm,hQ=Rn;class _Ee extends SEe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=hQ.LegalRefinementStage.Single,this.forceQueryClass=hQ.QueryClass.Grouping}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(e.isQueryFieldSpace()){const{pipeline:n,annotation:r}=this.view.pipelineComp(e,e.outputSpace()),i=(0,vEe.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}throw this.internalError("Unexpected namespace for nest")}}fm.NestFieldDeclaration=_Ee;var n2={},Kr={};Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.ErrorFactory=void 0;const pQ={type:"struct",name:"~malformed~",dialect:"~malformed~",structSource:{type:"table",tablePath:"//undefined_error_table_path"},structRelationship:{type:"basetable",connectionName:"//undefined_error_connection"},fields:[]};class nD{static get structDef(){return{...pQ}}static isErrorStructDef(e){return e.name.includes(pQ.name)}static get query(){return{structRef:nD.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}Kr.ErrorFactory=nD;var ym={};Object.defineProperty(ym,"__esModule",{value:!0}),ym.HasParameter=void 0;const CEe=ne,bEe=Ve;class TEe extends bEe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,this.isCondition=e.isCondition,e.type&&(0,CEe.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e,n;const r=this.name,i=this.type||"string";if(this.isCondition){const o=((e=this.default)===null||e===void 0?void 0:e.constantCondition(i).value)||null;return{type:i,name:r,condition:o}}return{value:((n=this.default)===null||n===void 0?void 0:n.constantValue().value)||null,type:i,name:this.name,constant:!1}}}ym.HasParameter=TEe,Object.defineProperty(n2,"__esModule",{value:!0}),n2.DefineSourceList=n2.DefineSource=void 0;const REe=Kr,OEe=ym,gQ=Ve,NEe=Vr;class DEe extends gQ.MalloyElement{constructor(e,n,r,i){if(super(),this.name=e,this.sourceExpr=n,this.exported=r,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=NEe.extendNoteMethod,n&&this.has({sourceExpr:n}),i){this.parameters=[];for(const s of i)s instanceof OEe.HasParameter?this.parameters.push(s):this.log(`Unexpected element type in define statement: ${s.elementType}`);this.has({parameters:this.parameters})}}execute(e){var n;if(e.modelEntry(this.name))this.log(`Cannot redefine '${this.name}'`);else{const r=(n=this.sourceExpr)===null||n===void 0?void 0:n.getSource();if(r===void 0)return;const i=r.withParameters(this.parameters);if(REe.ErrorFactory.isErrorStructDef(i))return;const s={...i,as:this.name,location:this.location};this.note&&(s.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:this.exported})}}}n2.DefineSource=DEe;class FEe extends gQ.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}n2.DefineSourceList=FEe;var r2={};Object.defineProperty(r2,"__esModule",{value:!0}),r2.DefineQueryList=r2.DefineQuery=void 0;const mQ=Ve,wEe=Vr;class LEe extends mQ.MalloyElement{constructor(e,n){super({queryExpr:n}),this.name=e,this.queryExpr=n,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=wEe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.log(`'${this.name}' is already defined, cannot redefine`);return}const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("Cannot define a query from this expression");return}const i={...r.query(),type:"query",name:this.name,location:this.location};this.note&&(i.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:i,exported:!0})}}r2.DefineQuery=LEe;class IEe extends mQ.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}r2.DefineQueryList=IEe;var Qo={};Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.Source=void 0;const $Ee=Ve;class BEe extends $Ee.MalloyElement{structRef(){return this.structDef()}withParameters(e){const n=this.structDef();if(e){const r={...n.parameters||{}};for(const i of e){const s=i.parameter();r[s.name]=s}return{...n,parameters:r}}return n}}Qo.Source=BEe;var Em={},i2={},k4={},I0={};Object.defineProperty(I0,"__esModule",{value:!0}),I0.mergeFields=I0.nameFromDef=void 0;function rD(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}I0.nameFromDef=rD;function kEe(t,e){if(t===void 0)return e;const n=new Set(e.map(i=>rD(i))),r=t.filter(i=>!n.has(rD(i)));return r.push(...e),r}I0.mergeFields=kEe;var Am={},Xr={},Xu={};Object.defineProperty(Xu,"__esModule",{value:!0}),Xu.DefinedParameter=Xu.AbstractParameter=Xu.SpaceParam=void 0;const PEe=L0;class iD extends PEe.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Xu.SpaceParam=iD;class MEe extends iD{constructor(e){super(),this.astParam=e}parameter(){return this.astParam.parameter()}typeDesc(){return{dataType:this.astParam.type||"error",expressionType:"scalar",evalSpace:"input"}}}Xu.AbstractParameter=MEe;class jEe extends iD{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{dataType:this.paramDef.type,expressionType:"scalar",evalSpace:"input"}}}Xu.DefinedParameter=jEe;var px={};Object.defineProperty(px,"__esModule",{value:!0}),px.StructSpaceFieldBase=void 0;const UEe=Yr;class qEe extends UEe.SpaceField{constructor(e){super(),this.sourceDef=e}get structRelationship(){return this.sourceDef.structRelationship}fieldDef(){return this.sourceDef}typeDesc(){return{dataType:"struct",expressionType:"scalar",evalSpace:"input"}}}px.StructSpaceFieldBase=qEe;var vm={};Object.defineProperty(vm,"__esModule",{value:!0}),vm.ColumnSpaceField=void 0;const HEe=Yr;class zEe extends HEe.SpaceField{constructor(e){super(),this.haveFieldDef=e}fieldDef(){return this.haveFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.haveFieldDef)}}vm.ColumnSpaceField=zEe;var P4={};Object.defineProperty(P4,"__esModule",{value:!0}),P4.IRViewField=void 0;const QEe=t2;class GEe extends QEe.ViewField{constructor(e,n){super(e),this.turtleDef=n,this.haveFieldDef=n}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}P4.IRViewField=GEe,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.StructSpaceField=Xr.StaticSpace=void 0;const WEe=Du,VEe=ne,YEe=Xu,KEe=Yr,M4=px,XEe=vm,JEe=P4;class yQ{constructor(e){this.type="fieldSpace",this.fromStruct=e}dialectObj(){try{return(0,WEe.getDialect)(this.fromStruct.dialect)}catch{return}}defToSpaceField(e){return e.type==="struct"?new EQ(e):(0,VEe.isTurtleDef)(e)?new JEe.IRViewField(this,e):new XEe.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const n=e.as||e.name;this.memoMap[n]=this.defToSpaceField(e)}if(this.fromStruct.parameters)for(const[e,n]of Object.entries(this.fromStruct.parameters)){if(this.memoMap[e])throw new Error(`In struct '${this.fromStruct.as||this.fromStruct.name}': : Field and parameter name conflict '${e}`);this.memoMap[e]=new YEe.DefinedParameter(n)}}return this.memoMap}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,n){this.map[e]=n}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){return{...this.fromStruct,fields:[]}}lookup(e){const n=e[0],r=e.slice(1),i=this.entry(n.refString);if(!i)return{error:`'${n}' is not defined`,found:i};if(i instanceof KEe.SpaceField){const o=i.fieldDef();o&&n.addReference({type:i instanceof M4.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:n.location,text:n.refString})}const s=i instanceof M4.StructSpaceFieldBase?[{name:n.refString,structRelationship:i.structRelationship}]:[];if(r.length){if(i instanceof M4.StructSpaceFieldBase){const o=i.fieldSpace.lookup(r);return o.found?{...o,relationship:[...s,...o.relationship]}:o}return{error:`'${n}' cannot contain a '${r[0]}'`,found:void 0}}return{found:i,error:void 0,relationship:s,isOutputField:!1}}isQueryFieldSpace(){return!1}}Xr.StaticSpace=yQ;class EQ extends M4.StructSpaceFieldBase{constructor(e){super(e)}get fieldSpace(){return new yQ(this.sourceDef)}}Xr.StructSpaceField=EQ,Object.defineProperty(Am,"__esModule",{value:!0}),Am.JoinSpaceField=void 0;const ZEe=Xr;class eAe extends ZEe.StructSpaceField{constructor(e){super(e.structDef()),this.join=e}}Am.JoinSpaceField=eAe;var Sm={};Object.defineProperty(Sm,"__esModule",{value:!0}),Sm.SpaceSeed=void 0;const tAe=Xr;function AQ(t){return t.type==="fieldSpace"}class nAe{constructor(e){this.sourceSpec=e,this.spaceSpec=e}get structDef(){return AQ(this.spaceSpec)?(this.asStruct||(this.asStruct=this.spaceSpec.structDef()),this.asStruct):this.spaceSpec}get fieldSpace(){return AQ(this.spaceSpec)?this.spaceSpec:(this.asFS||(this.asFS=new tAe.StaticSpace(this.spaceSpec)),this.asFS)}}Sm.SpaceSeed=nAe,Object.defineProperty(k4,"__esModule",{value:!0}),k4.DynamicSpace=void 0;const rAe=I0,iAe=Kr,sAe=Yr,oAe=Am,uAe=t2,vQ=Xu,aAe=Sm,lAe=Xr,cAe=px;class fAe extends lAe.StaticSpace{constructor(e){const n=new aAe.SpaceSeed(e);super(structuredClone(n.structDef)),this.completions=[],this.complete=!1,this.final=void 0,this.source=n}isComplete(){this.complete=!0}setEntry(e,n){if(this.final)throw new Error("Space already final");super.setEntry(e,n)}addParameters(e){for(const n of e)this.setEntry(n.name,new vQ.AbstractParameter(n));return this}newEntry(e,n,r){if(this.entry(e)){n.log(`Cannot redefine '${e}'`);return}this.setEntry(e,r)}renameEntry(e,n,r){this.dropEntry(e),this.setEntry(n,r)}addFieldDef(e){this.setEntry((0,rAe.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){const e=this.fromStruct.parameters||{};if(this.final===void 0){this.final={...this.fromStruct,fields:[]};const n=[],r=[],i=[],s=[];for(const[u,a]of this.entries())a instanceof cAe.StructSpaceFieldBase?r.push([u,a]):a instanceof uAe.ViewField?i.push([u,a]):a instanceof sAe.SpaceField?n.push([u,a]):a instanceof vQ.SpaceParam&&(e[u]=a.parameter());const o=[...n,...r,...i];for(const[,u]of o)if(u instanceof oAe.JoinSpaceField){const a=u.join.structDef();iAe.ErrorFactory.isErrorStructDef(a)||(this.final.fields.push(a),s.push([u.join,a]))}else{const a=u.fieldDef();a&&this.final.fields.push(a)}Object.entries(e).length>0&&(this.final.parameters=e);for(const[u,a]of s)u.fixupJoinOn(this,a)}return this.newTimezone&&(this.final.queryTimezone=this.newTimezone),this.isComplete(),this.final}}k4.DynamicSpace=fAe,Object.defineProperty(i2,"__esModule",{value:!0}),i2.RefinedSpace=void 0;const xAe=k4,dAe=L0;class sD extends xAe.DynamicSpace{static filteredFrom(e,n){const r=new sD(e);if(n){const i=n.refs.list,s=r.entries();r.dropEntries();for(const[o,u]of s){const a=!!i.find(c=>c.refString===o),l=n.edit==="accept";a===l&&r.setEntry(o,u)}}return r}pushFields(...e){for(const n of e)(0,dAe.canMakeEntry)(n)?n.makeEntry(this):n.log(`Internal error, ${n.elementType} not expected in this context`)}}i2.RefinedSpace=sD;var $0={},Ds={};Object.defineProperty(Ds,"__esModule",{value:!0}),Ds.DefinitionList=void 0;const hAe=Ve,SQ=Vr;class pAe extends hAe.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,SQ.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,SQ.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Ds.DefinitionList=pAe,Object.defineProperty($0,"__esModule",{value:!0}),$0.DeclareFields=void 0;const gAe=Ds,mAe=Rn;class yAe extends gAe.DefinitionList{constructor(e){super(e),this.elementType="declareFields",this.queryRefinementStage=mAe.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}}$0.DeclareFields=yAe;var Go={},hn={};Object.defineProperty(hn,"__esModule",{value:!0}),hn.nullsafeNot=hn.compressExpr=hn.compose=void 0;const EAe=ne;function _Q(t){return t.length>1?["(",...t,")"]:t.length===0?["__MISSING_VALUE__"]:t}function AAe(t,e,n){const r=e.match(/^[A-Za-z]/),i=t.length===1&&r?" ":"",s=n.length===1&&r?" ":"",o=i+e+s;return[..._Q(t),o,..._Q(n)]}hn.compose=AAe;function vAe(t){const e=[];let n;for(const r of t.flat())typeof r=="string"?n=n?n+r:r:(n&&(e.push(n),n=void 0),e.push(r));return n&&e.push(n),e}hn.compressExpr=vAe;function SAe(t,e){return e===void 0||e==="!="||e==="!~"?(0,EAe.mkExpr)`COALESCE(NOT(${t}),FALSE)`:t}hn.nullsafeNot=SAe,Object.defineProperty(Go,"__esModule",{value:!0}),Go.Filter=Go.FilterElement=void 0;const CQ=ne,_Ae=hn,bQ=Ve,oD=Rn;class CAe extends bQ.MalloyElement{constructor(e,n){super({expr:e}),this.expr=e,this.exprSrc=n,this.elementType="filterElement"}filterExpression(e){const n=this.expr.getExpression(e);return n.dataType!=="boolean"?(this.expr.log("Filter expression must have boolean value"),{code:this.exprSrc,expression:["_FILTER_MUST_RETURN_BOOLEAN_"],expressionType:"scalar"}):{code:this.exprSrc,expression:(0,_Ae.compressExpr)(n.value),expressionType:n.expressionType}}}Go.FilterElement=CAe;let bAe=class extends bQ.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=oD.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?oD.LegalRefinementStage.Tail:oD.LegalRefinementStage.Head}getFilterList(e){const n=[];for(const r of this.list){const i=r.filterExpression(e);if(this.havingClause!==void 0){const s=(0,CQ.expressionIsAggregate)(i.expressionType),o=(0,CQ.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.log("Analytic expressions are not allowed in `having:`");continue}}else if(o){r.log("Analytic expressions are not allowed in `where:`");continue}else s&&r.log("Aggregate expressions are not allowed in `where:`; use `having:`")}n.push(i)}return n}};Go.Filter=bAe;var rs={};Object.defineProperty(rs,"__esModule",{value:!0}),rs.Joins=rs.ExpressionJoin=rs.KeyJoin=rs.Join=void 0;const TAe=ne,RAe=hn,OAe=Am,NAe=Ds,DAe=Ve,FAe=Vr,wAe=Rn,TQ=Kr;class uD extends DAe.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=FAe.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new OAe.JoinSpaceField(this))}getStructDefFromExpr(){const e=this.sourceExpr.getSource();return e?e.structDef():(this.sourceExpr.sqLog("Cannot great a source to join from"),TQ.ErrorFactory.structDef)}}rs.Join=uD;class LAe extends uD{constructor(e,n,r){super({name:e,sourceExpr:n,keyExpr:r}),this.name=e,this.sourceExpr=n,this.keyExpr=r,this.elementType="joinOnKey"}structDef(){var e;const n=this.getStructDefFromExpr(),r={...n,structRelationship:{type:"one",matrixOperation:"left",onExpression:["('join fixup'='not done yet')"]},location:this.location};return n.structSource.type==="query"?r.name=this.name.refString:r.as=this.name.refString,this.note&&(r.annotation=this.note),(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(r),r}fixupJoinOn(e,n){const r=this.keyExpr.getExpression(e);if(n.primaryKey){const i=n.fields.find(s=>(s.as||s.name)===n.primaryKey);if(i)if(i.type===r.dataType){n.structRelationship={type:"one",matrixOperation:"left",onExpression:[{type:"field",path:[this.name.refString,n.primaryKey]},"=",...r.value]};return}else this.log(`join_one: with type mismatch with primary key: ${r.dataType}/${i.type}`);else this.log(`join_one: Primary key '${i}' not found in source`)}else this.log("join_one: Cannot use with unless source has a primary key")}}rs.KeyJoin=LAe;class IAe extends uD{constructor(e,n){super({name:e,sourceExpr:n}),this.name=e,this.sourceExpr=n,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,n){if(this.expr===void 0)return;const r=this.expr.getExpression(e);if(r.dataType!=="boolean"){this.log("join conditions must be boolean expressions");return}const i=n.structRelationship;(0,TAe.isJoinOn)(i)&&(i.onExpression=(0,RAe.compressExpr)(r.value))}structDef(){var e;const n=this.sourceExpr.getSource();if(!n)return this.sourceExpr.sqLog("Cannot create a source to join from"),TQ.ErrorFactory.structDef;const r=n.structDef();let i="left";this.inExperiment("join_types",!0)&&(i=this.matrixOperation);const s={...r,structRelationship:{type:this.joinType,matrixOperation:i},location:this.location};return r.structSource.type==="query"?(s.name=this.name.refString,delete s.as):s.as=this.name.refString,this.note&&(s.annotation=this.note),(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(s),s}}rs.ExpressionJoin=IAe;class $Ae extends NAe.DefinitionList{constructor(e){super(e),this.elementType="joinList",this.forceQueryClass=void 0,this.queryRefinementStage=wAe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}}rs.Joins=$Ae;var s2={};Object.defineProperty(s2,"__esModule",{value:!0}),s2.FieldListEdit=void 0;const BAe=Ve;class kAe extends BAe.MalloyElement{constructor(e,n){super({refs:n}),this.edit=e,this.refs=n,this.elementType="fieldListEdit"}}s2.FieldListEdit=kAe;var o2={};Object.defineProperty(o2,"__esModule",{value:!0}),o2.PrimaryKey=void 0;const PAe=Ve;class MAe extends PAe.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}o2.PrimaryKey=MAe;var u2={};Object.defineProperty(u2,"__esModule",{value:!0}),u2.Views=void 0;const jAe=Ds;class UAe extends jAe.DefinitionList{constructor(){super(...arguments),this.elementType="turtleDefList"}}u2.Views=UAe;var a2={};Object.defineProperty(a2,"__esModule",{value:!0}),a2.TimezoneStatement=void 0;const qAe=Ve;class HAe extends qAe.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return Intl.DateTimeFormat(void 0,{timeZone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}a2.TimezoneStatement=HAe;var B0={};Object.defineProperty(B0,"__esModule",{value:!0}),B0.ModelAnnotation=B0.ObjectAnnotation=void 0;const zAe=dl,QAe=Ve;class RQ extends QAe.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}B0.ObjectAnnotation=RQ;class GAe extends RQ{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,n){const r=zAe.Tag.annotationToTag({notes:this.notes},{prefix:/^##! /,extending:e});return r.log.forEach(i=>n.log(i)),r.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}B0.ModelAnnotation=GAe;var k0={},j4={};Object.defineProperty(j4,"__esModule",{value:!0}),j4.RenameSpaceField=void 0;const WAe=Yr;class VAe extends WAe.SpaceField{constructor(e,n,r){super(),this.otherField=e,this.newName=n,this.location=r}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}j4.RenameSpaceField=VAe,Object.defineProperty(k0,"__esModule",{value:!0}),k0.Renames=k0.RenameField=void 0;const YAe=j4,OQ=Ve,KAe=Yr;class XAe extends OQ.MalloyElement{constructor(e,n){super(),this.newName=e,this.oldName=n,this.elementType="renameField",this.has({oldName:n})}makeEntry(e){if(this.oldName.refString===this.newName){this.log("Can't rename field to itself");return}const n=this.oldName.getField(e);n.found?n.found instanceof KAe.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new YAe.RenameSpaceField(n.found,this.newName,this.location)):this.log(`'${this.oldName}' cannot be renamed`):this.log(`Can't rename '${this.oldName}', no such field`)}}k0.RenameField=XAe;class JAe extends OQ.ListOf{constructor(){super(...arguments),this.elementType="renameFields"}}k0.Renames=JAe,Object.defineProperty(Em,"__esModule",{value:!0}),Em.RefinedSource=void 0;const ZAe=ne,eve=i2,tve=$0,nve=Go,rve=rs,ive=s2,sve=o2,ove=u2,uve=Qo,ave=a2,lve=B0,cve=k0;class fve extends uve.Source{constructor(e,n){super({source:e,refinement:n}),this.source=e,this.refinement=n,this.elementType="refinedSource"}structDef(){return this.withParameters([])}withParameters(e){var n;let r,i;const s=[],o=[];let u;for(const h of this.refinement.list){if(h instanceof lve.ObjectAnnotation)continue;const p=h;h instanceof sve.PrimaryKey?(r&&(r.log("Primary key already defined"),h.log("Primary key redefined")),r=h):h instanceof ive.FieldListEdit?(i&&(i.log("Too many accept/except statements"),h.log("Too many accept/except statements")),i=h):h instanceof tve.DeclareFields||h instanceof rve.Joins||h instanceof ove.Views||h instanceof cve.Renames?s.push(...h.list):h instanceof nve.Filter?o.push(h):h instanceof ave.TimezoneStatement?u=h.tz:p.log(`Unexpected source property: '${p.elementType}'`)}const a=structuredClone(this.source.structDef());r&&(a.primaryKey=r.field.name);const l=eve.RefinedSpace.filteredFrom(a,i);if(u&&l.setTimezone(u),l.pushFields(...s),e&&l.addParameters(e),r){const h=r.field.getField(l);h.error&&r.log(h.error)}const c=l.structDef(),f=c.filterList||[];let x=!1;for(const h of o)for(const p of h.list){const m=p.filterExpression(l);(0,ZAe.expressionIsCalculation)(m.expressionType)?p.log("Can't use aggregate computations in top level filters"):(f.push(m),x=!0)}return x?{...c,filterList:f}:((n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(c),c)}}Em.RefinedSource=fve;var Ju={};Object.defineProperty(Ju,"__esModule",{value:!0}),Ju.SourceQueryElement=void 0;const xve=Ve;class aD extends xve.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e){this.isErrorFree()&&this.log(e),this.errored=!0}isErrorFree(){if(this.errored)return!1;let e=!0;for(const n of this.walk())if(n instanceof aD&&n.errored){e=!1;break}return e}}Ju.SourceQueryElement=aD;var U4={},gx={};Object.defineProperty(gx,"__esModule",{value:!0}),gx.QuerySource=void 0;const dve=Qo;class hve extends dve.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}structDef(){var e;const n=this.query.queryComp(!1),r={...n.outputStruct,structSource:{type:"query",query:n.query}};return(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(r),r}}gx.QuerySource=hve;var l2={},_m={};Object.defineProperty(_m,"__esModule",{value:!0}),_m.QueryBase=void 0;const pve=Jh,gve=Ve;class mve extends gve.MalloyElement{query(){const e=this.queryComp(!0).query;return{...e,pipeline:(0,pve.detectAndRemovePartialStages)(e.pipeline,this)}}}_m.QueryBase=mve,Object.defineProperty(l2,"__esModule",{value:!0}),l2.QueryArrow=void 0;const yve=ne,Eve=Qo,NQ=Xr,Ave=_m;class vve extends Ave.QueryBase{constructor(e,n){super({source:e,view:n}),this.source=e,this.view=n,this.elementType="arrow"}queryComp(e){let n,r,i;if(this.source instanceof Eve.Source){const l=e?this.source.structRef():this.source.structDef();r={type:"query",structRef:l,pipeline:[],location:this.location},n=(0,yve.refIsStructDef)(l)?l:this.source.structDef(),i=new NQ.StaticSpace(n)}else{const l=this.source.queryComp(e);r=l.query,n=l.outputStruct,i=new NQ.StaticSpace(l.outputStruct)}const{pipeline:s,annotation:o,outputStruct:u,name:a}=this.view.pipelineComp(i);return{query:{...r,name:a,annotation:o,pipeline:[...r.pipeline,...s]},outputStruct:u,inputStruct:n}}}l2.QueryArrow=vve,Object.defineProperty(U4,"__esModule",{value:!0}),U4.SQArrow=void 0;const Sve=Ju,_ve=gx,Cve=l2;class bve extends Sve.SourceQueryElement{constructor(e,n){super({applyTo:e,operation:n}),this.applyTo=e,this.operation=n,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("Could not get LHS of arrow operation");return}const n=new Cve.QueryArrow(e,this.operation);return this.has({query:n}),n}getSource(){const e=this.getQuery();if(!e){this.sqLog("Couldn't comprehend query well enough to make a source");return}const n=new _ve.QuerySource(e);return this.has({asSource:n}),n}}U4.SQArrow=bve;var q4={},c2={},Fs={};Object.defineProperty(Fs,"__esModule",{value:!0}),Fs.getStructFieldDef=Fs.getFinalStruct=Fs.opOutputStruct=void 0;const Tve=m0,Rve=Lf,Ove=ne,DQ=Kr;function FQ(t,e,n){const r=DQ.ErrorFactory.isErrorStructDef(e);if((0,Ove.isPartialSegment)(n)&&(n={...n,type:"reduce"}),!r)try{return Rve.Segment.nextStructDef(e,n)}catch(i){t.log(`INTERNAL ERROR model/Segment.nextStructDef: ${i.message}
1283
1283
  QUERY: ${(0,Tve.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...DQ.ErrorFactory.structDef,dialect:e.dialect}}Fs.opOutputStruct=FQ;function Nve(t,e,n){for(const r of n)e=FQ(t,e,r);return e}Fs.getFinalStruct=Nve;function Dve(t,e){return t.fields.find(n=>(n.as||n.name)===e)}Fs.getStructFieldDef=Dve,Object.defineProperty(c2,"__esModule",{value:!0}),c2.QueryRefine=void 0;const Fve=Xr,wve=Fs,Lve=_m;class Ive extends Lve.QueryBase{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="query-refine"}queryComp(e){const n=this.base.queryComp(e),r=new Fve.StaticSpace(n.inputStruct),i=this.refinement.refine(r,n.query.pipeline,void 0);return{query:{...n.query,pipeline:i},outputStruct:(0,wve.getFinalStruct)(this.refinement,n.inputStruct,i),inputStruct:n.inputStruct}}}c2.QueryRefine=Ive;var Cm={},P0={},On={};Object.defineProperty(On,"__esModule",{value:!0}),On.dateOffset=On.timestampOffset=On.timeResult=On.resolution=On.castDateToTimestamp=On.castTimestampToDate=On.castTo=On.timeOffset=void 0;const $ve=ne,wQ=hn;function Bve(t,e,n,r,i){return[{type:"dialect",function:"delta",base:{valueType:t,value:e},op:n,delta:r,units:i}]}On.timeOffset=Bve;function kve(t,e,n,r=!1){const i={type:"dialect",function:"cast",dstType:t,expr:e,safe:r};return(0,$ve.isAtomicFieldType)(n)&&(i.srcType=n),[i]}On.castTo=kve;function Pve(t,e=!1){return[{type:"dialect",function:"cast",dstType:"date",srcType:"timestamp",expr:t,safe:e}]}On.castTimestampToDate=Pve;function Mve(t,e=!1){return[{type:"dialect",function:"cast",dstType:"timestamp",srcType:"date",expr:t,safe:e}]}On.castDateToTimestamp=Mve;function jve(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}On.resolution=jve;function Uve(t,e){return e?{...t,timeframe:e}:t}On.timeResult=Uve;function qve(t,e,n,r,i=!1){const s=["week","month","quarter","year"].includes(r),o=e==="+"?"_ADD":"_SUB",u=r.toUpperCase();if(s)return[`TIMESTAMP(DATETIME${o}(DATETIME(`,...t,"),INTERVAL ",...n,` ${u}))`];const a=i?["TIMESTAMP(",...t,")"]:t;return(0,wQ.compressExpr)([`TIMESTAMP${o}(`,...a,",INTERVAL ",...n,` ${u})`])}On.timestampOffset=qve;function Hve(t,e,n,r){const i=e==="+"?"_ADD":"_SUB",s=r.toUpperCase();return(0,wQ.compressExpr)([`DATE${i}(`,...t,",INTERVAL ",...n,` ${s})`])}On.dateOffset=Hve,Object.defineProperty(P0,"__esModule",{value:!0}),P0.NamedSource=P0.IsValueBlock=void 0;const H4=ne,zve=Qo,Qve=Kr,Gve=On,z4=Ve;class LQ extends z4.MalloyElement{constructor(e){super(),this.isMap=e,this.elementType="isValueBlock",this.has(e)}}P0.IsValueBlock=LQ;class Wve extends zve.Source{constructor(e,n={}){super(),this.ref=e,this.elementType="namedSource",n&&Object.keys(n).length>0&&(this.isBlock=new LQ(n),this.has({parameterValues:this.isBlock})),e instanceof z4.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof z4.ModelEntryReference?this.ref.name:this.ref}structRef(){if(this.isBlock)return this.structDef();const e=this.modelEntry(this.ref);return e&&!e.exported?this.structDef():this.refName}modelStruct(){var e;const n=this.modelEntry(this.ref),r=n==null?void 0:n.entry;if(!r){const i=`Undefined source '${this.refName}'`;(this.ref instanceof z4.ModelEntryReference?this.ref:this).log(i);return}if(r.type==="query"){this.log(`Cannot construct a source from a query '${this.refName}'`);return}else if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot construct a source from a connection '${this.refName}'`);return}else if((0,H4.isSQLBlockStruct)(r)&&r.declaredSQLBlock){this.log(`Must use 'from_sql()' for sql source '${this.refName}'`);return}else(e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,r.dialect);return{...r}}structDef(){var e,n;const r=this.modelStruct();if(!r){const o=Qve.ErrorFactory.structDef,u=`${this.refName}-undefined`;return o.name=o.name+u,o.dialect=o.dialect+u,o}const i={...r.parameters},s=((e=this.isBlock)===null||e===void 0?void 0:e.isMap)||{};for(const[o,u]of Object.entries(s)){const a=i[o];if(!a)this.log(`Value given for undeclared parameter '${o}`);else if((0,H4.isValueParameter)(a))if(a.constant)u.log(`Cannot override constant parameter ${o}`);else{const l=u.constantValue();let c=l.value;l.dataType!==a.type&&(0,H4.isCastType)(a.type)&&(c=(0,Gve.castTo)(a.type,l.value,l.dataType,!0)),a.value=c}else a.condition=u.constantCondition(a.type).value}for(const o in r.parameters)(0,H4.paramHasValue)(i[o])||this.log(`Value not provided for required parameter ${o}`);return(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(r),r}}P0.NamedSource=Wve;var bm={},Q4={};Object.defineProperty(Q4,"__esModule",{value:!0}),Q4.QueryHeadStruct=void 0;const Vve=ne,Yve=Qo,Kve=P0;class Xve extends Yve.Source{constructor(e){super(),this.fromRef=e,this.elementType="internalOnlyQueryHead"}structRef(){return this.fromRef}structDef(){if((0,Vve.refIsStructDef)(this.fromRef))return this.fromRef;const e=new Kve.NamedSource(this.fromRef);return this.has({exploreReference:e}),e.structDef()}}Q4.QueryHeadStruct=Xve,Object.defineProperty(bm,"__esModule",{value:!0}),bm.QueryReference=void 0;const lD=Kr,Jve=Ve,Zve=Q4,eSe=ne,tSe=Fs;class nSe extends Jve.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const n=this.modelEntry(this.name),r=n==null?void 0:n.entry,i=function(){return{inputStruct:lD.ErrorFactory.structDef,outputStruct:lD.ErrorFactory.structDef,query:lD.ErrorFactory.query}};if(!r)return this.log(`Reference to undefined query '${this.name.refString}'`),i();if(r.type==="query"){const s=new Zve.QueryHeadStruct(r.structRef);this.has({queryHead:s});const o=s.structDef(),u=(0,tSe.getFinalStruct)(this,o,r.pipeline);return{query:e||(0,eSe.refIsStructDef)(r.structRef)?r:{...r,structRef:o},outputStruct:u,inputStruct:o}}return this.log(`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}}bm.QueryReference=nSe,Object.defineProperty(Cm,"__esModule",{value:!0}),Cm.SQReference=void 0;const rSe=Ju,iSe=gx,sSe=P0,IQ=bm;class oSe extends rSe.SourceQueryElement{constructor(e){super({ref:e}),this.ref=e,this.elementType="sq-reference"}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const n=new IQ.QueryReference(this.ref);return this.has({query:n}),n}else this.sqLog(`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){var e;return((e=this.ref.getNamed())===null||e===void 0?void 0:e.type)==="struct"}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){const n=new IQ.QueryReference(this.ref);this.asSource=new iSe.QuerySource(n)}else if(e.type==="struct")this.asSource=new sSe.NamedSource(this.ref);else{this.sqLog(`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}Cm.SQReference=oSe,Object.defineProperty(q4,"__esModule",{value:!0}),q4.SQRefine=void 0;const uSe=Ju,aSe=gx,lSe=c2,cSe=Cm;class fSe extends uSe.SourceQueryElement{constructor(e,n){super({toRefine:e,refine:n}),this.toRefine=e,this.refine=n,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof cSe.SQReference?this.sqLog(`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const n=new lSe.QueryRefine(e,this.refine);return this.has({query:n}),n}}getSource(){const e=this.getQuery();if(e){const n=new aSe.QuerySource(e);return this.has({queryAsSource:n}),n}}}q4.SQRefine=fSe;var G4={},Tm={};Object.defineProperty(Tm,"__esModule",{value:!0}),Tm.QueryRaw=void 0;const xSe=ne,dSe=Ve;class hSe extends dSe.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const n=e?this.source.structRef():this.source.structDef(),r=(0,xSe.refIsStructDef)(n)?n:this.source.structDef();return{query:{type:"query",structRef:n,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:r,inputStruct:r}}query(){return this.queryComp(!0).query}}Tm.QueryRaw=hSe;var Rm={},W4={};Object.defineProperty(W4,"__esModule",{value:!0}),W4.makeSQLBlock=void 0;const pSe=ne,gSe=Vt;function mSe(t,e){const n={name:`md5:/${e||"$default"}//${ySe(t)}`,select:t};return e&&(n.connection=e),n}W4.makeSQLBlock=mSe;function ySe(t){const e=t.map(n=>(0,pSe.isSQLFragment)(n)?n.sql:JSON.stringify(n));return(0,gSe.generateHash)(e.join(";"))}Object.defineProperty(Rm,"__esModule",{value:!0}),Rm.SQLSource=void 0;const ESe=W4,ASe=Qo,V4=Kr;class vSe extends ASe.Source{constructor(e,n){super(),this.connectionName=e,this.select=n,this.elementType="sqlSource",this.connectionNameInvalid=!1,this.has({connectionName:e,select:n})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,ESe.makeSQLBlock)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return this.structDef()}validateConnectionName(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection")return this.connectionName.log(`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var n;if(!this.validateConnectionName())return;const r=super.needs(e);if(r)return r;const i=this.sqlBlock(),s=(n=this.translator())===null||n===void 0?void 0:n.root.sqlQueryZone;if(!s){this.log("Cant't look up schema for sql block");return}s.reference(i.name,this.location);const o=s.getEntry(i.name);if(o.status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0};o.status==="present"&&e.checkExperimentalDialect(this,o.value.dialect)}structDef(){var e;if(!this.validateConnectionName())return V4.ErrorFactory.structDef;const n=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!n)return this.log("Cant't look up schema for sql block"),V4.ErrorFactory.structDef;const r=this.sqlBlock();n.reference(r.name,this.location);const i=n.getEntry(r.name);if(i.status==="error"){const s=i.message.split(/\r?\n/);return this.select.log("Invalid SQL, "+s.join(`
1284
- `)),V4.ErrorFactory.structDef}else if(i.status==="present"){const s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},u=this.document(),a=u==null?void 0:u.currentModelAnnotation();return a&&(o.modelAnnotation=a),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),V4.ErrorFactory.structDef}}Rm.SQLSource=vSe,Object.defineProperty(G4,"__esModule",{value:!0}),G4.SQSource=void 0;const SSe=Ju,_Se=Tm,CSe=Rm;class bSe extends SSe.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof CSe.SQLSource){const e=new _Se.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}}G4.SQSource=bSe;var Y4={};Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.SQExtend=void 0;const TSe=Em,RSe=Ju;class OSe extends RSe.SourceQueryElement{constructor(e,n){super({sqSrc:e,extend:n}),this.sqSrc=e,this.extend=n,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new TSe.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}}Y4.SQExtend=OSe;var K4={},M0={};Object.defineProperty(M0,"__esModule",{value:!0}),M0.isComparison=M0.Comparison=void 0;var cD;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(cD||(M0.Comparison=cD={}));function NSe(t){return Object.values(cD).includes(t)}M0.isComparison=NSe;var Om={},ln={};Object.defineProperty(ln,"__esModule",{value:!0}),ln.FT=void 0;const DSe=Fu;function mx(t,e="scalar",n="constant"){return{dataType:t,expressionType:e,evalSpace:n}}class Lr{static in(e,n){return e?n.find(i=>Lr.eq(i,e))!==void 0:!1}static eq(e,n){return n!==void 0&&e.dataType===n.dataType&&e.expressionType===n.expressionType}static typeIn(e,n){return e?n.find(i=>Lr.typeEq(i,e))!==void 0:!1}static typeEq(e,n,r=!1,i=!0){const s=e.dataType===n.dataType,o=r&&(e.dataType==="null"||n.dataType==="null"),u=i&&(e.dataType==="error"||n.dataType==="error");return s||o||u}static inspect(...e){return e.map(r=>{if(r){let i=r.dataType;return(0,DSe.expressionIsScalar)(r.expressionType)||(i=`${r.expressionType} ${i}`),i}return"undefined"}).join(",")}}ln.FT=Lr,Lr.nullT=mx("null"),Lr.numberT=mx("number"),Lr.stringT=mx("string"),Lr.dateT=mx("date"),Lr.timestampT=mx("timestamp"),Lr.boolT=mx("boolean"),Lr.anyAtomicT=[Lr.numberT,Lr.stringT,Lr.dateT,Lr.timestampT,Lr.boolT],Lr.aggregateBoolT=mx("boolean","aggregate");var f2={},hr={};Object.defineProperty(hr,"__esModule",{value:!0}),hr.errorFor=void 0;function FSe(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}hr.errorFor=FSe;var pt={},x2={};Object.defineProperty(x2,"__esModule",{value:!0}),x2.isEquality=x2.Equality=void 0;var fD;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(fD||(x2.Equality=fD={}));function wSe(t){return Object.values(fD).includes(t)}x2.isEquality=wSe;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.isGranularResult=void 0;function LSe(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}d2.isGranularResult=LSe,Object.defineProperty(pt,"__esModule",{value:!0}),pt.applyBinary=pt.getMorphicValue=pt.ExprDuration=pt.ExpressionDef=void 0;const Nn=ne,h2=hr,pl=hn,yx=ln,X4=On,ISe=M0,$Se=x2,$Q=d2,BSe=Ve;class kSe extends Error{}class BQ extends BSe.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=yx.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.dataType!=="error"&&!yx.FT.in(n,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${yx.FT.inspect(n)}`),!1):!0}apply(e,n,r){return qQ(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Nn.expressionIsAggregate)(e.expressionType)}}pt.ExpressionDef=BQ;class xD extends BQ{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[yx.FT.timestampT,yx.FT.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,Nn.isTimeFieldType)(i.dataType)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!yx.FT.typeEq(s,yx.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,h2.errorFor)("illegal unit expression");let o;if((0,$Q.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){const u=(0,X4.timeOffset)("timestamp",i.value,n,s.value,this.timeframe);return(0,X4.timeResult)({dataType:"timestamp",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u},o)}return(0,Nn.isDateUnit)(this.timeframe)?(0,X4.timeResult)({dataType:"date",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,X4.timeOffset)("date",i.value,n,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,h2.errorFor)("ofsset date error"))}return super.apply(e,n,r)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}}pt.ExprDuration=xD;function kQ(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function PSe(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}pt.getMorphicValue=PSe;function PQ(t,e,n,r){const i=(0,Nn.isTimeFieldType)(e.dataType),s=(0,Nn.isTimeFieldType)(r.dataType);if(i&&s)if(e.dataType!==r.dataType){const o=kQ(e,"timestamp"),u=kQ(r,"timestamp");if(o&&u)return(0,pl.compose)(o,n,u)}else return(0,pl.compose)(e.value,n,r.value);if((i||s)&&e.dataType!=="null"&&r.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${r.dataType}`),["false"]}function MQ(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:t.value,regexp:e.value}]}else if(e.dataType==="string"&&t.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:e.value,regexp:t.value}]}function MSe(t,e,n){const r=e==="!="||e==="!~";if(t.dataType==="null"||n.dataType==="null"){const i=r?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:n.dataType!=="null"?[...n.value,`IS${i} NULL`]:[r?"false":"true"]}}function jSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Nm("boolean",i,s);if(o)return o;if(i.dataType==="unsupported"||s.dataType==="unsupported"){const l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){const f=Dm(e,i,r,s);if(f)return{...f,dataType:"boolean"}}}let a=PQ(e,i,n,s)||(0,pl.compose)(i.value,n,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(n){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")a=(0,pl.compose)(i.value,"LIKE",s.value);else{const l=MQ(i,s);if(l===void 0)throw new kSe("Incompatible types for match('~') operator");a=l}a=(0,pl.nullsafeNot)(a,n);break}case"=":case"!=":{const l=MSe(i,n,s);l?a=l:a=(0,pl.nullsafeNot)(MQ(i,s)||(0,pl.compose)(i.value,"=",s.value),n);break}}return{dataType:"boolean",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a}}function USe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Nm("boolean",i,s);if(o)return o;const u=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),a=Dm(e,i,r,s);if(a)return{...a,dataType:"boolean"};const l=PQ(e,i,n,s)||(0,pl.compose)(i.value,n,s.value);return{dataType:"boolean",expressionType:u,evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function jQ(t,...e){return e.includes(t)}function qSe(t,...e){for(const n of e)if(n.dataType!==t)return!1;return!0}function UQ(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Nm("number",i,s);if(o)return o;const u=Dm(e,i,r,s);if(u)return u;const a=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType);return qSe("number",i,s)?{dataType:"number",expressionType:a,value:(0,pl.compose)(i.value,n,s.value),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)}:(e.log(`Non numeric('${i.dataType},${s.dataType}') value with '${n}'`),(0,h2.errorFor)("numbers required"))}function HSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Dm(e,i,r,s);if(o)return o;const u=(0,Nn.isTimeFieldType)(i.dataType),a=Nm(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.dataType!=="duration")if((0,$Q.isGranularResult)(i))l=new xD(r,i.timeframe);else if(i.dataType==="date")l=new xD(r,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,h2.errorFor)(`time plus ${s.dataType}`);return l.apply(t,n,e)}return UQ(t,e,n,r)}function qQ(t,e,n,r){if((0,$Se.isEquality)(n))return jSe(t,e,n,r);if((0,ISe.isComparison)(n))return USe(t,e,n,r);if(jQ(n,"+","-"))return HSe(t,e,n,r);if(n==="*")return UQ(t,e,n,r);if(jQ(n,"/","%")){const i=e.getExpression(t),s=r.getExpression(t),o=Dm(e,i,r,s);if(o)return e.log("Cannot operate with unsupported type"),o;const u=Nm("number",i,s);if(u)return u;if(i.dataType!=="number")e.log("Numerator must be a number");else if(s.dataType!=="number")r.log("Denominator must be a number");else{const a={type:"dialect",function:n==="/"?"div":"mod",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[a]}}return(0,h2.errorFor)("divide type mismatch")}return e.log(`Cannot use ${n} operator here`),(0,h2.errorFor)("applybinary bad operator")}pt.applyBinary=qQ;function Nm(t,...e){if(e.some(n=>n.dataType==="error"))return{dataType:t,expressionType:(0,Nn.maxOfExpressionTypes)(e.map(n=>n.expressionType)),value:["'cascading error'"],evalSpace:(0,Nn.mergeEvalSpaces)(...e.map(n=>n.evalSpace))}}function Dm(t,e,n,r){const i={dataType:e.dataType,expressionType:(0,Nn.maxExpressionType)(e.expressionType,r.expressionType),value:["'unsupported operation'"],evalSpace:(0,Nn.mergeEvalSpaces)(e.evalSpace,r.evalSpace)};if(e.dataType==="unsupported")return t.log("Unsupported type not allowed in expression"),{...i,dataType:r.dataType};if(r.dataType==="unsupported")return n.log("Unsupported type not allowed in expression"),i}Object.defineProperty(f2,"__esModule",{value:!0}),f2.BinaryBoolean=void 0;const HQ=ne,zSe=hr,QSe=ln,GSe=pt,WSe=hn;class VSe extends GSe.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="abstract boolean binary",this.legalChildTypes=[QSe.FT.boolT]}getExpression(e){const n=this.left.getExpression(e),r=this.right.getExpression(e);if(this.typeCheck(this.left,n)&&this.typeCheck(this.right,r)){const i=(0,HQ.mergeEvalSpaces)(n.evalSpace,r.evalSpace);return{dataType:"boolean",expressionType:(0,HQ.maxExpressionType)(n.expressionType,r.expressionType),evalSpace:i,value:(0,WSe.compose)(n.value,this.op,r.value)}}return(0,zSe.errorFor)("logial required boolean")}}f2.BinaryBoolean=VSe,Object.defineProperty(Om,"__esModule",{value:!0}),Om.ExprCompare=void 0;const Yt=ln,YSe=f2,KSe={"~":[Yt.FT.stringT],"!~":[Yt.FT.stringT],"<":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"<=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"!=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],">=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],">":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT]};class XSe extends YSe.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="a<=>b",this.legalChildTypes=KSe[n]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Om.ExprCompare=XSe;var Fm={},p2={};Object.defineProperty(p2,"__esModule",{value:!0}),p2.ExprTime=void 0;const JSe=ne,ZSe=hn,e4e=pt;class dD extends e4e.ExpressionDef{constructor(e,n,r="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:r,value:typeof n=="string"?[n]:n,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,n){let r=n.value;if(e!==n.dataType){const i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:n.value};(0,JSe.isTimeFieldType)(n.dataType)&&(i.srcType=n.dataType),r=(0,ZSe.compressExpr)([i])}return new dD(e,r,n.expressionType)}}p2.ExprTime=dD;var j0={};Object.defineProperty(j0,"__esModule",{value:!0}),j0.Range=void 0;const zQ=ne,t4e=hr,n4e=pt,r4e=hn;class i4e extends n4e.ExpressionDef{constructor(e,n){super({first:e,last:n}),this.first=e,this.last=n,this.elementType="range"}apply(e,n,r){switch(n){case"=":case"!=":{const i=n==="="?">=":"<",s=n==="="?"and":"or",o=n==="="?"<":">=",u=this.first.apply(e,i,r),a=this.last.apply(e,o,r);return{dataType:"boolean",expressionType:(0,zQ.maxExpressionType)(u.expressionType,a.expressionType),evalSpace:(0,zQ.mergeEvalSpaces)(u.evalSpace,a.evalSpace),value:(0,r4e.compose)(u.value,s,a.value)}}case">":return this.last.apply(e,">=",r);case">=":return this.first.apply(e,">=",r);case"<":return this.first.apply(e,"<",r);case"<=":return this.last.apply(e,"<",r)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,t4e.errorFor)("a range is not a value")}}j0.Range=i4e,Object.defineProperty(Fm,"__esModule",{value:!0}),Fm.ExprGranularTime=void 0;const hD=ne,s4e=hr,QQ=ln,GQ=On,o4e=pt,J4=p2,WQ=j0;class u4e extends o4e.ExpressionDef{constructor(e,n,r){super({expr:e}),this.expr=e,this.units=n,this.truncate=r,this.elementType="granularTime",this.legalChildTypes=[QQ.FT.timestampT,QQ.FT.dateT]}granular(){return!0}getExpression(e){const n=this.units,r=this.expr.getExpression(e);if((0,hD.isTimeFieldType)(r.dataType)){const s={...r,dataType:r.dataType,timeframe:n};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:r.value,valueType:r.dataType},units:n}]),s}r.dataType!=="error"&&this.log(`Cannot do time truncation on type '${r.dataType}'`);const i=r.dataType==="error"?(0,hD.isDateUnit)(n)?"date":"timestamp":r.dataType;return{...r,dataType:i,value:(0,s4e.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const n=this.getExpression(e);if(n.dataType==="timestamp"){const o=J4.ExprTime.fromValue("timestamp",n),u=new J4.ExprTime("timestamp",(0,GQ.timeOffset)("timestamp",n.value,"+",(0,hD.mkExpr)`1`,this.units),n.expressionType);return new WQ.Range(o,u)}const r=new J4.ExprTime("date",n.value,n.expressionType),i=(0,GQ.timeOffset)("date",n.value,"+",["1"],this.units),s=new J4.ExprTime("date",i,n.expressionType);return new WQ.Range(r,s)}}Fm.ExprGranularTime=u4e,Object.defineProperty(K4,"__esModule",{value:!0}),K4.Apply=void 0;const a4e=M0,l4e=Om,c4e=d2,VQ=Fm;class f4e extends l4e.ExprCompare{constructor(e,n){super(e,a4e.Comparison.EqualTo,n),this.left=e,this.right=n,this.elementType="apply"}getExpression(e){let n=this.right;if(!this.right.granular()){const r=this.right.requestExpression(e);r&&(0,c4e.isGranularResult)(r)&&(n=new VQ.ExprGranularTime(this.right,r.timeframe,!1))}return n instanceof VQ.ExprGranularTime?n.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}K4.Apply=f4e;var g2={};Object.defineProperty(g2,"__esModule",{value:!0}),g2.BinaryNumeric=void 0;const x4e=ln,d4e=pt;class h4e extends d4e.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="numeric binary abstract",this.legalChildTypes=[x4e.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}g2.BinaryNumeric=h4e;var Z4={};Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.Boolean=void 0;const p4e=pt,g4e=ln;let m4e=class extends p4e.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...g4e.FT.boolT,value:[this.value]}}};Z4.Boolean=m4e;var U0={},m2={};Object.defineProperty(m2,"__esModule",{value:!0}),m2.ExprIdReference=void 0;const pD=ne,y4e=hr,E4e=Xu,A4e=pt;class v4e extends A4e.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const n=this.fieldReference.getField(e);if(n.found){const r=n.found.typeDesc();if(n.isOutputField)return{...r,evalSpace:r.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};const i=[{type:n.found.refType,path:this.fieldReference.path}],s=(0,pD.expressionIsAggregate)(r.expressionType)?"output":r.evalSpace;return{...r,value:i,evalSpace:s}}return this.log(n.error),(0,y4e.errorFor)(n.error)}apply(e,n,r){const i=this.fieldReference.getField(e).found;if(i instanceof E4e.SpaceParam){const s=i.parameter();if((0,pD.isConditionParameter)(s)){const o=r.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,pD.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,n,r)}}m2.ExprIdReference=v4e,Object.defineProperty(U0,"__esModule",{value:!0}),U0.FunctionOrdering=U0.FunctionOrderBy=void 0;const gD=ne,YQ=Ve,S4e=m2;class _4e extends YQ.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.log("analytic `order_by` must specify an aggregate expression or output field reference"),{e:["error"],dir:this.dir};const n=this.field.getExpression(e);return(0,gD.expressionIsAggregate)(n.expressionType)||((0,gD.expressionIsScalar)(n.expressionType)?(!(this.field instanceof S4e.ExprIdReference)||n.evalSpace==="input")&&this.field.log("analytic `order_by` must be an aggregate or an output field reference"):this.field.log("analytic `order_by` must be scalar or aggregate")),{e:n.value,dir:this.dir}}getAggregateOrderBy(e,n){if(this.field){const r=this.field.getExpression(e);return(0,gD.expressionIsScalar)(r.expressionType)||this.field.log("aggregate `order_by` must be scalar"),n||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:r.value,dir:this.dir}}else return this.dir===void 0?(this.log("field or order direction must be specified"),{e:void 0,dir:"asc"}):{e:void 0,dir:this.dir}}}U0.FunctionOrderBy=_4e;class C4e extends YQ.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(n=>n.getAnalyticOrderBy(e))}getAggregateOrderBy(e,n){return this.list.map(r=>r.getAggregateOrderBy(e,n))}}U0.FunctionOrdering=C4e;var e_={};Object.defineProperty(e_,"__esModule",{value:!0}),e_.ExprAddSub=void 0;const b4e=g2;class T4e extends b4e.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}e_.ExprAddSub=T4e;var gl={},mt={},wm={};Object.defineProperty(wm,"__esModule",{value:!0}),wm.ReferenceField=void 0;const KQ=Yr;class R4e extends KQ.SpaceField{constructor(e,n){super(),this.fieldRef=e,this.inFS=n,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const n=this.fieldRef.getField(e);n.error&&this.fieldRef.log(n.error),this.queryFieldDef={type:"fieldref",path:this.fieldRef.list.map(i=>i.name)};const r=this.referenceTo;if(r instanceof KQ.SpaceField&&r.haveFieldDef){const i=r.haveFieldDef,s=this.fieldRef.note;if(i.annotation||s){const o=s||{};i.annotation&&(o.inherits=i.annotation),this.queryFieldDef.annotation=o}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}}wm.ReferenceField=R4e;var Zn={};Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.typecheckGroupBy=Zn.typecheckAggregate=Zn.typecheckCalculate=Zn.typecheckDeclare=Zn.typecheckMeasure=Zn.typecheckDimension=Zn.typecheckIndex=Zn.typecheckProject=void 0;const Dn=Fu;function O4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckProject=O4e;function N4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n;if(t.dataType==="turtle")n="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in an index operation`)}}Zn.typecheckIndex=N4e;function D4e(t,e){if(!(0,Dn.expressionIsScalar)(t.expressionType))if((0,Dn.expressionIsAggregate)(t.expressionType))e.log("Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,Dn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Zn.typecheckDimension=D4e;function F4e(t,e){if(!(0,Dn.expressionIsAggregate)(t.expressionType))if((0,Dn.expressionIsScalar)(t.expressionType))e.log("Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,Dn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Zn.typecheckMeasure=F4e;function w4e(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,Dn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Zn.typecheckDeclare=w4e;function L4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsAnalytic)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else if((0,Dn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckCalculate=L4e;function I4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsAggregate)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckAggregate=I4e;function $4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckGroupBy=$4e,Object.defineProperty(mt,"__esModule",{value:!0}),mt.FieldReferences=mt.WildcardFieldReference=mt.ViewOrScalarFieldReference=mt.DimensionFieldReference=mt.MeasureFieldReference=mt.DeclareFieldReference=mt.ProjectFieldReference=mt.GroupByFieldReference=mt.AggregateFieldReference=mt.IndexFieldReference=mt.CalculateFieldReference=mt.PartitionByFieldReference=mt.ExpressionFieldReference=mt.AcceptExceptFieldReference=mt.FieldReference=void 0;const B4e=wm,k4e=Ds,XQ=Ve,JQ=Vr,q0=Zn;class ws extends XQ.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=JQ.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.log(`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new B4e.ReferenceField(this,r))}}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const n=e.lookup(this.list);if(n.found){const r=n.found.typeDesc();this.typecheck(r)}return n}}mt.FieldReference=ws;class P4e extends ws{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}mt.AcceptExceptFieldReference=P4e;class M4e extends ws{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}mt.ExpressionFieldReference=M4e;class j4e extends ws{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}mt.PartitionByFieldReference=j4e;class U4e extends ws{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,q0.typecheckCalculate)(e,this)}}mt.CalculateFieldReference=U4e;class mD extends ws{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,q0.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return mD.indexOutputName(this.path)}}mt.IndexFieldReference=mD;class q4e extends ws{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,q0.typecheckAggregate)(e,this)}}mt.AggregateFieldReference=q4e;class H4e extends ws{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,q0.typecheckGroupBy)(e,this)}}mt.GroupByFieldReference=H4e;class z4e extends ws{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,q0.typecheckProject)(e,this)}}mt.ProjectFieldReference=z4e;class Q4e extends ws{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,q0.typecheckDeclare)(e,this)}}mt.DeclareFieldReference=Q4e;class G4e extends ws{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,q0.typecheckMeasure)(e,this)}}mt.MeasureFieldReference=G4e;class W4e extends ws{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,q0.typecheckDimension)(e,this)}}mt.DimensionFieldReference=W4e;class V4e extends ws{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}mt.ViewOrScalarFieldReference=V4e;class Y4e extends XQ.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=JQ.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}mt.WildcardFieldReference=Y4e;class K4e extends k4e.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}mt.FieldReferences=K4e,Object.defineProperty(gl,"__esModule",{value:!0}),gl.ExprAggregateFunction=void 0;const ZQ=ne,X4e=Vt,Lm=hr,J4e=Xr,Z4e=px,e_e=ln,t_e=mt,n_e=pt,r_e=Yr,i_e=m2;class s_e extends n_e.ExpressionDef{constructor(e,n,r){super(),this.func=e,this.legalChildTypes=[e_e.FT.numberT],this.elementType=e,this.explicitSource=r,n&&(this.expr=n,this.has({expr:n}))}returns(e){return"number"}getExpression(e){var n,r;const i=e.isQueryFieldSpace()?e.inputSpace():e;let s=this.expr,o=(n=this.expr)===null||n===void 0?void 0:n.getExpression(i),u=(r=this.source)===null||r===void 0?void 0:r.path,a=[];if(this.source){const c=this.source.getField(i);if(c.found){a=c.relationship;const f=c.found,x=f.typeDesc();if((0,ZQ.isAtomicFieldType)(x.dataType)){s=this.source,o={dataType:x.dataType,expressionType:x.expressionType,value:[x.evalSpace==="output"?{type:"outputField",name:this.source.refString}:{type:"field",path:this.source.path}],evalSpace:x.evalSpace},u=this.source.path;const h=this.getJoinUsage(i);(h.length===1||h.length>1&&h.slice(1).every(m=>o_e(m,h[0])))&&(u=h[0].map(m=>m.name),a=h[0])}else if(!(f instanceof Z4e.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,Lm.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,Lm.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,Lm.errorFor)("agggregate without expression");if((0,ZQ.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,Lm.errorFor)("reagggregate");if(!(o.dataType==="error")){const c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(h=>h.length===0))&&!this.isSymmetricFunction()){const h=ED(a,c),p=AD(this.elementType,h),m=f?p:"Join path is required for this calculation";if(m){const g=u_e(m,c,s,this.elementType);this.log(g,p?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){const c={type:"aggregate",function:this.func,e:o.value};return u&&u.length>0&&(c.structPath=u),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,Lm.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const n=[];if(this.source&&this.source.getField(e).found){const i=[{type:"field",path:this.source.path}];n.push(...yD(e,i))}if(this.expr){const r=this.expr.getExpression(e).value;n.push(...yD(e,r))}return n}}gl.ExprAggregateFunction=s_e;function o_e(t,e){let n=t.length;if(n!==e.length)return!1;for(;n>0;)if(n-=1,t[n].name!==e[n].name)return!1;return!0}function yD(t,e){const n=[],r=(i,s)=>{const o=s[0],u=s.slice(1),a=i.entry(o);if(a===void 0)throw new Error(`Invalid field lookup ${o}`);if(a instanceof J4e.StructSpaceField&&u.length>0){const l=r(a.fieldSpace,u);return{...l,relationship:[{name:o,structRelationship:a.structRelationship},...l.relationship]}}else if(a instanceof r_e.SpaceField){if(u.length!==0)throw new Error(`${o} cannot contain a ${u.join(".")}`);const l=a.fieldDef();if(l)return{fs:i,def:l,relationship:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};return(0,X4e.exprWalk)(e,i=>{if(typeof i!="string"){if(i.type==="field"){const s=r(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){const o=yD(s.fs,s.def.e);n.push(...o.map(u=>[...s.relationship,...u]))}else n.push(s.relationship)}else if(i.type==="source-reference")if(i.path){const s=r(t,i.path);n.push(s.relationship)}else n.push([])}}),n}function ED(t,e){const n=[];for(const r of e){let i=0;for(let a=0;a<t.length&&a<r.length&&t[a].name===r[a].name;a++)i=a+1;const s=t.slice(i),o=r.slice(i),u=[...s.map(a=>({...a,reverse:!0})),...o.map(a=>({...a,reverse:!1}))];n.push(u)}return n}function AD(t,e){for(const n of e)for(const r of n){if(r.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${r.name}\``;if(r.structRelationship.type==="many"&&!r.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${r.name}\``;if(r.structRelationship.type==="nested"&&!r.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${r.name}\``}}function u_e(t,e,n,r){if(e.length===0)return t;let i=e[0];for(const p of e.slice(1))for(let m=0;m<i.length;m++){const g=i[m],y=p[m];if(g.name!==y.name){i=i.slice(0,m);break}}const s=ED(i,e),o=AD(r,s),u=i.slice().reverse().findIndex(p=>p.structRelationship.type==="many"||p.structRelationship.type==="cross"),a=u===-1?0:i.length-u,l=i.slice(0,a),c=ED(l,e),f=AD(r,c),x=i.length>0?i.map(p=>p.name).join("."):"source",h=l.length>0?l.map(p=>p.name).join("."):"source";if(o)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const p=n instanceof t_e.FieldReference?`${n.refString}.${r}()`:n instanceof i_e.ExprIdReference?`${n.fieldReference.refString}.${r}()`:`${x}.${r}(${n.code})`,m=`${h}.${r}(${n.code})`;let g=`${t}; use \`${p}\``;return f===void 0&&h!==x&&(g+=` or \`${m}\` to get a result weighted with respect to \`${h}\``),g}}var t_={};Object.defineProperty(t_,"__esModule",{value:!0}),t_.ExprAlternationTree=void 0;const eG=ne,a_e=hr,l_e=f2,c_e=hn;class f_e extends l_e.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="alternation",this.elementType=`${n}alternation${n}`}apply(e,n,r){const i=this.left.apply(e,n,r),s=this.right.apply(e,n,r);return{dataType:"boolean",expressionType:(0,eG.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,eG.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,c_e.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,a_e.errorFor)("no value from alternation tree")}}t_.ExprAlternationTree=f_e;var y2={};Object.defineProperty(y2,"__esModule",{value:!0}),y2.ExprAsymmetric=void 0;const x_e=gl;class d_e extends x_e.ExprAggregateFunction{constructor(e,n,r,i){super(e,n,i),this.func=e,this.expr=n,this.source=r,this.has({source:r})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}y2.ExprAsymmetric=d_e;var n_={};Object.defineProperty(n_,"__esModule",{value:!0}),n_.ExprAvg=void 0;const h_e=y2;class p_e extends h_e.ExprAsymmetric{constructor(e,n,r){super("avg",e,n,r),this.has({source:n})}}n_.ExprAvg=p_e;var r_={};Object.defineProperty(r_,"__esModule",{value:!0}),r_.ExprCast=void 0;const g_e=On,m_e=pt,y_e=hn;class E_e extends m_e.ExpressionDef{constructor(e,n,r=!1){super({expr:e}),this.expr=e,this.castType=n,this.safe=r,this.elementType="cast"}getExpression(e){var n,r,i;const s=this.expr.getExpression(e);let o="unsupported";if(typeof this.castType=="string")o=this.castType;else{const u=e.dialectObj();u&&(u.validateTypeName(this.castType.raw)?o=(i=(r=(n=e.dialectObj())===null||n===void 0?void 0:n.sqlTypeToMalloyType(this.castType.raw))===null||r===void 0?void 0:r.type)!==null&&i!==void 0?i:"unsupported":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${u.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,y_e.compressExpr)((0,g_e.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}}r_.ExprCast=E_e;var i_={};Object.defineProperty(i_,"__esModule",{value:!0}),i_.ExprCoalesce=void 0;const vD=Fu,tG=ln,A_e=pt;class v_e extends A_e.ExpressionDef{constructor(e,n){super({expr:e,altExpr:n}),this.expr=e,this.altExpr=n,this.elementType="coalesce expression",this.legalChildTypes=tG.FT.anyAtomicT}getExpression(e){const n=this.expr.getExpression(e),r=this.altExpr.getExpression(e);return n.dataType==="null"?r:(tG.FT.typeEq(n,r)||this.log(`Mismatched types for coalesce (${n.dataType}, ${r.dataType})`),{...r,dataType:n.dataType==="error"?r.dataType:n.dataType,expressionType:(0,vD.maxExpressionType)(n.expressionType,r.expressionType),value:(0,vD.mkExpr)`COALESCE(${n.value},${r.value})`,evalSpace:(0,vD.mergeEvalSpaces)(n.evalSpace,r.evalSpace)})}}i_.ExprCoalesce=v_e;var s_={};Object.defineProperty(s_,"__esModule",{value:!0}),s_.ExprCount=void 0;const S_e=gl;class __e extends S_e.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}getExpression(e){const n={type:"aggregate",function:"count",e:[]};return this.source&&(n.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[n],evalSpace:"output"}}}s_.ExprCount=__e;var o_={};Object.defineProperty(o_,"__esModule",{value:!0}),o_.ExprCountDistinct=void 0;const u_=ln,C_e=gl;class b_e extends C_e.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[u_.FT.numberT,u_.FT.stringT,u_.FT.dateT,u_.FT.timestampT]}}o_.ExprCountDistinct=b_e;var a_={},H0={};Object.defineProperty(H0,"__esModule",{value:!0}),H0.Limit=void 0;const T_e=Ve,R_e=Rn;class O_e extends T_e.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=R_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}H0.Limit=O_e;var E2={};Object.defineProperty(E2,"__esModule",{value:!0}),E2.PartitionBy=void 0;const N_e=Ve;class D_e extends N_e.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}E2.PartitionBy=D_e;var Im={};Object.defineProperty(Im,"__esModule",{value:!0}),Im.ExprFunc=void 0;const ao=ne,ml=hr,F_e=px,w_e=pt,nG=hn;class L_e extends w_e.ExpressionDef{constructor(e,n,r,i,s){super({args:n}),this.name=e,this.args=n,this.isRaw=r,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}getPropsExpression(e,n){var r,i,s,o,u;const a=this.args.map(O=>O.getExpression(e));if(this.isRaw){let O="scalar",L;const M=[`${this.name}(`];for(const W of a)O=(0,ao.maxExpressionType)(O,W.expressionType),L?M.push(","):L=W.dataType,M.push(...W.value);return M.push(")"),{dataType:(i=(r=this.rawType)!==null&&r!==void 0?r:L)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,nG.compressExpr)(M),evalSpace:(0,ao.mergeEvalSpaces)(...a.map(W=>W.evalSpace))}}const l=(s=this.modelEntry(this.name.toLowerCase()))===null||s===void 0?void 0:s.entry;if(l===void 0)return this.log(`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),(0,ml.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,ml.errorFor)("called non function");l.name!==this.name&&this.log(`Case insensitivity for function names is deprecated, use '${l.name}' instead`,"warn");let c,f=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const O=this.source.getField(e).found;if(O){const L=O.typeDesc();if((0,ao.isAtomicFieldType)(L.dataType))c={dataType:L.dataType,expressionType:L.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:L.evalSpace},f=this.source.path.slice(0,-1);else if(!(O instanceof F_e.StructSpaceFieldBase)){const M=`Aggregate source cannot be a ${L.dataType}`;return this.log(M),(0,ml.errorFor)(M)}}else{const L=`Reference to undefined value ${this.source.refString}`;return this.log(L),(0,ml.errorFor)(L)}}const x=[...c?[c]:[],...a],h=I_e(l,x);if(h===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,ml.errorFor)("no matching overload");const{overload:p,expressionTypeErrors:m,evalSpaceErrors:g,nullabilityErrors:y}=h;for(const O of m){const L=O.argIndex-(c?1:0),M=(0,ao.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[L].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${M}, but received ${O.actualExpressionType}`)}for(const O of g){const L=O.argIndex-(c?1:0),M=O.maxEvalSpace==="literal"?"literal":O.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[L].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${M}, but received ${O.actualEvalSpace}`)}for(const O of y){const L=O.argIndex-(c?1:0);this.args[L].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must not be a literal null`)}const E=p.returnType,A=(0,ao.maxOfExpressionTypes)([E.expressionType,...x.map(O=>O.expressionType)]);if(!(0,ao.expressionIsAggregate)(p.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(O=>O.dataType).join(", ")}) with source`),(0,ml.errorFor)("cannot call with source");const v={type:"function_call",overload:p,name:this.name,args:x.map(O=>O.value),expressionType:A,structPath:f};let S=[v];const C=(u=e.dialectObj())===null||u===void 0?void 0:u.name,_=C?p.dialect[C]:void 0;if(_===void 0)this.log(`Function ${this.name} is not defined in dialect ${C}`);else{if(n!=null&&n.orderBys&&n.orderBys.length>0){const O=(0,ao.expressionIsAnalytic)(p.returnType.expressionType);if(O||this.inExperiment("aggregate_order_by",!0)||n.orderBys[0].log("Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),_.supportsOrderBy||O){const L=_.supportsOrderBy!=="only_default",M=n.orderBys.flatMap(q=>O?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,L));v.orderBy=M}else n.orderBys[0].log(`Function \`${this.name}\` does not support \`order_by\``)}(n==null?void 0:n.limit)!==void 0&&(_.supportsLimit?v.limit=n.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(n!=null&&n.partitionBys&&n.partitionBys.length>0){const O=[];for(const L of n.partitionBys)for(const M of L.partitionFields){const q=M.getField(e);q.found===void 0?M.log(`${M.refString} is not defined`):(0,ao.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,ao.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?M.log("Partition expression must be scalar or aggregate"):O.push(M.nameString)}v.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,ml.errorFor)(`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);const O=x[0].value;if(O.length!==1||typeof O[0]=="string"||O[0].type!=="dialect"||O[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{const L=O[0].literal,M=$_e(L),q=M.filter(W=>W.type==="interpolation"&&W.name.includes(".")).map(W=>W.type==="interpolation"?`\${${W.name}}`:`\${${W.value}}`);if(q.length>0){const W=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${q.join(", ")}]`;return this.log(W),(0,ml.errorFor)(`${W}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}S=[{type:"sql-string",e:M.map(W=>W.type==="string"?W.value:W.name==="TABLE"?{type:"source-reference"}:{type:"field",path:[W.name]})}]}}if(E.dataType==="any")return this.log(`Invalid return type ${E.dataType} for function '${this.name}'`),(0,ml.errorFor)("invalid return type");const b=(0,ao.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),R=b==="constant"?"constant":(0,ao.expressionIsScalar)(A)?b:"output";return{dataType:E.dataType,expressionType:A,value:(0,nG.compressExpr)(S),evalSpace:R}}}Im.ExprFunc=L_e;function I_e(t,e){for(const n of t.overloads){let r=0,i=!0,s=!1;const o=[],u=[],a=[];for(let l=0;l<e.length;l++){const c=e[l],f=n.params[r];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(h=>{const p=h.dataType===c.dataType||h.dataType==="any"||c.dataType==="null"||c.dataType==="error";return h.expressionType&&((0,ao.isExpressionTypeLEQ)(c.expressionType,h.expressionType)||o.push({argIndex:l,maxExpressionType:h.expressionType,actualExpressionType:c.expressionType,param:f})),(h.evalSpace==="literal"&&c.evalSpace!=="literal"||h.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||h.evalSpace==="output"&&c.evalSpace==="input")&&u.push({argIndex:l,param:f,maxEvalSpace:h.evalSpace,actualEvalSpace:c.evalSpace}),h.evalSpace==="literal"&&c.dataType==="null"&&a.push({argIndex:l,param:f}),p})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):r++}if(!(!s&&(r!==e.length||r!==n.params.length))&&i)return{overload:n,expressionTypeErrors:o,evalSpaceErrors:u,nullabilityErrors:a}}}function $_e(t){const e=[];let n=t;for(;n.length;){const r=n.indexOf("${");if(r===-1){e.push({type:"string",value:n});break}else{const i=n.slice(r).indexOf("}");if(i===-1){e.push({type:"string",value:n});break}r>0&&e.push({type:"string",value:n.slice(0,r)}),e.push({type:"interpolation",name:n.slice(r+2,i+r)}),n=n.slice(i+r+1)}}return e}Object.defineProperty(a_,"__esModule",{value:!0}),a_.ExprProps=void 0;const B_e=ne,k_e=hr,P_e=ln,M_e=U0,j_e=H0,U_e=E2,q_e=pt,H_e=Im;class z_e extends q_e.ExpressionDef{constructor(e,n){super({expr:e,statements:n}),this.expr=e,this.statements=n,this.elementType="expression with props",this.legalChildTypes=P_e.FT.anyAtomicT}getFilteredExpression(e,n,r){if(r.length>0){if(!this.expr.supportsWhere(n))return this.expr.log("Filtered expression requires an aggregate computation"),n;const i=[];for(const s of r){const o=s.getFilterList(e);if(o.find(u=>(0,B_e.expressionIsCalculation)(u.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),n;i.push(...o)}return this.typeCheck(this.expr,{...n,expressionType:"scalar"})?{...n,value:[{type:"filterExpression",e:n.value,filterList:i}]}:(this.expr.log(`Cannot filter '${n.dataType}' data`),(0,k_e.errorFor)("cannot filter type"))}return n}getExpression(e){const n=[];let r;const i=[],s=[];for(const u of this.statements)u instanceof U_e.PartitionBy?this.expr.canSupportPartitionBy()?n.push(u):u.log("`partition_by` is not supported for this kind of expression"):u instanceof j_e.Limit?r?u.log("limit already specified"):this.expr.canSupportLimit()?r=u:u.log("`limit` is not supported for this kind of expression"):u instanceof M_e.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(u):u.log("`order_by` is not supported for this kind of expression"):s.push(u);const o=this.expr instanceof H_e.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:n,limit:r,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}}a_.ExprProps=z_e;var l_={};Object.defineProperty(l_,"__esModule",{value:!0}),l_.ExprLogicalOp=void 0;const Q_e=f2,rG=ln;class G_e extends Q_e.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[rG.FT.boolT,rG.FT.aggregateBoolT]}}l_.ExprLogicalOp=G_e;var c_={};Object.defineProperty(c_,"__esModule",{value:!0}),c_.ExprMax=void 0;const f_=ln,W_e=gl;class V_e extends W_e.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[f_.FT.numberT,f_.FT.stringT,f_.FT.dateT,f_.FT.timestampT]}returns(e){return e.dataType}}c_.ExprMax=V_e;var x_={};Object.defineProperty(x_,"__esModule",{value:!0}),x_.ExprMin=void 0;const d_=ln,Y_e=gl;class K_e extends Y_e.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[d_.FT.numberT,d_.FT.stringT,d_.FT.dateT,d_.FT.timestampT]}returns(e){return e.dataType}}x_.ExprMin=K_e;var h_={};Object.defineProperty(h_,"__esModule",{value:!0}),h_.ExprMinus=void 0;const X_e=hr,iG=ln,J_e=pt;class Z_e extends J_e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[iG.FT.numberT]}getExpression(e){const n=this.expr.getExpression(e);return iG.FT.typeIn(n,this.legalChildTypes)?n.value.length>1?{...n,dataType:"number",value:["-(",...n.value,")"]}:{...n,dataType:"number",value:["-",...n.value]}:(0,X_e.errorFor)("negate requires number")}}h_.ExprMinus=Z_e;var p_={};Object.defineProperty(p_,"__esModule",{value:!0}),p_.ExprMulDiv=void 0;const e5e=g2;class t5e extends e5e.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}p_.ExprMulDiv=t5e;var g_={},$m={};Object.defineProperty($m,"__esModule",{value:!0}),$m.Unary=void 0;const n5e=pt;class r5e extends n5e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}$m.Unary=r5e,Object.defineProperty(g_,"__esModule",{value:!0}),g_.ExprNot=void 0;const sG=ln,i5e=$m,s5e=hn;class o5e extends i5e.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[sG.FT.boolT,sG.FT.nullT]}getExpression(e){const n=this.expr.getExpression(e),r=this.typeCheck(this.expr,n);return{...n,dataType:"boolean",value:r?(0,s5e.nullsafeNot)(n.value):["false"]}}}g_.ExprNot=o5e;var m_={};Object.defineProperty(m_,"__esModule",{value:!0}),m_.ExprNow=void 0;const u5e=pt;class a5e extends u5e.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}}m_.ExprNow=a5e;var y_={};Object.defineProperty(y_,"__esModule",{value:!0}),y_.ExprNULL=void 0;const l5e=pt;class c5e extends l5e.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}}y_.ExprNULL=c5e;var E_={};Object.defineProperty(E_,"__esModule",{value:!0}),E_.ExprNumber=void 0;const f5e=ln,x5e=pt;class d5e extends x5e.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...f5e.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}}E_.ExprNumber=d5e;var A_={};Object.defineProperty(A_,"__esModule",{value:!0}),A_.ExprParens=void 0;const h5e=pt;class p5e extends h5e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const n=this.expr.getExpression(e);return{...n,value:["(",...n.value,")"]}}}A_.ExprParens=p5e;var v_={};Object.defineProperty(v_,"__esModule",{value:!0}),v_.ExprRegEx=void 0;const g5e=pt;class m5e extends g5e.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:[{type:"dialect",function:"regexpLiteral",literal:this.regex}],evalSpace:"literal"}}}v_.ExprRegEx=m5e;var S_={};Object.defineProperty(S_,"__esModule",{value:!0}),S_.ExprString=void 0;const y5e=pt,E5e=ln;class A5e extends y5e.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...E5e.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}}S_.ExprString=A5e;var __={};Object.defineProperty(__,"__esModule",{value:!0}),__.ExprSum=void 0;const v5e=y2;class S5e extends v5e.ExprAsymmetric{constructor(e,n,r){super("sum",e,n,r),this.has({source:n})}}__.ExprSum=S5e;var C_={};Object.defineProperty(C_,"__esModule",{value:!0}),C_.ExprTimeExtract=void 0;const Ex=ne,z0=hr,SD=pt,_5e=j0;class Bm extends SD.ExpressionDef{static extractor(e){const n=Bm.pluralMap[e];if(n)return n;if((0,Ex.isExtractUnit)(e))return e}constructor(e,n){super({args:n}),this.extractText=e,this.args=n,this.elementType="timeExtract"}getExpression(e){const n=Bm.extractor(this.extractText);if(n){if(this.args.length!==1)return this.log(`Extraction function ${n} requires one argument`),(0,z0.errorFor)("{this.name} arg count");const r=this.args[0];if(r instanceof _5e.Range){let i=r.first.getExpression(e),s=r.last.getExpression(e);const o=(0,Ex.maxExpressionType)(i.expressionType,s.expressionType),u=(0,Ex.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:u,value:(0,z0.errorFor)("extract from error").value};if(!(0,Ex.isTimeFieldType)(i.dataType))return r.first.log(`Can't extract ${n} from '${i.dataType}'`),(0,z0.errorFor)(`${n} bad type ${i.dataType}`);if(!(0,Ex.isTimeFieldType)(s.dataType))return r.last.log(`Cannot extract ${n} from '${s.dataType}'`),(0,z0.errorFor)(`${n} bad type ${s.dataType}`);let a=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(a="timestamp",i.dataType==="date"){const c=(0,SD.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{const c=(0,SD.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return r.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,z0.errorFor)(`${n} range mismatch`)}return["week","month","quarter","year"].includes(n)?(this.log(`Cannot measure interval using '${n}'`),(0,z0.errorFor)(`${n} civil extraction`)):(0,Ex.isTimestampUnit)(n)?{dataType:"number",expressionType:o,evalSpace:u,value:[{type:"dialect",function:"timeDiff",units:n,left:{valueType:a,value:i.value},right:{valueType:a,value:s.value}}]}:(this.log(`Cannot extract ${n} from a range`),(0,z0.errorFor)(`${n} bad extraction`))}else{const i=r.getExpression(e);return(0,Ex.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:n}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,z0.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}C_.ExprTimeExtract=Bm,Bm.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var b_={},Wo={},Ax={};Object.defineProperty(Ax,"__esModule",{value:!0}),Ax.FieldName=void 0;const C5e=Ve;class b5e extends C5e.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}Ax.FieldName=b5e;var T_={};Object.defineProperty(T_,"__esModule",{value:!0}),T_.QueryInputSpace=void 0;const T5e=rs,R5e=Sm,O5e=i2;class N5e extends O5e.RefinedSpace{constructor(e,n){const r=new R5e.SpaceSeed(e);super(r.structDef),this.queryOutput=n,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof T5e.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}}T_.QueryInputSpace=N5e;var D5e=N&&N.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),F5e=N&&N.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),w5e=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&D5e(e,t,n);return F5e(e,t),e};Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.ReduceFieldSpace=Wo.QuerySpace=Wo.QueryOperationSpace=void 0;const R_=w5e(ne),_D=I0,L5e=Ax,I5e=Yr,$5e=mt,B5e=i2,k5e=vm,P5e=Xr,M5e=T_;class oG extends B5e.RefinedSpace{constructor(e,n,r,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=r,this.astEl=i,this.expandedWild={},this.exprSpace=new M5e.QueryInputSpace(e,this),n&&this.addRefineFromFields(n)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof P5e.StructSpaceField)r=l.fieldSpace;else{u.log(`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.log(`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries())if(!e.except.has(u))if(this.entry(u)){const l=(n=this.expandedWild[u])===null||n===void 0?void 0:n.join(".");e.log(`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{const l=a.typeDesc();R_.isAtomicFieldType(l.dataType)&&R_.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:u,entry:a}),this.expandedWild[u]=i.concat(u))}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}Wo.QueryOperationSpace=oG;class uG extends oG{addRefineFromFields(e){var n;if(R_.isQuerySegment(e))for(const r of e.queryFields)if(r.type==="fieldref"){const i=this.exprSpace.lookup(r.path.map(s=>new L5e.FieldName(s)));i.found&&this.setEntry(r.path[r.path.length-1],i.found)}else r.type!=="turtle"&&this.setEntry((n=r.as)!==null&&n!==void 0?n:r.name,new k5e.ColumnSpaceField(r))}pushFields(...e){for(const n of e)n instanceof $5e.WildcardFieldReference?this.addWild(n):super.pushFields(n)}canContain(e){return!0}queryFieldDefs(){const e=[];for(const[n,r]of this.entries())if(r instanceof I5e.SpaceField){const i=this.expandedWild[n];if(i){e.push({type:"fieldref",path:i});continue}const s=r.getQueryFieldDef(this.exprSpace);if(s){const o=r.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!U5e(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){const n=this.getPipeSegment(e);if(R_.isQuerySegment(n))return n;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.log("internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};if(e!=null&&e.extendSource)for(const r of e.extendSource)this.exprSpace.addFieldDef(r);const n={type:this.segmentType,queryFields:this.queryFieldDefs()};if(n.queryFields=(0,_D.mergeFields)(e==null?void 0:e.queryFields,n.queryFields),e!=null&&e.extendSource&&(n.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const r=[],i=this.exprSpace.structDef();for(const s of this.exprSpace.extendList){const o=i.fields.find(u=>(0,_D.nameFromDef)(u)===s);o&&r.push(o)}n.extendSource=(0,_D.mergeFields)(n.extendSource,r)}return this.newTimezone&&(n.queryTimezone=this.newTimezone),this.isComplete(),n}lookup(e){const n=super.lookup(e);return n.found?{...n,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Wo.QuerySpace=uG;class j5e extends uG{constructor(){super(...arguments),this.segmentType="reduce"}}Wo.ReduceFieldSpace=j5e;function U5e(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}Object.defineProperty(b_,"__esModule",{value:!0}),b_.ExprUngroup=void 0;const aG=ne,CD=hr,q5e=Wo,H5e=ln,z5e=pt;class Q5e extends z5e.ExpressionDef{constructor(e,n,r){super({expr:n,fields:r}),this.control=e,this.expr=n,this.fields=r,this.legalChildTypes=H5e.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){const n=this.expr.getExpression(e);if(!(0,aG.expressionIsAggregate)(n.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,CD.errorFor)("ungrouped scalar");if((0,aG.expressionIsUngroupedAggregate)(n.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,CD.errorFor)("doubly-ungrouped aggregate");const r={type:this.control,e:n.value};if(this.typeCheck(this.expr,{...n,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const i=[],s=this.control==="exclude";for(const o of this.fields){let u=e.outputSpace(),a=!0;for(;u;){const l=u.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),a=!1;else if(u instanceof q5e.QuerySpace){u=u.nestParent;continue}break}if(a){const l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}r.fields=i}return{dataType:this.returns(n),expressionType:"ungrouped_aggregate",value:[r],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,CD.errorFor)("ungrouped type check")}}b_.ExprUngroup=Q5e;var O_={};Object.defineProperty(O_,"__esModule",{value:!0}),O_.ForRange=void 0;const lG=Fu,bD=hr,cG=ln,N_=On,G5e=pt,D_=p2,fG=j0;class W5e extends G5e.ExpressionDef{constructor(e,n,r){super({from:e,duration:n,timeframe:r}),this.from=e,this.duration=n,this.timeframe=r,this.elementType="forRange",this.legalChildTypes=[cG.FT.timestampT,cG.FT.dateT]}apply(e,n,r){const i=this.from.getExpression(e),s=r.getExpression(e);if(!this.typeCheck(r,s))return(0,bD.errorFor)("no time for range");const o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.log(`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,lG.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,lG.maxExpressionType)(i.expressionType,s.expressionType),value:(0,bD.errorFor)("for not number").value};const u=this.timeframe.text;let a=(0,N_.resolution)(u);if(i.dataType==="timestamp"&&(a="timestamp"),s.dataType==="date"&&a==="date"){const p=this.from,m=(0,N_.timeOffset)("date",i.value,"+",o.value,u),g=new D_.ExprTime("date",m);return new fG.Range(p,g).apply(e,n,r)}const l=D_.ExprTime.fromValue("timestamp",s);let c=this.from,f=i.value;if(i.dataType==="date"){const p=i.morphic&&i.morphic.timestamp;p?f=p:f=(0,N_.castDateToTimestamp)(f),c=new D_.ExprTime("timestamp",f,i.expressionType)}const x=(0,N_.timeOffset)("timestamp",f,"+",o.value,u),h=new D_.ExprTime("timestamp",x,i.expressionType);return new fG.Range(c,h).apply(e,n,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,bD.errorFor)("range has no value")}}O_.ForRange=W5e;var pr={};class vx extends Error{}class V5e extends vx{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Y5e extends vx{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class K5e extends vx{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class km extends vx{}class xG extends vx{constructor(e){super(`Invalid unit ${e}`)}}class lo extends vx{}class Q0 extends vx{constructor(){super("Zone is an abstract class")}}const ke="numeric",Vo="short",Ls="long",TD={year:ke,month:ke,day:ke},dG={year:ke,month:Vo,day:ke},X5e={year:ke,month:Vo,day:ke,weekday:Vo},hG={year:ke,month:Ls,day:ke},pG={year:ke,month:Ls,day:ke,weekday:Ls},gG={hour:ke,minute:ke},mG={hour:ke,minute:ke,second:ke},yG={hour:ke,minute:ke,second:ke,timeZoneName:Vo},EG={hour:ke,minute:ke,second:ke,timeZoneName:Ls},AG={hour:ke,minute:ke,hourCycle:"h23"},vG={hour:ke,minute:ke,second:ke,hourCycle:"h23"},SG={hour:ke,minute:ke,second:ke,hourCycle:"h23",timeZoneName:Vo},_G={hour:ke,minute:ke,second:ke,hourCycle:"h23",timeZoneName:Ls},CG={year:ke,month:ke,day:ke,hour:ke,minute:ke},bG={year:ke,month:ke,day:ke,hour:ke,minute:ke,second:ke},TG={year:ke,month:Vo,day:ke,hour:ke,minute:ke},RG={year:ke,month:Vo,day:ke,hour:ke,minute:ke,second:ke},J5e={year:ke,month:Vo,day:ke,weekday:Vo,hour:ke,minute:ke},OG={year:ke,month:Ls,day:ke,hour:ke,minute:ke,timeZoneName:Vo},NG={year:ke,month:Ls,day:ke,hour:ke,minute:ke,second:ke,timeZoneName:Vo},DG={year:ke,month:Ls,day:ke,weekday:Ls,hour:ke,minute:ke,timeZoneName:Ls},FG={year:ke,month:Ls,day:ke,weekday:Ls,hour:ke,minute:ke,second:ke,timeZoneName:Ls};function At(t){return typeof t>"u"}function Sx(t){return typeof t=="number"}function F_(t){return typeof t=="number"&&t%1===0}function Z5e(t){return typeof t=="string"}function eCe(t){return Object.prototype.toString.call(t)==="[object Date]"}function wG(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function tCe(t){return Array.isArray(t)?t:[t]}function LG(t,e,n){if(t.length!==0)return t.reduce((r,i)=>{const s=[e(i),i];return r&&n(r[0],s[0])===r[0]?r:s},null)[1]}function nCe(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function A2(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function yl(t,e,n){return F_(t)&&t>=e&&t<=n}function rCe(t,e){return t-e*Math.floor(t/e)}function Hn(t,e=2){const n=t<0;let r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function G0(t){if(!(At(t)||t===null||t===""))return parseInt(t,10)}function _x(t){if(!(At(t)||t===null||t===""))return parseFloat(t)}function RD(t){if(!(At(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function OD(t,e,n=!1){const r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function Pm(t){return t%4===0&&(t%100!==0||t%400===0)}function Mm(t){return Pm(t)?366:365}function w_(t,e){const n=rCe(e-1,12)+1,r=t+(e-n)/12;return n===2?Pm(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function ND(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(e.getUTCFullYear()-1900)),+e}function L_(t){const e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,n=t-1,r=(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400))%7;return e===4||r===3?53:52}function DD(t){return t>99?t:t>60?1900+t:2e3+t}function IG(t,e,n,r=null){const i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(s.timeZone=r);const o={timeZoneName:e,...s},u=new Intl.DateTimeFormat(n,o).formatToParts(i).find(a=>a.type.toLowerCase()==="timezonename");return u?u.value:null}function I_(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const r=parseInt(e,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function $G(t){const e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new lo(`Invalid unit value ${t}`);return e}function $_(t,e){const n={};for(const r in t)if(A2(t,r)){const i=t[r];if(i==null)continue;n[e(r)]=$G(i)}return n}function jm(t,e){const n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Hn(n,2)}:${Hn(r,2)}`;case"narrow":return`${i}${n}${r>0?`:${r}`:""}`;case"techie":return`${i}${Hn(n,2)}${Hn(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function B_(t){return nCe(t,["hour","minute","second","millisecond"])}const BG=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,iCe=["January","February","March","April","May","June","July","August","September","October","November","December"],kG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],sCe=["J","F","M","A","M","J","J","A","S","O","N","D"];function PG(t){switch(t){case"narrow":return[...sCe];case"short":return[...kG];case"long":return[...iCe];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const MG=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],jG=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],oCe=["M","T","W","T","F","S","S"];function UG(t){switch(t){case"narrow":return[...oCe];case"short":return[...jG];case"long":return[...MG];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const qG=["AM","PM"],uCe=["Before Christ","Anno Domini"],aCe=["BC","AD"],lCe=["B","A"];function HG(t){switch(t){case"narrow":return[...lCe];case"short":return[...aCe];case"long":return[...uCe];default:return null}}function cCe(t){return qG[t.hour<12?0:1]}function fCe(t,e){return UG(e)[t.weekday-1]}function xCe(t,e){return PG(e)[t.month-1]}function dCe(t,e){return HG(e)[t.year<0?0:1]}function hCe(t,e,n="always",r=!1){const i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},s=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&s){const f=t==="days";switch(e){case 1:return f?"tomorrow":`next ${i[t][0]}`;case-1:return f?"yesterday":`last ${i[t][0]}`;case 0:return f?"today":`this ${i[t][0]}`}}const o=Object.is(e,-0)||e<0,u=Math.abs(e),a=u===1,l=i[t],c=r?a?l[1]:l[2]||l[1]:a?i[t][0]:t;return o?`${u} ${c} ago`:`in ${u} ${c}`}function zG(t,e){let n="";for(const r of t)r.literal?n+=r.val:n+=e(r.val);return n}const pCe={D:TD,DD:dG,DDD:hG,DDDD:pG,t:gG,tt:mG,ttt:yG,tttt:EG,T:AG,TT:vG,TTT:SG,TTTT:_G,f:CG,ff:TG,fff:OG,ffff:DG,F:bG,FF:RG,FFF:NG,FFFF:FG};class is{static create(e,n={}){return new is(e,n)}static parseFormat(e){let n=null,r="",i=!1;const s=[];for(let o=0;o<e.length;o++){const u=e.charAt(o);u==="'"?(r.length>0&&s.push({literal:i,val:r}),n=null,r="",i=!i):i||u===n?r+=u:(r.length>0&&s.push({literal:!1,val:r}),r=u,n=u)}return r.length>0&&s.push({literal:i,val:r}),s}static macroTokenToFormatOpts(e){return pCe[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTime(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTimeParts(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).formatToParts()}resolvedOptions(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Hn(e,n);const r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const r=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(h,p)=>this.loc.extract(e,h,p),o=h=>e.isOffsetFixed&&e.offset===0&&h.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,h.format):"",u=()=>r?cCe(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),a=(h,p)=>r?xCe(e,h):s(p?{month:h}:{month:h,day:"numeric"},"month"),l=(h,p)=>r?fCe(e,h):s(p?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),c=h=>{const p=is.macroTokenToFormatOpts(h);return p?this.formatWithSystemDefault(e,p):h},f=h=>r?dCe(e,h):s({era:h},"era"),x=h=>{switch(h){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return u();case"d":return i?s({day:"numeric"},"day"):this.num(e.day);case"dd":return i?s({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?s({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?s({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return a("short",!0);case"LLLL":return a("long",!0);case"LLLLL":return a("narrow",!0);case"M":return i?s({month:"numeric"},"month"):this.num(e.month);case"MM":return i?s({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return a("short",!1);case"MMMM":return a("long",!1);case"MMMMM":return a("narrow",!1);case"y":return i?s({year:"numeric"},"year"):this.num(e.year);case"yy":return i?s({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?s({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?s({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(h)}};return zG(is.parseFormat(n),x)}formatDurationFromString(e,n){const r=a=>{switch(a[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=a=>l=>{const c=r(l);return c?this.num(a.get(c),l.length):l},s=is.parseFormat(n),o=s.reduce((a,{literal:l,val:c})=>l?a:a.concat(c),[]),u=e.shiftTo(...o.map(r).filter(a=>a));return zG(s,i(u))}}class Yo{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}let v2=class{get type(){throw new Q0}get name(){throw new Q0}get ianaName(){return this.name}get isUniversal(){throw new Q0}offsetName(e,n){throw new Q0}formatOffset(e,n){throw new Q0}offset(e){throw new Q0}equals(e){throw new Q0}get isValid(){throw new Q0}},FD=null;class k_ extends v2{static get instance(){return FD===null&&(FD=new k_),FD}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return IG(e,n,r)}formatOffset(e,n){return jm(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}let P_={};function gCe(t){return P_[t]||(P_[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),P_[t]}const mCe={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function yCe(t,e){const n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,i,s,o,u,a,l,c]=r;return[o,i,s,u,a,l,c]}function ECe(t,e){const n=t.formatToParts(e),r=[];for(let i=0;i<n.length;i++){const{type:s,value:o}=n[i],u=mCe[s];s==="era"?r[u]=o:At(u)||(r[u]=parseInt(o,10))}return r}let M_={};class Zu extends v2{static create(e){return M_[e]||(M_[e]=new Zu(e)),M_[e]}static resetCache(){M_={},P_={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=Zu.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return IG(e,n,r,this.name)}formatOffset(e,n){return jm(this.offset(e),n)}offset(e){const n=new Date(e);if(isNaN(n))return NaN;const r=gCe(this.name);let[i,s,o,u,a,l,c]=r.formatToParts?ECe(r,n):yCe(r,n);u==="BC"&&(i=-Math.abs(i)+1);const x=ND({year:i,month:s,day:o,hour:a===24?0:a,minute:l,second:c,millisecond:0});let h=+n;const p=h%1e3;return h-=p>=0?p:1e3+p,(x-h)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let wD=null;class Jr extends v2{static get utcInstance(){return wD===null&&(wD=new Jr(0)),wD}static instance(e){return e===0?Jr.utcInstance:new Jr(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Jr(I_(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${jm(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${jm(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return jm(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class QG extends v2{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function W0(t,e){if(At(t)||t===null)return e;if(t instanceof v2)return t;if(Z5e(t)){const n=t.toLowerCase();return n==="local"||n==="system"?e:n==="utc"||n==="gmt"?Jr.utcInstance:Jr.parseSpecifier(n)||Zu.create(t)}else return Sx(t)?Jr.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new QG(t)}let GG=()=>Date.now(),WG="system",VG=null,YG=null,KG=null,XG;class zn{static get now(){return GG}static set now(e){GG=e}static set defaultZone(e){WG=e}static get defaultZone(){return W0(WG,k_.instance)}static get defaultLocale(){return VG}static set defaultLocale(e){VG=e}static get defaultNumberingSystem(){return YG}static set defaultNumberingSystem(e){YG=e}static get defaultOutputCalendar(){return KG}static set defaultOutputCalendar(e){KG=e}static get throwOnInvalid(){return XG}static set throwOnInvalid(e){XG=e}static resetCaches(){pn.resetCache(),Zu.resetCache()}}let JG={};function ACe(t,e={}){const n=JSON.stringify([t,e]);let r=JG[n];return r||(r=new Intl.ListFormat(t,e),JG[n]=r),r}let LD={};function ID(t,e={}){const n=JSON.stringify([t,e]);let r=LD[n];return r||(r=new Intl.DateTimeFormat(t,e),LD[n]=r),r}let $D={};function vCe(t,e={}){const n=JSON.stringify([t,e]);let r=$D[n];return r||(r=new Intl.NumberFormat(t,e),$D[n]=r),r}let BD={};function SCe(t,e={}){const{base:n,...r}=e,i=JSON.stringify([t,r]);let s=BD[i];return s||(s=new Intl.RelativeTimeFormat(t,e),BD[i]=s),s}let Um=null;function _Ce(){return Um||(Um=new Intl.DateTimeFormat().resolvedOptions().locale,Um)}function CCe(t){const e=t.indexOf("-u-");if(e===-1)return[t];{let n;const r=t.substring(0,e);try{n=ID(t).resolvedOptions()}catch{n=ID(r).resolvedOptions()}const{numberingSystem:i,calendar:s}=n;return[r,i,s]}}function bCe(t,e,n){return(n||e)&&(t+="-u",n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function TCe(t){const e=[];for(let n=1;n<=12;n++){const r=ot.utc(2016,n,1);e.push(t(r))}return e}function RCe(t){const e=[];for(let n=1;n<=7;n++){const r=ot.utc(2016,11,13+n);e.push(t(r))}return e}function j_(t,e,n,r,i){const s=t.listingMode(n);return s==="error"?null:s==="en"?r(e):i(e)}function OCe(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}class NCe{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;const{padTo:i,floor:s,...o}=r;if(!n||Object.keys(o).length>0){const u={useGrouping:!1,...r};r.padTo>0&&(u.minimumIntegerDigits=r.padTo),this.inf=vCe(e,u)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):OD(e,3);return Hn(n,this.padTo)}}}class DCe{constructor(e,n,r){this.opts=r;let i;if(e.zone.isUniversal){const o=-1*(e.offset/60),u=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&Zu.create(u).valid?(i=u,this.dt=e):(i="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:ot.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);const s={...this.opts};i&&(s.timeZone=i),this.dtf=ID(n,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}}class FCe{constructor(e,n,r){this.opts={style:"long",...r},!n&&wG()&&(this.rtf=SCe(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):hCe(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}class pn{static fromOpts(e){return pn.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,n,r,i=!1){const s=e||zn.defaultLocale,o=s||(i?"en-US":_Ce()),u=n||zn.defaultNumberingSystem,a=r||zn.defaultOutputCalendar;return new pn(o,u,a,s)}static resetCache(){Um=null,LD={},$D={},BD={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r}={}){return pn.create(e,n,r)}constructor(e,n,r,i){const[s,o,u]=CCe(e);this.locale=s,this.numberingSystem=n||o||null,this.outputCalendar=r||u||null,this.intl=bCe(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=OCe(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:pn.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1,r=!0){return j_(this,e,r,PG,()=>{const i=n?{month:e,day:"numeric"}:{month:e},s=n?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=TCe(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,n=!1,r=!0){return j_(this,e,r,UG,()=>{const i=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=n?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=RCe(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return j_(this,void 0,e,()=>qG,()=>{if(!this.meridiemCache){const n={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ot.utc(2016,11,13,9),ot.utc(2016,11,13,19)].map(r=>this.extract(r,n,"dayperiod"))}return this.meridiemCache})}eras(e,n=!0){return j_(this,e,n,HG,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[ot.utc(-40,1,1),ot.utc(2017,1,1)].map(i=>this.extract(i,r,"era"))),this.eraCache[e]})}extract(e,n,r){const i=this.dtFormatter(e,n),s=i.formatToParts(),o=s.find(u=>u.type.toLowerCase()===r);return o?o.value:null}numberFormatter(e={}){return new NCe(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new DCe(e,this.intl,n)}relFormatter(e={}){return new FCe(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ACe(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}}function S2(...t){const e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function _2(...t){return e=>t.reduce(([n,r,i],s)=>{const[o,u,a]=s(e,i);return[{...n,...o},u||r,a]},[{},null,1]).slice(0,2)}function C2(t,...e){if(t==null)return[null,null];for(const[n,r]of e){const i=n.exec(t);if(i)return r(i)}return[null,null]}function ZG(...t){return(e,n)=>{const r={};let i;for(i=0;i<t.length;i++)r[t[i]]=G0(e[n+i]);return[r,null,n+i]}}const eW=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,wCe=`(?:${eW.source}?(?:\\[(${BG.source})\\])?)?`,kD=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,tW=RegExp(`${kD.source}${wCe}`),PD=RegExp(`(?:T${tW.source})?`),LCe=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,ICe=/(\d{4})-?W(\d\d)(?:-?(\d))?/,$Ce=/(\d{4})-?(\d{3})/,BCe=ZG("weekYear","weekNumber","weekDay"),kCe=ZG("year","ordinal"),PCe=/(\d{4})-(\d\d)-(\d\d)/,nW=RegExp(`${kD.source} ?(?:${eW.source}|(${BG.source}))?`),MCe=RegExp(`(?: ${nW.source})?`);function b2(t,e,n){const r=t[e];return At(r)?n:G0(r)}function jCe(t,e){return[{year:b2(t,e),month:b2(t,e+1,1),day:b2(t,e+2,1)},null,e+3]}function T2(t,e){return[{hours:b2(t,e,0),minutes:b2(t,e+1,0),seconds:b2(t,e+2,0),milliseconds:RD(t[e+3])},null,e+4]}function qm(t,e){const n=!t[e]&&!t[e+1],r=I_(t[e+1],t[e+2]),i=n?null:Jr.instance(r);return[{},i,e+3]}function Hm(t,e){const n=t[e]?Zu.create(t[e]):null;return[{},n,e+1]}const UCe=RegExp(`^T?${kD.source}$`),qCe=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function HCe(t){const[e,n,r,i,s,o,u,a,l]=t,c=e[0]==="-",f=a&&a[0]==="-",x=(h,p=!1)=>h!==void 0&&(p||h&&c)?-h:h;return[{years:x(_x(n)),months:x(_x(r)),weeks:x(_x(i)),days:x(_x(s)),hours:x(_x(o)),minutes:x(_x(u)),seconds:x(_x(a),a==="-0"),milliseconds:x(RD(l),f)}]}const zCe={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function MD(t,e,n,r,i,s,o){const u={year:e.length===2?DD(G0(e)):G0(e),month:kG.indexOf(n)+1,day:G0(r),hour:G0(i),minute:G0(s)};return o&&(u.second=G0(o)),t&&(u.weekday=t.length>3?MG.indexOf(t)+1:jG.indexOf(t)+1),u}const QCe=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function GCe(t){const[,e,n,r,i,s,o,u,a,l,c,f]=t,x=MD(e,i,r,n,s,o,u);let h;return a?h=zCe[a]:l?h=0:h=I_(c,f),[x,new Jr(h)]}function WCe(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const VCe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,YCe=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,KCe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function rW(t){const[,e,n,r,i,s,o,u]=t;return[MD(e,i,r,n,s,o,u),Jr.utcInstance]}function XCe(t){const[,e,n,r,i,s,o,u]=t;return[MD(e,u,n,r,i,s,o),Jr.utcInstance]}const JCe=S2(LCe,PD),ZCe=S2(ICe,PD),ebe=S2($Ce,PD),tbe=S2(tW),iW=_2(jCe,T2,qm,Hm),nbe=_2(BCe,T2,qm,Hm),rbe=_2(kCe,T2,qm,Hm),ibe=_2(T2,qm,Hm);function sbe(t){return C2(t,[JCe,iW],[ZCe,nbe],[ebe,rbe],[tbe,ibe])}function obe(t){return C2(WCe(t),[QCe,GCe])}function ube(t){return C2(t,[VCe,rW],[YCe,rW],[KCe,XCe])}function abe(t){return C2(t,[qCe,HCe])}const lbe=_2(T2);function cbe(t){return C2(t,[UCe,lbe])}const fbe=S2(PCe,MCe),xbe=S2(nW),dbe=_2(T2,qm,Hm);function hbe(t){return C2(t,[fbe,iW],[xbe,dbe])}const pbe="Invalid Duration",sW={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},gbe={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...sW},co=146097/400,R2=146097/4800,mbe={years:{quarters:4,months:12,weeks:co/7,days:co,hours:co*24,minutes:co*24*60,seconds:co*24*60*60,milliseconds:co*24*60*60*1e3},quarters:{months:3,weeks:co/28,days:co/4,hours:co*24/4,minutes:co*24*60/4,seconds:co*24*60*60/4,milliseconds:co*24*60*60*1e3/4},months:{weeks:R2/7,days:R2,hours:R2*24,minutes:R2*24*60,seconds:R2*24*60*60,milliseconds:R2*24*60*60*1e3},...sW},Cx=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ybe=Cx.slice(0).reverse();function bx(t,e,n=!1){const r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new vt(r)}function Ebe(t){return t<0?Math.floor(t):Math.ceil(t)}function oW(t,e,n,r,i){const s=t[i][n],o=e[n]/s,u=Math.sign(o)===Math.sign(r[i]),a=!u&&r[i]!==0&&Math.abs(o)<=1?Ebe(o):Math.trunc(o);r[i]+=a,e[n]-=a*s}function Abe(t,e){ybe.reduce((n,r)=>At(e[r])?n:(n&&oW(t,e,n,e,r),r),null)}class vt{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||pn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n?mbe:gbe,this.isLuxonDuration=!0}static fromMillis(e,n){return vt.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new lo(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new vt({values:$_(e,vt.normalizeUnit),loc:pn.fromObject(n),conversionAccuracy:n.conversionAccuracy})}static fromDurationLike(e){if(Sx(e))return vt.fromMillis(e);if(vt.isDuration(e))return e;if(typeof e=="object")return vt.fromObject(e);throw new lo(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[r]=abe(e);return r?vt.fromObject(r,n):vt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[r]=cbe(e);return r?vt.fromObject(r,n):vt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new lo("need to specify a reason the Duration is invalid");const r=e instanceof Yo?e:new Yo(e,n);if(zn.throwOnInvalid)throw new K5e(r);return new vt({invalid:r})}static normalizeUnit(e){const n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new xG(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){const r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?is.create(this.loc,r).formatDurationFromString(this,e):pbe}toHuman(e={}){const n=Cx.map(r=>{const i=this.values[r];return At(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=OD(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();if(n<0||n>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};const r=this.shiftTo("hours","minutes","seconds","milliseconds");let i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||r.seconds!==0||r.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||r.milliseconds!==0)&&(i+=".SSS"));let s=r.toFormat(i);return e.includePrefix&&(s="T"+s),s}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e),r={};for(const i of Cx)(A2(n.values,i)||A2(this.values,i))&&(r[i]=n.get(i)+this.get(i));return bx(this,{values:r},!0)}minus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const r of Object.keys(this.values))n[r]=$G(e(this.values[r],r));return bx(this,{values:n},!0)}get(e){return this[vt.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...$_(e,vt.normalizeUnit)};return bx(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n}),s={loc:i};return r&&(s.conversionAccuracy=r),bx(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Abe(this.matrix,e),bx(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>vt.normalizeUnit(o));const n={},r={},i=this.toObject();let s;for(const o of Cx)if(e.indexOf(o)>=0){s=o;let u=0;for(const l in r)u+=this.matrix[l][o]*r[l],r[l]=0;Sx(i[o])&&(u+=i[o]);const a=Math.trunc(u);n[o]=a,r[o]=(u*1e3-a*1e3)/1e3;for(const l in i)Cx.indexOf(l)>Cx.indexOf(o)&&oW(this.matrix,i,l,n,o)}else Sx(i[o])&&(r[o]=i[o]);for(const o in r)r[o]!==0&&(n[s]+=o===s?r[o]:r[o]/this.matrix[s][o]);return bx(this,{values:n},!0).normalize()}negate(){if(!this.isValid)return this;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return bx(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(r,i){return r===void 0||r===0?i===void 0||i===0:r===i}for(const r of Cx)if(!n(this.values[r],e.values[r]))return!1;return!0}}const zm="Invalid Interval";function vbe(t,e){return!t||!t.isValid?gn.invalid("missing or invalid start"):!e||!e.isValid?gn.invalid("missing or invalid end"):e<t?gn.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class gn{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new lo("need to specify a reason the Interval is invalid");const r=e instanceof Yo?e:new Yo(e,n);if(zn.throwOnInvalid)throw new Y5e(r);return new gn({invalid:r})}static fromDateTimes(e,n){const r=Vm(e),i=Vm(n),s=vbe(r,i);return s??new gn({start:r,end:i})}static after(e,n){const r=vt.fromDurationLike(n),i=Vm(e);return gn.fromDateTimes(i,i.plus(r))}static before(e,n){const r=vt.fromDurationLike(n),i=Vm(e);return gn.fromDateTimes(i.minus(r),i)}static fromISO(e,n){const[r,i]=(e||"").split("/",2);if(r&&i){let s,o;try{s=ot.fromISO(r,n),o=s.isValid}catch{o=!1}let u,a;try{u=ot.fromISO(i,n),a=u.isValid}catch{a=!1}if(o&&a)return gn.fromDateTimes(s,u);if(o){const l=vt.fromISO(i,n);if(l.isValid)return gn.after(s,l)}else if(a){const l=vt.fromISO(r,n);if(l.isValid)return gn.before(u,l)}}return gn.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;const n=this.start.startOf(e),r=this.end.startOf(e);return Math.floor(r.diff(n,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?gn.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Vm).filter(o=>this.contains(o)).sort(),r=[];let{s:i}=this,s=0;for(;i<this.e;){const o=n[s]||this.e,u=+o>+this.e?this.e:o;r.push(gn.fromDateTimes(i,u)),i=u,s+=1}return r}splitBy(e){const n=vt.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,i=1,s;const o=[];for(;r<this.e;){const u=this.start.plus(n.mapUnits(a=>a*i));s=+u>+this.e?this.e:u,o.push(gn.fromDateTimes(r,s)),r=s,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:gn.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return gn.fromDateTimes(n,r)}static merge(e){const[n,r]=e.sort((i,s)=>i.s-s.s).reduce(([i,s],o)=>s?s.overlaps(o)||s.abutsStart(o)?[i,s.union(o)]:[i.concat([s]),o]:[i,o],[[],null]);return r&&n.push(r),n}static xor(e){let n=null,r=0;const i=[],s=e.map(a=>[{time:a.s,type:"s"},{time:a.e,type:"e"}]),o=Array.prototype.concat(...s),u=o.sort((a,l)=>a.time-l.time);for(const a of u)r+=a.type==="s"?1:-1,r===1?n=a.time:(n&&+n!=+a.time&&i.push(gn.fromDateTimes(n,a.time)),n=null);return gn.merge(i)}difference(...e){return gn.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:zm}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:zm}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:zm}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:zm}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:zm}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):vt.invalid(this.invalidReason)}mapEndpoints(e){return gn.fromDateTimes(e(this.s),e(this.e))}}let Qm=class{static hasDST(e=zn.defaultZone){const n=ot.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Zu.isValidZone(e)}static normalizeZone(e){return W0(e,zn.defaultZone)}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||pn.create(n,r,s)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||pn.create(n,r,s)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||pn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||pn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return pn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return pn.create(n,null,"gregory").eras(e)}static features(){return{relative:wG()}}};function uW(t,e){const n=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(vt.fromMillis(r).as("days"))}function Sbe(t,e,n){const r=[["years",(u,a)=>a.year-u.year],["quarters",(u,a)=>a.quarter-u.quarter],["months",(u,a)=>a.month-u.month+(a.year-u.year)*12],["weeks",(u,a)=>{const l=uW(u,a);return(l-l%7)/7}],["days",uW]],i={};let s,o;for(const[u,a]of r)if(n.indexOf(u)>=0){s=u;let l=a(t,e);o=t.plus({[u]:l}),o>e?(t=t.plus({[u]:l-1}),l-=1):t=o,i[u]=l}return[t,i,o,s]}function _be(t,e,n,r){let[i,s,o,u]=Sbe(t,e,n);const a=e-i,l=n.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[u]:1})),o!==i&&(s[u]=(s[u]||0)+a/(o-i)));const c=vt.fromObject(s,r);return l.length>0?vt.fromMillis(a,r).shiftTo(...l).plus(c):c}const jD={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},aW={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Cbe=jD.hanidec.replace(/[\[|\]]/g,"").split("");function bbe(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);if(t[n].search(jD.hanidec)!==-1)e+=Cbe.indexOf(t[n]);else for(const i in aW){const[s,o]=aW[i];r>=s&&r<=o&&(e+=r-s)}}return parseInt(e,10)}else return e}function Ko({numberingSystem:t},e=""){return new RegExp(`${jD[t||"latn"]}${e}`)}const Tbe="missing Intl.DateTimeFormat.formatToParts support";function Ft(t,e=n=>n){return{regex:t,deser:([n])=>e(bbe(n))}}const lW="[  ]",cW=new RegExp(lW,"g");function Rbe(t){return t.replace(/\./g,"\\.?").replace(cW,lW)}function fW(t){return t.replace(/\./g,"").replace(cW," ").toLowerCase()}function Xo(t,e){return t===null?null:{regex:RegExp(t.map(Rbe).join("|")),deser:([n])=>t.findIndex(r=>fW(n)===fW(r))+e}}function xW(t,e){return{regex:t,deser:([,n,r])=>I_(n,r),groups:e}}function UD(t){return{regex:t,deser:([e])=>e}}function Obe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Nbe(t,e){const n=Ko(e),r=Ko(e,"{2}"),i=Ko(e,"{3}"),s=Ko(e,"{4}"),o=Ko(e,"{6}"),u=Ko(e,"{1,2}"),a=Ko(e,"{1,3}"),l=Ko(e,"{1,6}"),c=Ko(e,"{1,9}"),f=Ko(e,"{2,4}"),x=Ko(e,"{4,6}"),h=g=>({regex:RegExp(Obe(g.val)),deser:([y])=>y,literal:!0}),m=(g=>{if(t.literal)return h(g);switch(g.val){case"G":return Xo(e.eras("short",!1),0);case"GG":return Xo(e.eras("long",!1),0);case"y":return Ft(l);case"yy":return Ft(f,DD);case"yyyy":return Ft(s);case"yyyyy":return Ft(x);case"yyyyyy":return Ft(o);case"M":return Ft(u);case"MM":return Ft(r);case"MMM":return Xo(e.months("short",!0,!1),1);case"MMMM":return Xo(e.months("long",!0,!1),1);case"L":return Ft(u);case"LL":return Ft(r);case"LLL":return Xo(e.months("short",!1,!1),1);case"LLLL":return Xo(e.months("long",!1,!1),1);case"d":return Ft(u);case"dd":return Ft(r);case"o":return Ft(a);case"ooo":return Ft(i);case"HH":return Ft(r);case"H":return Ft(u);case"hh":return Ft(r);case"h":return Ft(u);case"mm":return Ft(r);case"m":return Ft(u);case"q":return Ft(u);case"qq":return Ft(r);case"s":return Ft(u);case"ss":return Ft(r);case"S":return Ft(a);case"SSS":return Ft(i);case"u":return UD(c);case"uu":return UD(u);case"uuu":return Ft(n);case"a":return Xo(e.meridiems(),0);case"kkkk":return Ft(s);case"kk":return Ft(f,DD);case"W":return Ft(u);case"WW":return Ft(r);case"E":case"c":return Ft(n);case"EEE":return Xo(e.weekdays("short",!1,!1),1);case"EEEE":return Xo(e.weekdays("long",!1,!1),1);case"ccc":return Xo(e.weekdays("short",!0,!1),1);case"cccc":return Xo(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return xW(new RegExp(`([+-]${u.source})(?::(${r.source}))?`),2);case"ZZZ":return xW(new RegExp(`([+-]${u.source})(${r.source})?`),2);case"z":return UD(/[a-z_+-/]{1,256}?/i);default:return h(g)}})(t)||{invalidReason:Tbe};return m.token=t,m}const Dbe={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"}};function Fbe(t,e,n){const{type:r,value:i}=t;if(r==="literal")return{literal:!0,val:i};const s=n[r];let o=Dbe[r];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function wbe(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function Lbe(t,e,n){const r=t.match(e);if(r){const i={};let s=1;for(const o in n)if(A2(n,o)){const u=n[o],a=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(r.slice(s,s+a))),s+=a}return[r,i]}else return[r,{}]}function Ibe(t){const e=s=>{switch(s){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let n=null,r;return At(t.z)||(n=Zu.create(t.z)),At(t.Z)||(n||(n=new Jr(t.Z)),r=t.Z),At(t.q)||(t.M=(t.q-1)*3+1),At(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),At(t.u)||(t.S=RD(t.u)),[Object.keys(t).reduce((s,o)=>{const u=e(o);return u&&(s[u]=t[o]),s},{}),n,r]}let qD=null;function $be(){return qD||(qD=ot.fromMillis(1555555555555)),qD}function Bbe(t,e){if(t.literal)return t;const n=is.macroTokenToFormatOpts(t.val);if(!n)return t;const s=is.create(e,n).formatDateTimeParts($be()).map(o=>Fbe(o,e,n));return s.includes(void 0)?t:s}function kbe(t,e){return Array.prototype.concat(...t.map(n=>Bbe(n,e)))}function dW(t,e,n){const r=kbe(is.parseFormat(n),t),i=r.map(o=>Nbe(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:r,invalidReason:s.invalidReason};{const[o,u]=wbe(i),a=RegExp(o,"i"),[l,c]=Lbe(e,a,u),[f,x,h]=c?Ibe(c):[null,null,void 0];if(A2(c,"a")&&A2(c,"H"))throw new km("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:r,regex:a,rawMatches:l,matches:c,result:f,zone:x,specificOffset:h}}}function Pbe(t,e,n){const{result:r,zone:i,specificOffset:s,invalidReason:o}=dW(t,e,n);return[r,i,s,o]}const hW=[0,31,59,90,120,151,181,212,243,273,304,334],pW=[0,31,60,91,121,152,182,213,244,274,305,335];function fo(t,e){return new Yo("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function gW(t,e,n){const r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);const i=r.getUTCDay();return i===0?7:i}function mW(t,e,n){return n+(Pm(t)?pW:hW)[e-1]}function yW(t,e){const n=Pm(t)?pW:hW,r=n.findIndex(s=>s<e),i=e-n[r];return{month:r+1,day:i}}function HD(t){const{year:e,month:n,day:r}=t,i=mW(e,n,r),s=gW(e,n,r);let o=Math.floor((i-s+10)/7),u;return o<1?(u=e-1,o=L_(u)):o>L_(e)?(u=e+1,o=1):u=e,{weekYear:u,weekNumber:o,weekday:s,...B_(t)}}function EW(t){const{weekYear:e,weekNumber:n,weekday:r}=t,i=gW(e,1,4),s=Mm(e);let o=n*7+r-i-3,u;o<1?(u=e-1,o+=Mm(u)):o>s?(u=e+1,o-=Mm(e)):u=e;const{month:a,day:l}=yW(u,o);return{year:u,month:a,day:l,...B_(t)}}function zD(t){const{year:e,month:n,day:r}=t,i=mW(e,n,r);return{year:e,ordinal:i,...B_(t)}}function AW(t){const{year:e,ordinal:n}=t,{month:r,day:i}=yW(e,n);return{year:e,month:r,day:i,...B_(t)}}function Mbe(t){const e=F_(t.weekYear),n=yl(t.weekNumber,1,L_(t.weekYear)),r=yl(t.weekday,1,7);return e?n?r?!1:fo("weekday",t.weekday):fo("week",t.week):fo("weekYear",t.weekYear)}function jbe(t){const e=F_(t.year),n=yl(t.ordinal,1,Mm(t.year));return e?n?!1:fo("ordinal",t.ordinal):fo("year",t.year)}function vW(t){const e=F_(t.year),n=yl(t.month,1,12),r=yl(t.day,1,w_(t.year,t.month));return e?n?r?!1:fo("day",t.day):fo("month",t.month):fo("year",t.year)}function SW(t){const{hour:e,minute:n,second:r,millisecond:i}=t,s=yl(e,0,23)||e===24&&n===0&&r===0&&i===0,o=yl(n,0,59),u=yl(r,0,59),a=yl(i,0,999);return s?o?u?a?!1:fo("millisecond",i):fo("second",r):fo("minute",n):fo("hour",e)}const QD="Invalid DateTime",_W=864e13;function U_(t){return new Yo("unsupported zone",`the zone "${t.name}" is not supported`)}function GD(t){return t.weekData===null&&(t.weekData=HD(t.c)),t.weekData}function Gm(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new ot({...n,...e,old:n})}function CW(t,e,n){let r=t-e*60*1e3;const i=n.offset(r);if(e===i)return[r,e];r-=(i-e)*60*1e3;const s=n.offset(r);return i===s?[r,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function bW(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function q_(t,e,n){return CW(ND(t),e,n)}function TW(t,e){const n=t.o,r=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:r,month:i,day:Math.min(t.c.day,w_(r,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=vt.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),u=ND(s);let[a,l]=CW(u,n,t.zone);return o!==0&&(a+=o,l=t.zone.offset(a)),{ts:a,o:l}}function Wm(t,e,n,r,i,s){const{setZone:o,zone:u}=n;if(t&&Object.keys(t).length!==0){const a=e||u,l=ot.fromObject(t,{...n,zone:a,specificOffset:s});return o?l:l.setZone(u)}else return ot.invalid(new Yo("unparsable",`the input "${i}" can't be parsed as ${r}`))}function H_(t,e,n=!0){return t.isValid?is.create(pn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function WD(t,e){const n=t.c.year>9999||t.c.year<0;let r="";return n&&t.c.year>=0&&(r+="+"),r+=Hn(t.c.year,n?6:4),e?(r+="-",r+=Hn(t.c.month),r+="-",r+=Hn(t.c.day)):(r+=Hn(t.c.month),r+=Hn(t.c.day)),r}function RW(t,e,n,r,i,s){let o=Hn(t.c.hour);return e?(o+=":",o+=Hn(t.c.minute),(t.c.second!==0||!n)&&(o+=":")):o+=Hn(t.c.minute),(t.c.second!==0||!n)&&(o+=Hn(t.c.second),(t.c.millisecond!==0||!r)&&(o+=".",o+=Hn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=Hn(Math.trunc(-t.o/60)),o+=":",o+=Hn(Math.trunc(-t.o%60))):(o+="+",o+=Hn(Math.trunc(t.o/60)),o+=":",o+=Hn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}const OW={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ube={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},qbe={ordinal:1,hour:0,minute:0,second:0,millisecond:0},NW=["year","month","day","hour","minute","second","millisecond"],Hbe=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],zbe=["year","ordinal","hour","minute","second","millisecond"];function DW(t){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new xG(t);return e}function FW(t,e){const n=W0(e.zone,zn.defaultZone),r=pn.fromObject(e),i=zn.now();let s,o;if(At(t.year))s=i;else{for(const l of NW)At(t[l])&&(t[l]=OW[l]);const u=vW(t)||SW(t);if(u)return ot.invalid(u);const a=n.offset(i);[s,o]=q_(t,a,n)}return new ot({ts:s,zone:n,loc:r,o})}function wW(t,e,n){const r=At(n.round)?!0:n.round,i=(o,u)=>(o=OD(o,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(o,u)),s=o=>n.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(n.unit)return i(s(n.unit),n.unit);for(const o of n.units){const u=s(o);if(Math.abs(u)>=1)return i(u,o)}return i(t>e?-0:0,n.units[n.units.length-1])}function LW(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}class ot{constructor(e){const n=e.zone||zn.defaultZone;let r=e.invalid||(Number.isNaN(e.ts)?new Yo("invalid input"):null)||(n.isValid?null:U_(n));this.ts=At(e.ts)?zn.now():e.ts;let i=null,s=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[i,s]=[e.old.c,e.old.o];else{const u=n.offset(this.ts);i=bW(this.ts,u),r=Number.isNaN(i.year)?new Yo("invalid input"):null,i=r?null:i,s=r?null:u}this._zone=n,this.loc=e.loc||pn.create(),this.invalid=r,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new ot({})}static local(){const[e,n]=LW(arguments),[r,i,s,o,u,a,l]=n;return FW({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static utc(){const[e,n]=LW(arguments),[r,i,s,o,u,a,l]=n;return e.zone=Jr.utcInstance,FW({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static fromJSDate(e,n={}){const r=eCe(e)?e.valueOf():NaN;if(Number.isNaN(r))return ot.invalid("invalid input");const i=W0(n.zone,zn.defaultZone);return i.isValid?new ot({ts:r,zone:i,loc:pn.fromObject(n)}):ot.invalid(U_(i))}static fromMillis(e,n={}){if(Sx(e))return e<-_W||e>_W?ot.invalid("Timestamp out of range"):new ot({ts:e,zone:W0(n.zone,zn.defaultZone),loc:pn.fromObject(n)});throw new lo(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(Sx(e))return new ot({ts:e*1e3,zone:W0(n.zone,zn.defaultZone),loc:pn.fromObject(n)});throw new lo("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const r=W0(n.zone,zn.defaultZone);if(!r.isValid)return ot.invalid(U_(r));const i=zn.now(),s=At(n.specificOffset)?r.offset(i):n.specificOffset,o=$_(e,DW),u=!At(o.ordinal),a=!At(o.year),l=!At(o.month)||!At(o.day),c=a||l,f=o.weekYear||o.weekNumber,x=pn.fromObject(n);if((c||u)&&f)throw new km("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&u)throw new km("Can't mix ordinal dates with month/day");const h=f||o.weekday&&!c;let p,m,g=bW(i,s);h?(p=Hbe,m=Ube,g=HD(g)):u?(p=zbe,m=qbe,g=zD(g)):(p=NW,m=OW);let y=!1;for(const b of p){const R=o[b];At(R)?y?o[b]=m[b]:o[b]=g[b]:y=!0}const E=h?Mbe(o):u?jbe(o):vW(o),A=E||SW(o);if(A)return ot.invalid(A);const v=h?EW(o):u?AW(o):o,[S,C]=q_(v,s,r),_=new ot({ts:S,zone:r,o:C,loc:x});return o.weekday&&c&&e.weekday!==_.weekday?ot.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,n={}){const[r,i]=sbe(e);return Wm(r,i,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[r,i]=obe(e);return Wm(r,i,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[r,i]=ube(e);return Wm(r,i,n,"HTTP",n)}static fromFormat(e,n,r={}){if(At(e)||At(n))throw new lo("fromFormat requires an input string and a format");const{locale:i=null,numberingSystem:s=null}=r,o=pn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[u,a,l,c]=Pbe(o,e,n);return c?ot.invalid(c):Wm(u,a,r,`format ${n}`,e,l)}static fromString(e,n,r={}){return ot.fromFormat(e,n,r)}static fromSQL(e,n={}){const[r,i]=hbe(e);return Wm(r,i,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new lo("need to specify a reason the DateTime is invalid");const r=e instanceof Yo?e:new Yo(e,n);if(zn.throwOnInvalid)throw new V5e(r);return new ot({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?GD(this).weekYear:NaN}get weekNumber(){return this.isValid?GD(this).weekNumber:NaN}get weekday(){return this.isValid?GD(this).weekday:NaN}get ordinal(){return this.isValid?zD(this.c).ordinal:NaN}get monthShort(){return this.isValid?Qm.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Qm.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Qm.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Qm.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}get isInLeapYear(){return Pm(this.year)}get daysInMonth(){return w_(this.year,this.month)}get daysInYear(){return this.isValid?Mm(this.year):NaN}get weeksInWeekYear(){return this.isValid?L_(this.weekYear):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:r,calendar:i}=is.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:i}}toUTC(e=0,n={}){return this.setZone(Jr.instance(e),n)}toLocal(){return this.setZone(zn.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=W0(e,zn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(n||r){const s=e.offset(this.ts),o=this.toObject();[i]=q_(o,s,e)}return Gm(this,{ts:i,zone:e})}else return ot.invalid(U_(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return Gm(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=$_(e,DW),r=!At(n.weekYear)||!At(n.weekNumber)||!At(n.weekday),i=!At(n.ordinal),s=!At(n.year),o=!At(n.month)||!At(n.day),u=s||o,a=n.weekYear||n.weekNumber;if((u||i)&&a)throw new km("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new km("Can't mix ordinal dates with month/day");let l;r?l=EW({...HD(this.c),...n}):At(n.ordinal)?(l={...this.toObject(),...n},At(n.day)&&(l.day=Math.min(w_(l.year,l.month),l.day))):l=AW({...zD(this.c),...n});const[c,f]=q_(l,this.o,this.zone);return Gm(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e);return Gm(this,TW(this,n))}minus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e).negate();return Gm(this,TW(this,n))}startOf(e){if(!this.isValid)return this;const n={},r=vt.normalizeUnit(e);switch(r){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break}if(r==="weeks"&&(n.weekday=1),r==="quarters"){const i=Math.ceil(this.month/3);n.month=(i-1)*3+1}return this.set(n)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,n={}){return this.isValid?is.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):QD}toLocaleString(e=TD,n={}){return this.isValid?is.create(this.loc.clone(n),e).formatDateTime(this):QD}toLocaleParts(e={}){return this.isValid?is.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;const o=e==="extended";let u=WD(this,o);return u+="T",u+=RW(this,o,n,r,i,s),u}toISODate({format:e="extended"}={}){return this.isValid?WD(this,e==="extended"):null}toISOWeekDate(){return H_(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+RW(this,o==="extended",n,e,r,s):null}toRFC2822(){return H_(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return H_(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?WD(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let i="HH:mm:ss.SSS";return(n||e)&&(r&&(i+=" "),n?i+="z":e&&(i+="ZZ")),H_(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():QD}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return vt.invalid("created by diffing an invalid DateTime");const i={locale:this.locale,numberingSystem:this.numberingSystem,...r},s=tCe(n).map(vt.normalizeUnit),o=e.valueOf()>this.valueOf(),u=o?this:e,a=o?e:this,l=_be(u,a,s,i);return o?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(ot.now(),e,n)}until(e){return this.isValid?gn.fromDateTimes(this,e):this}hasSame(e,n){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n)<=r&&r<=i.endOf(n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const n=e.base||ot.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0;let i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),wW(n,this.plus(r),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?wW(e.base||ot.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(ot.isDateTime))throw new lo("min requires all arguments be DateTimes");return LG(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(ot.isDateTime))throw new lo("max requires all arguments be DateTimes");return LG(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){const{locale:i=null,numberingSystem:s=null}=r,o=pn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return dW(o,e,n)}static fromStringExplain(e,n,r={}){return ot.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return TD}static get DATE_MED(){return dG}static get DATE_MED_WITH_WEEKDAY(){return X5e}static get DATE_FULL(){return hG}static get DATE_HUGE(){return pG}static get TIME_SIMPLE(){return gG}static get TIME_WITH_SECONDS(){return mG}static get TIME_WITH_SHORT_OFFSET(){return yG}static get TIME_WITH_LONG_OFFSET(){return EG}static get TIME_24_SIMPLE(){return AG}static get TIME_24_WITH_SECONDS(){return vG}static get TIME_24_WITH_SHORT_OFFSET(){return SG}static get TIME_24_WITH_LONG_OFFSET(){return _G}static get DATETIME_SHORT(){return CG}static get DATETIME_SHORT_WITH_SECONDS(){return bG}static get DATETIME_MED(){return TG}static get DATETIME_MED_WITH_SECONDS(){return RG}static get DATETIME_MED_WITH_WEEKDAY(){return J5e}static get DATETIME_FULL(){return OG}static get DATETIME_FULL_WITH_SECONDS(){return NG}static get DATETIME_HUGE(){return DG}static get DATETIME_HUGE_WITH_SECONDS(){return FG}}function Vm(t){if(ot.isDateTime(t))return t;if(t&&t.valueOf&&Sx(t.valueOf()))return ot.fromJSDate(t);if(t&&typeof t=="object")return ot.fromObject(t);throw new lo(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const IW=GP(Object.freeze(Object.defineProperty({__proto__:null,DateTime:ot,Duration:vt,FixedOffsetZone:Jr,IANAZone:Zu,Info:Qm,Interval:gn,InvalidZone:QG,Settings:zn,SystemZone:k_,VERSION:"2.5.2",Zone:v2},Symbol.toStringTag,{value:"Module"})));Object.defineProperty(pr,"__esModule",{value:!0}),pr.LiteralYear=pr.LiteralQuarter=pr.LiteralMonth=pr.LiteralWeek=pr.LiteralDay=pr.LiteralHour=pr.LiteralTimestamp=pr.TimeFormatError=void 0;const V0=IW,Qbe=ne,Gbe=j0,$W=p2,VD=pt;class Wbe extends Error{}pr.TimeFormatError=Wbe;function Tx(t,e){const n=t.slice(1);if(e){const r=n.match(/\[[^\]]+]$/);if(r)return{tzSpec:r[0].slice(1,-1),text:n.slice(0,-r[0].length)}}return{text:n}}const BW="yyyy",kW=`${BW}-LL`,xo=`${kW}-dd`,PW=`${xo} HH`,MW=`${PW}:mm`,YD=`${MW}:ss`;class jW extends VD.ExpressionDef{constructor(e,n,r){super(),this.units=n,this.timeType=r,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,n){const r={type:"dialect",function:"timeLiteral",literal:e,literalType:n};return this.timeZone&&(r.timezone=this.timeZone),r}makeValue(e,n){const r=this.makeLiteral(e,n),i="scalar",s=[r];return this.units?{dataType:n,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:n,expressionType:i,value:s,evalSpace:"literal"}}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class KD extends jW{constructor(e,n){super(e,n,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let n;const r=Tx(e,!0);e=r.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),r.text=e);const i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=V0.DateTime.fromFormat(e,YD);if(s.isValid)return new KD(r,n);if(s=V0.DateTime.fromFormat(e,MW),s.isValid){r.text=r.text+":00",n="minute";const o=s.plus({minute:1}).toFormat(YD);return new XD(r,n,"timestamp",o)}}}pr.LiteralTimestamp=KD;class XD extends jW{constructor(e,n,r,i){super(e,n,r),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,n,r){let i=this.getExpression(e),s=this.getNext();if(s){const o=r.getExpression(e);if(o.dataType==="timestamp"){const u=(0,VD.getMorphicValue)(i,"timestamp"),a=(0,VD.getMorphicValue)(s,"timestamp");if(u&&a)i=u,s=a;else return super.apply(e,n,r)}if((0,Qbe.isTimeFieldType)(o.dataType)){const u=o.dataType;return new Gbe.Range(new $W.ExprTime(u,i.value),new $W.ExprTime(u,s.value)).apply(e,n,r)}}return super.apply(e,n,r)}}class JD extends XD{constructor(e,n){super(e,"hour","timestamp",n),this.elementType="literal:hour"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,PW);if(i.isValid)return n.text=n.text+":00:00",r=i.plus({hour:1}).toFormat(YD),new JD(n,r)}}pr.LiteralHour=JD;class Ym extends XD{constructor(e,n,r){super(e,n,"date",r)}getExpression(e){const n=this.makeValue(this.literalPart,"date"),r=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...n,morphic:{timestamp:r},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),n=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:n}}}}class ZD extends Ym{constructor(e,n){super(e,"day",n),this.elementType="literal:day"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,xo);if(i.isValid)return r=i.plus({day:1}).toFormat(xo),new ZD(n,r)}}pr.LiteralDay=ZD;class eF extends Ym{constructor(e,n){super(e,"week",n),this.elementType="literal:week"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=n.text.slice(0,10),s=V0.DateTime.fromFormat(i,xo);if(s.isValid&&s.weekday===7){const u=s.plus({days:7});return n.text=s.toFormat(xo),r=u.toFormat(xo),new eF(n,r)}}}pr.LiteralWeek=eF;class tF extends Ym{constructor(e,n){super(e,"month",n),this.elementType="literal:month"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,kW);if(i.isValid){const s=i.plus({months:1});return n.text=i.toFormat(xo),r=s.toFormat(xo),new tF(n,r)}}}pr.LiteralMonth=tF;class nF extends Ym{constructor(e,n){super(e,"quarter",n),this.elementType="literal:quarter"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=n.text.match(/(^\d{4})-[qQ](\d)$/);if(i){const s=Number.parseInt(i[2])-1;let o=V0.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));const u=o.plus({quarter:1});return n.text=o.toFormat(xo),r=u.toFormat(xo),new nF(n,r)}}}pr.LiteralQuarter=nF;class rF extends Ym{constructor(e,n){super(e,"year",n),this.elementType="literal:year"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,BW);if(i.isValid){const s=i.plus({year:1});return n.text=i.toFormat(xo),r=s.toFormat(xo),new rF(n,r)}}}pr.LiteralYear=rF;var z_={};Object.defineProperty(z_,"__esModule",{value:!0}),z_.PartialCompare=void 0;const Vbe=hr,Ybe=pt;class Kbe extends Ybe.ExpressionDef{constructor(e,n){super({right:n}),this.op=e,this.right=n,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,n,r){return this.right.apply(e,this.op,r)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,Vbe.errorFor)("no value for partial compare")}}z_.PartialCompare=Kbe;var O2={};Object.defineProperty(O2,"__esModule",{value:!0}),O2.PickWhen=O2.Pick=void 0;const ea=ne,Y0=hr,Jo=ln,Xbe=pt,Jbe=Ve,UW=hn;function Q_(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class Zbe extends Xbe.ExpressionDef{constructor(e,n){super({choices:e}),this.choices=e,this.elsePick=n,this.elementType="pick",this.has({elsePick:n})}requestExpression(e){if(this.elsePick!==void 0){for(const n of this.choices){if(n.pick===void 0)return;const r=n.when.requestExpression(e);if(r===void 0||r.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,n,r){const i=["CASE"];let s,o="scalar",u="constant";for(const c of this.choices){const f=c.when.apply(e,"=",r),x=c.pick?c.pick.getExpression(e):r.getExpression(e);if(o=(0,ea.maxExpressionType)(o,(0,ea.maxExpressionType)(f.expressionType,x.expressionType)),u=(0,ea.mergeEvalSpaces)(u,f.evalSpace,x.evalSpace),s&&!Jo.FT.typeEq(s,x,!0)){const h=Jo.FT.inspect(x);return this.log(`pick type '${h}', expected '${s.dataType}'`),(0,Y0.errorFor)("pick when type")}s=Q_(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}const l=(this.elsePick||r).getExpression(e);if(s=Q_(s,l),!Jo.FT.typeEq(s,l,!0)){const c=this.elsePick?"else":"pick default";return this.log(`${c} type '${Jo.FT.inspect(l)}', expected '${s.dataType}'`),(0,Y0.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,ea.maxExpressionType)(o,l.expressionType),evalSpace:(0,ea.mergeEvalSpaces)(u,l.evalSpace),value:(0,UW.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,Y0.errorFor)("no value for partial pick");const n=[];for(const a of this.choices){if(a.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,Y0.errorFor)("no value for partial pick");if(a.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,Y0.errorFor)("partial when");n.push({pick:a.pick.getExpression(e),when:a.when.getExpression(e)})}let r;const i=["CASE"];let s="scalar",o="constant";for(const a of n){if(!Jo.FT.typeEq(a.when,Jo.FT.boolT))return this.log(`when expression must be boolean, not '${Jo.FT.inspect(a.when)}`),(0,Y0.errorFor)("pick when type");if(r&&!Jo.FT.typeEq(r,a.pick,!0)){const l=Jo.FT.inspect(a.pick);return this.log(`pick type '${l}', expected '${r.dataType}'`),(0,Y0.errorFor)("pick value type")}r=Q_(r,a.pick),s=(0,ea.maxExpressionType)(s,(0,ea.maxExpressionType)(a.pick.expressionType,a.when.expressionType)),o=(0,ea.mergeEvalSpaces)(o,a.pick.evalSpace,a.when.evalSpace),i.push(" WHEN ",...a.when.value," THEN ",...a.pick.value)}const u=this.elsePick.getExpression(e);return s=(0,ea.maxExpressionType)(s,u.expressionType),o=(0,ea.mergeEvalSpaces)(o,u.evalSpace),r=Q_(r,u),Jo.FT.typeEq(r,u,!0)?(i.push(" ELSE ",...u.value," END"),{dataType:r.dataType,expressionType:s,value:(0,UW.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${Jo.FT.inspect(u)}', expected '${r.dataType}'`),(0,Y0.errorFor)("pick value type mismatch"))}}O2.Pick=Zbe;class eTe extends Jbe.MalloyElement{constructor(e,n){super({when:n}),this.pick=e,this.when=n,this.elementType="pickWhen",this.has({pick:e})}}O2.PickWhen=eTe;var G_={};Object.defineProperty(G_,"__esModule",{value:!0}),G_.Timeframe=void 0;const tTe=ne,nTe=Ve;class rTe extends nTe.MalloyElement{constructor(e){super(),this.elementType="timeframe";let n=e.toLowerCase();n.endsWith("s")&&(n=n.slice(0,-1)),this.text=(0,tTe.isTimestampUnit)(n)?n:"second"}}G_.Timeframe=rTe;var W_={};Object.defineProperty(W_,"__esModule",{value:!0}),W_.TopBy=void 0;const iTe=ne,qW=pt,sTe=Ve,oTe=hn;class uTe extends sTe.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof qW.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof qW.ExpressionDef){const n=this.by.getExpression(e);return(0,iTe.expressionIsAggregate)(n.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,oTe.compressExpr)(n.value)}}return{by:"name",name:this.by}}}W_.TopBy=uTe;var K0={};Object.defineProperty(K0,"__esModule",{value:!0}),K0.ImportStatement=K0.ImportSelect=K0.ImportSourceName=void 0;const iF=Ve;class aTe extends iF.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}K0.ImportSourceName=aTe;class lTe extends iF.MalloyElement{constructor(e,n){super(),this.text=e,this.from=n,this.elementType="importName",n&&this.has({from:n})}}K0.ImportSelect=lTe;class cTe extends iF.ListOf{constructor(e,n){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,n).toString())}catch{this.log("Invalid URI in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const r=e.childRequest(this.fullURL);if(r)return r}}execute(e){const n=this.translator();if(!n)this.log("Cannot import without translation context");else if(this.fullURL){const r=n.root.importZone.getEntry(this.fullURL);if(r.status==="present"){const i=n.getChildExports(this.fullURL);if(this.notEmpty())for(const s of this.list){const o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){const u={...i[o.text]};s.from&&(u.as=s.text),e.setEntry(s.text,{entry:u,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(const[s,o]of Object.entries(n.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else r.status==="error"?this.log(`import failed: '${r.message}'`):this.log(`import failed with status: '${r.status}'`)}}}K0.ImportStatement=cTe;var Km={};Object.defineProperty(Km,"__esModule",{value:!0}),Km.ExtendBlock=void 0;const fTe=Ve,xTe=Rn;class dTe extends fTe.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=xTe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)for(const r of n.list)e.inputFS.extendSource(r)}}Km.ExtendBlock=dTe;var V_={};Object.defineProperty(V_,"__esModule",{value:!0}),V_.AnonymousQuery=void 0;const hTe=Ve,pTe=Vr;class gTe extends hTe.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=pTe.extendNoteMethod,this.has({queryExpr:e})}execute(e){const n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("Cannot run this object as a query");return}const r={...n.query()},i=this.note||{};r.annotation&&(i.inherits=r.annotation),(i.notes||i.blockNotes||i.inherits)&&(r.annotation=i),e.queryList.push(r)}}V_.AnonymousQuery=gTe;var X0={};Object.defineProperty(X0,"__esModule",{value:!0}),X0.View=void 0;const mTe=Ve;let yTe=class extends mTe.MalloyElement{pipeline(e,n){return this.pipelineComp(e,n).pipeline}};X0.View=yTe;var Y_={};Object.defineProperty(Y_,"__esModule",{value:!0}),Y_.ViewArrow=void 0;const ETe=Xr,ATe=X0;class vTe extends ATe.View{constructor(e,n){super({base:e,operation:n}),this.base=e,this.operation=n,this.elementType="viewArrow"}pipelineComp(e){const n=this.base.pipelineComp(e),r=new ETe.StaticSpace(n.outputStruct),i=this.operation.pipelineComp(r);return{pipeline:[...n.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,n,r){return this.log("A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Y_.ViewArrow=vTe;var K_={},Xm={};Object.defineProperty(Xm,"__esModule",{value:!0}),Xm.refine=void 0;const sF=Fu,oF=I0;function STe(t,e,n){var r,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;const s={...e[0]},o=n;if((0,sF.isRawSegment)(s))t.log("Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.log(`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&((o.orderBy!==void 0||o.by!==void 0)&&(s.orderBy===void 0&&s.by===void 0?o.orderBy?s.orderBy=o.orderBy:o.by&&(s.by=o.by):t.log("refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.log("refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(r=s.filterList)!==null&&r!==void 0?r:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,sF.isQuerySegment)(o)&&(0,sF.isQuerySegment)(s)){const u=[],a=[],l=new Map(s.queryFields.map(c=>[(0,oF.nameFromDef)(c),c]));for(const c of o.queryFields)l.has((0,oF.nameFromDef)(c))?u.push(c):a.push(c);s.queryFields=[...s.queryFields,...a],u.length>0&&t.log(`overlapping fields in refinement: ${u.map(oF.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}Xm.refine=STe,Object.defineProperty(K_,"__esModule",{value:!0}),K_.ViewRefine=void 0;const _Te=Kr,CTe=Fs,bTe=Xm,TTe=X0;class RTe extends TTe.View{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="refine"}pipelineComp(e,n){const r=this.base.pipelineComp(e),i=this.refinement.refine(e,r.pipeline,n);return{pipeline:i,annotation:r.annotation,outputStruct:i.length>0?(0,CTe.getFinalStruct)(this.refinement,e.structDef(),i):_Te.ErrorFactory.structDef}}refine(e,n,r){const i=this.pipeline(e,r);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),n):(0,bTe.refine)(this,n,i[0])}getImplicitName(){return this.base.getImplicitName()}}K_.ViewRefine=RTe;var X_={};Object.defineProperty(X_,"__esModule",{value:!0}),X_.ReferenceView=void 0;const HW=ne,zW=Kr,OTe=Fs,NTe=Yr,DTe=Xm,FTe=X0;class wTe extends FTe.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,n){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:n}={forRefinement:!1}){const r=this.reference.getField(e),i=function(){return{inputStruct:zW.ErrorFactory.structDef,outputStruct:zW.ErrorFactory.structDef,pipeline:[],error:!0}};if(!r.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(r.found instanceof NTe.SpaceField))throw new Error("Expected space field");const s=r.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,HW.isAtomicFieldType)(s.type)){const o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:u,queryTimezone:a,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:u,queryTimezone:a,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,HW.isTurtleDef)(s)?this.reference.list.length>1?(n?this.log("Cannot use view from join as refinement"):this.log("Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,OTe.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(n?this.reference.log(`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.log("This operation is not supported"),i())}getRefinementSegment(e){const{pipeline:n,error:r}=this._pipelineComp(e,{forRefinement:!0});if(!r){if(n.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return n[0]}}refine(e,n,r){const i=this.getRefinementSegment(e);return i?(0,DTe.refine)(this,n,i):n}getImplicitName(){return this.reference.nameString}}X_.ReferenceView=wTe;var J_={},Jm={},Z_={},Zm={};Object.defineProperty(Zm,"__esModule",{value:!0}),Zm.Index=void 0;const LTe=Ve,ITe=Rn;let $Te=class extends LTe.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=ITe.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};Zm.Index=$Te;var e3={};Object.defineProperty(e3,"__esModule",{value:!0}),e3.SampleProperty=void 0;const BTe=Ve,QW=Rn;class kTe extends BTe.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=QW.LegalRefinementStage.Tail,this.forceQueryClass=QW.QueryClass.Index}sampling(){return this.sample}}e3.SampleProperty=kTe;var e5={};Object.defineProperty(e5,"__esModule",{value:!0}),e5.IndexFieldSpace=void 0;const GW=ne,uF=mt,PTe=Yr,MTe=Wo,jTe=wm,UTe=Xr;class qTe extends MTe.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const n of e)n instanceof uF.FieldReference?super.pushFields(n):n instanceof uF.WildcardFieldReference?this.addWild(n):n.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};const n=[];for(const[r,i]of this.entries())if(i instanceof PTe.SpaceField){const s=this.expandedWild[r];if(s){n.push({type:"fieldref",path:s});continue}if(i instanceof jTe.ReferenceField){const o=i.fieldRef,u=o.getField(this.exprSpace);u.error?o.log(u.error):n.push(o.refToField)}}return{type:"index",indexFields:n}}addRefineFromFields(e){}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof UTe.StructSpaceField)r=l.fieldSpace;else{u.log(`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.log(`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries()){if(e.except.has(u))continue;const l=uF.IndexFieldReference.indexOutputName([...i,u]);if(this.entry(l)){const c=(n=this.expandedWild[l])===null||n===void 0?void 0:n.join(".");e.log(`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=a.typeDesc();(0,GW.isAtomicFieldType)(c.dataType)&&(0,GW.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:l,entry:a}),this.expandedWild[l]=i.concat(u))}}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}e5.IndexFieldSpace=qTe,Object.defineProperty(Z_,"__esModule",{value:!0}),Z_.IndexBuilder=void 0;const aF=ne,HTe=Kr,zTe=Go,QTe=Zm,GTe=H0,WTe=e3,VTe=e5;class YTe{constructor(e,n,r,i){this.filters=[],this.type="index",this.resultFS=new VTe.IndexFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof zTe.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof GTe.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof QTe.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof WTe.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,aF.isIndexSegment)(e)&&!(0,aF.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),HTe.ErrorFactory.indexSegment;const n=this.resultFS.getPipeSegment(e),r=(e==null?void 0:e.filterList)||[];return this.filters.length>0&&!r?n.filterList=this.filters:r&&(n.filterList=[...r,...this.filters]),e!=null&&e.limit&&(n.limit=e.limit),this.limit&&(n.limit=this.limit.limit),this.indexOn&&(n.weightMeasure=this.indexOn.refString),e&&(0,aF.isIndexSegment)(e)&&(e!=null&&e.sample)&&(n.sample=e.sample),this.sample&&(n.sample=this.sample),n}}Z_.IndexBuilder=YTe;var t5={},t3={};Object.defineProperty(t3,"__esModule",{value:!0}),t3.GroupBy=void 0;const KTe=Ds,WW=Rn;class XTe extends KTe.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=WW.LegalRefinementStage.Single,this.forceQueryClass=WW.QueryClass.Grouping}}t3.GroupBy=XTe;var n5={};Object.defineProperty(n5,"__esModule",{value:!0}),n5.ProjectFieldSpace=void 0;const lF=ne,JTe=Wo;class ZTe extends JTe.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,lF.expressionIsAggregate)(e.expressionType)?!1:(0,lF.expressionInvolvesAggregate)(e.expressionType)&&(0,lF.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}}n5.ProjectFieldSpace=ZTe;var J0={},Rx={};Object.defineProperty(Rx,"__esModule",{value:!0}),Rx.Ordering=Rx.OrderBy=void 0;const e6e=ne,VW=Ax,YW=Ve,t6e=Rn;class n6e extends YW.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e instanceof VW.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var n;if(this.field instanceof VW.FieldName&&e.isQueryFieldSpace()){const i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.log(s.error),(!s.found||!s.isOutputField)&&this.log(`Unknown field ${this.field.refString} in output space`),(0,e6e.expressionIsAnalytic)((n=s.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}const r={field:this.modelField};return this.dir&&(r.dir=this.dir),r}}Rx.OrderBy=n6e;class r6e extends YW.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=t6e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(n=>n.getOrderBy(e))}}Rx.Ordering=r6e;var n3={};Object.defineProperty(n3,"__esModule",{value:!0}),n3.Top=void 0;const KW=ne,i6e=hn,s6e=Ax,o6e=Ve,u6e=Rn;let a6e=class extends o6e.MalloyElement{constructor(e,n){super(),this.limit=e,this.by=n,this.elementType="top",this.queryRefinementStage=u6e.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:n})}getBy(e){var n;if(this.by)if(this.by instanceof s6e.FieldName){if(e.isQueryFieldSpace()){const r=e.outputSpace(),i=this.by.getField(r);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,KW.expressionIsAnalytic)((n=i.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{const r=this.by.getExpression(e);return(0,KW.expressionIsAggregate)(r.expressionType)&&this.by.log("top by expression must be an aggregate"),r.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,i6e.compressExpr)(r.value)}}}};n3.Top=a6e,Object.defineProperty(J0,"__esModule",{value:!0}),J0.ReduceBuilder=J0.QuerySegmentBuilder=void 0;const XW=ne,l6e=Kr,c6e=Go,f6e=H0,JW=Rx,ZW=n3,x6e=Wo,d6e=Ds;class eV{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof d6e.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof c6e.Filter){const n=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(n))}else e instanceof ZW.Top?(this.limit?e.log("Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.log("Query operation is already sorted"):this.order=e)):e instanceof f6e.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof JW.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,n){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?n.orderBy=e.orderBy:e.by&&(n.by=e.by)),!this.limit&&e.limit&&(n.limit=e.limit)),this.limit&&(n.limit=this.limit),this.order instanceof ZW.Top){const i=this.order.getBy(this.inputFS);i&&(n.by=i)}this.order instanceof JW.Ordering&&(n.orderBy=this.order.getOrderBy(this.inputFS));const r=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!r?n.filterList=this.filters:r&&(n.filterList=[...r,...this.filters])}}J0.QuerySegmentBuilder=eV;class h6e extends eV{constructor(e,n,r,i){super(),this.type="grouping",this.resultFS=new x6e.ReduceFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let n;if(e)if((0,XW.isReduceSegment)(e)||(0,XW.isPartialSegment)(e))n=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),l6e.ErrorFactory.reduceSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}J0.ReduceBuilder=h6e,Object.defineProperty(t5,"__esModule",{value:!0}),t5.ProjectBuilder=void 0;const tV=ne,p6e=Kr,g6e=t3,m6e=n5,y6e=J0;class E6e extends y6e.QuerySegmentBuilder{constructor(e,n,r,i){super(),this.type="project",this.resultFS=new m6e.ProjectFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof g6e.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let n;if(e)if((0,tV.isProjectSegment)(e)||(0,tV.isPartialSegment)(e))n=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),p6e.ErrorFactory.projectSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}t5.ProjectBuilder=E6e;var r5={};Object.defineProperty(r5,"__esModule",{value:!0}),r5.PartialBuilder=void 0;const A6e=Fu,v6e=J0;class S6e extends v6e.ReduceBuilder{finalize(e){const n=super.finalize(e);if((0,A6e.isQuerySegment)(n))return{...n,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${n.type}`)}}r5.PartialBuilder=S6e,Object.defineProperty(Jm,"__esModule",{value:!0}),Jm.QOpDesc=void 0;const _6e=Z_,C6e=t5,b6e=J0,T6e=Ve,R6e=Fs,O6e=Xr,Ox=Rn,N6e=r5;class D6e extends T6e.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let n,r=!1;this.refineThis&&(this.refineThis.type==="reduce"?n=Ox.QueryClass.Grouping:this.refineThis.type==="project"?n=Ox.QueryClass.Project:this.refineThis.type==="index"&&(n=Ox.QueryClass.Index));for(const i of this.list)i.forceQueryClass&&(n?n!==i.forceQueryClass&&i.log(`Not legal in ${n} query`):n=i.forceQueryClass),r||(r=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return n===void 0&&r&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),n=Ox.QueryClass.Project),this.opClass=n,n}refineFrom(e){this.refineThis=e}getBuilder(e,n,r){switch(this.computeType()){case Ox.QueryClass.Grouping:return new b6e.ReduceBuilder(e,this.refineThis,n,r);case Ox.QueryClass.Project:return new C6e.ProjectBuilder(e,this.refineThis,n,r);case Ox.QueryClass.Index:return new _6e.IndexBuilder(e,this.refineThis,n,r);case void 0:return new N6e.PartialBuilder(e,this.refineThis,n,r)}}getOp(e,n){const r=this.getBuilder(e,n,this);for(const s of this.list)r.execute(s);const i=r.finalize(this.refineThis);return{segment:i,outputSpace:()=>new O6e.StaticSpace((0,R6e.opOutputStruct)(this,e.structDef(),i))}}}Jm.QOpDesc=D6e,Object.defineProperty(J_,"__esModule",{value:!0}),J_.QOpDescView=void 0;const F6e=ne,w6e=Xr,nV=Jm,L6e=Fs,cF=Rn,I6e=X0;class $6e extends I6e.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,n){const r=this.operation.getOp(e,n);return{pipeline:[r.segment],outputStruct:r.outputSpace().structDef()}}getOp(e,n,r,i){return(0,F6e.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(r.refineFrom(i),r.getOp(e,n).segment)}refine(e,n,r){const i=[...n];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,r,this.operation,i[0])];const s=new nV.QOpDesc([]),o=new nV.QOpDesc([]);for(const u of this.operation.list)switch(u.queryRefinementStage){case cF.LegalRefinementStage.Head:s.push(u);break;case cF.LegalRefinementStage.Single:u.log("Illegal in refinement of a query with more than one stage");break;case cF.LegalRefinementStage.Tail:o.push(u);break;default:u.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){const u=i.length-1;this.has({tailRefinements:o});const a=(0,L6e.getFinalStruct)(this,e.structDef(),i.slice(-1));i[u]=this.getOp(new w6e.StaticSpace(a),void 0,o,i[u])}return i}getImplicitName(){}}J_.QOpDescView=$6e;var mn={};Object.defineProperty(mn,"__esModule",{value:!0}),mn.FieldDefinitionValue=mn.DefSpace=mn.DimensionFieldDeclaration=mn.MeasureFieldDeclaration=mn.DeclareFieldDeclaration=mn.ProjectFieldDeclaration=mn.GroupByFieldDeclaration=mn.AggregateFieldDeclaration=mn.CalculateFieldDeclaration=mn.AtomicFieldDeclaration=void 0;const B6e=ne,k6e=hn,P6e=ln,M6e=d2,j6e=Ve,Nx=Zn,U6e=Vr,q6e=Yr;class Z0 extends j6e.MalloyElement{constructor(e,n,r){super({expr:e}),this.expr=e,this.defineName=n,this.exprSrc=r,this.isNoteableObj=!0,this.extendNote=U6e.extendNoteMethod}fieldDef(e,n){return this.queryFieldDef(new fF(e,this),n)}executesInOutputSpace(){return!1}queryFieldDef(e,n){let r;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const a=this.executesInOutputSpace()?i():e;r=this.expr.getExpression(a)}catch(a){return this.log(`Cannot define '${n}', ${a.message}`),{name:n,type:"error"}}const s=(0,k6e.compressExpr)(r.value);let o=r.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,B6e.isAtomicFieldType)(o)&&o!=="error"){const a={name:n,type:o,location:this.location};return s.length>0&&(a.e=s),r.expressionType&&(a.expressionType=r.expressionType),this.typecheckExprValue(r),this.exprSrc&&(a.code=this.exprSrc),(0,M6e.isGranularResult)(r)&&a.type==="timestamp"&&(a.timeframe=r.timeframe),this.note&&(a.annotation=this.note),a}if(!(e instanceof fF&&e.foundCircle)&&r.dataType!=="error"){const a=P6e.FT.inspect(r);this.log(`Cannot define '${n}', unexpected type: ${a}`)}return{name:n,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new rV(e,this))}}mn.AtomicFieldDeclaration=Z0;class H6e extends Z0{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}mn.CalculateFieldDeclaration=H6e;class z6e extends Z0{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckAggregate)(e,this)}}mn.AggregateFieldDeclaration=z6e;class Q6e extends Z0{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckGroupBy)(e,this)}}mn.GroupByFieldDeclaration=Q6e;class G6e extends Z0{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckProject)(e,this)}}mn.ProjectFieldDeclaration=G6e;class W6e extends Z0{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckDeclare)(e,this)}}mn.DeclareFieldDeclaration=W6e;class V6e extends Z0{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckMeasure)(e,this)}}mn.MeasureFieldDeclaration=V6e;class Y6e extends Z0{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckDimension)(e,this)}}mn.DimensionFieldDeclaration=Y6e;class fF{constructor(e,n){this.realFS=e,this.circular=n,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:`Circular reference to '${this.circular.defineName}' in definition`,found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}}mn.DefSpace=fF;class rV extends q6e.SpaceField{constructor(e,n){super(),this.space=e,this.exprDef=n,this.fieldName=n.defineName}get name(){return this.fieldName}fieldDef(){return this.haveFieldDef||(this.haveFieldDef=this.exprDef.fieldDef(this.space,this.name)),this.haveFieldDef}getQueryFieldDef(e){if(!this.qfd){const n=this.exprDef.queryFieldDef(e,this.name);this.qfd=n}return this.qfd}typeDesc(){const e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}}mn.FieldDefinitionValue=rV;var i5={};Object.defineProperty(i5,"__esModule",{value:!0}),i5.Aggregate=void 0;const K6e=Ds,iV=Rn;let X6e=class extends K6e.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=iV.LegalRefinementStage.Single,this.forceQueryClass=iV.QueryClass.Grouping}};i5.Aggregate=X6e;var s5={};Object.defineProperty(s5,"__esModule",{value:!0}),s5.Calculate=void 0;const J6e=Ds,Z6e=Rn;class eRe extends J6e.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=Z6e.LegalRefinementStage.Single}}s5.Calculate=eRe;var r3={};Object.defineProperty(r3,"__esModule",{value:!0}),r3.Dimensions=void 0;const tRe=$0;class nRe extends tRe.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}r3.Dimensions=nRe;var i3={};Object.defineProperty(i3,"__esModule",{value:!0}),i3.Measures=void 0;const rRe=$0;class iRe extends rRe.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}i3.Measures=iRe;var o5={};Object.defineProperty(o5,"__esModule",{value:!0}),o5.Nests=void 0;const sRe=Ds,sV=Rn;class oRe extends sRe.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=sV.LegalRefinementStage.Single,this.forceQueryClass=sV.QueryClass.Grouping}}o5.Nests=oRe;var u5={};Object.defineProperty(u5,"__esModule",{value:!0}),u5.ProjectStatement=void 0;const uRe=Ds,oV=Rn;class aRe extends uRe.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=oV.QueryClass.Project,this.queryRefinementStage=oV.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}u5.ProjectStatement=aRe;var ec={},El={};Object.defineProperty(El,"__esModule",{value:!0}),El.findReferences=El.deprecatedParseTableURI=El.constructTableKey=void 0;const lRe=dx,xF=Pn;function dF(t){const e=(0,xF.getStringIfShort)(t);if(e)return e;const n=[],r=t.string().sqlString();if(r){for(const i of(0,xF.getStringParts)(r))typeof i=="string"&&n.push(i);return n.join("")}return""}class cRe{constructor(e,n){this.trans=e,this.tokens=n,this.needTables={},this.needImports={}}registerTableReference(e,n,r){const i=uV(e,n);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:n,firstReference:r})}enterTableMethod(e){const n=(0,xF.getId)(e.connectionId()),r=dF(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(n,r,i)}enterTableFunction(e){const n=dF(e.tableURI()),{connectionName:r,tablePath:i}=aV(n),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const n=dF(e);this.needImports[n]||(this.needImports[n]=this.trans.rangeFromContext(e))}}function uV(t,e){return t===void 0?e:`${t}:${e}`}El.constructTableKey=uV;function aV(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,n,r]=e;return{connectionName:n,tablePath:r}}else return{tablePath:t}}El.deprecatedParseTableURI=aV;function fRe(t,e,n){const r=new cRe(t,e),i=r;return lRe.ParseTreeWalker.DEFAULT.walk(i,n),{tables:r.needTables,urls:r.needImports}}El.findReferences=fRe,Object.defineProperty(ec,"__esModule",{value:!0}),ec.TableFunctionSource=ec.TableMethodSource=ec.TableSource=void 0;const lV=El,xRe=Qo,cV=Kr;class hF extends xRe.Source{structDef(){var e,n,r;const i=this.getTableInfo();if(i===void 0)return cV.ErrorFactory.structDef;const{tablePath:s,connectionName:o}=i,u=(0,lV.constructTableKey)(o,s),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(u);let l=`Schema read failure for table '${s}' for connection '${o}'`;if(a){if(a.status==="present"){(n=this.document())===null||n===void 0||n.checkExperimentalDialect(this,a.value.dialect),a.value.location=this.location,a.value.fields.forEach(f=>{f.location=this.location});const c={...a.value,fields:a.value.fields.map(f=>({...f,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(c),c}a.status==="error"&&(l=a.message)}return this.log(l),cV.ErrorFactory.structDef}}ec.TableSource=hF;class dRe extends hF{constructor(e,n){super(),this.connectionName=e,this.tablePath=n,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}ec.TableMethodSource=dRe;class hRe extends hF{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,lV.deprecatedParseTableURI)(this.tableURI)}}ec.TableFunctionSource=hRe;var a5={};Object.defineProperty(a5,"__esModule",{value:!0}),a5.SQLString=void 0;const pRe=Ve,fV=Ju;class gRe extends pRe.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(mRe)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof fV.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.log("This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const n of this.elements)if(typeof n=="string")e.push({sql:n});else{const r=n.getQuery();r?e.push(r.query()):n.sqLog("Cannot expand into a query")}return e}}a5.SQLString=gRe;function mRe(t){return t instanceof fV.SourceQueryElement}var l5={};Object.defineProperty(l5,"__esModule",{value:!0}),l5.SourceDesc=void 0;const yRe=Ve;class ERe extends yRe.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}l5.SourceDesc=ERe;var c5={};Object.defineProperty(c5,"__esModule",{value:!0}),c5.isSourceProperty=void 0;const ARe=Go,vRe=rs,SRe=$0,_Re=s2,CRe=k0,bRe=o2,TRe=u2,RRe=a2,ORe=B0;function NRe(t){return t instanceof ARe.Filter||t instanceof vRe.Joins||t instanceof SRe.DeclareFields||t instanceof _Re.FieldListEdit||t instanceof CRe.Renames||t instanceof bRe.PrimaryKey||t instanceof ORe.ObjectAnnotation||t instanceof TRe.Views||t instanceof RRe.TimezoneStatement}c5.isSourceProperty=NRe;var f5={};Object.defineProperty(f5,"__esModule",{value:!0}),f5.isFieldCollectionMember=void 0;const DRe=mn,xV=mt;function FRe(t){return t instanceof xV.FieldReference||t instanceof xV.WildcardFieldReference||t instanceof DRe.AtomicFieldDeclaration}f5.isFieldCollectionMember=FRe;var x5={};Object.defineProperty(x5,"__esModule",{value:!0}),x5.isQueryElement=void 0;const wRe=l2,LRe=c2,IRe=bm,$Re=Tm;function BRe(t){return t instanceof wRe.QueryArrow||t instanceof LRe.QueryRefine||t instanceof IRe.QueryReference||t instanceof $Re.QueryRaw}x5.isQueryElement=BRe;var dV={};Object.defineProperty(dV,"__esModule",{value:!0});var d5={};Object.defineProperty(d5,"__esModule",{value:!0}),d5.isQueryProperty=void 0;function kRe(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}d5.isQueryProperty=kRe;var h5={};Object.defineProperty(h5,"__esModule",{value:!0}),h5.isQueryExtendProperty=void 0;const PRe=r3,MRe=rs,jRe=i3;function URe(t){return t instanceof PRe.Dimensions||t instanceof jRe.Measures||t instanceof MRe.Joins}h5.isQueryExtendProperty=URe;var p5={};Object.defineProperty(p5,"__esModule",{value:!0}),p5.isFieldPropStatement=void 0;const qRe=U0,HRe=Go,zRe=H0,QRe=E2;function GRe(t){return t instanceof HRe.Filter||t instanceof zRe.Limit||t instanceof QRe.PartitionBy||t instanceof qRe.FunctionOrdering}p5.isFieldPropStatement=GRe,function(t){var e=N&&N.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=N&&N.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(fm,t),n(n2,t),n(r2,t),n(Qo,t),n(Em,t),n(Ju,t),n(U4,t),n(q4,t),n(G4,t),n(Cm,t),n(Y4,t),n(s2,t),n(o2,t),n(k0,t),n(u2,t),n(a2,t),n(K4,t),n(g2,t),n(Z4,t),n(U0,t),n(e_,t),n(gl,t),n(t_,t),n(y2,t),n(n_,t),n(r_,t),n(i_,t),n(Om,t),n(s_,t),n(o_,t),n(a_,t),n(Im,t),n(Fm,t),n(m2,t),n(l_,t),n(c_,t),n(x_,t),n(h_,t),n(p_,t),n(g_,t),n(m_,t),n(y_,t),n(E_,t),n(A_,t),n(v_,t),n(S_,t),n(__,t),n(C_,t),n(b_,t),n(O_,t),n(pr,t),n(z_,t),n(E2,t),n(O2,t),n(j0,t),n(G_,t),n(W_,t),n($m,t),n(hn,t),n(K0,t),n(Km,t),n(ym,t),n(V_,t),n(c2,t),n(l2,t),n(X0,t),n(Y_,t),n(K_,t),n(X_,t),n(J_,t),n(mn,t),n(mt,t),n(i5,t),n(s5,t),n($0,t),n(r3,t),n(Km,t),n(Go,t),n(t3,t),n(Zm,t),n(rs,t),n(xm,t),n(H0,t),n(i3,t),n(fm,t),n(o5,t),n(Rx,t),n(u5,t),n(Jm,t),n(e3,t),n(n3,t),n(P0,t),n(gx,t),n(Rm,t),n(ec,t),n(a5,t),n(B0,t),n(M0,t),n(l5,t),n(c5,t),n(pt,t),n(f5,t),n(Ax,t),n(Ve,t),n(x5,t),n(dV,t),n(d5,t),n(h5,t),n(p5,t)}(T4);var g5={},WRe=N&&N.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),VRe=N&&N.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),YRe=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&WRe(e,t,n);return VRe(e,t),e};Object.defineProperty(g5,"__esModule",{value:!0}),g5.MalloyToAST=void 0;const hV=Lv,KRe=dm,re=YRe(T4),XRe=xr,JRe=T4,Qn=Pn,pF=ne,ZRe=dl;class pV extends re.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class gF extends re.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const eOe=["##! m4warnings=error"];class tOe extends KRe.AbstractParseTreeVisitor{constructor(e,n,r){super(),this.parseInfo=e,this.msgLog=n,this.compilerFlags=r;for(const i of eOe){const s=ZRe.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,n){const r=`Internal Translator Error: ${n}`;return this.contextError(e,r),new Error(r)}astError(e,n,r="error"){this.msgLog.log({message:n,at:e.location,severity:r})}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}contextError(e,n,r="error"){this.msgLog.log({message:n,at:this.getLocation(e),severity:r})}inExperiment(e,n){const r=this.compilerFlags.tag("experimental");return r&&(r.bare()||r.has(e))?!0:(this.contextError(n,`Experimental flag '${e}' required to enable this feature`),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,n){const r=this.m4Severity();r&&this.contextError(e,n,r)}only(e,n,r){const i=[];for(const s of e){const o=n(s);o?i.push(o):s instanceof gF||this.astError(s,`Parser enountered unexpected statement type '${s.elementType}' when it needed '${r}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new re.FieldName((0,Qn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new re.ModelEntryReference((0,Qn.getId)(e)),e.id())}defaultResult(){return new re.Unimplemented}astAt(e,n){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(n)},e}getSourceCode(e){const n=e.start.startIndex,r=e.stop||e.start,i=new XRe.Interval(n,r.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){const n=this.getFieldExpr(e),r=new re.FilterElement(n,this.getSourceCode(e));return this.astAt(r,e)}getFieldDefs(e,n){return e.map(r=>this.getFieldDef(r,n))}getFieldExpr(e){const n=this.visit(e);if(n instanceof re.ExpressionDef)return this.astAt(n,e);throw this.internalError(e,`expression node unknown type '${n.elementType}'`)}getFilterShortcut(e){const n=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new re.Filter([n])}getPlainString(e){const n=(0,Qn.getStringIfShort)(e);if(n)return n;const r=[],i=e.string().sqlString();if(i){for(const s of(0,Qn.getStringParts)(i))s instanceof hV.ParserRuleContext?this.contextError(s,"%{ query } illegal in this string"):r.push(s);return(0,Qn.unIndent)(r),r.join("")}return""}makeSqlString(e,n){for(const r of e.sqlInterpolation())r.CLOSE_CODE()&&this.m4advisory(r,"Use %{ ... } instead of %{ ... }%");for(const r of(0,Qn.getStringParts)(e))r instanceof hV.ParserRuleContext?n.push(this.visit(r)):n.push(r);n.complete(),this.astAt(n,e)}parseTime(e,n){let r=n(e.text);return r||(this.contextError(e,"Time data parse error"),r=new re.LiteralTimestamp({text:e.text})),this.astAt(r,e)}getNotes(e){return e.ANNOTATION().map(n=>({text:n.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const n=this.only(e.malloyStatement().map(r=>this.visit(r)),r=>re.isDocStatementOrDocStatementList(r)&&r,"statement");return new re.Document(n)}visitDefineSourceStatement(e){const r=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new re.DefineSourceList(r);return s.extendNote({blockNotes:i}),s}visitSourceDefinition(e){const n=this.visit(e.sqExplore()),r=new re.DefineSource((0,Qn.getId)(e.sourceNameDef()),n instanceof re.SourceQueryElement?n:void 0,!0,[]),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return r.extendNote({notes:i}),this.astAt(r,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const n=e.filterShortcut(),r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>re.isSourceProperty(s)&&s,"source property"),i=new re.SourceDesc(r);return n&&i.push(this.getFilterShortcut(n)),i}visitTableFunction(e){const n=this.getPlainString(e.tableURI()),r=this.astAt(new re.TableFunctionSource(n),e);return this.m4advisory(e,"`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),r}visitTableMethod(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=this.getPlainString(e.tablePath());return this.astAt(new re.TableMethodSource(r,i),e)}visitSqlSource(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=new re.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);const o=e.shortString();o&&i.push((0,Qn.getShortString)(o));const u=new re.SQLSource(r,i);return this.astAt(u,e)}visitDefJoinMany(e){const n=[];for(const i of e.joinList().joinDef()){const s=this.visit(i);s instanceof re.Join&&(n.push(s),s instanceof re.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof re.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}const r=new re.Joins(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitDefJoinOne(e){const n=this.getJoinList(e.joinList()),r=[];for(const s of n)s instanceof re.Join&&(r.push(s),s instanceof re.ExpressionJoin&&(s.joinType="one"));const i=new re.Joins(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinCross(e){const n=this.getJoinList(e.joinList()),r=[];for(const s of n)s instanceof re.Join&&(r.push(s),s instanceof re.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));const i=new re.Joins(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return e.joinDef().map(n=>this.visit(n))}getJoinSource(e,n){if(n){const r=this.getSqExpr(n.sqExpr()),i=this.getNotes(n._before_is).concat(this.getNotes(n._after_is));return{joinFrom:r,notes:i}}return{joinFrom:new re.SQReference(e),notes:[]}}visitQueryJoinStatement(e){const n=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"Joins in queries are deprecated, move into an `extend:` block."),n}visitJoinOn(e){var n;const r=this.getModelEntryName(e.joinNameDef()),{joinFrom:i,notes:s}=this.getJoinSource(r,e.isExplore()),o=new re.ExpressionJoin(r,i),u=e.joinExpression(),a=((n=e.matrixOperation())===null||n===void 0?void 0:n.text.toLocaleLowerCase())||"left";return(0,pF.isMatrixOperation)(a)?o.matrixOperation=a:this.contextError(e,"Internal Error: Unknown matrixOperation"),u&&(o.joinOn=this.getFieldExpr(u)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){const n=this.getModelEntryName(e.joinNameDef()),{joinFrom:r,notes:i}=this.getJoinSource(n,e.isExplore()),s=this.getFieldExpr(e.fieldExpr()),o=new re.KeyJoin(n,r,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,n){const r=e.fieldExpr(),i=(0,Qn.getId)(e.fieldNameDef()),s=this.getFieldExpr(r),o=new n(s,i,this.getSourceCode(r)),u=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:u}),this.astAt(o,e)}visitDefDimensions(e){const n=this.getFieldDefs(e.defList().fieldDef(),re.DimensionFieldDeclaration),r=new re.Dimensions(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitDefMeasures(e){const n=this.getFieldDefs(e.defList().fieldDef(),re.MeasureFieldDeclaration),r=new re.Measures(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitQueryExtend(e){const n=[],r=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(const s of r)if(re.isQueryExtendProperty(s))n.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);const i=new re.ExtendBlock(n);return this.astAt(i,e)}visitDeclareStatement(e){const n=this.getFieldDefs(e.defList().fieldDef(),re.DeclareFieldDeclaration),r=new re.DeclareFields(n),i=this.astAt(r,e);return this.m4advisory(e,"`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),i}visitExploreRenameDef(e){const n=e.fieldName(0),r=e.fieldName(1),i=new re.RenameField((0,Qn.getId)(n),this.getFieldName(r));return this.astAt(i,e)}visitDefExploreRename(e){const r=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new re.Renames(r);return this.astAt(i,e)}visitFilterClauseList(e){return new re.Filter(e.fieldExpr().map(n=>this.getFilterElement(n)))}visitWhereStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!1,this.astAt(n,e)}visitHavingStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!0,this.astAt(n,e)}visitSubQueryDefList(e){const n=e.exploreQueryDef().map(r=>this.visitExploreQueryDef(r));return new re.Views(n)}visitDefExploreQuery(e){const n=this.visitSubQueryDefList(e.subQueryDefList()),r=this.getNotes(e.tags());return n.extendNote({blockNotes:r}),e.QUERY()&&this.m4advisory(e,"Use view: inside of a source instead of query:"),n}visitDefExplorePrimaryKey(e){const n=new re.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(n,e)}visitFieldNameList(e){const n=e.fieldName().map(r=>new re.AcceptExceptFieldReference([this.getFieldName(r)]));return new re.FieldReferences(n)}visitDefExploreEditField(e){const n=e.ACCEPT()?"accept":"except";return new re.FieldListEdit(n,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const n=this.getPlainString(e),r=this.astAt(new re.TimezoneStatement(n),e.string());return r.isValid||this.astError(r,`Invalid timezone: ${r.tz}`),this.astAt(r,e)}visitQueryProperties(e){const n=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>re.isQueryProperty(i)&&i,"query statement"),r=e.filterShortcut();return r&&n.push(this.getFilterShortcut(r)),new re.QOpDesc(n)}getFieldPath(e,n){const r=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new n(r),e)}getQueryFieldDef(e,n){const r=this.getFieldDef(e,n);return this.astAt(r,e)}getQueryFieldEntry(e,n,r){const i=e.taggedRef();if(i)return this.getTaggedRef(i,n,r);const s=e.fieldDef();if(s)return this.getQueryFieldDef(s,n);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,n,r){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,n,r)),i=>i instanceof re.FieldReference||i instanceof re.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){const n=new re.Aggregate(this.getQueryItems(e.queryFieldList(),re.AggregateFieldDeclaration,re.AggregateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitGroupByStatement(e){const n=new re.GroupBy(this.getQueryItems(e.queryFieldList(),re.GroupByFieldDeclaration,re.GroupByFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCalculateStatement(e){const n=new re.Calculate(this.getQueryItems(e.queryFieldList(),re.CalculateFieldDeclaration,re.CalculateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}getTaggedRef(e,n,r){const i=e.refExpr();if(i){const o=this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference);let u;const a=i.timeframe();a&&(u=new re.ExprGranularTime(new re.ExprIdReference(o),this.visitTimeframe(a).text,!0));const l=i.aggregate();if(l){const f=l.text.toLowerCase();if(f==="sum")u=new re.ExprSum(void 0,o);else return this.contextError(l,`\`${f}\` is not legal in a reference-only aggregation`),o}const c=new n(u,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}const s=this.getFieldPath(e.fieldPath(),r);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,n,r){const i=e.fieldDef();if(i)return this.getFieldDef(i,n);const s=e.taggedRef();if(s)return this.getTaggedRef(s,n,r);const o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const n=e.collectionMember().map(r=>this.getFieldCollectionMember(r,re.ProjectFieldDeclaration,re.ProjectFieldReference));return this.astAt(new re.ProjectStatement(n),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project: keyword is deprecated, use select:");const n=this.visitFieldCollection(e.fieldCollection());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCollectionWildCard(e){var n;const r=e.fieldPath(),i=r?this.getFieldPath(r,re.ProjectFieldReference):void 0,s=this.astAt(new re.WildcardFieldReference(i),e),o=((n=e.starQualified())===null||n===void 0?void 0:n.fieldNameList())||[];for(const u of o)for(const a of u.fieldName())s.except.add((0,Qn.getId)(a));return s}visitIndexFields(e){const n=e.indexElement().map(r=>{const i=r.fieldPath();if(!i)return this.astAt(new re.WildcardFieldReference(void 0),e);const s=this.getFieldPath(i,re.IndexFieldReference);return r.STAR()?this.astAt(new re.WildcardFieldReference(s),e):this.astAt(s,e)});return new re.FieldReferences(n)}visitIndexStatement(e){const n=this.visitIndexFields(e.indexFields()),r=new re.Index(n),i=e.fieldName();return i&&r.useWeight(this.getFieldName(i)),this.astAt(r,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new re.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0;return this.astAt(new re.FunctionOrderBy(i,n),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const n=e.aggregateOrderBySpec().map(r=>this.visitAggregateOrderBySpec(r));return this.astAt(new re.FunctionOrdering(n),e)}visitOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.INTEGER_LITERAL();if(r)return new re.OrderBy(this.getNumber(r),n);const i=e.fieldName();if(i)return new re.OrderBy(this.getFieldName(i),n);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const n=e.orderBySpec().map(r=>this.visitOrderBySpec(r));return this.astAt(new re.Ordering(n),e)}visitTopStatement(e){const n=e.bySpec(),r=this.getNumber(e.INTEGER_LITERAL());let i;if(n){this.m4advisory(n,"by clause of top statement unupported. Use order_by instead");const s=n.fieldName();if(s){const u=this.getFieldName(s);i=new re.Top(r,u)}const o=n.fieldExpr();o&&(i=new re.Top(r,this.getFieldExpr(o)))}return i||(i=new re.Top(r,void 0)),this.astAt(i,e)}visitSourceID(e){return this.astAt(new re.NamedSource((0,Qn.getId)(e)),e)}visitTopLevelQueryDefs(e){const n=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),r=this.getNotes(e.tags()),i=new re.DefineQueryList(n);return i.extendNote({blockNotes:r}),i}visitTopLevelQueryDef(e){const n=(0,Qn.getId)(e.queryName()),r=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(r instanceof re.SourceQueryElement){const s=new re.DefineQuery(n,r);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${r.elementType}'`)}visitAnonymousQuery(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new re.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(n,"Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new re.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){const n=this.visitNestedQueryList(e.nestedQueryList());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitNestedQueryList(e){return new re.Nests(this.only(e.nestEntry().map(n=>this.visit(n)),n=>n instanceof re.NestFieldDeclaration&&n,"query"))}visitNestDef(e){const n=e.queryName();let r;const i=this.getVExpr(e.vExpr());if(n)r=(0,Qn.getId)(n);else{const u=i.getImplicitName();u===void 0&&this.contextError(e,"`nest:` view requires a name (add `nest_name is ...`)"),r=u??"__unnamed__"}const s=new re.NestFieldDeclaration(r,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){const n=(0,Qn.getId)(e.exploreQueryNameDef()),r=new re.ViewFieldDeclaration(n,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return r.extendNote({notes:i}),this.astAt(r,e)}visitExprNot(e){return new re.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new re.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(n=>this.getFieldExpr(n))}visitExprLogicalOr(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(n,"or",r)}visitExprLogicalAnd(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(n,"and",r)}visitExprOrTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(n,"|",r),e)}visitExprAndTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(n,"&",r),e)}visitExprCoalesce(e){const n=this.getFieldExpr(e.fieldExpr()[0]),r=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new re.ExprCoalesce(n,r),e)}visitPartialAllowedFieldExpr(e){var n;const r=this.getFieldExpr(e.fieldExpr()),i=(n=e.compareOp())===null||n===void 0?void 0:n.text;if(i){if(re.isComparison(i))return this.astAt(new re.PartialCompare(i,r),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return r}visitExprString(e){const n=this.getPlainString(e);return new re.ExprString(n)}visitExprRegex(e){const n=e.HACKY_REGEX().text;return new re.ExprRegEx(n.slice(2,-1))}visitExprNow(e){return new re.ExprNow}visitExprNumber(e){return new re.ExprNumber(e.text)}visitExprFieldPath(e){const n=new re.ExprIdReference(this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference));return this.astAt(n,e)}visitExprNULL(e){return new re.ExprNULL}visitExprExpr(e){return new re.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new re.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new re.ExprAddSub(n,i,r)}visitExprMulDiv(e){const n=e.STAR()?"*":e.SLASH()?"/":"%";return new re.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const n=e.compareOp().text;if(re.isComparison(n))return new re.ExprCompare(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)));throw this.internalError(e,`untranslatable comparison operator '${n}'`)}visitExprCountDisinct(e){return this.m4advisory(e,"`count(distinct expression)` deprecated, use `count(expression)` instead"),this.astAt(new re.ExprCountDistinct(this.getFieldExpr(e.fieldExpr())),e)}visitExprUngroup(e){const n=e.fieldName().map(i=>this.getFieldName(i)),r=e.ungroup().text.toLowerCase();return this.astAt(new re.ExprUngroup(r==="all"?r:"exclude",this.getFieldExpr(e.fieldExpr()),n),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const n=e.fieldPath(),r=this.getFieldPath(n,re.ExpressionFieldReference),i=n&&r?this.astAt(r,n):void 0,s=e.aggregate().text.toLowerCase(),o=e.fieldExpr();if(e.aggregate().COUNT())return o&&this.contextError(o,"Expression illegal inside path.count()"),new re.ExprCount(i);const u=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(u)this.contextError(e,this.symmetricAggregateUsageError(s));else{const a=this.astAt(new re.ExprIdReference(r),n);return s==="min"?new re.ExprMin(a):new re.ExprMax(a)}else{if(s==="avg")return new re.ExprAvg(u,i);if(s==="sum")return new re.ExprSum(u,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new re.ExprNULL}visitExprPathlessAggregate(e){const n=e.fieldExpr(),r=n?this.getFieldExpr(n):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,`* illegal inside ${s}()`),s==="count")return this.astAt(r?new re.ExprCountDistinct(r):new re.ExprCount,e);if(s==="min"){if(r)return new re.ExprMin(r);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(r)return new re.ExprMax(r);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(r===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new re.ExprNULL;const o=e.SOURCE_KW()!==void 0;if(s==="avg")return new re.ExprAvg(r,i,o);if(s==="sum")return new re.ExprSum(r,i,o)}return new re.ExprNULL}visitExprApply(e){return new re.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new re.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new re.ExprCast(this.getFieldExpr(e.fieldExpr()),n)}getMalloyOrSQLType(e){const n=e.malloyType();if(n){const i=n.text;if((0,pF.isCastType)(i))return i;throw this.internalError(e,`unknown type '${i}'`)}const r=e.string();if(r)return{raw:this.getPlainString({string:()=>r})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new re.ExprCast(this.getFieldExpr(e.fieldExpr()),n,!0)}visitExprTimeTrunc(e){return new re.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new re.Timeframe(e.text)}visitExprForRange(e){const n=this.getFieldExpr(e._startAt),r=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new re.ForRange(n,r,i)}visitExprAggFunc(e){const n=e.argumentList(),r=n?this.allFieldExpressions(n.fieldExpr()):[],i=(0,Qn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,re.ExpressionFieldReference):void 0,u=s&&o?this.astAt(o,s):void 0;return re.ExprTimeExtract.extractor(i)?this.astAt(new re.ExprTimeExtract(i,r),e):this.astAt(new re.ExprFunc(i,r,!1,void 0,u),e)}visitExprFunc(e){var n,r;const i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,u=(n=e.malloyType())===null||n===void 0?void 0:n.text;let a;u&&((0,pF.isCastType)(u)?a=u:(this.contextError(e,`'#' assertion for unknown type '${u}'`),a=void 0));let l=(0,Qn.getOptionalId)(e)||((r=e.timeframe())===null||r===void 0?void 0:r.text);return l===void 0&&(this.contextError(e,"Function name error"),l="FUNCTION_NAME_ERROR"),re.ExprTimeExtract.extractor(l)?this.astAt(new re.ExprTimeExtract(l,s),e):this.astAt(new re.ExprFunc(l,s,o,a),e)}visitExprDuration(e){return new re.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitPickStatement(e){const n=e.pick().map(r=>{let i;return r._pickValue&&(i=this.getFieldExpr(r._pickValue)),new re.PickWhen(i,this.getFieldExpr(r._pickWhen))});return e.ELSE()?new re.Pick(n,this.getFieldExpr(e._pickElse)):new re.Pick(n)}visitExprFieldProps(e){const n=this.only(e.fieldProperties().fieldPropertyStatement().map(r=>this.visit(r)),r=>re.isFieldPropStatement(r)&&r,"field property statement");return new re.ExprProps(this.getFieldExpr(e.fieldExpr()),n)}visitPartitionByStatement(e){return this.astAt(new re.PartitionBy(e.id().map(n=>this.astAt(new re.PartitionByFieldReference([this.astAt(new re.FieldName((0,Qn.idToStr)(n)),n)]),n))),e)}visitLiteralTimestamp(e){return this.parseTime(e,re.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,re.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,re.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,re.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,re.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,re.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,re.LiteralYear.parse)}visitImportStatement(e){const n=this.getPlainString(e.importURL()),r=this.astAt(new re.ImportStatement(n,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(const s of i.importItem()){const o=s.id(),u=o[1]?this.astAt(new re.ImportSourceName((0,Qn.idToStr)(o[1])),o[1]):void 0;r.push(this.astAt(new re.ImportSelect((0,Qn.idToStr)(o[0]),u),o[0]))}return r}visitJustExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const n=e.sampleSpec().INTEGER_LITERAL();if(n)return new re.SampleProperty({rows:this.getNumber(n)});const r=e.sampleSpec().PERCENT_LITERAL();if(r)return new re.SampleProperty({percent:this.getNumber(r)});const i=e.sampleSpec().TRUE()!==void 0;return new re.SampleProperty({enable:i})}visitDocAnnotations(e){const n=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),r=new re.ModelAnnotation(n);return this.compilerFlags=r.getCompilerFlags(this.compilerFlags,this.msgLog),r}visitIgnoredObjectAnnotations(e){return this.contextError(e,"Object annotation not connected to any object"),new gF(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new gF(e.text)}visitDefExploreAnnotation(e){const n=this.getNotes(e);return new re.ObjectAnnotation(n)}visitSQID(e){const n=this.getModelEntryName(e);return this.astAt(new re.SQReference(n),e.id())}getSqExpr(e){const n=this.visit(e);return n instanceof re.SourceQueryElement?n:(this.contextError(e,`Expected a source/query expression, not '${n.elementType}'`),new pV)}visitSQExtendedSource(e){const n=this.getSqExpr(e.sqExpr()),r=new re.SQExtend(n,this.getSourceExtensions(e.exploreProperties()));return this.astAt(r,e)}visitSQParens(e){const n=this.getSqExpr(e.sqExpr());return this.astAt(n,e)}visitSQArrow(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new re.SQArrow(n,this.getVExpr(r));return this.astAt(i,e)}getVExpr(e){const n=this.visit(e);if(n instanceof re.View)return n;throw this.internalError(e,`Expected view, got a '${n.elementType}'`)}visitSegField(e){return new re.ReferenceView(this.getFieldPath(e.fieldPath(),re.ViewOrScalarFieldReference))}visitSegOps(e){return new re.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new re.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new re.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new re.SQRefine(n,this.getVExpr(r));return this.astAt(i,e)}visitSQTable(e){const n=this.visit(e.exploreTable());if(n instanceof JRe.TableSource){const r=new re.SQSource(n);return this.astAt(r,e)}return new pV}visitSQSQL(e){const n=new re.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(n,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new re.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}}g5.MalloyToAST=tOe;var m5={};Object.defineProperty(m5,"__esModule",{value:!0}),m5.MessageLog=void 0;class nOe{constructor(){this.rawLog=[]}getLog(){return this.rawLog}log(e){this.rawLog.push(e)}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(n=>n.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}}m5.MessageLog=nOe;var y5={};Object.defineProperty(y5,"__esModule",{value:!0}),y5.Zone=void 0;class rOe{constructor(){this.location={},this.zone=new Map}get(e){const n=this.zone.get(e);if((n==null?void 0:n.status)==="present")return n.value}getEntry(e){const n=this.zone.get(e);return n?n.firstReference||!this.location[e]?n:{...n,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,n){this.zone.set(e,{status:"present",value:n})}reference(e,n){const r=this.zone.get(e);(r==null?void 0:r.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:n}),this.location[e]=n)}getUndefined(){const e=[];for(const[n,r]of this.zone)r.status==="reference"&&e.push(n);return e.length>0?e:void 0}updateFrom(e,n){if(e)for(const[r,i]of Object.entries(e))i!==void 0&&this.define(r,i);if(n)for(const[r,i]of Object.entries(n))this.zone.set(r,{status:"error",message:i})}}y5.Zone=rOe;var E5={};Object.defineProperty(E5,"__esModule",{value:!0}),E5.walkForDocumentSymbols=void 0;const iOe=dx,sOe=Pn;class oOe{constructor(e,n,r,i){this.translator=e,this.tokens=n,this.scopes=r,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const n=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=n)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const n=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=n)}enterSourceDefinition(e){const n=this.translator.rangeFromContext(e);this.scopes.push({range:n,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const n=this.popScope();n&&this.symbols.push(n)}enterDefExploreQuery(e){const n=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=n)}enterExploreQueryDef(e){const n={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},r=this.peekScope();r&&r.children.push(n),this.scopes.push(n),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const n=e.queryName();if(n)return n.id().text;let r,i=!1;const s={enterVArrow(u){u.vExpr().enterRule(s)},enterVSeg(u){u.segExpr().enterRule(o)}},o={enterSegField(u){const a=u.fieldPath().fieldName();i||(r??(r=a[a.length-1].id().text))},enterSegParen(u){u.vExpr().enterRule(s)},enterSegRefine(u){u._lhs.enterRule(o)},enterSegOps(){r=void 0,i=!0}};return e.vExpr().enterRule(s),r}handleNestEntry(e){const n=this.getNestDefName(e);if(n===void 0)return;const r={range:this.translator.rangeFromContext(e),name:n,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(r),r}enterNestDef(e){const n=this.handleNestEntry(e);n&&this.scopes.push(n)}exitNestDef(e){this.popScope()}enterFieldDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterQueryFieldEntry(e){var n;const r=(n=e.taggedRef())===null||n===void 0?void 0:n.fieldPath();if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const n={range:this.translator.rangeFromContext(e),name:e.joinNameDef().id().text,type:"join",children:[]},r=this.peekScope();r&&r.children.push(n)}enterImportStatement(e){const n=(0,sOe.getStringIfShort)(e.importURL());n&&this.scopes.push({range:this.translator.rangeFromContext(e),name:n,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const n=this.peekScope();if(n)for(const r of e.importItem()){const i={range:this.translator.rangeFromContext(e),name:r.text,type:"import_item",children:[]};n.children.push(i)}}}function uOe(t,e,n){const r=new oOe(t,e,[],[]),i=r;return iOe.ParseTreeWalker.DEFAULT.walk(i,n),r.symbols}E5.walkForDocumentSymbols=uOe;var A5={};Object.defineProperty(A5,"__esModule",{value:!0}),A5.walkForDocumentCompletions=void 0;const aOe=dx,lOe=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],cOe=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],fOe=["source","explore","query","sql"];class xOe{constructor(e,n,r){this.tokens=e,this.completions=n,this.position=r}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){const{start:n,end:r}=e,i=this.position.line>n.line||this.position.line===n.line&&this.position.character>=n.character,s=this.position.line<r.line||this.position.line===r.line&&this.position.character<=r.character;return i&&s}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.exploreStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of lOe)this.completions.push({type:"explore_property",text:`${r}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.queryStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of cOe)this.completions.push({type:"query_property",text:`${r}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.malloyStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of fOe)this.completions.push({type:"model_property",text:`${r}: `})}}}function dOe(t,e,n){const r=new xOe(t,[],n),i=r;return aOe.ParseTreeWalker.DEFAULT.walk(i,e),r.completions}A5.walkForDocumentCompletions=dOe;var v5={};Object.defineProperty(v5,"__esModule",{value:!0}),v5.walkForDocumentHelpContext=void 0;const hOe=K7;class pOe extends hOe.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let n=this.defaultResult();if(this.inRange(this.rangeOf(e))){n={type:this.type,token:e.start.text};const r=e.childCount;for(let i=0;i<r;i++){const o=e.getChild(i).accept(this);o&&(n=this.aggregateResult(n,o))}}return n}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,n){return n}}function gOe(t,e){return new pOe(e).visit(t)}v5.walkForDocumentHelpContext=gOe;var S5={},s3={};Object.defineProperty(s3,"__esModule",{value:!0}),s3.locationContainsPosition=void 0;function mOe(t,e){return t.range.start.line<=e.line&&t.range.end.line>=e.line&&(e.line!==t.range.start.line||e.character>=t.range.start.character)&&(e.line!==t.range.end.line||e.character<=t.range.end.character)}s3.locationContainsPosition=mOe,Object.defineProperty(S5,"__esModule",{value:!0}),S5.ReferenceList=void 0;const yOe=s3;class EOe{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let n=0,r=this.references.length;for(;n<r;){const i=Math.floor((n+r)/2),s=this.references[i].location.range.end;s.line<e.line||s.line===e.line&&s.character<e.character?n=i+1:r=i}return n}add(e){if(e.location.url!==this.sourceURL)return;const n=this.findIndexBefore(e.location.range.end);n<this.references.length&&this.isPositionEqual(e,this.references[n])||this.references.splice(n,0,e)}isPositionEqual(e,n){const r=e.location.range,i=n.location.range;return r.start.line===i.start.line&&r.start.character===i.start.character&&r.end.line===i.end.line&&r.end.character===i.end.character}find(e){const n=this.findIndexBefore(e);if(n===this.references.length)return;const r=this.references[n];if((0,yOe.locationContainsPosition)(r.location,e))return r}}S5.ReferenceList=EOe;var _5={};Object.defineProperty(_5,"__esModule",{value:!0}),_5.isNeedResponse=void 0;function AOe(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}_5.isNeedResponse=AOe;var C5={};Object.defineProperty(C5,"__esModule",{value:!0}),C5.walkForModelAnnotation=void 0;const vOe=dx;class SOe{constructor(e,n,r){this.translator=e,this.tokens=n,this.parseInfo=r,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}enterDocAnnotations(e){const n=e.DOC_ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}));this.notes.push(...n)}get annotation(){return{notes:this.notes}}}function _Oe(t,e,n){const r=new SOe(t,e,n),i=r;return vOe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.annotation}C5.walkForModelAnnotation=_Oe;var COe=N&&N.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),bOe=N&&N.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),TOe=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&COe(e,t,n);return bOe(e,t),e};Object.defineProperty(Lu,"__esModule",{value:!0}),Lu.MalloyParserErrorHandler=Lu.MalloyTranslator=Lu.MalloyChildTranslator=Lu.MalloyTranslation=void 0;const gV=Lv,ROe=qS,OOe=F,mV=TOe(T4),NOe=g5,DOe=m5,FOe=El,mF=y5,wOe=E5,LOe=A5,IOe=v5,$Oe=S5,b5=_5,BOe=s3,yV=dl,kOe=C5;class POe extends ROe.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}class MOe{step(e){if(this.response)return this.response;if(e.urlIsFullPath===void 0)try{const s=new URL(e.sourceURL);e.urlIsFullPath=!0}catch(s){const o=s instanceof Error?s.message:"";e.urlIsFullPath=!1,e.root.logger.log({message:`Could not compute full path URL: ${o}`,severity:"error"})}if(!e.urlIsFullPath)return e.fatalResponse();const n=e.root.importZone.getEntry(e.sourceURL);if(n.status!=="present"){if(n.status==="error"){const s=n.message.includes(e.sourceURL)?`import error: ${n.message}`:`import '${e.sourceURL}' error: ${n.message}`,o=n.firstReference||e.defaultLocation();return e.root.logger.log({message:s,at:o,severity:"error"}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const r=n.value===""?`
1284
+ `)),V4.ErrorFactory.structDef}else if(i.status==="present"){const s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},u=this.document(),a=u==null?void 0:u.currentModelAnnotation();return a&&(o.modelAnnotation=a),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),V4.ErrorFactory.structDef}}Rm.SQLSource=vSe,Object.defineProperty(G4,"__esModule",{value:!0}),G4.SQSource=void 0;const SSe=Ju,_Se=Tm,CSe=Rm;class bSe extends SSe.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof CSe.SQLSource){const e=new _Se.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}}G4.SQSource=bSe;var Y4={};Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.SQExtend=void 0;const TSe=Em,RSe=Ju;class OSe extends RSe.SourceQueryElement{constructor(e,n){super({sqSrc:e,extend:n}),this.sqSrc=e,this.extend=n,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new TSe.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}}Y4.SQExtend=OSe;var K4={},M0={};Object.defineProperty(M0,"__esModule",{value:!0}),M0.isComparison=M0.Comparison=void 0;var cD;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(cD||(M0.Comparison=cD={}));function NSe(t){return Object.values(cD).includes(t)}M0.isComparison=NSe;var Om={},ln={};Object.defineProperty(ln,"__esModule",{value:!0}),ln.FT=void 0;const DSe=Fu;function mx(t,e="scalar",n="constant"){return{dataType:t,expressionType:e,evalSpace:n}}class Lr{static in(e,n){return e?n.find(i=>Lr.eq(i,e))!==void 0:!1}static eq(e,n){return n!==void 0&&e.dataType===n.dataType&&e.expressionType===n.expressionType}static typeIn(e,n){return e?n.find(i=>Lr.typeEq(i,e))!==void 0:!1}static typeEq(e,n,r=!1,i=!0){const s=e.dataType===n.dataType,o=r&&(e.dataType==="null"||n.dataType==="null"),u=i&&(e.dataType==="error"||n.dataType==="error");return s||o||u}static inspect(...e){return e.map(r=>{if(r){let i=r.dataType;return(0,DSe.expressionIsScalar)(r.expressionType)||(i=`${r.expressionType} ${i}`),i}return"undefined"}).join(",")}}ln.FT=Lr,Lr.nullT=mx("null"),Lr.numberT=mx("number"),Lr.stringT=mx("string"),Lr.dateT=mx("date"),Lr.timestampT=mx("timestamp"),Lr.boolT=mx("boolean"),Lr.anyAtomicT=[Lr.numberT,Lr.stringT,Lr.dateT,Lr.timestampT,Lr.boolT],Lr.aggregateBoolT=mx("boolean","aggregate");var f2={},hr={};Object.defineProperty(hr,"__esModule",{value:!0}),hr.errorFor=void 0;function FSe(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}hr.errorFor=FSe;var pt={},x2={};Object.defineProperty(x2,"__esModule",{value:!0}),x2.isEquality=x2.Equality=void 0;var fD;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(fD||(x2.Equality=fD={}));function wSe(t){return Object.values(fD).includes(t)}x2.isEquality=wSe;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.isGranularResult=void 0;function LSe(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}d2.isGranularResult=LSe,Object.defineProperty(pt,"__esModule",{value:!0}),pt.applyBinary=pt.getMorphicValue=pt.ExprDuration=pt.ExpressionDef=void 0;const Nn=ne,h2=hr,pl=hn,yx=ln,X4=On,ISe=M0,$Se=x2,$Q=d2,BSe=Ve;class kSe extends Error{}class BQ extends BSe.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=yx.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.dataType!=="error"&&!yx.FT.in(n,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${yx.FT.inspect(n)}`),!1):!0}apply(e,n,r){return qQ(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Nn.expressionIsAggregate)(e.expressionType)}}pt.ExpressionDef=BQ;class xD extends BQ{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[yx.FT.timestampT,yx.FT.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,Nn.isTimeFieldType)(i.dataType)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!yx.FT.typeEq(s,yx.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,h2.errorFor)("illegal unit expression");let o;if((0,$Q.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){const u=(0,X4.timeOffset)("timestamp",i.value,n,s.value,this.timeframe);return(0,X4.timeResult)({dataType:"timestamp",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u},o)}return(0,Nn.isDateUnit)(this.timeframe)?(0,X4.timeResult)({dataType:"date",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,X4.timeOffset)("date",i.value,n,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,h2.errorFor)("ofsset date error"))}return super.apply(e,n,r)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}}pt.ExprDuration=xD;function kQ(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function PSe(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}pt.getMorphicValue=PSe;function PQ(t,e,n,r){const i=(0,Nn.isTimeFieldType)(e.dataType),s=(0,Nn.isTimeFieldType)(r.dataType);if(i&&s)if(e.dataType!==r.dataType){const o=kQ(e,"timestamp"),u=kQ(r,"timestamp");if(o&&u)return(0,pl.compose)(o,n,u)}else return(0,pl.compose)(e.value,n,r.value);if((i||s)&&e.dataType!=="null"&&r.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${r.dataType}`),["false"]}function MQ(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:t.value,regexp:e.value}]}else if(e.dataType==="string"&&t.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:e.value,regexp:t.value}]}function MSe(t,e,n){const r=e==="!="||e==="!~";if(t.dataType==="null"||n.dataType==="null"){const i=r?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:n.dataType!=="null"?[...n.value,`IS${i} NULL`]:[r?"false":"true"]}}function jSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Nm("boolean",i,s);if(o)return o;if(i.dataType==="unsupported"||s.dataType==="unsupported"){const l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){const f=Dm(e,i,r,s);if(f)return{...f,dataType:"boolean"}}}let a=PQ(e,i,n,s)||(0,pl.compose)(i.value,n,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(n){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")a=(0,pl.compose)(i.value,"LIKE",s.value);else{const l=MQ(i,s);if(l===void 0)throw new kSe("Incompatible types for match('~') operator");a=l}a=(0,pl.nullsafeNot)(a,n);break}case"=":case"!=":{const l=MSe(i,n,s);l?a=l:a=(0,pl.nullsafeNot)(MQ(i,s)||(0,pl.compose)(i.value,"=",s.value),n);break}}return{dataType:"boolean",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a}}function USe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Nm("boolean",i,s);if(o)return o;const u=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),a=Dm(e,i,r,s);if(a)return{...a,dataType:"boolean"};const l=PQ(e,i,n,s)||(0,pl.compose)(i.value,n,s.value);return{dataType:"boolean",expressionType:u,evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function jQ(t,...e){return e.includes(t)}function qSe(t,...e){for(const n of e)if(n.dataType!==t)return!1;return!0}function UQ(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Nm("number",i,s);if(o)return o;const u=Dm(e,i,r,s);if(u)return u;const a=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType);return qSe("number",i,s)?{dataType:"number",expressionType:a,value:(0,pl.compose)(i.value,n,s.value),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)}:(e.log(`Non numeric('${i.dataType},${s.dataType}') value with '${n}'`),(0,h2.errorFor)("numbers required"))}function HSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Dm(e,i,r,s);if(o)return o;const u=(0,Nn.isTimeFieldType)(i.dataType),a=Nm(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.dataType!=="duration")if((0,$Q.isGranularResult)(i))l=new xD(r,i.timeframe);else if(i.dataType==="date")l=new xD(r,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,h2.errorFor)(`time plus ${s.dataType}`);return l.apply(t,n,e)}return UQ(t,e,n,r)}function qQ(t,e,n,r){if((0,$Se.isEquality)(n))return jSe(t,e,n,r);if((0,ISe.isComparison)(n))return USe(t,e,n,r);if(jQ(n,"+","-"))return HSe(t,e,n,r);if(n==="*")return UQ(t,e,n,r);if(jQ(n,"/","%")){const i=e.getExpression(t),s=r.getExpression(t),o=Dm(e,i,r,s);if(o)return e.log("Cannot operate with unsupported type"),o;const u=Nm("number",i,s);if(u)return u;if(i.dataType!=="number")e.log("Numerator must be a number");else if(s.dataType!=="number")r.log("Denominator must be a number");else{const a={type:"dialect",function:n==="/"?"div":"mod",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[a]}}return(0,h2.errorFor)("divide type mismatch")}return e.log(`Cannot use ${n} operator here`),(0,h2.errorFor)("applybinary bad operator")}pt.applyBinary=qQ;function Nm(t,...e){if(e.some(n=>n.dataType==="error"))return{dataType:t,expressionType:(0,Nn.maxOfExpressionTypes)(e.map(n=>n.expressionType)),value:["'cascading error'"],evalSpace:(0,Nn.mergeEvalSpaces)(...e.map(n=>n.evalSpace))}}function Dm(t,e,n,r){const i={dataType:e.dataType,expressionType:(0,Nn.maxExpressionType)(e.expressionType,r.expressionType),value:["'unsupported operation'"],evalSpace:(0,Nn.mergeEvalSpaces)(e.evalSpace,r.evalSpace)};if(e.dataType==="unsupported")return t.log("Unsupported type not allowed in expression"),{...i,dataType:r.dataType};if(r.dataType==="unsupported")return n.log("Unsupported type not allowed in expression"),i}Object.defineProperty(f2,"__esModule",{value:!0}),f2.BinaryBoolean=void 0;const HQ=ne,zSe=hr,QSe=ln,GSe=pt,WSe=hn;class VSe extends GSe.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="abstract boolean binary",this.legalChildTypes=[QSe.FT.boolT]}getExpression(e){const n=this.left.getExpression(e),r=this.right.getExpression(e);if(this.typeCheck(this.left,n)&&this.typeCheck(this.right,r)){const i=(0,HQ.mergeEvalSpaces)(n.evalSpace,r.evalSpace);return{dataType:"boolean",expressionType:(0,HQ.maxExpressionType)(n.expressionType,r.expressionType),evalSpace:i,value:(0,WSe.compose)(n.value,this.op,r.value)}}return(0,zSe.errorFor)("logial required boolean")}}f2.BinaryBoolean=VSe,Object.defineProperty(Om,"__esModule",{value:!0}),Om.ExprCompare=void 0;const Yt=ln,YSe=f2,KSe={"~":[Yt.FT.stringT],"!~":[Yt.FT.stringT],"<":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"<=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"!=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],">=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],">":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT]};class XSe extends YSe.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="a<=>b",this.legalChildTypes=KSe[n]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Om.ExprCompare=XSe;var Fm={},p2={};Object.defineProperty(p2,"__esModule",{value:!0}),p2.ExprTime=void 0;const JSe=ne,ZSe=hn,e4e=pt;class dD extends e4e.ExpressionDef{constructor(e,n,r="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:r,value:typeof n=="string"?[n]:n,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,n){let r=n.value;if(e!==n.dataType){const i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:n.value};(0,JSe.isTimeFieldType)(n.dataType)&&(i.srcType=n.dataType),r=(0,ZSe.compressExpr)([i])}return new dD(e,r,n.expressionType)}}p2.ExprTime=dD;var j0={};Object.defineProperty(j0,"__esModule",{value:!0}),j0.Range=void 0;const zQ=ne,t4e=hr,n4e=pt,r4e=hn;class i4e extends n4e.ExpressionDef{constructor(e,n){super({first:e,last:n}),this.first=e,this.last=n,this.elementType="range"}apply(e,n,r){switch(n){case"=":case"!=":{const i=n==="="?">=":"<",s=n==="="?"and":"or",o=n==="="?"<":">=",u=this.first.apply(e,i,r),a=this.last.apply(e,o,r);return{dataType:"boolean",expressionType:(0,zQ.maxExpressionType)(u.expressionType,a.expressionType),evalSpace:(0,zQ.mergeEvalSpaces)(u.evalSpace,a.evalSpace),value:(0,r4e.compose)(u.value,s,a.value)}}case">":return this.last.apply(e,">=",r);case">=":return this.first.apply(e,">=",r);case"<":return this.first.apply(e,"<",r);case"<=":return this.last.apply(e,"<",r)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,t4e.errorFor)("a range is not a value")}}j0.Range=i4e,Object.defineProperty(Fm,"__esModule",{value:!0}),Fm.ExprGranularTime=void 0;const hD=ne,s4e=hr,QQ=ln,GQ=On,o4e=pt,J4=p2,WQ=j0;class u4e extends o4e.ExpressionDef{constructor(e,n,r){super({expr:e}),this.expr=e,this.units=n,this.truncate=r,this.elementType="granularTime",this.legalChildTypes=[QQ.FT.timestampT,QQ.FT.dateT]}granular(){return!0}getExpression(e){const n=this.units,r=this.expr.getExpression(e);if((0,hD.isTimeFieldType)(r.dataType)){const s={...r,dataType:r.dataType,timeframe:n};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:r.value,valueType:r.dataType},units:n}]),s}r.dataType!=="error"&&this.log(`Cannot do time truncation on type '${r.dataType}'`);const i=r.dataType==="error"?(0,hD.isDateUnit)(n)?"date":"timestamp":r.dataType;return{...r,dataType:i,value:(0,s4e.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const n=this.getExpression(e);if(n.dataType==="timestamp"){const o=J4.ExprTime.fromValue("timestamp",n),u=new J4.ExprTime("timestamp",(0,GQ.timeOffset)("timestamp",n.value,"+",(0,hD.mkExpr)`1`,this.units),n.expressionType);return new WQ.Range(o,u)}const r=new J4.ExprTime("date",n.value,n.expressionType),i=(0,GQ.timeOffset)("date",n.value,"+",["1"],this.units),s=new J4.ExprTime("date",i,n.expressionType);return new WQ.Range(r,s)}}Fm.ExprGranularTime=u4e,Object.defineProperty(K4,"__esModule",{value:!0}),K4.Apply=void 0;const a4e=M0,l4e=Om,c4e=d2,VQ=Fm;class f4e extends l4e.ExprCompare{constructor(e,n){super(e,a4e.Comparison.EqualTo,n),this.left=e,this.right=n,this.elementType="apply"}getExpression(e){let n=this.right;if(!this.right.granular()){const r=this.right.requestExpression(e);r&&(0,c4e.isGranularResult)(r)&&(n=new VQ.ExprGranularTime(this.right,r.timeframe,!1))}return n instanceof VQ.ExprGranularTime?n.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}K4.Apply=f4e;var g2={};Object.defineProperty(g2,"__esModule",{value:!0}),g2.BinaryNumeric=void 0;const x4e=ln,d4e=pt;class h4e extends d4e.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="numeric binary abstract",this.legalChildTypes=[x4e.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}g2.BinaryNumeric=h4e;var Z4={};Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.Boolean=void 0;const p4e=pt,g4e=ln;let m4e=class extends p4e.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...g4e.FT.boolT,value:[this.value]}}};Z4.Boolean=m4e;var U0={},m2={};Object.defineProperty(m2,"__esModule",{value:!0}),m2.ExprIdReference=void 0;const pD=ne,y4e=hr,E4e=Xu,A4e=pt;class v4e extends A4e.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const n=this.fieldReference.getField(e);if(n.found){const r=n.found.typeDesc();if(n.isOutputField)return{...r,evalSpace:r.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};const i=[{type:n.found.refType,path:this.fieldReference.path}],s=(0,pD.expressionIsAggregate)(r.expressionType)?"output":r.evalSpace;return{...r,value:i,evalSpace:s}}return this.log(n.error),(0,y4e.errorFor)(n.error)}apply(e,n,r){const i=this.fieldReference.getField(e).found;if(i instanceof E4e.SpaceParam){const s=i.parameter();if((0,pD.isConditionParameter)(s)){const o=r.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,pD.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,n,r)}}m2.ExprIdReference=v4e,Object.defineProperty(U0,"__esModule",{value:!0}),U0.FunctionOrdering=U0.FunctionOrderBy=void 0;const gD=ne,YQ=Ve,S4e=m2;class _4e extends YQ.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.log("analytic `order_by` must specify an aggregate expression or output field reference"),{e:["error"],dir:this.dir};const n=this.field.getExpression(e);return(0,gD.expressionIsAggregate)(n.expressionType)||((0,gD.expressionIsScalar)(n.expressionType)?(!(this.field instanceof S4e.ExprIdReference)||n.evalSpace==="input")&&this.field.log("analytic `order_by` must be an aggregate or an output field reference"):this.field.log("analytic `order_by` must be scalar or aggregate")),{e:n.value,dir:this.dir}}getAggregateOrderBy(e,n){if(this.field){const r=this.field.getExpression(e);return(0,gD.expressionIsScalar)(r.expressionType)||this.field.log("aggregate `order_by` must be scalar"),n||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:r.value,dir:this.dir}}else return this.dir===void 0?(this.log("field or order direction must be specified"),{e:void 0,dir:"asc"}):{e:void 0,dir:this.dir}}}U0.FunctionOrderBy=_4e;class C4e extends YQ.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(n=>n.getAnalyticOrderBy(e))}getAggregateOrderBy(e,n){return this.list.map(r=>r.getAggregateOrderBy(e,n))}}U0.FunctionOrdering=C4e;var e_={};Object.defineProperty(e_,"__esModule",{value:!0}),e_.ExprAddSub=void 0;const b4e=g2;class T4e extends b4e.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}e_.ExprAddSub=T4e;var gl={},mt={},wm={};Object.defineProperty(wm,"__esModule",{value:!0}),wm.ReferenceField=void 0;const KQ=Yr;class R4e extends KQ.SpaceField{constructor(e,n){super(),this.fieldRef=e,this.inFS=n,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const n=this.fieldRef.getField(e);n.error&&this.fieldRef.log(n.error),this.queryFieldDef={type:"fieldref",path:this.fieldRef.list.map(i=>i.name)};const r=this.referenceTo;if(r instanceof KQ.SpaceField&&r.haveFieldDef){const i=r.haveFieldDef,s=this.fieldRef.note;if(i.annotation||s){const o=s||{};i.annotation&&(o.inherits=i.annotation),this.queryFieldDef.annotation=o}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}}wm.ReferenceField=R4e;var Zn={};Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.typecheckGroupBy=Zn.typecheckAggregate=Zn.typecheckCalculate=Zn.typecheckDeclare=Zn.typecheckMeasure=Zn.typecheckDimension=Zn.typecheckIndex=Zn.typecheckProject=void 0;const Dn=Fu;function O4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckProject=O4e;function N4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n;if(t.dataType==="turtle")n="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in an index operation`)}}Zn.typecheckIndex=N4e;function D4e(t,e){if(!(0,Dn.expressionIsScalar)(t.expressionType))if((0,Dn.expressionIsAggregate)(t.expressionType))e.log("Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,Dn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Zn.typecheckDimension=D4e;function F4e(t,e){if(!(0,Dn.expressionIsAggregate)(t.expressionType))if((0,Dn.expressionIsScalar)(t.expressionType))e.log("Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,Dn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Zn.typecheckMeasure=F4e;function w4e(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,Dn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Zn.typecheckDeclare=w4e;function L4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsAnalytic)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else if((0,Dn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckCalculate=L4e;function I4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsAggregate)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckAggregate=I4e;function $4e(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}Zn.typecheckGroupBy=$4e,Object.defineProperty(mt,"__esModule",{value:!0}),mt.FieldReferences=mt.WildcardFieldReference=mt.ViewOrScalarFieldReference=mt.DimensionFieldReference=mt.MeasureFieldReference=mt.DeclareFieldReference=mt.ProjectFieldReference=mt.GroupByFieldReference=mt.AggregateFieldReference=mt.IndexFieldReference=mt.CalculateFieldReference=mt.PartitionByFieldReference=mt.ExpressionFieldReference=mt.AcceptExceptFieldReference=mt.FieldReference=void 0;const B4e=wm,k4e=Ds,XQ=Ve,JQ=Vr,q0=Zn;class ws extends XQ.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=JQ.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.log(`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new B4e.ReferenceField(this,r))}}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const n=e.lookup(this.list);if(n.found){const r=n.found.typeDesc();this.typecheck(r)}return n}}mt.FieldReference=ws;class P4e extends ws{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}mt.AcceptExceptFieldReference=P4e;class M4e extends ws{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}mt.ExpressionFieldReference=M4e;class j4e extends ws{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}mt.PartitionByFieldReference=j4e;class U4e extends ws{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,q0.typecheckCalculate)(e,this)}}mt.CalculateFieldReference=U4e;class mD extends ws{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,q0.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return mD.indexOutputName(this.path)}}mt.IndexFieldReference=mD;class q4e extends ws{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,q0.typecheckAggregate)(e,this)}}mt.AggregateFieldReference=q4e;class H4e extends ws{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,q0.typecheckGroupBy)(e,this)}}mt.GroupByFieldReference=H4e;class z4e extends ws{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,q0.typecheckProject)(e,this)}}mt.ProjectFieldReference=z4e;class Q4e extends ws{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,q0.typecheckDeclare)(e,this)}}mt.DeclareFieldReference=Q4e;class G4e extends ws{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,q0.typecheckMeasure)(e,this)}}mt.MeasureFieldReference=G4e;class W4e extends ws{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,q0.typecheckDimension)(e,this)}}mt.DimensionFieldReference=W4e;class V4e extends ws{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}mt.ViewOrScalarFieldReference=V4e;class Y4e extends XQ.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=JQ.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}mt.WildcardFieldReference=Y4e;class K4e extends k4e.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}mt.FieldReferences=K4e,Object.defineProperty(gl,"__esModule",{value:!0}),gl.ExprAggregateFunction=void 0;const ZQ=ne,X4e=Vt,Lm=hr,J4e=Xr,Z4e=px,e_e=ln,t_e=mt,n_e=pt,r_e=Yr,i_e=m2;class s_e extends n_e.ExpressionDef{constructor(e,n,r){super(),this.func=e,this.legalChildTypes=[e_e.FT.numberT],this.elementType=e,this.explicitSource=r,n&&(this.expr=n,this.has({expr:n}))}returns(e){return"number"}getExpression(e){var n,r;const i=e.isQueryFieldSpace()?e.inputSpace():e;let s=this.expr,o=(n=this.expr)===null||n===void 0?void 0:n.getExpression(i),u=(r=this.source)===null||r===void 0?void 0:r.path,a=[];if(this.source){const c=this.source.getField(i);if(c.found){a=c.relationship;const f=c.found,x=f.typeDesc();if((0,ZQ.isAtomicFieldType)(x.dataType)){s=this.source,o={dataType:x.dataType,expressionType:x.expressionType,value:[x.evalSpace==="output"?{type:"outputField",name:this.source.refString}:{type:"field",path:this.source.path}],evalSpace:x.evalSpace},u=this.source.path;const h=this.getJoinUsage(i);(h.length===1||h.length>1&&h.slice(1).every(m=>o_e(m,h[0])))&&(u=h[0].map(m=>m.name),a=h[0])}else if(!(f instanceof Z4e.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,Lm.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,Lm.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,Lm.errorFor)("agggregate without expression");if((0,ZQ.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,Lm.errorFor)("reagggregate");if(!(o.dataType==="error")){const c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(h=>h.length===0))&&!this.isSymmetricFunction()){const h=ED(a,c),p=AD(this.elementType,h),m=f?p:"Join path is required for this calculation";if(m){const g=u_e(m,c,s,this.elementType);this.log(g,p?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){const c={type:"aggregate",function:this.func,e:o.value};return u&&u.length>0&&(c.structPath=u),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,Lm.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const n=[];if(this.source&&this.source.getField(e).found){const i=[{type:"field",path:this.source.path}];n.push(...yD(e,i))}if(this.expr){const r=this.expr.getExpression(e).value;n.push(...yD(e,r))}return n}}gl.ExprAggregateFunction=s_e;function o_e(t,e){let n=t.length;if(n!==e.length)return!1;for(;n>0;)if(n-=1,t[n].name!==e[n].name)return!1;return!0}function yD(t,e){const n=[],r=(i,s)=>{const o=s[0],u=s.slice(1),a=i.entry(o);if(a===void 0)throw new Error(`Invalid field lookup ${o}`);if(a instanceof J4e.StructSpaceField&&u.length>0){const l=r(a.fieldSpace,u);return{...l,relationship:[{name:o,structRelationship:a.structRelationship},...l.relationship]}}else if(a instanceof r_e.SpaceField){if(u.length!==0)throw new Error(`${o} cannot contain a ${u.join(".")}`);const l=a.fieldDef();if(l)return{fs:i,def:l,relationship:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};return(0,X4e.exprWalk)(e,i=>{if(typeof i!="string"){if(i.type==="field"){const s=r(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){const o=yD(s.fs,s.def.e);n.push(...o.map(u=>[...s.relationship,...u]))}else n.push(s.relationship)}else if(i.type==="source-reference")if(i.path){const s=r(t,i.path);n.push(s.relationship)}else n.push([])}}),n}function ED(t,e){const n=[];for(const r of e){let i=0;for(let a=0;a<t.length&&a<r.length&&t[a].name===r[a].name;a++)i=a+1;const s=t.slice(i),o=r.slice(i),u=[...s.map(a=>({...a,reverse:!0})),...o.map(a=>({...a,reverse:!1}))];n.push(u)}return n}function AD(t,e){for(const n of e)for(const r of n){if(r.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${r.name}\``;if(r.structRelationship.type==="many"&&!r.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${r.name}\``;if(r.structRelationship.type==="nested"&&!r.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${r.name}\``}}function u_e(t,e,n,r){if(e.length===0)return t;let i=e[0];for(const p of e.slice(1))for(let m=0;m<i.length;m++){const g=i[m],y=p[m];if(g.name!==y.name){i=i.slice(0,m);break}}const s=ED(i,e),o=AD(r,s),u=i.slice().reverse().findIndex(p=>p.structRelationship.type==="many"||p.structRelationship.type==="cross"),a=u===-1?0:i.length-u,l=i.slice(0,a),c=ED(l,e),f=AD(r,c),x=i.length>0?i.map(p=>p.name).join("."):"source",h=l.length>0?l.map(p=>p.name).join("."):"source";if(o)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const p=n instanceof t_e.FieldReference?`${n.refString}.${r}()`:n instanceof i_e.ExprIdReference?`${n.fieldReference.refString}.${r}()`:`${x}.${r}(${n.code})`,m=`${h}.${r}(${n.code})`;let g=`${t}; use \`${p}\``;return f===void 0&&h!==x&&(g+=` or \`${m}\` to get a result weighted with respect to \`${h}\``),g}}var t_={};Object.defineProperty(t_,"__esModule",{value:!0}),t_.ExprAlternationTree=void 0;const eG=ne,a_e=hr,l_e=f2,c_e=hn;class f_e extends l_e.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="alternation",this.elementType=`${n}alternation${n}`}apply(e,n,r){const i=this.left.apply(e,n,r),s=this.right.apply(e,n,r);return{dataType:"boolean",expressionType:(0,eG.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,eG.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,c_e.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,a_e.errorFor)("no value from alternation tree")}}t_.ExprAlternationTree=f_e;var y2={};Object.defineProperty(y2,"__esModule",{value:!0}),y2.ExprAsymmetric=void 0;const x_e=gl;class d_e extends x_e.ExprAggregateFunction{constructor(e,n,r,i){super(e,n,i),this.func=e,this.expr=n,this.source=r,this.has({source:r})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}y2.ExprAsymmetric=d_e;var n_={};Object.defineProperty(n_,"__esModule",{value:!0}),n_.ExprAvg=void 0;const h_e=y2;class p_e extends h_e.ExprAsymmetric{constructor(e,n,r){super("avg",e,n,r),this.has({source:n})}}n_.ExprAvg=p_e;var r_={};Object.defineProperty(r_,"__esModule",{value:!0}),r_.ExprCast=void 0;const g_e=On,m_e=pt,y_e=hn;class E_e extends m_e.ExpressionDef{constructor(e,n,r=!1){super({expr:e}),this.expr=e,this.castType=n,this.safe=r,this.elementType="cast"}getExpression(e){var n,r,i;const s=this.expr.getExpression(e);let o="unsupported";if(typeof this.castType=="string")o=this.castType;else{const u=e.dialectObj();u&&(u.validateTypeName(this.castType.raw)?o=(i=(r=(n=e.dialectObj())===null||n===void 0?void 0:n.sqlTypeToMalloyType(this.castType.raw))===null||r===void 0?void 0:r.type)!==null&&i!==void 0?i:"unsupported":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${u.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,y_e.compressExpr)((0,g_e.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}}r_.ExprCast=E_e;var i_={};Object.defineProperty(i_,"__esModule",{value:!0}),i_.ExprCoalesce=void 0;const vD=Fu,tG=ln,A_e=pt;class v_e extends A_e.ExpressionDef{constructor(e,n){super({expr:e,altExpr:n}),this.expr=e,this.altExpr=n,this.elementType="coalesce expression",this.legalChildTypes=tG.FT.anyAtomicT}getExpression(e){const n=this.expr.getExpression(e),r=this.altExpr.getExpression(e);return n.dataType==="null"?r:(tG.FT.typeEq(n,r)||this.log(`Mismatched types for coalesce (${n.dataType}, ${r.dataType})`),{...r,dataType:n.dataType==="error"?r.dataType:n.dataType,expressionType:(0,vD.maxExpressionType)(n.expressionType,r.expressionType),value:(0,vD.mkExpr)`COALESCE(${n.value},${r.value})`,evalSpace:(0,vD.mergeEvalSpaces)(n.evalSpace,r.evalSpace)})}}i_.ExprCoalesce=v_e;var s_={};Object.defineProperty(s_,"__esModule",{value:!0}),s_.ExprCount=void 0;const S_e=gl;class __e extends S_e.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}getExpression(e){const n={type:"aggregate",function:"count",e:[]};return this.source&&(n.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[n],evalSpace:"output"}}}s_.ExprCount=__e;var o_={};Object.defineProperty(o_,"__esModule",{value:!0}),o_.ExprCountDistinct=void 0;const u_=ln,C_e=gl;class b_e extends C_e.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[u_.FT.numberT,u_.FT.stringT,u_.FT.dateT,u_.FT.timestampT]}}o_.ExprCountDistinct=b_e;var a_={},H0={};Object.defineProperty(H0,"__esModule",{value:!0}),H0.Limit=void 0;const T_e=Ve,R_e=Rn;class O_e extends T_e.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=R_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}H0.Limit=O_e;var E2={};Object.defineProperty(E2,"__esModule",{value:!0}),E2.PartitionBy=void 0;const N_e=Ve;class D_e extends N_e.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}E2.PartitionBy=D_e;var Im={};Object.defineProperty(Im,"__esModule",{value:!0}),Im.ExprFunc=void 0;const ao=ne,ml=hr,F_e=px,w_e=pt,nG=hn;class L_e extends w_e.ExpressionDef{constructor(e,n,r,i,s){super({args:n}),this.name=e,this.args=n,this.isRaw=r,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}getPropsExpression(e,n){var r,i,s,o,u;const a=this.args.map(O=>O.getExpression(e));if(this.isRaw){let O="scalar",L;const M=[`${this.name}(`];for(const W of a)O=(0,ao.maxExpressionType)(O,W.expressionType),L?M.push(","):L=W.dataType,M.push(...W.value);return M.push(")"),{dataType:(i=(r=this.rawType)!==null&&r!==void 0?r:L)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,nG.compressExpr)(M),evalSpace:(0,ao.mergeEvalSpaces)(...a.map(W=>W.evalSpace))}}const l=(s=this.modelEntry(this.name.toLowerCase()))===null||s===void 0?void 0:s.entry;if(l===void 0)return this.log(`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),(0,ml.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,ml.errorFor)("called non function");l.name!==this.name&&this.log(`Case insensitivity for function names is deprecated, use '${l.name}' instead`,"warn");let c,f=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const O=this.source.getField(e).found;if(O){const L=O.typeDesc();if((0,ao.isAtomicFieldType)(L.dataType))c={dataType:L.dataType,expressionType:L.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:L.evalSpace},f=this.source.path.slice(0,-1);else if(!(O instanceof F_e.StructSpaceFieldBase)){const M=`Aggregate source cannot be a ${L.dataType}`;return this.log(M),(0,ml.errorFor)(M)}}else{const L=`Reference to undefined value ${this.source.refString}`;return this.log(L),(0,ml.errorFor)(L)}}const x=[...c?[c]:[],...a],h=I_e(l,x);if(h===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,ml.errorFor)("no matching overload");const{overload:p,expressionTypeErrors:m,evalSpaceErrors:g,nullabilityErrors:y}=h;for(const O of m){const L=O.argIndex-(c?1:0),M=(0,ao.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[L].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${M}, but received ${O.actualExpressionType}`)}for(const O of g){const L=O.argIndex-(c?1:0),M=O.maxEvalSpace==="literal"?"literal":O.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[L].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${M}, but received ${O.actualEvalSpace}`)}for(const O of y){const L=O.argIndex-(c?1:0);this.args[L].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must not be a literal null`)}const E=p.returnType,A=(0,ao.maxOfExpressionTypes)([E.expressionType,...x.map(O=>O.expressionType)]);if(!(0,ao.expressionIsAggregate)(p.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(O=>O.dataType).join(", ")}) with source`),(0,ml.errorFor)("cannot call with source");const v={type:"function_call",overload:p,name:this.name,args:x.map(O=>O.value),expressionType:A,structPath:f};let S=[v];const C=(u=e.dialectObj())===null||u===void 0?void 0:u.name,_=C?p.dialect[C]:void 0;if(_===void 0)this.log(`Function ${this.name} is not defined in dialect ${C}`);else{if(n!=null&&n.orderBys&&n.orderBys.length>0){const O=(0,ao.expressionIsAnalytic)(p.returnType.expressionType);if(O||this.inExperiment("aggregate_order_by",!0)||n.orderBys[0].log("Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),_.supportsOrderBy||O){const L=_.supportsOrderBy!=="only_default",M=n.orderBys.flatMap(q=>O?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,L));v.orderBy=M}else n.orderBys[0].log(`Function \`${this.name}\` does not support \`order_by\``)}(n==null?void 0:n.limit)!==void 0&&(_.supportsLimit?v.limit=n.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(n!=null&&n.partitionBys&&n.partitionBys.length>0){const O=[];for(const L of n.partitionBys)for(const M of L.partitionFields){const q=M.getField(e);q.found===void 0?M.log(`${M.refString} is not defined`):(0,ao.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,ao.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?M.log("Partition expression must be scalar or aggregate"):O.push(M.nameString)}v.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,ml.errorFor)(`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);const O=x[0].value;if(O.length!==1||typeof O[0]=="string"||O[0].type!=="dialect"||O[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{const L=O[0].literal,M=$_e(L),q=M.filter(W=>W.type==="interpolation"&&W.name.includes(".")).map(W=>W.type==="interpolation"?`\${${W.name}}`:`\${${W.value}}`);if(q.length>0){const W=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${q.join(", ")})`;return this.log(W),(0,ml.errorFor)(`${W}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}S=[{type:"sql-string",e:M.map(W=>W.type==="string"?W.value:W.name==="TABLE"?{type:"source-reference"}:{type:"field",path:[W.name]})}]}}if(E.dataType==="any")return this.log(`Invalid return type ${E.dataType} for function '${this.name}'`),(0,ml.errorFor)("invalid return type");const b=(0,ao.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),R=b==="constant"?"constant":(0,ao.expressionIsScalar)(A)?b:"output";return{dataType:E.dataType,expressionType:A,value:(0,nG.compressExpr)(S),evalSpace:R}}}Im.ExprFunc=L_e;function I_e(t,e){for(const n of t.overloads){let r=0,i=!0,s=!1;const o=[],u=[],a=[];for(let l=0;l<e.length;l++){const c=e[l],f=n.params[r];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(h=>{const p=h.dataType===c.dataType||h.dataType==="any"||c.dataType==="null"||c.dataType==="error";return h.expressionType&&((0,ao.isExpressionTypeLEQ)(c.expressionType,h.expressionType)||o.push({argIndex:l,maxExpressionType:h.expressionType,actualExpressionType:c.expressionType,param:f})),(h.evalSpace==="literal"&&c.evalSpace!=="literal"||h.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||h.evalSpace==="output"&&c.evalSpace==="input")&&u.push({argIndex:l,param:f,maxEvalSpace:h.evalSpace,actualEvalSpace:c.evalSpace}),h.evalSpace==="literal"&&c.dataType==="null"&&a.push({argIndex:l,param:f}),p})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):r++}if(!(!s&&(r!==e.length||r!==n.params.length))&&i)return{overload:n,expressionTypeErrors:o,evalSpaceErrors:u,nullabilityErrors:a}}}function $_e(t){const e=[];let n=t;for(;n.length;){const r=n.indexOf("${");if(r===-1){e.push({type:"string",value:n});break}else{const i=n.slice(r).indexOf("}");if(i===-1){e.push({type:"string",value:n});break}r>0&&e.push({type:"string",value:n.slice(0,r)}),e.push({type:"interpolation",name:n.slice(r+2,i+r)}),n=n.slice(i+r+1)}}return e}Object.defineProperty(a_,"__esModule",{value:!0}),a_.ExprProps=void 0;const B_e=ne,k_e=hr,P_e=ln,M_e=U0,j_e=H0,U_e=E2,q_e=pt,H_e=Im;class z_e extends q_e.ExpressionDef{constructor(e,n){super({expr:e,statements:n}),this.expr=e,this.statements=n,this.elementType="expression with props",this.legalChildTypes=P_e.FT.anyAtomicT}getFilteredExpression(e,n,r){if(r.length>0){if(!this.expr.supportsWhere(n))return this.expr.log("Filtered expression requires an aggregate computation"),n;const i=[];for(const s of r){const o=s.getFilterList(e);if(o.find(u=>(0,B_e.expressionIsCalculation)(u.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),n;i.push(...o)}return this.typeCheck(this.expr,{...n,expressionType:"scalar"})?{...n,value:[{type:"filterExpression",e:n.value,filterList:i}]}:(this.expr.log(`Cannot filter '${n.dataType}' data`),(0,k_e.errorFor)("cannot filter type"))}return n}getExpression(e){const n=[];let r;const i=[],s=[];for(const u of this.statements)u instanceof U_e.PartitionBy?this.expr.canSupportPartitionBy()?n.push(u):u.log("`partition_by` is not supported for this kind of expression"):u instanceof j_e.Limit?r?u.log("limit already specified"):this.expr.canSupportLimit()?r=u:u.log("`limit` is not supported for this kind of expression"):u instanceof M_e.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(u):u.log("`order_by` is not supported for this kind of expression"):s.push(u);const o=this.expr instanceof H_e.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:n,limit:r,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}}a_.ExprProps=z_e;var l_={};Object.defineProperty(l_,"__esModule",{value:!0}),l_.ExprLogicalOp=void 0;const Q_e=f2,rG=ln;class G_e extends Q_e.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[rG.FT.boolT,rG.FT.aggregateBoolT]}}l_.ExprLogicalOp=G_e;var c_={};Object.defineProperty(c_,"__esModule",{value:!0}),c_.ExprMax=void 0;const f_=ln,W_e=gl;class V_e extends W_e.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[f_.FT.numberT,f_.FT.stringT,f_.FT.dateT,f_.FT.timestampT]}returns(e){return e.dataType}}c_.ExprMax=V_e;var x_={};Object.defineProperty(x_,"__esModule",{value:!0}),x_.ExprMin=void 0;const d_=ln,Y_e=gl;class K_e extends Y_e.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[d_.FT.numberT,d_.FT.stringT,d_.FT.dateT,d_.FT.timestampT]}returns(e){return e.dataType}}x_.ExprMin=K_e;var h_={};Object.defineProperty(h_,"__esModule",{value:!0}),h_.ExprMinus=void 0;const X_e=hr,iG=ln,J_e=pt;class Z_e extends J_e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[iG.FT.numberT]}getExpression(e){const n=this.expr.getExpression(e);return iG.FT.typeIn(n,this.legalChildTypes)?n.value.length>1?{...n,dataType:"number",value:["-(",...n.value,")"]}:{...n,dataType:"number",value:["-",...n.value]}:(0,X_e.errorFor)("negate requires number")}}h_.ExprMinus=Z_e;var p_={};Object.defineProperty(p_,"__esModule",{value:!0}),p_.ExprMulDiv=void 0;const e5e=g2;class t5e extends e5e.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}p_.ExprMulDiv=t5e;var g_={},$m={};Object.defineProperty($m,"__esModule",{value:!0}),$m.Unary=void 0;const n5e=pt;class r5e extends n5e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}$m.Unary=r5e,Object.defineProperty(g_,"__esModule",{value:!0}),g_.ExprNot=void 0;const sG=ln,i5e=$m,s5e=hn;class o5e extends i5e.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[sG.FT.boolT,sG.FT.nullT]}getExpression(e){const n=this.expr.getExpression(e),r=this.typeCheck(this.expr,n);return{...n,dataType:"boolean",value:r?(0,s5e.nullsafeNot)(n.value):["false"]}}}g_.ExprNot=o5e;var m_={};Object.defineProperty(m_,"__esModule",{value:!0}),m_.ExprNow=void 0;const u5e=pt;class a5e extends u5e.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}}m_.ExprNow=a5e;var y_={};Object.defineProperty(y_,"__esModule",{value:!0}),y_.ExprNULL=void 0;const l5e=pt;class c5e extends l5e.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}}y_.ExprNULL=c5e;var E_={};Object.defineProperty(E_,"__esModule",{value:!0}),E_.ExprNumber=void 0;const f5e=ln,x5e=pt;class d5e extends x5e.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...f5e.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}}E_.ExprNumber=d5e;var A_={};Object.defineProperty(A_,"__esModule",{value:!0}),A_.ExprParens=void 0;const h5e=pt;class p5e extends h5e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const n=this.expr.getExpression(e);return{...n,value:["(",...n.value,")"]}}}A_.ExprParens=p5e;var v_={};Object.defineProperty(v_,"__esModule",{value:!0}),v_.ExprRegEx=void 0;const g5e=pt;class m5e extends g5e.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:[{type:"dialect",function:"regexpLiteral",literal:this.regex}],evalSpace:"literal"}}}v_.ExprRegEx=m5e;var S_={};Object.defineProperty(S_,"__esModule",{value:!0}),S_.ExprString=void 0;const y5e=pt,E5e=ln;class A5e extends y5e.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...E5e.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}}S_.ExprString=A5e;var __={};Object.defineProperty(__,"__esModule",{value:!0}),__.ExprSum=void 0;const v5e=y2;class S5e extends v5e.ExprAsymmetric{constructor(e,n,r){super("sum",e,n,r),this.has({source:n})}}__.ExprSum=S5e;var C_={};Object.defineProperty(C_,"__esModule",{value:!0}),C_.ExprTimeExtract=void 0;const Ex=ne,z0=hr,SD=pt,_5e=j0;class Bm extends SD.ExpressionDef{static extractor(e){const n=Bm.pluralMap[e];if(n)return n;if((0,Ex.isExtractUnit)(e))return e}constructor(e,n){super({args:n}),this.extractText=e,this.args=n,this.elementType="timeExtract"}getExpression(e){const n=Bm.extractor(this.extractText);if(n){if(this.args.length!==1)return this.log(`Extraction function ${n} requires one argument`),(0,z0.errorFor)("{this.name} arg count");const r=this.args[0];if(r instanceof _5e.Range){let i=r.first.getExpression(e),s=r.last.getExpression(e);const o=(0,Ex.maxExpressionType)(i.expressionType,s.expressionType),u=(0,Ex.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:u,value:(0,z0.errorFor)("extract from error").value};if(!(0,Ex.isTimeFieldType)(i.dataType))return r.first.log(`Can't extract ${n} from '${i.dataType}'`),(0,z0.errorFor)(`${n} bad type ${i.dataType}`);if(!(0,Ex.isTimeFieldType)(s.dataType))return r.last.log(`Cannot extract ${n} from '${s.dataType}'`),(0,z0.errorFor)(`${n} bad type ${s.dataType}`);let a=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(a="timestamp",i.dataType==="date"){const c=(0,SD.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{const c=(0,SD.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return r.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,z0.errorFor)(`${n} range mismatch`)}return["week","month","quarter","year"].includes(n)?(this.log(`Cannot measure interval using '${n}'`),(0,z0.errorFor)(`${n} civil extraction`)):(0,Ex.isTimestampUnit)(n)?{dataType:"number",expressionType:o,evalSpace:u,value:[{type:"dialect",function:"timeDiff",units:n,left:{valueType:a,value:i.value},right:{valueType:a,value:s.value}}]}:(this.log(`Cannot extract ${n} from a range`),(0,z0.errorFor)(`${n} bad extraction`))}else{const i=r.getExpression(e);return(0,Ex.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:n}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,z0.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}C_.ExprTimeExtract=Bm,Bm.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var b_={},Wo={},Ax={};Object.defineProperty(Ax,"__esModule",{value:!0}),Ax.FieldName=void 0;const C5e=Ve;class b5e extends C5e.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}Ax.FieldName=b5e;var T_={};Object.defineProperty(T_,"__esModule",{value:!0}),T_.QueryInputSpace=void 0;const T5e=rs,R5e=Sm,O5e=i2;class N5e extends O5e.RefinedSpace{constructor(e,n){const r=new R5e.SpaceSeed(e);super(r.structDef),this.queryOutput=n,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof T5e.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}}T_.QueryInputSpace=N5e;var D5e=N&&N.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),F5e=N&&N.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),w5e=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&D5e(e,t,n);return F5e(e,t),e};Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.ReduceFieldSpace=Wo.QuerySpace=Wo.QueryOperationSpace=void 0;const R_=w5e(ne),_D=I0,L5e=Ax,I5e=Yr,$5e=mt,B5e=i2,k5e=vm,P5e=Xr,M5e=T_;class oG extends B5e.RefinedSpace{constructor(e,n,r,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=r,this.astEl=i,this.expandedWild={},this.exprSpace=new M5e.QueryInputSpace(e,this),n&&this.addRefineFromFields(n)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof P5e.StructSpaceField)r=l.fieldSpace;else{u.log(`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.log(`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries())if(!e.except.has(u))if(this.entry(u)){const l=(n=this.expandedWild[u])===null||n===void 0?void 0:n.join(".");e.log(`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{const l=a.typeDesc();R_.isAtomicFieldType(l.dataType)&&R_.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:u,entry:a}),this.expandedWild[u]=i.concat(u))}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}Wo.QueryOperationSpace=oG;class uG extends oG{addRefineFromFields(e){var n;if(R_.isQuerySegment(e))for(const r of e.queryFields)if(r.type==="fieldref"){const i=this.exprSpace.lookup(r.path.map(s=>new L5e.FieldName(s)));i.found&&this.setEntry(r.path[r.path.length-1],i.found)}else r.type!=="turtle"&&this.setEntry((n=r.as)!==null&&n!==void 0?n:r.name,new k5e.ColumnSpaceField(r))}pushFields(...e){for(const n of e)n instanceof $5e.WildcardFieldReference?this.addWild(n):super.pushFields(n)}canContain(e){return!0}queryFieldDefs(){const e=[];for(const[n,r]of this.entries())if(r instanceof I5e.SpaceField){const i=this.expandedWild[n];if(i){e.push({type:"fieldref",path:i});continue}const s=r.getQueryFieldDef(this.exprSpace);if(s){const o=r.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!U5e(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){const n=this.getPipeSegment(e);if(R_.isQuerySegment(n))return n;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.log("internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};if(e!=null&&e.extendSource)for(const r of e.extendSource)this.exprSpace.addFieldDef(r);const n={type:this.segmentType,queryFields:this.queryFieldDefs()};if(n.queryFields=(0,_D.mergeFields)(e==null?void 0:e.queryFields,n.queryFields),e!=null&&e.extendSource&&(n.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const r=[],i=this.exprSpace.structDef();for(const s of this.exprSpace.extendList){const o=i.fields.find(u=>(0,_D.nameFromDef)(u)===s);o&&r.push(o)}n.extendSource=(0,_D.mergeFields)(n.extendSource,r)}return this.newTimezone&&(n.queryTimezone=this.newTimezone),this.isComplete(),n}lookup(e){const n=super.lookup(e);return n.found?{...n,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Wo.QuerySpace=uG;class j5e extends uG{constructor(){super(...arguments),this.segmentType="reduce"}}Wo.ReduceFieldSpace=j5e;function U5e(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}Object.defineProperty(b_,"__esModule",{value:!0}),b_.ExprUngroup=void 0;const aG=ne,CD=hr,q5e=Wo,H5e=ln,z5e=pt;class Q5e extends z5e.ExpressionDef{constructor(e,n,r){super({expr:n,fields:r}),this.control=e,this.expr=n,this.fields=r,this.legalChildTypes=H5e.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){const n=this.expr.getExpression(e);if(!(0,aG.expressionIsAggregate)(n.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,CD.errorFor)("ungrouped scalar");if((0,aG.expressionIsUngroupedAggregate)(n.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,CD.errorFor)("doubly-ungrouped aggregate");const r={type:this.control,e:n.value};if(this.typeCheck(this.expr,{...n,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const i=[],s=this.control==="exclude";for(const o of this.fields){let u=e.outputSpace(),a=!0;for(;u;){const l=u.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),a=!1;else if(u instanceof q5e.QuerySpace){u=u.nestParent;continue}break}if(a){const l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}r.fields=i}return{dataType:this.returns(n),expressionType:"ungrouped_aggregate",value:[r],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,CD.errorFor)("ungrouped type check")}}b_.ExprUngroup=Q5e;var O_={};Object.defineProperty(O_,"__esModule",{value:!0}),O_.ForRange=void 0;const lG=Fu,bD=hr,cG=ln,N_=On,G5e=pt,D_=p2,fG=j0;class W5e extends G5e.ExpressionDef{constructor(e,n,r){super({from:e,duration:n,timeframe:r}),this.from=e,this.duration=n,this.timeframe=r,this.elementType="forRange",this.legalChildTypes=[cG.FT.timestampT,cG.FT.dateT]}apply(e,n,r){const i=this.from.getExpression(e),s=r.getExpression(e);if(!this.typeCheck(r,s))return(0,bD.errorFor)("no time for range");const o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.log(`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,lG.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,lG.maxExpressionType)(i.expressionType,s.expressionType),value:(0,bD.errorFor)("for not number").value};const u=this.timeframe.text;let a=(0,N_.resolution)(u);if(i.dataType==="timestamp"&&(a="timestamp"),s.dataType==="date"&&a==="date"){const p=this.from,m=(0,N_.timeOffset)("date",i.value,"+",o.value,u),g=new D_.ExprTime("date",m);return new fG.Range(p,g).apply(e,n,r)}const l=D_.ExprTime.fromValue("timestamp",s);let c=this.from,f=i.value;if(i.dataType==="date"){const p=i.morphic&&i.morphic.timestamp;p?f=p:f=(0,N_.castDateToTimestamp)(f),c=new D_.ExprTime("timestamp",f,i.expressionType)}const x=(0,N_.timeOffset)("timestamp",f,"+",o.value,u),h=new D_.ExprTime("timestamp",x,i.expressionType);return new fG.Range(c,h).apply(e,n,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,bD.errorFor)("range has no value")}}O_.ForRange=W5e;var pr={};class vx extends Error{}class V5e extends vx{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Y5e extends vx{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class K5e extends vx{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class km extends vx{}class xG extends vx{constructor(e){super(`Invalid unit ${e}`)}}class lo extends vx{}class Q0 extends vx{constructor(){super("Zone is an abstract class")}}const ke="numeric",Vo="short",Ls="long",TD={year:ke,month:ke,day:ke},dG={year:ke,month:Vo,day:ke},X5e={year:ke,month:Vo,day:ke,weekday:Vo},hG={year:ke,month:Ls,day:ke},pG={year:ke,month:Ls,day:ke,weekday:Ls},gG={hour:ke,minute:ke},mG={hour:ke,minute:ke,second:ke},yG={hour:ke,minute:ke,second:ke,timeZoneName:Vo},EG={hour:ke,minute:ke,second:ke,timeZoneName:Ls},AG={hour:ke,minute:ke,hourCycle:"h23"},vG={hour:ke,minute:ke,second:ke,hourCycle:"h23"},SG={hour:ke,minute:ke,second:ke,hourCycle:"h23",timeZoneName:Vo},_G={hour:ke,minute:ke,second:ke,hourCycle:"h23",timeZoneName:Ls},CG={year:ke,month:ke,day:ke,hour:ke,minute:ke},bG={year:ke,month:ke,day:ke,hour:ke,minute:ke,second:ke},TG={year:ke,month:Vo,day:ke,hour:ke,minute:ke},RG={year:ke,month:Vo,day:ke,hour:ke,minute:ke,second:ke},J5e={year:ke,month:Vo,day:ke,weekday:Vo,hour:ke,minute:ke},OG={year:ke,month:Ls,day:ke,hour:ke,minute:ke,timeZoneName:Vo},NG={year:ke,month:Ls,day:ke,hour:ke,minute:ke,second:ke,timeZoneName:Vo},DG={year:ke,month:Ls,day:ke,weekday:Ls,hour:ke,minute:ke,timeZoneName:Ls},FG={year:ke,month:Ls,day:ke,weekday:Ls,hour:ke,minute:ke,second:ke,timeZoneName:Ls};function At(t){return typeof t>"u"}function Sx(t){return typeof t=="number"}function F_(t){return typeof t=="number"&&t%1===0}function Z5e(t){return typeof t=="string"}function eCe(t){return Object.prototype.toString.call(t)==="[object Date]"}function wG(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function tCe(t){return Array.isArray(t)?t:[t]}function LG(t,e,n){if(t.length!==0)return t.reduce((r,i)=>{const s=[e(i),i];return r&&n(r[0],s[0])===r[0]?r:s},null)[1]}function nCe(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function A2(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function yl(t,e,n){return F_(t)&&t>=e&&t<=n}function rCe(t,e){return t-e*Math.floor(t/e)}function Hn(t,e=2){const n=t<0;let r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function G0(t){if(!(At(t)||t===null||t===""))return parseInt(t,10)}function _x(t){if(!(At(t)||t===null||t===""))return parseFloat(t)}function RD(t){if(!(At(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function OD(t,e,n=!1){const r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function Pm(t){return t%4===0&&(t%100!==0||t%400===0)}function Mm(t){return Pm(t)?366:365}function w_(t,e){const n=rCe(e-1,12)+1,r=t+(e-n)/12;return n===2?Pm(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function ND(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(e.getUTCFullYear()-1900)),+e}function L_(t){const e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,n=t-1,r=(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400))%7;return e===4||r===3?53:52}function DD(t){return t>99?t:t>60?1900+t:2e3+t}function IG(t,e,n,r=null){const i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(s.timeZone=r);const o={timeZoneName:e,...s},u=new Intl.DateTimeFormat(n,o).formatToParts(i).find(a=>a.type.toLowerCase()==="timezonename");return u?u.value:null}function I_(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const r=parseInt(e,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function $G(t){const e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new lo(`Invalid unit value ${t}`);return e}function $_(t,e){const n={};for(const r in t)if(A2(t,r)){const i=t[r];if(i==null)continue;n[e(r)]=$G(i)}return n}function jm(t,e){const n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Hn(n,2)}:${Hn(r,2)}`;case"narrow":return`${i}${n}${r>0?`:${r}`:""}`;case"techie":return`${i}${Hn(n,2)}${Hn(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function B_(t){return nCe(t,["hour","minute","second","millisecond"])}const BG=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,iCe=["January","February","March","April","May","June","July","August","September","October","November","December"],kG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],sCe=["J","F","M","A","M","J","J","A","S","O","N","D"];function PG(t){switch(t){case"narrow":return[...sCe];case"short":return[...kG];case"long":return[...iCe];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const MG=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],jG=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],oCe=["M","T","W","T","F","S","S"];function UG(t){switch(t){case"narrow":return[...oCe];case"short":return[...jG];case"long":return[...MG];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const qG=["AM","PM"],uCe=["Before Christ","Anno Domini"],aCe=["BC","AD"],lCe=["B","A"];function HG(t){switch(t){case"narrow":return[...lCe];case"short":return[...aCe];case"long":return[...uCe];default:return null}}function cCe(t){return qG[t.hour<12?0:1]}function fCe(t,e){return UG(e)[t.weekday-1]}function xCe(t,e){return PG(e)[t.month-1]}function dCe(t,e){return HG(e)[t.year<0?0:1]}function hCe(t,e,n="always",r=!1){const i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},s=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&s){const f=t==="days";switch(e){case 1:return f?"tomorrow":`next ${i[t][0]}`;case-1:return f?"yesterday":`last ${i[t][0]}`;case 0:return f?"today":`this ${i[t][0]}`}}const o=Object.is(e,-0)||e<0,u=Math.abs(e),a=u===1,l=i[t],c=r?a?l[1]:l[2]||l[1]:a?i[t][0]:t;return o?`${u} ${c} ago`:`in ${u} ${c}`}function zG(t,e){let n="";for(const r of t)r.literal?n+=r.val:n+=e(r.val);return n}const pCe={D:TD,DD:dG,DDD:hG,DDDD:pG,t:gG,tt:mG,ttt:yG,tttt:EG,T:AG,TT:vG,TTT:SG,TTTT:_G,f:CG,ff:TG,fff:OG,ffff:DG,F:bG,FF:RG,FFF:NG,FFFF:FG};class is{static create(e,n={}){return new is(e,n)}static parseFormat(e){let n=null,r="",i=!1;const s=[];for(let o=0;o<e.length;o++){const u=e.charAt(o);u==="'"?(r.length>0&&s.push({literal:i,val:r}),n=null,r="",i=!i):i||u===n?r+=u:(r.length>0&&s.push({literal:!1,val:r}),r=u,n=u)}return r.length>0&&s.push({literal:i,val:r}),s}static macroTokenToFormatOpts(e){return pCe[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTime(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTimeParts(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).formatToParts()}resolvedOptions(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Hn(e,n);const r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const r=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(h,p)=>this.loc.extract(e,h,p),o=h=>e.isOffsetFixed&&e.offset===0&&h.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,h.format):"",u=()=>r?cCe(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),a=(h,p)=>r?xCe(e,h):s(p?{month:h}:{month:h,day:"numeric"},"month"),l=(h,p)=>r?fCe(e,h):s(p?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),c=h=>{const p=is.macroTokenToFormatOpts(h);return p?this.formatWithSystemDefault(e,p):h},f=h=>r?dCe(e,h):s({era:h},"era"),x=h=>{switch(h){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return u();case"d":return i?s({day:"numeric"},"day"):this.num(e.day);case"dd":return i?s({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?s({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?s({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return a("short",!0);case"LLLL":return a("long",!0);case"LLLLL":return a("narrow",!0);case"M":return i?s({month:"numeric"},"month"):this.num(e.month);case"MM":return i?s({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return a("short",!1);case"MMMM":return a("long",!1);case"MMMMM":return a("narrow",!1);case"y":return i?s({year:"numeric"},"year"):this.num(e.year);case"yy":return i?s({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?s({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?s({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(h)}};return zG(is.parseFormat(n),x)}formatDurationFromString(e,n){const r=a=>{switch(a[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=a=>l=>{const c=r(l);return c?this.num(a.get(c),l.length):l},s=is.parseFormat(n),o=s.reduce((a,{literal:l,val:c})=>l?a:a.concat(c),[]),u=e.shiftTo(...o.map(r).filter(a=>a));return zG(s,i(u))}}class Yo{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}let v2=class{get type(){throw new Q0}get name(){throw new Q0}get ianaName(){return this.name}get isUniversal(){throw new Q0}offsetName(e,n){throw new Q0}formatOffset(e,n){throw new Q0}offset(e){throw new Q0}equals(e){throw new Q0}get isValid(){throw new Q0}},FD=null;class k_ extends v2{static get instance(){return FD===null&&(FD=new k_),FD}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return IG(e,n,r)}formatOffset(e,n){return jm(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}let P_={};function gCe(t){return P_[t]||(P_[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),P_[t]}const mCe={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function yCe(t,e){const n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,i,s,o,u,a,l,c]=r;return[o,i,s,u,a,l,c]}function ECe(t,e){const n=t.formatToParts(e),r=[];for(let i=0;i<n.length;i++){const{type:s,value:o}=n[i],u=mCe[s];s==="era"?r[u]=o:At(u)||(r[u]=parseInt(o,10))}return r}let M_={};class Zu extends v2{static create(e){return M_[e]||(M_[e]=new Zu(e)),M_[e]}static resetCache(){M_={},P_={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=Zu.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return IG(e,n,r,this.name)}formatOffset(e,n){return jm(this.offset(e),n)}offset(e){const n=new Date(e);if(isNaN(n))return NaN;const r=gCe(this.name);let[i,s,o,u,a,l,c]=r.formatToParts?ECe(r,n):yCe(r,n);u==="BC"&&(i=-Math.abs(i)+1);const x=ND({year:i,month:s,day:o,hour:a===24?0:a,minute:l,second:c,millisecond:0});let h=+n;const p=h%1e3;return h-=p>=0?p:1e3+p,(x-h)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let wD=null;class Jr extends v2{static get utcInstance(){return wD===null&&(wD=new Jr(0)),wD}static instance(e){return e===0?Jr.utcInstance:new Jr(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Jr(I_(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${jm(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${jm(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return jm(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class QG extends v2{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function W0(t,e){if(At(t)||t===null)return e;if(t instanceof v2)return t;if(Z5e(t)){const n=t.toLowerCase();return n==="local"||n==="system"?e:n==="utc"||n==="gmt"?Jr.utcInstance:Jr.parseSpecifier(n)||Zu.create(t)}else return Sx(t)?Jr.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new QG(t)}let GG=()=>Date.now(),WG="system",VG=null,YG=null,KG=null,XG;class zn{static get now(){return GG}static set now(e){GG=e}static set defaultZone(e){WG=e}static get defaultZone(){return W0(WG,k_.instance)}static get defaultLocale(){return VG}static set defaultLocale(e){VG=e}static get defaultNumberingSystem(){return YG}static set defaultNumberingSystem(e){YG=e}static get defaultOutputCalendar(){return KG}static set defaultOutputCalendar(e){KG=e}static get throwOnInvalid(){return XG}static set throwOnInvalid(e){XG=e}static resetCaches(){pn.resetCache(),Zu.resetCache()}}let JG={};function ACe(t,e={}){const n=JSON.stringify([t,e]);let r=JG[n];return r||(r=new Intl.ListFormat(t,e),JG[n]=r),r}let LD={};function ID(t,e={}){const n=JSON.stringify([t,e]);let r=LD[n];return r||(r=new Intl.DateTimeFormat(t,e),LD[n]=r),r}let $D={};function vCe(t,e={}){const n=JSON.stringify([t,e]);let r=$D[n];return r||(r=new Intl.NumberFormat(t,e),$D[n]=r),r}let BD={};function SCe(t,e={}){const{base:n,...r}=e,i=JSON.stringify([t,r]);let s=BD[i];return s||(s=new Intl.RelativeTimeFormat(t,e),BD[i]=s),s}let Um=null;function _Ce(){return Um||(Um=new Intl.DateTimeFormat().resolvedOptions().locale,Um)}function CCe(t){const e=t.indexOf("-u-");if(e===-1)return[t];{let n;const r=t.substring(0,e);try{n=ID(t).resolvedOptions()}catch{n=ID(r).resolvedOptions()}const{numberingSystem:i,calendar:s}=n;return[r,i,s]}}function bCe(t,e,n){return(n||e)&&(t+="-u",n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function TCe(t){const e=[];for(let n=1;n<=12;n++){const r=ot.utc(2016,n,1);e.push(t(r))}return e}function RCe(t){const e=[];for(let n=1;n<=7;n++){const r=ot.utc(2016,11,13+n);e.push(t(r))}return e}function j_(t,e,n,r,i){const s=t.listingMode(n);return s==="error"?null:s==="en"?r(e):i(e)}function OCe(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}class NCe{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;const{padTo:i,floor:s,...o}=r;if(!n||Object.keys(o).length>0){const u={useGrouping:!1,...r};r.padTo>0&&(u.minimumIntegerDigits=r.padTo),this.inf=vCe(e,u)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):OD(e,3);return Hn(n,this.padTo)}}}class DCe{constructor(e,n,r){this.opts=r;let i;if(e.zone.isUniversal){const o=-1*(e.offset/60),u=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&Zu.create(u).valid?(i=u,this.dt=e):(i="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:ot.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);const s={...this.opts};i&&(s.timeZone=i),this.dtf=ID(n,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}}class FCe{constructor(e,n,r){this.opts={style:"long",...r},!n&&wG()&&(this.rtf=SCe(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):hCe(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}class pn{static fromOpts(e){return pn.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,n,r,i=!1){const s=e||zn.defaultLocale,o=s||(i?"en-US":_Ce()),u=n||zn.defaultNumberingSystem,a=r||zn.defaultOutputCalendar;return new pn(o,u,a,s)}static resetCache(){Um=null,LD={},$D={},BD={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r}={}){return pn.create(e,n,r)}constructor(e,n,r,i){const[s,o,u]=CCe(e);this.locale=s,this.numberingSystem=n||o||null,this.outputCalendar=r||u||null,this.intl=bCe(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=OCe(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:pn.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1,r=!0){return j_(this,e,r,PG,()=>{const i=n?{month:e,day:"numeric"}:{month:e},s=n?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=TCe(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,n=!1,r=!0){return j_(this,e,r,UG,()=>{const i=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=n?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=RCe(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return j_(this,void 0,e,()=>qG,()=>{if(!this.meridiemCache){const n={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ot.utc(2016,11,13,9),ot.utc(2016,11,13,19)].map(r=>this.extract(r,n,"dayperiod"))}return this.meridiemCache})}eras(e,n=!0){return j_(this,e,n,HG,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[ot.utc(-40,1,1),ot.utc(2017,1,1)].map(i=>this.extract(i,r,"era"))),this.eraCache[e]})}extract(e,n,r){const i=this.dtFormatter(e,n),s=i.formatToParts(),o=s.find(u=>u.type.toLowerCase()===r);return o?o.value:null}numberFormatter(e={}){return new NCe(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new DCe(e,this.intl,n)}relFormatter(e={}){return new FCe(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ACe(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}}function S2(...t){const e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function _2(...t){return e=>t.reduce(([n,r,i],s)=>{const[o,u,a]=s(e,i);return[{...n,...o},u||r,a]},[{},null,1]).slice(0,2)}function C2(t,...e){if(t==null)return[null,null];for(const[n,r]of e){const i=n.exec(t);if(i)return r(i)}return[null,null]}function ZG(...t){return(e,n)=>{const r={};let i;for(i=0;i<t.length;i++)r[t[i]]=G0(e[n+i]);return[r,null,n+i]}}const eW=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,wCe=`(?:${eW.source}?(?:\\[(${BG.source})\\])?)?`,kD=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,tW=RegExp(`${kD.source}${wCe}`),PD=RegExp(`(?:T${tW.source})?`),LCe=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,ICe=/(\d{4})-?W(\d\d)(?:-?(\d))?/,$Ce=/(\d{4})-?(\d{3})/,BCe=ZG("weekYear","weekNumber","weekDay"),kCe=ZG("year","ordinal"),PCe=/(\d{4})-(\d\d)-(\d\d)/,nW=RegExp(`${kD.source} ?(?:${eW.source}|(${BG.source}))?`),MCe=RegExp(`(?: ${nW.source})?`);function b2(t,e,n){const r=t[e];return At(r)?n:G0(r)}function jCe(t,e){return[{year:b2(t,e),month:b2(t,e+1,1),day:b2(t,e+2,1)},null,e+3]}function T2(t,e){return[{hours:b2(t,e,0),minutes:b2(t,e+1,0),seconds:b2(t,e+2,0),milliseconds:RD(t[e+3])},null,e+4]}function qm(t,e){const n=!t[e]&&!t[e+1],r=I_(t[e+1],t[e+2]),i=n?null:Jr.instance(r);return[{},i,e+3]}function Hm(t,e){const n=t[e]?Zu.create(t[e]):null;return[{},n,e+1]}const UCe=RegExp(`^T?${kD.source}$`),qCe=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function HCe(t){const[e,n,r,i,s,o,u,a,l]=t,c=e[0]==="-",f=a&&a[0]==="-",x=(h,p=!1)=>h!==void 0&&(p||h&&c)?-h:h;return[{years:x(_x(n)),months:x(_x(r)),weeks:x(_x(i)),days:x(_x(s)),hours:x(_x(o)),minutes:x(_x(u)),seconds:x(_x(a),a==="-0"),milliseconds:x(RD(l),f)}]}const zCe={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function MD(t,e,n,r,i,s,o){const u={year:e.length===2?DD(G0(e)):G0(e),month:kG.indexOf(n)+1,day:G0(r),hour:G0(i),minute:G0(s)};return o&&(u.second=G0(o)),t&&(u.weekday=t.length>3?MG.indexOf(t)+1:jG.indexOf(t)+1),u}const QCe=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function GCe(t){const[,e,n,r,i,s,o,u,a,l,c,f]=t,x=MD(e,i,r,n,s,o,u);let h;return a?h=zCe[a]:l?h=0:h=I_(c,f),[x,new Jr(h)]}function WCe(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const VCe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,YCe=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,KCe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function rW(t){const[,e,n,r,i,s,o,u]=t;return[MD(e,i,r,n,s,o,u),Jr.utcInstance]}function XCe(t){const[,e,n,r,i,s,o,u]=t;return[MD(e,u,n,r,i,s,o),Jr.utcInstance]}const JCe=S2(LCe,PD),ZCe=S2(ICe,PD),ebe=S2($Ce,PD),tbe=S2(tW),iW=_2(jCe,T2,qm,Hm),nbe=_2(BCe,T2,qm,Hm),rbe=_2(kCe,T2,qm,Hm),ibe=_2(T2,qm,Hm);function sbe(t){return C2(t,[JCe,iW],[ZCe,nbe],[ebe,rbe],[tbe,ibe])}function obe(t){return C2(WCe(t),[QCe,GCe])}function ube(t){return C2(t,[VCe,rW],[YCe,rW],[KCe,XCe])}function abe(t){return C2(t,[qCe,HCe])}const lbe=_2(T2);function cbe(t){return C2(t,[UCe,lbe])}const fbe=S2(PCe,MCe),xbe=S2(nW),dbe=_2(T2,qm,Hm);function hbe(t){return C2(t,[fbe,iW],[xbe,dbe])}const pbe="Invalid Duration",sW={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},gbe={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...sW},co=146097/400,R2=146097/4800,mbe={years:{quarters:4,months:12,weeks:co/7,days:co,hours:co*24,minutes:co*24*60,seconds:co*24*60*60,milliseconds:co*24*60*60*1e3},quarters:{months:3,weeks:co/28,days:co/4,hours:co*24/4,minutes:co*24*60/4,seconds:co*24*60*60/4,milliseconds:co*24*60*60*1e3/4},months:{weeks:R2/7,days:R2,hours:R2*24,minutes:R2*24*60,seconds:R2*24*60*60,milliseconds:R2*24*60*60*1e3},...sW},Cx=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ybe=Cx.slice(0).reverse();function bx(t,e,n=!1){const r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new vt(r)}function Ebe(t){return t<0?Math.floor(t):Math.ceil(t)}function oW(t,e,n,r,i){const s=t[i][n],o=e[n]/s,u=Math.sign(o)===Math.sign(r[i]),a=!u&&r[i]!==0&&Math.abs(o)<=1?Ebe(o):Math.trunc(o);r[i]+=a,e[n]-=a*s}function Abe(t,e){ybe.reduce((n,r)=>At(e[r])?n:(n&&oW(t,e,n,e,r),r),null)}class vt{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||pn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n?mbe:gbe,this.isLuxonDuration=!0}static fromMillis(e,n){return vt.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new lo(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new vt({values:$_(e,vt.normalizeUnit),loc:pn.fromObject(n),conversionAccuracy:n.conversionAccuracy})}static fromDurationLike(e){if(Sx(e))return vt.fromMillis(e);if(vt.isDuration(e))return e;if(typeof e=="object")return vt.fromObject(e);throw new lo(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[r]=abe(e);return r?vt.fromObject(r,n):vt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[r]=cbe(e);return r?vt.fromObject(r,n):vt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new lo("need to specify a reason the Duration is invalid");const r=e instanceof Yo?e:new Yo(e,n);if(zn.throwOnInvalid)throw new K5e(r);return new vt({invalid:r})}static normalizeUnit(e){const n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new xG(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){const r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?is.create(this.loc,r).formatDurationFromString(this,e):pbe}toHuman(e={}){const n=Cx.map(r=>{const i=this.values[r];return At(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=OD(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();if(n<0||n>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};const r=this.shiftTo("hours","minutes","seconds","milliseconds");let i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||r.seconds!==0||r.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||r.milliseconds!==0)&&(i+=".SSS"));let s=r.toFormat(i);return e.includePrefix&&(s="T"+s),s}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e),r={};for(const i of Cx)(A2(n.values,i)||A2(this.values,i))&&(r[i]=n.get(i)+this.get(i));return bx(this,{values:r},!0)}minus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const r of Object.keys(this.values))n[r]=$G(e(this.values[r],r));return bx(this,{values:n},!0)}get(e){return this[vt.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...$_(e,vt.normalizeUnit)};return bx(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n}),s={loc:i};return r&&(s.conversionAccuracy=r),bx(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Abe(this.matrix,e),bx(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>vt.normalizeUnit(o));const n={},r={},i=this.toObject();let s;for(const o of Cx)if(e.indexOf(o)>=0){s=o;let u=0;for(const l in r)u+=this.matrix[l][o]*r[l],r[l]=0;Sx(i[o])&&(u+=i[o]);const a=Math.trunc(u);n[o]=a,r[o]=(u*1e3-a*1e3)/1e3;for(const l in i)Cx.indexOf(l)>Cx.indexOf(o)&&oW(this.matrix,i,l,n,o)}else Sx(i[o])&&(r[o]=i[o]);for(const o in r)r[o]!==0&&(n[s]+=o===s?r[o]:r[o]/this.matrix[s][o]);return bx(this,{values:n},!0).normalize()}negate(){if(!this.isValid)return this;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return bx(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(r,i){return r===void 0||r===0?i===void 0||i===0:r===i}for(const r of Cx)if(!n(this.values[r],e.values[r]))return!1;return!0}}const zm="Invalid Interval";function vbe(t,e){return!t||!t.isValid?gn.invalid("missing or invalid start"):!e||!e.isValid?gn.invalid("missing or invalid end"):e<t?gn.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class gn{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new lo("need to specify a reason the Interval is invalid");const r=e instanceof Yo?e:new Yo(e,n);if(zn.throwOnInvalid)throw new Y5e(r);return new gn({invalid:r})}static fromDateTimes(e,n){const r=Vm(e),i=Vm(n),s=vbe(r,i);return s??new gn({start:r,end:i})}static after(e,n){const r=vt.fromDurationLike(n),i=Vm(e);return gn.fromDateTimes(i,i.plus(r))}static before(e,n){const r=vt.fromDurationLike(n),i=Vm(e);return gn.fromDateTimes(i.minus(r),i)}static fromISO(e,n){const[r,i]=(e||"").split("/",2);if(r&&i){let s,o;try{s=ot.fromISO(r,n),o=s.isValid}catch{o=!1}let u,a;try{u=ot.fromISO(i,n),a=u.isValid}catch{a=!1}if(o&&a)return gn.fromDateTimes(s,u);if(o){const l=vt.fromISO(i,n);if(l.isValid)return gn.after(s,l)}else if(a){const l=vt.fromISO(r,n);if(l.isValid)return gn.before(u,l)}}return gn.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;const n=this.start.startOf(e),r=this.end.startOf(e);return Math.floor(r.diff(n,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?gn.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Vm).filter(o=>this.contains(o)).sort(),r=[];let{s:i}=this,s=0;for(;i<this.e;){const o=n[s]||this.e,u=+o>+this.e?this.e:o;r.push(gn.fromDateTimes(i,u)),i=u,s+=1}return r}splitBy(e){const n=vt.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,i=1,s;const o=[];for(;r<this.e;){const u=this.start.plus(n.mapUnits(a=>a*i));s=+u>+this.e?this.e:u,o.push(gn.fromDateTimes(r,s)),r=s,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:gn.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return gn.fromDateTimes(n,r)}static merge(e){const[n,r]=e.sort((i,s)=>i.s-s.s).reduce(([i,s],o)=>s?s.overlaps(o)||s.abutsStart(o)?[i,s.union(o)]:[i.concat([s]),o]:[i,o],[[],null]);return r&&n.push(r),n}static xor(e){let n=null,r=0;const i=[],s=e.map(a=>[{time:a.s,type:"s"},{time:a.e,type:"e"}]),o=Array.prototype.concat(...s),u=o.sort((a,l)=>a.time-l.time);for(const a of u)r+=a.type==="s"?1:-1,r===1?n=a.time:(n&&+n!=+a.time&&i.push(gn.fromDateTimes(n,a.time)),n=null);return gn.merge(i)}difference(...e){return gn.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:zm}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:zm}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:zm}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:zm}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:zm}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):vt.invalid(this.invalidReason)}mapEndpoints(e){return gn.fromDateTimes(e(this.s),e(this.e))}}let Qm=class{static hasDST(e=zn.defaultZone){const n=ot.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Zu.isValidZone(e)}static normalizeZone(e){return W0(e,zn.defaultZone)}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||pn.create(n,r,s)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||pn.create(n,r,s)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||pn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||pn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return pn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return pn.create(n,null,"gregory").eras(e)}static features(){return{relative:wG()}}};function uW(t,e){const n=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(vt.fromMillis(r).as("days"))}function Sbe(t,e,n){const r=[["years",(u,a)=>a.year-u.year],["quarters",(u,a)=>a.quarter-u.quarter],["months",(u,a)=>a.month-u.month+(a.year-u.year)*12],["weeks",(u,a)=>{const l=uW(u,a);return(l-l%7)/7}],["days",uW]],i={};let s,o;for(const[u,a]of r)if(n.indexOf(u)>=0){s=u;let l=a(t,e);o=t.plus({[u]:l}),o>e?(t=t.plus({[u]:l-1}),l-=1):t=o,i[u]=l}return[t,i,o,s]}function _be(t,e,n,r){let[i,s,o,u]=Sbe(t,e,n);const a=e-i,l=n.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[u]:1})),o!==i&&(s[u]=(s[u]||0)+a/(o-i)));const c=vt.fromObject(s,r);return l.length>0?vt.fromMillis(a,r).shiftTo(...l).plus(c):c}const jD={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},aW={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Cbe=jD.hanidec.replace(/[\[|\]]/g,"").split("");function bbe(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);if(t[n].search(jD.hanidec)!==-1)e+=Cbe.indexOf(t[n]);else for(const i in aW){const[s,o]=aW[i];r>=s&&r<=o&&(e+=r-s)}}return parseInt(e,10)}else return e}function Ko({numberingSystem:t},e=""){return new RegExp(`${jD[t||"latn"]}${e}`)}const Tbe="missing Intl.DateTimeFormat.formatToParts support";function Ft(t,e=n=>n){return{regex:t,deser:([n])=>e(bbe(n))}}const lW="[  ]",cW=new RegExp(lW,"g");function Rbe(t){return t.replace(/\./g,"\\.?").replace(cW,lW)}function fW(t){return t.replace(/\./g,"").replace(cW," ").toLowerCase()}function Xo(t,e){return t===null?null:{regex:RegExp(t.map(Rbe).join("|")),deser:([n])=>t.findIndex(r=>fW(n)===fW(r))+e}}function xW(t,e){return{regex:t,deser:([,n,r])=>I_(n,r),groups:e}}function UD(t){return{regex:t,deser:([e])=>e}}function Obe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Nbe(t,e){const n=Ko(e),r=Ko(e,"{2}"),i=Ko(e,"{3}"),s=Ko(e,"{4}"),o=Ko(e,"{6}"),u=Ko(e,"{1,2}"),a=Ko(e,"{1,3}"),l=Ko(e,"{1,6}"),c=Ko(e,"{1,9}"),f=Ko(e,"{2,4}"),x=Ko(e,"{4,6}"),h=g=>({regex:RegExp(Obe(g.val)),deser:([y])=>y,literal:!0}),m=(g=>{if(t.literal)return h(g);switch(g.val){case"G":return Xo(e.eras("short",!1),0);case"GG":return Xo(e.eras("long",!1),0);case"y":return Ft(l);case"yy":return Ft(f,DD);case"yyyy":return Ft(s);case"yyyyy":return Ft(x);case"yyyyyy":return Ft(o);case"M":return Ft(u);case"MM":return Ft(r);case"MMM":return Xo(e.months("short",!0,!1),1);case"MMMM":return Xo(e.months("long",!0,!1),1);case"L":return Ft(u);case"LL":return Ft(r);case"LLL":return Xo(e.months("short",!1,!1),1);case"LLLL":return Xo(e.months("long",!1,!1),1);case"d":return Ft(u);case"dd":return Ft(r);case"o":return Ft(a);case"ooo":return Ft(i);case"HH":return Ft(r);case"H":return Ft(u);case"hh":return Ft(r);case"h":return Ft(u);case"mm":return Ft(r);case"m":return Ft(u);case"q":return Ft(u);case"qq":return Ft(r);case"s":return Ft(u);case"ss":return Ft(r);case"S":return Ft(a);case"SSS":return Ft(i);case"u":return UD(c);case"uu":return UD(u);case"uuu":return Ft(n);case"a":return Xo(e.meridiems(),0);case"kkkk":return Ft(s);case"kk":return Ft(f,DD);case"W":return Ft(u);case"WW":return Ft(r);case"E":case"c":return Ft(n);case"EEE":return Xo(e.weekdays("short",!1,!1),1);case"EEEE":return Xo(e.weekdays("long",!1,!1),1);case"ccc":return Xo(e.weekdays("short",!0,!1),1);case"cccc":return Xo(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return xW(new RegExp(`([+-]${u.source})(?::(${r.source}))?`),2);case"ZZZ":return xW(new RegExp(`([+-]${u.source})(${r.source})?`),2);case"z":return UD(/[a-z_+-/]{1,256}?/i);default:return h(g)}})(t)||{invalidReason:Tbe};return m.token=t,m}const Dbe={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"}};function Fbe(t,e,n){const{type:r,value:i}=t;if(r==="literal")return{literal:!0,val:i};const s=n[r];let o=Dbe[r];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function wbe(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function Lbe(t,e,n){const r=t.match(e);if(r){const i={};let s=1;for(const o in n)if(A2(n,o)){const u=n[o],a=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(r.slice(s,s+a))),s+=a}return[r,i]}else return[r,{}]}function Ibe(t){const e=s=>{switch(s){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let n=null,r;return At(t.z)||(n=Zu.create(t.z)),At(t.Z)||(n||(n=new Jr(t.Z)),r=t.Z),At(t.q)||(t.M=(t.q-1)*3+1),At(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),At(t.u)||(t.S=RD(t.u)),[Object.keys(t).reduce((s,o)=>{const u=e(o);return u&&(s[u]=t[o]),s},{}),n,r]}let qD=null;function $be(){return qD||(qD=ot.fromMillis(1555555555555)),qD}function Bbe(t,e){if(t.literal)return t;const n=is.macroTokenToFormatOpts(t.val);if(!n)return t;const s=is.create(e,n).formatDateTimeParts($be()).map(o=>Fbe(o,e,n));return s.includes(void 0)?t:s}function kbe(t,e){return Array.prototype.concat(...t.map(n=>Bbe(n,e)))}function dW(t,e,n){const r=kbe(is.parseFormat(n),t),i=r.map(o=>Nbe(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:r,invalidReason:s.invalidReason};{const[o,u]=wbe(i),a=RegExp(o,"i"),[l,c]=Lbe(e,a,u),[f,x,h]=c?Ibe(c):[null,null,void 0];if(A2(c,"a")&&A2(c,"H"))throw new km("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:r,regex:a,rawMatches:l,matches:c,result:f,zone:x,specificOffset:h}}}function Pbe(t,e,n){const{result:r,zone:i,specificOffset:s,invalidReason:o}=dW(t,e,n);return[r,i,s,o]}const hW=[0,31,59,90,120,151,181,212,243,273,304,334],pW=[0,31,60,91,121,152,182,213,244,274,305,335];function fo(t,e){return new Yo("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function gW(t,e,n){const r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);const i=r.getUTCDay();return i===0?7:i}function mW(t,e,n){return n+(Pm(t)?pW:hW)[e-1]}function yW(t,e){const n=Pm(t)?pW:hW,r=n.findIndex(s=>s<e),i=e-n[r];return{month:r+1,day:i}}function HD(t){const{year:e,month:n,day:r}=t,i=mW(e,n,r),s=gW(e,n,r);let o=Math.floor((i-s+10)/7),u;return o<1?(u=e-1,o=L_(u)):o>L_(e)?(u=e+1,o=1):u=e,{weekYear:u,weekNumber:o,weekday:s,...B_(t)}}function EW(t){const{weekYear:e,weekNumber:n,weekday:r}=t,i=gW(e,1,4),s=Mm(e);let o=n*7+r-i-3,u;o<1?(u=e-1,o+=Mm(u)):o>s?(u=e+1,o-=Mm(e)):u=e;const{month:a,day:l}=yW(u,o);return{year:u,month:a,day:l,...B_(t)}}function zD(t){const{year:e,month:n,day:r}=t,i=mW(e,n,r);return{year:e,ordinal:i,...B_(t)}}function AW(t){const{year:e,ordinal:n}=t,{month:r,day:i}=yW(e,n);return{year:e,month:r,day:i,...B_(t)}}function Mbe(t){const e=F_(t.weekYear),n=yl(t.weekNumber,1,L_(t.weekYear)),r=yl(t.weekday,1,7);return e?n?r?!1:fo("weekday",t.weekday):fo("week",t.week):fo("weekYear",t.weekYear)}function jbe(t){const e=F_(t.year),n=yl(t.ordinal,1,Mm(t.year));return e?n?!1:fo("ordinal",t.ordinal):fo("year",t.year)}function vW(t){const e=F_(t.year),n=yl(t.month,1,12),r=yl(t.day,1,w_(t.year,t.month));return e?n?r?!1:fo("day",t.day):fo("month",t.month):fo("year",t.year)}function SW(t){const{hour:e,minute:n,second:r,millisecond:i}=t,s=yl(e,0,23)||e===24&&n===0&&r===0&&i===0,o=yl(n,0,59),u=yl(r,0,59),a=yl(i,0,999);return s?o?u?a?!1:fo("millisecond",i):fo("second",r):fo("minute",n):fo("hour",e)}const QD="Invalid DateTime",_W=864e13;function U_(t){return new Yo("unsupported zone",`the zone "${t.name}" is not supported`)}function GD(t){return t.weekData===null&&(t.weekData=HD(t.c)),t.weekData}function Gm(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new ot({...n,...e,old:n})}function CW(t,e,n){let r=t-e*60*1e3;const i=n.offset(r);if(e===i)return[r,e];r-=(i-e)*60*1e3;const s=n.offset(r);return i===s?[r,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function bW(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function q_(t,e,n){return CW(ND(t),e,n)}function TW(t,e){const n=t.o,r=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:r,month:i,day:Math.min(t.c.day,w_(r,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=vt.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),u=ND(s);let[a,l]=CW(u,n,t.zone);return o!==0&&(a+=o,l=t.zone.offset(a)),{ts:a,o:l}}function Wm(t,e,n,r,i,s){const{setZone:o,zone:u}=n;if(t&&Object.keys(t).length!==0){const a=e||u,l=ot.fromObject(t,{...n,zone:a,specificOffset:s});return o?l:l.setZone(u)}else return ot.invalid(new Yo("unparsable",`the input "${i}" can't be parsed as ${r}`))}function H_(t,e,n=!0){return t.isValid?is.create(pn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function WD(t,e){const n=t.c.year>9999||t.c.year<0;let r="";return n&&t.c.year>=0&&(r+="+"),r+=Hn(t.c.year,n?6:4),e?(r+="-",r+=Hn(t.c.month),r+="-",r+=Hn(t.c.day)):(r+=Hn(t.c.month),r+=Hn(t.c.day)),r}function RW(t,e,n,r,i,s){let o=Hn(t.c.hour);return e?(o+=":",o+=Hn(t.c.minute),(t.c.second!==0||!n)&&(o+=":")):o+=Hn(t.c.minute),(t.c.second!==0||!n)&&(o+=Hn(t.c.second),(t.c.millisecond!==0||!r)&&(o+=".",o+=Hn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=Hn(Math.trunc(-t.o/60)),o+=":",o+=Hn(Math.trunc(-t.o%60))):(o+="+",o+=Hn(Math.trunc(t.o/60)),o+=":",o+=Hn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}const OW={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ube={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},qbe={ordinal:1,hour:0,minute:0,second:0,millisecond:0},NW=["year","month","day","hour","minute","second","millisecond"],Hbe=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],zbe=["year","ordinal","hour","minute","second","millisecond"];function DW(t){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new xG(t);return e}function FW(t,e){const n=W0(e.zone,zn.defaultZone),r=pn.fromObject(e),i=zn.now();let s,o;if(At(t.year))s=i;else{for(const l of NW)At(t[l])&&(t[l]=OW[l]);const u=vW(t)||SW(t);if(u)return ot.invalid(u);const a=n.offset(i);[s,o]=q_(t,a,n)}return new ot({ts:s,zone:n,loc:r,o})}function wW(t,e,n){const r=At(n.round)?!0:n.round,i=(o,u)=>(o=OD(o,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(o,u)),s=o=>n.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(n.unit)return i(s(n.unit),n.unit);for(const o of n.units){const u=s(o);if(Math.abs(u)>=1)return i(u,o)}return i(t>e?-0:0,n.units[n.units.length-1])}function LW(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}class ot{constructor(e){const n=e.zone||zn.defaultZone;let r=e.invalid||(Number.isNaN(e.ts)?new Yo("invalid input"):null)||(n.isValid?null:U_(n));this.ts=At(e.ts)?zn.now():e.ts;let i=null,s=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[i,s]=[e.old.c,e.old.o];else{const u=n.offset(this.ts);i=bW(this.ts,u),r=Number.isNaN(i.year)?new Yo("invalid input"):null,i=r?null:i,s=r?null:u}this._zone=n,this.loc=e.loc||pn.create(),this.invalid=r,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new ot({})}static local(){const[e,n]=LW(arguments),[r,i,s,o,u,a,l]=n;return FW({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static utc(){const[e,n]=LW(arguments),[r,i,s,o,u,a,l]=n;return e.zone=Jr.utcInstance,FW({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static fromJSDate(e,n={}){const r=eCe(e)?e.valueOf():NaN;if(Number.isNaN(r))return ot.invalid("invalid input");const i=W0(n.zone,zn.defaultZone);return i.isValid?new ot({ts:r,zone:i,loc:pn.fromObject(n)}):ot.invalid(U_(i))}static fromMillis(e,n={}){if(Sx(e))return e<-_W||e>_W?ot.invalid("Timestamp out of range"):new ot({ts:e,zone:W0(n.zone,zn.defaultZone),loc:pn.fromObject(n)});throw new lo(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(Sx(e))return new ot({ts:e*1e3,zone:W0(n.zone,zn.defaultZone),loc:pn.fromObject(n)});throw new lo("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const r=W0(n.zone,zn.defaultZone);if(!r.isValid)return ot.invalid(U_(r));const i=zn.now(),s=At(n.specificOffset)?r.offset(i):n.specificOffset,o=$_(e,DW),u=!At(o.ordinal),a=!At(o.year),l=!At(o.month)||!At(o.day),c=a||l,f=o.weekYear||o.weekNumber,x=pn.fromObject(n);if((c||u)&&f)throw new km("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&u)throw new km("Can't mix ordinal dates with month/day");const h=f||o.weekday&&!c;let p,m,g=bW(i,s);h?(p=Hbe,m=Ube,g=HD(g)):u?(p=zbe,m=qbe,g=zD(g)):(p=NW,m=OW);let y=!1;for(const b of p){const R=o[b];At(R)?y?o[b]=m[b]:o[b]=g[b]:y=!0}const E=h?Mbe(o):u?jbe(o):vW(o),A=E||SW(o);if(A)return ot.invalid(A);const v=h?EW(o):u?AW(o):o,[S,C]=q_(v,s,r),_=new ot({ts:S,zone:r,o:C,loc:x});return o.weekday&&c&&e.weekday!==_.weekday?ot.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,n={}){const[r,i]=sbe(e);return Wm(r,i,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[r,i]=obe(e);return Wm(r,i,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[r,i]=ube(e);return Wm(r,i,n,"HTTP",n)}static fromFormat(e,n,r={}){if(At(e)||At(n))throw new lo("fromFormat requires an input string and a format");const{locale:i=null,numberingSystem:s=null}=r,o=pn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[u,a,l,c]=Pbe(o,e,n);return c?ot.invalid(c):Wm(u,a,r,`format ${n}`,e,l)}static fromString(e,n,r={}){return ot.fromFormat(e,n,r)}static fromSQL(e,n={}){const[r,i]=hbe(e);return Wm(r,i,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new lo("need to specify a reason the DateTime is invalid");const r=e instanceof Yo?e:new Yo(e,n);if(zn.throwOnInvalid)throw new V5e(r);return new ot({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?GD(this).weekYear:NaN}get weekNumber(){return this.isValid?GD(this).weekNumber:NaN}get weekday(){return this.isValid?GD(this).weekday:NaN}get ordinal(){return this.isValid?zD(this.c).ordinal:NaN}get monthShort(){return this.isValid?Qm.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Qm.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Qm.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Qm.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}get isInLeapYear(){return Pm(this.year)}get daysInMonth(){return w_(this.year,this.month)}get daysInYear(){return this.isValid?Mm(this.year):NaN}get weeksInWeekYear(){return this.isValid?L_(this.weekYear):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:r,calendar:i}=is.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:i}}toUTC(e=0,n={}){return this.setZone(Jr.instance(e),n)}toLocal(){return this.setZone(zn.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=W0(e,zn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(n||r){const s=e.offset(this.ts),o=this.toObject();[i]=q_(o,s,e)}return Gm(this,{ts:i,zone:e})}else return ot.invalid(U_(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return Gm(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=$_(e,DW),r=!At(n.weekYear)||!At(n.weekNumber)||!At(n.weekday),i=!At(n.ordinal),s=!At(n.year),o=!At(n.month)||!At(n.day),u=s||o,a=n.weekYear||n.weekNumber;if((u||i)&&a)throw new km("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new km("Can't mix ordinal dates with month/day");let l;r?l=EW({...HD(this.c),...n}):At(n.ordinal)?(l={...this.toObject(),...n},At(n.day)&&(l.day=Math.min(w_(l.year,l.month),l.day))):l=AW({...zD(this.c),...n});const[c,f]=q_(l,this.o,this.zone);return Gm(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e);return Gm(this,TW(this,n))}minus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e).negate();return Gm(this,TW(this,n))}startOf(e){if(!this.isValid)return this;const n={},r=vt.normalizeUnit(e);switch(r){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break}if(r==="weeks"&&(n.weekday=1),r==="quarters"){const i=Math.ceil(this.month/3);n.month=(i-1)*3+1}return this.set(n)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,n={}){return this.isValid?is.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):QD}toLocaleString(e=TD,n={}){return this.isValid?is.create(this.loc.clone(n),e).formatDateTime(this):QD}toLocaleParts(e={}){return this.isValid?is.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;const o=e==="extended";let u=WD(this,o);return u+="T",u+=RW(this,o,n,r,i,s),u}toISODate({format:e="extended"}={}){return this.isValid?WD(this,e==="extended"):null}toISOWeekDate(){return H_(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+RW(this,o==="extended",n,e,r,s):null}toRFC2822(){return H_(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return H_(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?WD(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let i="HH:mm:ss.SSS";return(n||e)&&(r&&(i+=" "),n?i+="z":e&&(i+="ZZ")),H_(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():QD}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return vt.invalid("created by diffing an invalid DateTime");const i={locale:this.locale,numberingSystem:this.numberingSystem,...r},s=tCe(n).map(vt.normalizeUnit),o=e.valueOf()>this.valueOf(),u=o?this:e,a=o?e:this,l=_be(u,a,s,i);return o?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(ot.now(),e,n)}until(e){return this.isValid?gn.fromDateTimes(this,e):this}hasSame(e,n){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n)<=r&&r<=i.endOf(n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const n=e.base||ot.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0;let i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),wW(n,this.plus(r),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?wW(e.base||ot.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(ot.isDateTime))throw new lo("min requires all arguments be DateTimes");return LG(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(ot.isDateTime))throw new lo("max requires all arguments be DateTimes");return LG(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){const{locale:i=null,numberingSystem:s=null}=r,o=pn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return dW(o,e,n)}static fromStringExplain(e,n,r={}){return ot.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return TD}static get DATE_MED(){return dG}static get DATE_MED_WITH_WEEKDAY(){return X5e}static get DATE_FULL(){return hG}static get DATE_HUGE(){return pG}static get TIME_SIMPLE(){return gG}static get TIME_WITH_SECONDS(){return mG}static get TIME_WITH_SHORT_OFFSET(){return yG}static get TIME_WITH_LONG_OFFSET(){return EG}static get TIME_24_SIMPLE(){return AG}static get TIME_24_WITH_SECONDS(){return vG}static get TIME_24_WITH_SHORT_OFFSET(){return SG}static get TIME_24_WITH_LONG_OFFSET(){return _G}static get DATETIME_SHORT(){return CG}static get DATETIME_SHORT_WITH_SECONDS(){return bG}static get DATETIME_MED(){return TG}static get DATETIME_MED_WITH_SECONDS(){return RG}static get DATETIME_MED_WITH_WEEKDAY(){return J5e}static get DATETIME_FULL(){return OG}static get DATETIME_FULL_WITH_SECONDS(){return NG}static get DATETIME_HUGE(){return DG}static get DATETIME_HUGE_WITH_SECONDS(){return FG}}function Vm(t){if(ot.isDateTime(t))return t;if(t&&t.valueOf&&Sx(t.valueOf()))return ot.fromJSDate(t);if(t&&typeof t=="object")return ot.fromObject(t);throw new lo(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const IW=GP(Object.freeze(Object.defineProperty({__proto__:null,DateTime:ot,Duration:vt,FixedOffsetZone:Jr,IANAZone:Zu,Info:Qm,Interval:gn,InvalidZone:QG,Settings:zn,SystemZone:k_,VERSION:"2.5.2",Zone:v2},Symbol.toStringTag,{value:"Module"})));Object.defineProperty(pr,"__esModule",{value:!0}),pr.LiteralYear=pr.LiteralQuarter=pr.LiteralMonth=pr.LiteralWeek=pr.LiteralDay=pr.LiteralHour=pr.LiteralTimestamp=pr.TimeFormatError=void 0;const V0=IW,Qbe=ne,Gbe=j0,$W=p2,VD=pt;class Wbe extends Error{}pr.TimeFormatError=Wbe;function Tx(t,e){const n=t.slice(1);if(e){const r=n.match(/\[[^\]]+]$/);if(r)return{tzSpec:r[0].slice(1,-1),text:n.slice(0,-r[0].length)}}return{text:n}}const BW="yyyy",kW=`${BW}-LL`,xo=`${kW}-dd`,PW=`${xo} HH`,MW=`${PW}:mm`,YD=`${MW}:ss`;class jW extends VD.ExpressionDef{constructor(e,n,r){super(),this.units=n,this.timeType=r,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,n){const r={type:"dialect",function:"timeLiteral",literal:e,literalType:n};return this.timeZone&&(r.timezone=this.timeZone),r}makeValue(e,n){const r=this.makeLiteral(e,n),i="scalar",s=[r];return this.units?{dataType:n,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:n,expressionType:i,value:s,evalSpace:"literal"}}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class KD extends jW{constructor(e,n){super(e,n,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let n;const r=Tx(e,!0);e=r.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),r.text=e);const i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=V0.DateTime.fromFormat(e,YD);if(s.isValid)return new KD(r,n);if(s=V0.DateTime.fromFormat(e,MW),s.isValid){r.text=r.text+":00",n="minute";const o=s.plus({minute:1}).toFormat(YD);return new XD(r,n,"timestamp",o)}}}pr.LiteralTimestamp=KD;class XD extends jW{constructor(e,n,r,i){super(e,n,r),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,n,r){let i=this.getExpression(e),s=this.getNext();if(s){const o=r.getExpression(e);if(o.dataType==="timestamp"){const u=(0,VD.getMorphicValue)(i,"timestamp"),a=(0,VD.getMorphicValue)(s,"timestamp");if(u&&a)i=u,s=a;else return super.apply(e,n,r)}if((0,Qbe.isTimeFieldType)(o.dataType)){const u=o.dataType;return new Gbe.Range(new $W.ExprTime(u,i.value),new $W.ExprTime(u,s.value)).apply(e,n,r)}}return super.apply(e,n,r)}}class JD extends XD{constructor(e,n){super(e,"hour","timestamp",n),this.elementType="literal:hour"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,PW);if(i.isValid)return n.text=n.text+":00:00",r=i.plus({hour:1}).toFormat(YD),new JD(n,r)}}pr.LiteralHour=JD;class Ym extends XD{constructor(e,n,r){super(e,n,"date",r)}getExpression(e){const n=this.makeValue(this.literalPart,"date"),r=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...n,morphic:{timestamp:r},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),n=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:n}}}}class ZD extends Ym{constructor(e,n){super(e,"day",n),this.elementType="literal:day"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,xo);if(i.isValid)return r=i.plus({day:1}).toFormat(xo),new ZD(n,r)}}pr.LiteralDay=ZD;class eF extends Ym{constructor(e,n){super(e,"week",n),this.elementType="literal:week"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=n.text.slice(0,10),s=V0.DateTime.fromFormat(i,xo);if(s.isValid&&s.weekday===7){const u=s.plus({days:7});return n.text=s.toFormat(xo),r=u.toFormat(xo),new eF(n,r)}}}pr.LiteralWeek=eF;class tF extends Ym{constructor(e,n){super(e,"month",n),this.elementType="literal:month"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,kW);if(i.isValid){const s=i.plus({months:1});return n.text=i.toFormat(xo),r=s.toFormat(xo),new tF(n,r)}}}pr.LiteralMonth=tF;class nF extends Ym{constructor(e,n){super(e,"quarter",n),this.elementType="literal:quarter"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=n.text.match(/(^\d{4})-[qQ](\d)$/);if(i){const s=Number.parseInt(i[2])-1;let o=V0.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));const u=o.plus({quarter:1});return n.text=o.toFormat(xo),r=u.toFormat(xo),new nF(n,r)}}}pr.LiteralQuarter=nF;class rF extends Ym{constructor(e,n){super(e,"year",n),this.elementType="literal:year"}static parse(e){const n=Tx(e,!1);let r=n.text;const i=V0.DateTime.fromFormat(n.text,BW);if(i.isValid){const s=i.plus({year:1});return n.text=i.toFormat(xo),r=s.toFormat(xo),new rF(n,r)}}}pr.LiteralYear=rF;var z_={};Object.defineProperty(z_,"__esModule",{value:!0}),z_.PartialCompare=void 0;const Vbe=hr,Ybe=pt;class Kbe extends Ybe.ExpressionDef{constructor(e,n){super({right:n}),this.op=e,this.right=n,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,n,r){return this.right.apply(e,this.op,r)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,Vbe.errorFor)("no value for partial compare")}}z_.PartialCompare=Kbe;var O2={};Object.defineProperty(O2,"__esModule",{value:!0}),O2.PickWhen=O2.Pick=void 0;const ea=ne,Y0=hr,Jo=ln,Xbe=pt,Jbe=Ve,UW=hn;function Q_(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class Zbe extends Xbe.ExpressionDef{constructor(e,n){super({choices:e}),this.choices=e,this.elsePick=n,this.elementType="pick",this.has({elsePick:n})}requestExpression(e){if(this.elsePick!==void 0){for(const n of this.choices){if(n.pick===void 0)return;const r=n.when.requestExpression(e);if(r===void 0||r.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,n,r){const i=["CASE"];let s,o="scalar",u="constant";for(const c of this.choices){const f=c.when.apply(e,"=",r),x=c.pick?c.pick.getExpression(e):r.getExpression(e);if(o=(0,ea.maxExpressionType)(o,(0,ea.maxExpressionType)(f.expressionType,x.expressionType)),u=(0,ea.mergeEvalSpaces)(u,f.evalSpace,x.evalSpace),s&&!Jo.FT.typeEq(s,x,!0)){const h=Jo.FT.inspect(x);return this.log(`pick type '${h}', expected '${s.dataType}'[pick-values-must-match]`),(0,Y0.errorFor)("pick when type")}s=Q_(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}const l=(this.elsePick||r).getExpression(e);if(s=Q_(s,l),!Jo.FT.typeEq(s,l,!0)){const c=this.elsePick?"else":"pick default";return this.log(`${c} type '${Jo.FT.inspect(l)}', expected '${s.dataType}'[pick-values-must-match]`),(0,Y0.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,ea.maxExpressionType)(o,l.expressionType),evalSpace:(0,ea.mergeEvalSpaces)(u,l.evalSpace),value:(0,UW.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,Y0.errorFor)("no value for partial pick");const n=[];for(const a of this.choices){if(a.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,Y0.errorFor)("no value for partial pick");if(a.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,Y0.errorFor)("partial when");n.push({pick:a.pick.getExpression(e),when:a.when.getExpression(e)})}let r;const i=["CASE"];let s="scalar",o="constant";for(const a of n){if(!Jo.FT.typeEq(a.when,Jo.FT.boolT))return this.log(`when expression must be boolean, not '${Jo.FT.inspect(a.when)}`),(0,Y0.errorFor)("pick when type");if(r&&!Jo.FT.typeEq(r,a.pick,!0)){const l=Jo.FT.inspect(a.pick);return this.log(`pick type '${l}', expected '${r.dataType}'[pick-values-must-match]`),(0,Y0.errorFor)("pick value type")}r=Q_(r,a.pick),s=(0,ea.maxExpressionType)(s,(0,ea.maxExpressionType)(a.pick.expressionType,a.when.expressionType)),o=(0,ea.mergeEvalSpaces)(o,a.pick.evalSpace,a.when.evalSpace),i.push(" WHEN ",...a.when.value," THEN ",...a.pick.value)}const u=this.elsePick.getExpression(e);return s=(0,ea.maxExpressionType)(s,u.expressionType),o=(0,ea.mergeEvalSpaces)(o,u.evalSpace),r=Q_(r,u),Jo.FT.typeEq(r,u,!0)?(i.push(" ELSE ",...u.value," END"),{dataType:r.dataType,expressionType:s,value:(0,UW.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${Jo.FT.inspect(u)}', expected '${r.dataType}'[pick-values-must-match]`),(0,Y0.errorFor)("pick value type mismatch"))}}O2.Pick=Zbe;class eTe extends Jbe.MalloyElement{constructor(e,n){super({when:n}),this.pick=e,this.when=n,this.elementType="pickWhen",this.has({pick:e})}}O2.PickWhen=eTe;var G_={};Object.defineProperty(G_,"__esModule",{value:!0}),G_.Timeframe=void 0;const tTe=ne,nTe=Ve;class rTe extends nTe.MalloyElement{constructor(e){super(),this.elementType="timeframe";let n=e.toLowerCase();n.endsWith("s")&&(n=n.slice(0,-1)),this.text=(0,tTe.isTimestampUnit)(n)?n:"second"}}G_.Timeframe=rTe;var W_={};Object.defineProperty(W_,"__esModule",{value:!0}),W_.TopBy=void 0;const iTe=ne,qW=pt,sTe=Ve,oTe=hn;class uTe extends sTe.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof qW.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof qW.ExpressionDef){const n=this.by.getExpression(e);return(0,iTe.expressionIsAggregate)(n.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,oTe.compressExpr)(n.value)}}return{by:"name",name:this.by}}}W_.TopBy=uTe;var K0={};Object.defineProperty(K0,"__esModule",{value:!0}),K0.ImportStatement=K0.ImportSelect=K0.ImportSourceName=void 0;const iF=Ve;class aTe extends iF.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}K0.ImportSourceName=aTe;class lTe extends iF.MalloyElement{constructor(e,n){super(),this.text=e,this.from=n,this.elementType="importName",n&&this.has({from:n})}}K0.ImportSelect=lTe;class cTe extends iF.ListOf{constructor(e,n){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,n).toString())}catch{this.log("Invalid URI in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const r=e.childRequest(this.fullURL);if(r)return r}}execute(e){const n=this.translator();if(!n)this.log("Cannot import without translation context");else if(this.fullURL){const r=n.root.importZone.getEntry(this.fullURL);if(r.status==="present"){const i=n.getChildExports(this.fullURL);if(this.notEmpty())for(const s of this.list){const o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){const u={...i[o.text]};s.from&&(u.as=s.text),e.setEntry(s.text,{entry:u,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(const[s,o]of Object.entries(n.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else r.status==="error"?this.log(`import failed: '${r.message}'`):this.log(`import failed with status: '${r.status}'`)}}}K0.ImportStatement=cTe;var Km={};Object.defineProperty(Km,"__esModule",{value:!0}),Km.ExtendBlock=void 0;const fTe=Ve,xTe=Rn;class dTe extends fTe.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=xTe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)for(const r of n.list)e.inputFS.extendSource(r)}}Km.ExtendBlock=dTe;var V_={};Object.defineProperty(V_,"__esModule",{value:!0}),V_.AnonymousQuery=void 0;const hTe=Ve,pTe=Vr;class gTe extends hTe.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=pTe.extendNoteMethod,this.has({queryExpr:e})}execute(e){const n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("Cannot run this object as a query");return}const r={...n.query()},i=this.note||{};r.annotation&&(i.inherits=r.annotation),(i.notes||i.blockNotes||i.inherits)&&(r.annotation=i),e.queryList.push(r)}}V_.AnonymousQuery=gTe;var X0={};Object.defineProperty(X0,"__esModule",{value:!0}),X0.View=void 0;const mTe=Ve;let yTe=class extends mTe.MalloyElement{pipeline(e,n){return this.pipelineComp(e,n).pipeline}};X0.View=yTe;var Y_={};Object.defineProperty(Y_,"__esModule",{value:!0}),Y_.ViewArrow=void 0;const ETe=Xr,ATe=X0;class vTe extends ATe.View{constructor(e,n){super({base:e,operation:n}),this.base=e,this.operation=n,this.elementType="viewArrow"}pipelineComp(e){const n=this.base.pipelineComp(e),r=new ETe.StaticSpace(n.outputStruct),i=this.operation.pipelineComp(r);return{pipeline:[...n.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,n,r){return this.log("A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Y_.ViewArrow=vTe;var K_={},Xm={};Object.defineProperty(Xm,"__esModule",{value:!0}),Xm.refine=void 0;const sF=Fu,oF=I0;function STe(t,e,n){var r,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;const s={...e[0]},o=n;if((0,sF.isRawSegment)(s))t.log("Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.log(`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&((o.orderBy!==void 0||o.by!==void 0)&&(s.orderBy===void 0&&s.by===void 0?o.orderBy?s.orderBy=o.orderBy:o.by&&(s.by=o.by):t.log("refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.log("refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(r=s.filterList)!==null&&r!==void 0?r:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,sF.isQuerySegment)(o)&&(0,sF.isQuerySegment)(s)){const u=[],a=[],l=new Map(s.queryFields.map(c=>[(0,oF.nameFromDef)(c),c]));for(const c of o.queryFields)l.has((0,oF.nameFromDef)(c))?u.push(c):a.push(c);s.queryFields=[...s.queryFields,...a],u.length>0&&t.log(`overlapping fields in refinement: ${u.map(oF.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}Xm.refine=STe,Object.defineProperty(K_,"__esModule",{value:!0}),K_.ViewRefine=void 0;const _Te=Kr,CTe=Fs,bTe=Xm,TTe=X0;class RTe extends TTe.View{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="refine"}pipelineComp(e,n){const r=this.base.pipelineComp(e),i=this.refinement.refine(e,r.pipeline,n);return{pipeline:i,annotation:r.annotation,outputStruct:i.length>0?(0,CTe.getFinalStruct)(this.refinement,e.structDef(),i):_Te.ErrorFactory.structDef}}refine(e,n,r){const i=this.pipeline(e,r);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),n):(0,bTe.refine)(this,n,i[0])}getImplicitName(){return this.base.getImplicitName()}}K_.ViewRefine=RTe;var X_={};Object.defineProperty(X_,"__esModule",{value:!0}),X_.ReferenceView=void 0;const HW=ne,zW=Kr,OTe=Fs,NTe=Yr,DTe=Xm,FTe=X0;class wTe extends FTe.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,n){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:n}={forRefinement:!1}){const r=this.reference.getField(e),i=function(){return{inputStruct:zW.ErrorFactory.structDef,outputStruct:zW.ErrorFactory.structDef,pipeline:[],error:!0}};if(!r.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(r.found instanceof NTe.SpaceField))throw new Error("Expected space field");const s=r.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,HW.isAtomicFieldType)(s.type)){const o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:u,queryTimezone:a,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:u,queryTimezone:a,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,HW.isTurtleDef)(s)?this.reference.list.length>1?(n?this.log("Cannot use view from join as refinement"):this.log("Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,OTe.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(n?this.reference.log(`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.log("This operation is not supported"),i())}getRefinementSegment(e){const{pipeline:n,error:r}=this._pipelineComp(e,{forRefinement:!0});if(!r){if(n.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return n[0]}}refine(e,n,r){const i=this.getRefinementSegment(e);return i?(0,DTe.refine)(this,n,i):n}getImplicitName(){return this.reference.nameString}}X_.ReferenceView=wTe;var J_={},Jm={},Z_={},Zm={};Object.defineProperty(Zm,"__esModule",{value:!0}),Zm.Index=void 0;const LTe=Ve,ITe=Rn;let $Te=class extends LTe.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=ITe.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};Zm.Index=$Te;var e3={};Object.defineProperty(e3,"__esModule",{value:!0}),e3.SampleProperty=void 0;const BTe=Ve,QW=Rn;class kTe extends BTe.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=QW.LegalRefinementStage.Tail,this.forceQueryClass=QW.QueryClass.Index}sampling(){return this.sample}}e3.SampleProperty=kTe;var e5={};Object.defineProperty(e5,"__esModule",{value:!0}),e5.IndexFieldSpace=void 0;const GW=ne,uF=mt,PTe=Yr,MTe=Wo,jTe=wm,UTe=Xr;class qTe extends MTe.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const n of e)n instanceof uF.FieldReference?super.pushFields(n):n instanceof uF.WildcardFieldReference?this.addWild(n):n.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};const n=[];for(const[r,i]of this.entries())if(i instanceof PTe.SpaceField){const s=this.expandedWild[r];if(s){n.push({type:"fieldref",path:s});continue}if(i instanceof jTe.ReferenceField){const o=i.fieldRef,u=o.getField(this.exprSpace);u.error?o.log(u.error):n.push(o.refToField)}}return{type:"index",indexFields:n}}addRefineFromFields(e){}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof UTe.StructSpaceField)r=l.fieldSpace;else{u.log(`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.log(`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries()){if(e.except.has(u))continue;const l=uF.IndexFieldReference.indexOutputName([...i,u]);if(this.entry(l)){const c=(n=this.expandedWild[l])===null||n===void 0?void 0:n.join(".");e.log(`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=a.typeDesc();(0,GW.isAtomicFieldType)(c.dataType)&&(0,GW.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:l,entry:a}),this.expandedWild[l]=i.concat(u))}}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}e5.IndexFieldSpace=qTe,Object.defineProperty(Z_,"__esModule",{value:!0}),Z_.IndexBuilder=void 0;const aF=ne,HTe=Kr,zTe=Go,QTe=Zm,GTe=H0,WTe=e3,VTe=e5;class YTe{constructor(e,n,r,i){this.filters=[],this.type="index",this.resultFS=new VTe.IndexFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof zTe.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof GTe.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof QTe.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof WTe.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,aF.isIndexSegment)(e)&&!(0,aF.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),HTe.ErrorFactory.indexSegment;const n=this.resultFS.getPipeSegment(e),r=(e==null?void 0:e.filterList)||[];return this.filters.length>0&&!r?n.filterList=this.filters:r&&(n.filterList=[...r,...this.filters]),e!=null&&e.limit&&(n.limit=e.limit),this.limit&&(n.limit=this.limit.limit),this.indexOn&&(n.weightMeasure=this.indexOn.refString),e&&(0,aF.isIndexSegment)(e)&&(e!=null&&e.sample)&&(n.sample=e.sample),this.sample&&(n.sample=this.sample),n}}Z_.IndexBuilder=YTe;var t5={},t3={};Object.defineProperty(t3,"__esModule",{value:!0}),t3.GroupBy=void 0;const KTe=Ds,WW=Rn;class XTe extends KTe.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=WW.LegalRefinementStage.Single,this.forceQueryClass=WW.QueryClass.Grouping}}t3.GroupBy=XTe;var n5={};Object.defineProperty(n5,"__esModule",{value:!0}),n5.ProjectFieldSpace=void 0;const lF=ne,JTe=Wo;class ZTe extends JTe.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,lF.expressionIsAggregate)(e.expressionType)?!1:(0,lF.expressionInvolvesAggregate)(e.expressionType)&&(0,lF.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}}n5.ProjectFieldSpace=ZTe;var J0={},Rx={};Object.defineProperty(Rx,"__esModule",{value:!0}),Rx.Ordering=Rx.OrderBy=void 0;const e6e=ne,VW=Ax,YW=Ve,t6e=Rn;class n6e extends YW.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e instanceof VW.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var n;if(this.field instanceof VW.FieldName&&e.isQueryFieldSpace()){const i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.log(s.error),(!s.found||!s.isOutputField)&&this.log(`Unknown field ${this.field.refString} in output space`),(0,e6e.expressionIsAnalytic)((n=s.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}const r={field:this.modelField};return this.dir&&(r.dir=this.dir),r}}Rx.OrderBy=n6e;class r6e extends YW.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=t6e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(n=>n.getOrderBy(e))}}Rx.Ordering=r6e;var n3={};Object.defineProperty(n3,"__esModule",{value:!0}),n3.Top=void 0;const KW=ne,i6e=hn,s6e=Ax,o6e=Ve,u6e=Rn;let a6e=class extends o6e.MalloyElement{constructor(e,n){super(),this.limit=e,this.by=n,this.elementType="top",this.queryRefinementStage=u6e.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:n})}getBy(e){var n;if(this.by)if(this.by instanceof s6e.FieldName){if(e.isQueryFieldSpace()){const r=e.outputSpace(),i=this.by.getField(r);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,KW.expressionIsAnalytic)((n=i.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{const r=this.by.getExpression(e);return(0,KW.expressionIsAggregate)(r.expressionType)&&this.by.log("top by expression must be an aggregate"),r.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,i6e.compressExpr)(r.value)}}}};n3.Top=a6e,Object.defineProperty(J0,"__esModule",{value:!0}),J0.ReduceBuilder=J0.QuerySegmentBuilder=void 0;const XW=ne,l6e=Kr,c6e=Go,f6e=H0,JW=Rx,ZW=n3,x6e=Wo,d6e=Ds;class eV{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof d6e.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof c6e.Filter){const n=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(n))}else e instanceof ZW.Top?(this.limit?e.log("Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.log("Query operation is already sorted"):this.order=e)):e instanceof f6e.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof JW.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,n){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?n.orderBy=e.orderBy:e.by&&(n.by=e.by)),!this.limit&&e.limit&&(n.limit=e.limit)),this.limit&&(n.limit=this.limit),this.order instanceof ZW.Top){const i=this.order.getBy(this.inputFS);i&&(n.by=i)}this.order instanceof JW.Ordering&&(n.orderBy=this.order.getOrderBy(this.inputFS));const r=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!r?n.filterList=this.filters:r&&(n.filterList=[...r,...this.filters])}}J0.QuerySegmentBuilder=eV;class h6e extends eV{constructor(e,n,r,i){super(),this.type="grouping",this.resultFS=new x6e.ReduceFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let n;if(e)if((0,XW.isReduceSegment)(e)||(0,XW.isPartialSegment)(e))n=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),l6e.ErrorFactory.reduceSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}J0.ReduceBuilder=h6e,Object.defineProperty(t5,"__esModule",{value:!0}),t5.ProjectBuilder=void 0;const tV=ne,p6e=Kr,g6e=t3,m6e=n5,y6e=J0;class E6e extends y6e.QuerySegmentBuilder{constructor(e,n,r,i){super(),this.type="project",this.resultFS=new m6e.ProjectFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof g6e.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let n;if(e)if((0,tV.isProjectSegment)(e)||(0,tV.isPartialSegment)(e))n=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),p6e.ErrorFactory.projectSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}t5.ProjectBuilder=E6e;var r5={};Object.defineProperty(r5,"__esModule",{value:!0}),r5.PartialBuilder=void 0;const A6e=Fu,v6e=J0;class S6e extends v6e.ReduceBuilder{finalize(e){const n=super.finalize(e);if((0,A6e.isQuerySegment)(n))return{...n,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${n.type}`)}}r5.PartialBuilder=S6e,Object.defineProperty(Jm,"__esModule",{value:!0}),Jm.QOpDesc=void 0;const _6e=Z_,C6e=t5,b6e=J0,T6e=Ve,R6e=Fs,O6e=Xr,Ox=Rn,N6e=r5;class D6e extends T6e.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let n,r=!1;this.refineThis&&(this.refineThis.type==="reduce"?n=Ox.QueryClass.Grouping:this.refineThis.type==="project"?n=Ox.QueryClass.Project:this.refineThis.type==="index"&&(n=Ox.QueryClass.Index));for(const i of this.list)i.forceQueryClass&&(n?n!==i.forceQueryClass&&i.log(`Not legal in ${n} query`):n=i.forceQueryClass),r||(r=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return n===void 0&&r&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),n=Ox.QueryClass.Project),this.opClass=n,n}refineFrom(e){this.refineThis=e}getBuilder(e,n,r){switch(this.computeType()){case Ox.QueryClass.Grouping:return new b6e.ReduceBuilder(e,this.refineThis,n,r);case Ox.QueryClass.Project:return new C6e.ProjectBuilder(e,this.refineThis,n,r);case Ox.QueryClass.Index:return new _6e.IndexBuilder(e,this.refineThis,n,r);case void 0:return new N6e.PartialBuilder(e,this.refineThis,n,r)}}getOp(e,n){const r=this.getBuilder(e,n,this);for(const s of this.list)r.execute(s);const i=r.finalize(this.refineThis);return{segment:i,outputSpace:()=>new O6e.StaticSpace((0,R6e.opOutputStruct)(this,e.structDef(),i))}}}Jm.QOpDesc=D6e,Object.defineProperty(J_,"__esModule",{value:!0}),J_.QOpDescView=void 0;const F6e=ne,w6e=Xr,nV=Jm,L6e=Fs,cF=Rn,I6e=X0;class $6e extends I6e.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,n){const r=this.operation.getOp(e,n);return{pipeline:[r.segment],outputStruct:r.outputSpace().structDef()}}getOp(e,n,r,i){return(0,F6e.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(r.refineFrom(i),r.getOp(e,n).segment)}refine(e,n,r){const i=[...n];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,r,this.operation,i[0])];const s=new nV.QOpDesc([]),o=new nV.QOpDesc([]);for(const u of this.operation.list)switch(u.queryRefinementStage){case cF.LegalRefinementStage.Head:s.push(u);break;case cF.LegalRefinementStage.Single:u.log("Illegal in refinement of a query with more than one stage");break;case cF.LegalRefinementStage.Tail:o.push(u);break;default:u.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){const u=i.length-1;this.has({tailRefinements:o});const a=(0,L6e.getFinalStruct)(this,e.structDef(),i.slice(-1));i[u]=this.getOp(new w6e.StaticSpace(a),void 0,o,i[u])}return i}getImplicitName(){}}J_.QOpDescView=$6e;var mn={};Object.defineProperty(mn,"__esModule",{value:!0}),mn.FieldDefinitionValue=mn.DefSpace=mn.DimensionFieldDeclaration=mn.MeasureFieldDeclaration=mn.DeclareFieldDeclaration=mn.ProjectFieldDeclaration=mn.GroupByFieldDeclaration=mn.AggregateFieldDeclaration=mn.CalculateFieldDeclaration=mn.AtomicFieldDeclaration=void 0;const B6e=ne,k6e=hn,P6e=ln,M6e=d2,j6e=Ve,Nx=Zn,U6e=Vr,q6e=Yr;class Z0 extends j6e.MalloyElement{constructor(e,n,r){super({expr:e}),this.expr=e,this.defineName=n,this.exprSrc=r,this.isNoteableObj=!0,this.extendNote=U6e.extendNoteMethod}fieldDef(e,n){return this.queryFieldDef(new fF(e,this),n)}executesInOutputSpace(){return!1}queryFieldDef(e,n){let r;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const a=this.executesInOutputSpace()?i():e;r=this.expr.getExpression(a)}catch(a){return this.log(`Cannot define '${n}', ${a.message}`),{name:n,type:"error"}}const s=(0,k6e.compressExpr)(r.value);let o=r.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,B6e.isAtomicFieldType)(o)&&o!=="error"){const a={name:n,type:o,location:this.location};return s.length>0&&(a.e=s),r.expressionType&&(a.expressionType=r.expressionType),this.typecheckExprValue(r),this.exprSrc&&(a.code=this.exprSrc),(0,M6e.isGranularResult)(r)&&a.type==="timestamp"&&(a.timeframe=r.timeframe),this.note&&(a.annotation=this.note),a}if(!(e instanceof fF&&e.foundCircle)&&r.dataType!=="error"){const a=P6e.FT.inspect(r);this.log(`Cannot define '${n}', unexpected type: ${a}`)}return{name:n,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new rV(e,this))}}mn.AtomicFieldDeclaration=Z0;class H6e extends Z0{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}mn.CalculateFieldDeclaration=H6e;class z6e extends Z0{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckAggregate)(e,this)}}mn.AggregateFieldDeclaration=z6e;class Q6e extends Z0{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckGroupBy)(e,this)}}mn.GroupByFieldDeclaration=Q6e;class G6e extends Z0{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckProject)(e,this)}}mn.ProjectFieldDeclaration=G6e;class W6e extends Z0{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckDeclare)(e,this)}}mn.DeclareFieldDeclaration=W6e;class V6e extends Z0{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckMeasure)(e,this)}}mn.MeasureFieldDeclaration=V6e;class Y6e extends Z0{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Nx.typecheckDimension)(e,this)}}mn.DimensionFieldDeclaration=Y6e;class fF{constructor(e,n){this.realFS=e,this.circular=n,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:`Circular reference to '${this.circular.defineName}' in definition`,found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}}mn.DefSpace=fF;class rV extends q6e.SpaceField{constructor(e,n){super(),this.space=e,this.exprDef=n,this.fieldName=n.defineName}get name(){return this.fieldName}fieldDef(){return this.haveFieldDef||(this.haveFieldDef=this.exprDef.fieldDef(this.space,this.name)),this.haveFieldDef}getQueryFieldDef(e){if(!this.qfd){const n=this.exprDef.queryFieldDef(e,this.name);this.qfd=n}return this.qfd}typeDesc(){const e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}}mn.FieldDefinitionValue=rV;var i5={};Object.defineProperty(i5,"__esModule",{value:!0}),i5.Aggregate=void 0;const K6e=Ds,iV=Rn;let X6e=class extends K6e.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=iV.LegalRefinementStage.Single,this.forceQueryClass=iV.QueryClass.Grouping}};i5.Aggregate=X6e;var s5={};Object.defineProperty(s5,"__esModule",{value:!0}),s5.Calculate=void 0;const J6e=Ds,Z6e=Rn;class eRe extends J6e.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=Z6e.LegalRefinementStage.Single}}s5.Calculate=eRe;var r3={};Object.defineProperty(r3,"__esModule",{value:!0}),r3.Dimensions=void 0;const tRe=$0;class nRe extends tRe.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}r3.Dimensions=nRe;var i3={};Object.defineProperty(i3,"__esModule",{value:!0}),i3.Measures=void 0;const rRe=$0;class iRe extends rRe.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}i3.Measures=iRe;var o5={};Object.defineProperty(o5,"__esModule",{value:!0}),o5.Nests=void 0;const sRe=Ds,sV=Rn;class oRe extends sRe.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=sV.LegalRefinementStage.Single,this.forceQueryClass=sV.QueryClass.Grouping}}o5.Nests=oRe;var u5={};Object.defineProperty(u5,"__esModule",{value:!0}),u5.ProjectStatement=void 0;const uRe=Ds,oV=Rn;class aRe extends uRe.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=oV.QueryClass.Project,this.queryRefinementStage=oV.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}u5.ProjectStatement=aRe;var ec={},El={};Object.defineProperty(El,"__esModule",{value:!0}),El.findReferences=El.deprecatedParseTableURI=El.constructTableKey=void 0;const lRe=dx,xF=Pn;function dF(t){const e=(0,xF.getStringIfShort)(t);if(e)return e;const n=[],r=t.string().sqlString();if(r){for(const i of(0,xF.getStringParts)(r))typeof i=="string"&&n.push(i);return n.join("")}return""}class cRe{constructor(e,n){this.trans=e,this.tokens=n,this.needTables={},this.needImports={}}registerTableReference(e,n,r){const i=uV(e,n);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:n,firstReference:r})}enterTableMethod(e){const n=(0,xF.getId)(e.connectionId()),r=dF(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(n,r,i)}enterTableFunction(e){const n=dF(e.tableURI()),{connectionName:r,tablePath:i}=aV(n),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const n=dF(e);this.needImports[n]||(this.needImports[n]=this.trans.rangeFromContext(e))}}function uV(t,e){return t===void 0?e:`${t}:${e}`}El.constructTableKey=uV;function aV(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,n,r]=e;return{connectionName:n,tablePath:r}}else return{tablePath:t}}El.deprecatedParseTableURI=aV;function fRe(t,e,n){const r=new cRe(t,e),i=r;return lRe.ParseTreeWalker.DEFAULT.walk(i,n),{tables:r.needTables,urls:r.needImports}}El.findReferences=fRe,Object.defineProperty(ec,"__esModule",{value:!0}),ec.TableFunctionSource=ec.TableMethodSource=ec.TableSource=void 0;const lV=El,xRe=Qo,cV=Kr;class hF extends xRe.Source{structDef(){var e,n,r;const i=this.getTableInfo();if(i===void 0)return cV.ErrorFactory.structDef;const{tablePath:s,connectionName:o}=i,u=(0,lV.constructTableKey)(o,s),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(u);let l=`Schema read failure for table '${s}' for connection '${o}'`;if(a){if(a.status==="present"){(n=this.document())===null||n===void 0||n.checkExperimentalDialect(this,a.value.dialect),a.value.location=this.location,a.value.fields.forEach(f=>{f.location=this.location});const c={...a.value,fields:a.value.fields.map(f=>({...f,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(c),c}a.status==="error"&&(l=a.message)}return this.log(l),cV.ErrorFactory.structDef}}ec.TableSource=hF;class dRe extends hF{constructor(e,n){super(),this.connectionName=e,this.tablePath=n,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}ec.TableMethodSource=dRe;class hRe extends hF{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,lV.deprecatedParseTableURI)(this.tableURI)}}ec.TableFunctionSource=hRe;var a5={};Object.defineProperty(a5,"__esModule",{value:!0}),a5.SQLString=void 0;const pRe=Ve,fV=Ju;class gRe extends pRe.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(mRe)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof fV.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.log("This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const n of this.elements)if(typeof n=="string")e.push({sql:n});else{const r=n.getQuery();r?e.push(r.query()):n.sqLog("Cannot expand into a query")}return e}}a5.SQLString=gRe;function mRe(t){return t instanceof fV.SourceQueryElement}var l5={};Object.defineProperty(l5,"__esModule",{value:!0}),l5.SourceDesc=void 0;const yRe=Ve;class ERe extends yRe.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}l5.SourceDesc=ERe;var c5={};Object.defineProperty(c5,"__esModule",{value:!0}),c5.isSourceProperty=void 0;const ARe=Go,vRe=rs,SRe=$0,_Re=s2,CRe=k0,bRe=o2,TRe=u2,RRe=a2,ORe=B0;function NRe(t){return t instanceof ARe.Filter||t instanceof vRe.Joins||t instanceof SRe.DeclareFields||t instanceof _Re.FieldListEdit||t instanceof CRe.Renames||t instanceof bRe.PrimaryKey||t instanceof ORe.ObjectAnnotation||t instanceof TRe.Views||t instanceof RRe.TimezoneStatement}c5.isSourceProperty=NRe;var f5={};Object.defineProperty(f5,"__esModule",{value:!0}),f5.isFieldCollectionMember=void 0;const DRe=mn,xV=mt;function FRe(t){return t instanceof xV.FieldReference||t instanceof xV.WildcardFieldReference||t instanceof DRe.AtomicFieldDeclaration}f5.isFieldCollectionMember=FRe;var x5={};Object.defineProperty(x5,"__esModule",{value:!0}),x5.isQueryElement=void 0;const wRe=l2,LRe=c2,IRe=bm,$Re=Tm;function BRe(t){return t instanceof wRe.QueryArrow||t instanceof LRe.QueryRefine||t instanceof IRe.QueryReference||t instanceof $Re.QueryRaw}x5.isQueryElement=BRe;var dV={};Object.defineProperty(dV,"__esModule",{value:!0});var d5={};Object.defineProperty(d5,"__esModule",{value:!0}),d5.isQueryProperty=void 0;function kRe(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}d5.isQueryProperty=kRe;var h5={};Object.defineProperty(h5,"__esModule",{value:!0}),h5.isQueryExtendProperty=void 0;const PRe=r3,MRe=rs,jRe=i3;function URe(t){return t instanceof PRe.Dimensions||t instanceof jRe.Measures||t instanceof MRe.Joins}h5.isQueryExtendProperty=URe;var p5={};Object.defineProperty(p5,"__esModule",{value:!0}),p5.isFieldPropStatement=void 0;const qRe=U0,HRe=Go,zRe=H0,QRe=E2;function GRe(t){return t instanceof HRe.Filter||t instanceof zRe.Limit||t instanceof QRe.PartitionBy||t instanceof qRe.FunctionOrdering}p5.isFieldPropStatement=GRe,function(t){var e=N&&N.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=N&&N.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(fm,t),n(n2,t),n(r2,t),n(Qo,t),n(Em,t),n(Ju,t),n(U4,t),n(q4,t),n(G4,t),n(Cm,t),n(Y4,t),n(s2,t),n(o2,t),n(k0,t),n(u2,t),n(a2,t),n(K4,t),n(g2,t),n(Z4,t),n(U0,t),n(e_,t),n(gl,t),n(t_,t),n(y2,t),n(n_,t),n(r_,t),n(i_,t),n(Om,t),n(s_,t),n(o_,t),n(a_,t),n(Im,t),n(Fm,t),n(m2,t),n(l_,t),n(c_,t),n(x_,t),n(h_,t),n(p_,t),n(g_,t),n(m_,t),n(y_,t),n(E_,t),n(A_,t),n(v_,t),n(S_,t),n(__,t),n(C_,t),n(b_,t),n(O_,t),n(pr,t),n(z_,t),n(E2,t),n(O2,t),n(j0,t),n(G_,t),n(W_,t),n($m,t),n(hn,t),n(K0,t),n(Km,t),n(ym,t),n(V_,t),n(c2,t),n(l2,t),n(X0,t),n(Y_,t),n(K_,t),n(X_,t),n(J_,t),n(mn,t),n(mt,t),n(i5,t),n(s5,t),n($0,t),n(r3,t),n(Km,t),n(Go,t),n(t3,t),n(Zm,t),n(rs,t),n(xm,t),n(H0,t),n(i3,t),n(fm,t),n(o5,t),n(Rx,t),n(u5,t),n(Jm,t),n(e3,t),n(n3,t),n(P0,t),n(gx,t),n(Rm,t),n(ec,t),n(a5,t),n(B0,t),n(M0,t),n(l5,t),n(c5,t),n(pt,t),n(f5,t),n(Ax,t),n(Ve,t),n(x5,t),n(dV,t),n(d5,t),n(h5,t),n(p5,t)}(T4);var g5={},WRe=N&&N.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),VRe=N&&N.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),YRe=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&WRe(e,t,n);return VRe(e,t),e};Object.defineProperty(g5,"__esModule",{value:!0}),g5.MalloyToAST=void 0;const hV=Lv,KRe=dm,re=YRe(T4),XRe=xr,JRe=T4,Qn=Pn,pF=ne,ZRe=dl;class pV extends re.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class gF extends re.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const eOe=["##! m4warnings=error"];class tOe extends KRe.AbstractParseTreeVisitor{constructor(e,n,r){super(),this.parseInfo=e,this.msgLog=n,this.compilerFlags=r;for(const i of eOe){const s=ZRe.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,n){const r=`Internal Translator Error: ${n}`;return this.contextError(e,r),new Error(r)}astError(e,n,r="error"){this.msgLog.log({message:n,at:e.location,severity:r})}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}contextError(e,n,r="error"){this.msgLog.log({message:n,at:this.getLocation(e),severity:r})}inExperiment(e,n){const r=this.compilerFlags.tag("experimental");return r&&(r.bare()||r.has(e))?!0:(this.contextError(n,`Experimental flag '${e}' required to enable this feature`),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,n){const r=this.m4Severity();r&&this.contextError(e,n,r)}only(e,n,r){const i=[];for(const s of e){const o=n(s);o?i.push(o):s instanceof gF||this.astError(s,`Parser enountered unexpected statement type '${s.elementType}' when it needed '${r}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new re.FieldName((0,Qn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new re.ModelEntryReference((0,Qn.getId)(e)),e.id())}defaultResult(){return new re.Unimplemented}astAt(e,n){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(n)},e}getSourceCode(e){const n=e.start.startIndex,r=e.stop||e.start,i=new XRe.Interval(n,r.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){const n=this.getFieldExpr(e),r=new re.FilterElement(n,this.getSourceCode(e));return this.astAt(r,e)}getFieldDefs(e,n){return e.map(r=>this.getFieldDef(r,n))}getFieldExpr(e){const n=this.visit(e);if(n instanceof re.ExpressionDef)return this.astAt(n,e);throw this.internalError(e,`expression node unknown type '${n.elementType}'`)}getFilterShortcut(e){const n=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new re.Filter([n])}getPlainString(e){const n=(0,Qn.getStringIfShort)(e);if(n)return n;const r=[],i=e.string().sqlString();if(i){for(const s of(0,Qn.getStringParts)(i))s instanceof hV.ParserRuleContext?this.contextError(s,"%{ query } illegal in this string"):r.push(s);return(0,Qn.unIndent)(r),r.join("")}return""}makeSqlString(e,n){for(const r of e.sqlInterpolation())r.CLOSE_CODE()&&this.m4advisory(r,"Use %{ ... } instead of %{ ... }%");for(const r of(0,Qn.getStringParts)(e))r instanceof hV.ParserRuleContext?n.push(this.visit(r)):n.push(r);n.complete(),this.astAt(n,e)}parseTime(e,n){let r=n(e.text);return r||(this.contextError(e,"Time data parse error"),r=new re.LiteralTimestamp({text:e.text})),this.astAt(r,e)}getNotes(e){return e.ANNOTATION().map(n=>({text:n.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const n=this.only(e.malloyStatement().map(r=>this.visit(r)),r=>re.isDocStatementOrDocStatementList(r)&&r,"statement");return new re.Document(n)}visitDefineSourceStatement(e){const r=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new re.DefineSourceList(r);return s.extendNote({blockNotes:i}),s}visitSourceDefinition(e){const n=this.visit(e.sqExplore()),r=new re.DefineSource((0,Qn.getId)(e.sourceNameDef()),n instanceof re.SourceQueryElement?n:void 0,!0,[]),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return r.extendNote({notes:i}),this.astAt(r,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const n=e.filterShortcut(),r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>re.isSourceProperty(s)&&s,"source property"),i=new re.SourceDesc(r);return n&&i.push(this.getFilterShortcut(n)),i}visitTableFunction(e){const n=this.getPlainString(e.tableURI()),r=this.astAt(new re.TableFunctionSource(n),e);return this.m4advisory(e,"`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),r}visitTableMethod(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=this.getPlainString(e.tablePath());return this.astAt(new re.TableMethodSource(r,i),e)}visitSqlSource(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=new re.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);const o=e.shortString();o&&i.push((0,Qn.getShortString)(o));const u=new re.SQLSource(r,i);return this.astAt(u,e)}visitDefJoinMany(e){const n=[];for(const i of e.joinList().joinDef()){const s=this.visit(i);s instanceof re.Join&&(n.push(s),s instanceof re.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof re.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}const r=new re.Joins(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitDefJoinOne(e){const n=this.getJoinList(e.joinList()),r=[];for(const s of n)s instanceof re.Join&&(r.push(s),s instanceof re.ExpressionJoin&&(s.joinType="one"));const i=new re.Joins(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinCross(e){const n=this.getJoinList(e.joinList()),r=[];for(const s of n)s instanceof re.Join&&(r.push(s),s instanceof re.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));const i=new re.Joins(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return e.joinDef().map(n=>this.visit(n))}getJoinSource(e,n){if(n){const r=this.getSqExpr(n.sqExpr()),i=this.getNotes(n._before_is).concat(this.getNotes(n._after_is));return{joinFrom:r,notes:i}}return{joinFrom:new re.SQReference(e),notes:[]}}visitQueryJoinStatement(e){const n=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"Joins in queries are deprecated, move into an `extend:` block."),n}visitJoinOn(e){var n;const r=this.getModelEntryName(e.joinNameDef()),{joinFrom:i,notes:s}=this.getJoinSource(r,e.isExplore()),o=new re.ExpressionJoin(r,i),u=e.joinExpression(),a=((n=e.matrixOperation())===null||n===void 0?void 0:n.text.toLocaleLowerCase())||"left";return(0,pF.isMatrixOperation)(a)?o.matrixOperation=a:this.contextError(e,"Internal Error: Unknown matrixOperation"),u&&(o.joinOn=this.getFieldExpr(u)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){const n=this.getModelEntryName(e.joinNameDef()),{joinFrom:r,notes:i}=this.getJoinSource(n,e.isExplore()),s=this.getFieldExpr(e.fieldExpr()),o=new re.KeyJoin(n,r,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,n){const r=e.fieldExpr(),i=(0,Qn.getId)(e.fieldNameDef()),s=this.getFieldExpr(r),o=new n(s,i,this.getSourceCode(r)),u=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:u}),this.astAt(o,e)}visitDefDimensions(e){const n=this.getFieldDefs(e.defList().fieldDef(),re.DimensionFieldDeclaration),r=new re.Dimensions(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitDefMeasures(e){const n=this.getFieldDefs(e.defList().fieldDef(),re.MeasureFieldDeclaration),r=new re.Measures(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitQueryExtend(e){const n=[],r=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(const s of r)if(re.isQueryExtendProperty(s))n.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);const i=new re.ExtendBlock(n);return this.astAt(i,e)}visitDeclareStatement(e){const n=this.getFieldDefs(e.defList().fieldDef(),re.DeclareFieldDeclaration),r=new re.DeclareFields(n),i=this.astAt(r,e);return this.m4advisory(e,"`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),i}visitExploreRenameDef(e){const n=e.fieldName(0),r=e.fieldName(1),i=new re.RenameField((0,Qn.getId)(n),this.getFieldName(r));return this.astAt(i,e)}visitDefExploreRename(e){const r=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new re.Renames(r);return this.astAt(i,e)}visitFilterClauseList(e){return new re.Filter(e.fieldExpr().map(n=>this.getFilterElement(n)))}visitWhereStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!1,this.astAt(n,e)}visitHavingStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!0,this.astAt(n,e)}visitSubQueryDefList(e){const n=e.exploreQueryDef().map(r=>this.visitExploreQueryDef(r));return new re.Views(n)}visitDefExploreQuery(e){const n=this.visitSubQueryDefList(e.subQueryDefList()),r=this.getNotes(e.tags());return n.extendNote({blockNotes:r}),e.QUERY()&&this.m4advisory(e,"Use view: inside of a source instead of query:"),n}visitDefExplorePrimaryKey(e){const n=new re.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(n,e)}visitFieldNameList(e){const n=e.fieldName().map(r=>new re.AcceptExceptFieldReference([this.getFieldName(r)]));return new re.FieldReferences(n)}visitDefExploreEditField(e){const n=e.ACCEPT()?"accept":"except";return new re.FieldListEdit(n,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const n=this.getPlainString(e),r=this.astAt(new re.TimezoneStatement(n),e.string());return r.isValid||this.astError(r,`Invalid timezone: ${r.tz}`),this.astAt(r,e)}visitQueryProperties(e){const n=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>re.isQueryProperty(i)&&i,"query statement"),r=e.filterShortcut();return r&&n.push(this.getFilterShortcut(r)),new re.QOpDesc(n)}getFieldPath(e,n){const r=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new n(r),e)}getQueryFieldDef(e,n){const r=this.getFieldDef(e,n);return this.astAt(r,e)}getQueryFieldEntry(e,n,r){const i=e.taggedRef();if(i)return this.getTaggedRef(i,n,r);const s=e.fieldDef();if(s)return this.getQueryFieldDef(s,n);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,n,r){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,n,r)),i=>i instanceof re.FieldReference||i instanceof re.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){const n=new re.Aggregate(this.getQueryItems(e.queryFieldList(),re.AggregateFieldDeclaration,re.AggregateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitGroupByStatement(e){const n=new re.GroupBy(this.getQueryItems(e.queryFieldList(),re.GroupByFieldDeclaration,re.GroupByFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCalculateStatement(e){const n=new re.Calculate(this.getQueryItems(e.queryFieldList(),re.CalculateFieldDeclaration,re.CalculateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}getTaggedRef(e,n,r){const i=e.refExpr();if(i){const o=this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference);let u;const a=i.timeframe();a&&(u=new re.ExprGranularTime(new re.ExprIdReference(o),this.visitTimeframe(a).text,!0));const l=i.aggregate();if(l){const f=l.text.toLowerCase();if(f==="sum")u=new re.ExprSum(void 0,o);else return this.contextError(l,`\`${f}\` is not legal in a reference-only aggregation`),o}const c=new n(u,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}const s=this.getFieldPath(e.fieldPath(),r);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,n,r){const i=e.fieldDef();if(i)return this.getFieldDef(i,n);const s=e.taggedRef();if(s)return this.getTaggedRef(s,n,r);const o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const n=e.collectionMember().map(r=>this.getFieldCollectionMember(r,re.ProjectFieldDeclaration,re.ProjectFieldReference));return this.astAt(new re.ProjectStatement(n),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project: keyword is deprecated, use select:");const n=this.visitFieldCollection(e.fieldCollection());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCollectionWildCard(e){var n;const r=e.fieldPath(),i=r?this.getFieldPath(r,re.ProjectFieldReference):void 0,s=this.astAt(new re.WildcardFieldReference(i),e),o=((n=e.starQualified())===null||n===void 0?void 0:n.fieldNameList())||[];for(const u of o)for(const a of u.fieldName())s.except.add((0,Qn.getId)(a));return s}visitIndexFields(e){const n=e.indexElement().map(r=>{const i=r.fieldPath();if(!i)return this.astAt(new re.WildcardFieldReference(void 0),e);const s=this.getFieldPath(i,re.IndexFieldReference);return r.STAR()?this.astAt(new re.WildcardFieldReference(s),e):this.astAt(s,e)});return new re.FieldReferences(n)}visitIndexStatement(e){const n=this.visitIndexFields(e.indexFields()),r=new re.Index(n),i=e.fieldName();return i&&r.useWeight(this.getFieldName(i)),this.astAt(r,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new re.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0;return this.astAt(new re.FunctionOrderBy(i,n),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const n=e.aggregateOrderBySpec().map(r=>this.visitAggregateOrderBySpec(r));return this.astAt(new re.FunctionOrdering(n),e)}visitOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.INTEGER_LITERAL();if(r)return new re.OrderBy(this.getNumber(r),n);const i=e.fieldName();if(i)return new re.OrderBy(this.getFieldName(i),n);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const n=e.orderBySpec().map(r=>this.visitOrderBySpec(r));return this.astAt(new re.Ordering(n),e)}visitTopStatement(e){const n=e.bySpec(),r=this.getNumber(e.INTEGER_LITERAL());let i;if(n){this.m4advisory(n,"by clause of top statement unupported. Use order_by instead");const s=n.fieldName();if(s){const u=this.getFieldName(s);i=new re.Top(r,u)}const o=n.fieldExpr();o&&(i=new re.Top(r,this.getFieldExpr(o)))}return i||(i=new re.Top(r,void 0)),this.astAt(i,e)}visitSourceID(e){return this.astAt(new re.NamedSource((0,Qn.getId)(e)),e)}visitTopLevelQueryDefs(e){const n=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),r=this.getNotes(e.tags()),i=new re.DefineQueryList(n);return i.extendNote({blockNotes:r}),i}visitTopLevelQueryDef(e){const n=(0,Qn.getId)(e.queryName()),r=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(r instanceof re.SourceQueryElement){const s=new re.DefineQuery(n,r);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${r.elementType}'`)}visitAnonymousQuery(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new re.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(n,"Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new re.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){const n=this.visitNestedQueryList(e.nestedQueryList());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitNestedQueryList(e){return new re.Nests(this.only(e.nestEntry().map(n=>this.visit(n)),n=>n instanceof re.NestFieldDeclaration&&n,"query"))}visitNestDef(e){const n=e.queryName();let r;const i=this.getVExpr(e.vExpr());if(n)r=(0,Qn.getId)(n);else{const u=i.getImplicitName();u===void 0&&this.contextError(e,"`nest:` view requires a name (add `nest_name is ...`)"),r=u??"__unnamed__"}const s=new re.NestFieldDeclaration(r,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){const n=(0,Qn.getId)(e.exploreQueryNameDef()),r=new re.ViewFieldDeclaration(n,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return r.extendNote({notes:i}),this.astAt(r,e)}visitExprNot(e){return new re.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new re.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(n=>this.getFieldExpr(n))}visitExprLogicalOr(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(n,"or",r)}visitExprLogicalAnd(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(n,"and",r)}visitExprOrTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(n,"|",r),e)}visitExprAndTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(n,"&",r),e)}visitExprCoalesce(e){const n=this.getFieldExpr(e.fieldExpr()[0]),r=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new re.ExprCoalesce(n,r),e)}visitPartialAllowedFieldExpr(e){var n;const r=this.getFieldExpr(e.fieldExpr()),i=(n=e.compareOp())===null||n===void 0?void 0:n.text;if(i){if(re.isComparison(i))return this.astAt(new re.PartialCompare(i,r),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return r}visitExprString(e){const n=this.getPlainString(e);return new re.ExprString(n)}visitExprRegex(e){const n=e.HACKY_REGEX().text;return new re.ExprRegEx(n.slice(2,-1))}visitExprNow(e){return new re.ExprNow}visitExprNumber(e){return new re.ExprNumber(e.text)}visitExprFieldPath(e){const n=new re.ExprIdReference(this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference));return this.astAt(n,e)}visitExprNULL(e){return new re.ExprNULL}visitExprExpr(e){return new re.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new re.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new re.ExprAddSub(n,i,r)}visitExprMulDiv(e){const n=e.STAR()?"*":e.SLASH()?"/":"%";return new re.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const n=e.compareOp().text;if(re.isComparison(n))return new re.ExprCompare(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)));throw this.internalError(e,`untranslatable comparison operator '${n}'`)}visitExprCountDisinct(e){return this.m4advisory(e,"`count(distinct expression)` deprecated, use `count(expression)` instead"),this.astAt(new re.ExprCountDistinct(this.getFieldExpr(e.fieldExpr())),e)}visitExprUngroup(e){const n=e.fieldName().map(i=>this.getFieldName(i)),r=e.ungroup().text.toLowerCase();return this.astAt(new re.ExprUngroup(r==="all"?r:"exclude",this.getFieldExpr(e.fieldExpr()),n),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const n=e.fieldPath(),r=this.getFieldPath(n,re.ExpressionFieldReference),i=n&&r?this.astAt(r,n):void 0,s=e.aggregate().text.toLowerCase(),o=e.fieldExpr();if(e.aggregate().COUNT())return o&&this.contextError(o,"Expression illegal inside path.count()"),new re.ExprCount(i);const u=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(u)this.contextError(e,this.symmetricAggregateUsageError(s));else{const a=this.astAt(new re.ExprIdReference(r),n);return s==="min"?new re.ExprMin(a):new re.ExprMax(a)}else{if(s==="avg")return new re.ExprAvg(u,i);if(s==="sum")return new re.ExprSum(u,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new re.ExprNULL}visitExprPathlessAggregate(e){const n=e.fieldExpr(),r=n?this.getFieldExpr(n):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,`* illegal inside ${s}()`),s==="count")return this.astAt(r?new re.ExprCountDistinct(r):new re.ExprCount,e);if(s==="min"){if(r)return new re.ExprMin(r);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(r)return new re.ExprMax(r);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(r===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new re.ExprNULL;const o=e.SOURCE_KW()!==void 0;if(s==="avg")return new re.ExprAvg(r,i,o);if(s==="sum")return new re.ExprSum(r,i,o)}return new re.ExprNULL}visitExprApply(e){return new re.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new re.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new re.ExprCast(this.getFieldExpr(e.fieldExpr()),n)}getMalloyOrSQLType(e){const n=e.malloyType();if(n){const i=n.text;if((0,pF.isCastType)(i))return i;throw this.internalError(e,`unknown type '${i}'`)}const r=e.string();if(r)return{raw:this.getPlainString({string:()=>r})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new re.ExprCast(this.getFieldExpr(e.fieldExpr()),n,!0)}visitExprTimeTrunc(e){return new re.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new re.Timeframe(e.text)}visitExprForRange(e){const n=this.getFieldExpr(e._startAt),r=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new re.ForRange(n,r,i)}visitExprAggFunc(e){const n=e.argumentList(),r=n?this.allFieldExpressions(n.fieldExpr()):[],i=(0,Qn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,re.ExpressionFieldReference):void 0,u=s&&o?this.astAt(o,s):void 0;return re.ExprTimeExtract.extractor(i)?this.astAt(new re.ExprTimeExtract(i,r),e):this.astAt(new re.ExprFunc(i,r,!1,void 0,u),e)}visitExprFunc(e){var n,r;const i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,u=(n=e.malloyType())===null||n===void 0?void 0:n.text;let a;u&&((0,pF.isCastType)(u)?a=u:(this.contextError(e,`'#' assertion for unknown type '${u}'`),a=void 0));let l=(0,Qn.getOptionalId)(e)||((r=e.timeframe())===null||r===void 0?void 0:r.text);return l===void 0&&(this.contextError(e,"Function name error"),l="FUNCTION_NAME_ERROR"),re.ExprTimeExtract.extractor(l)?this.astAt(new re.ExprTimeExtract(l,s),e):this.astAt(new re.ExprFunc(l,s,o,a),e)}visitExprDuration(e){return new re.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitPickStatement(e){const n=e.pick().map(r=>{let i;return r._pickValue&&(i=this.getFieldExpr(r._pickValue)),new re.PickWhen(i,this.getFieldExpr(r._pickWhen))});return e.ELSE()?new re.Pick(n,this.getFieldExpr(e._pickElse)):new re.Pick(n)}visitExprFieldProps(e){const n=this.only(e.fieldProperties().fieldPropertyStatement().map(r=>this.visit(r)),r=>re.isFieldPropStatement(r)&&r,"field property statement");return new re.ExprProps(this.getFieldExpr(e.fieldExpr()),n)}visitPartitionByStatement(e){return this.astAt(new re.PartitionBy(e.id().map(n=>this.astAt(new re.PartitionByFieldReference([this.astAt(new re.FieldName((0,Qn.idToStr)(n)),n)]),n))),e)}visitLiteralTimestamp(e){return this.parseTime(e,re.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,re.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,re.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,re.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,re.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,re.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,re.LiteralYear.parse)}visitImportStatement(e){const n=this.getPlainString(e.importURL()),r=this.astAt(new re.ImportStatement(n,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(const s of i.importItem()){const o=s.id(),u=o[1]?this.astAt(new re.ImportSourceName((0,Qn.idToStr)(o[1])),o[1]):void 0;r.push(this.astAt(new re.ImportSelect((0,Qn.idToStr)(o[0]),u),o[0]))}return r}visitJustExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const n=e.sampleSpec().INTEGER_LITERAL();if(n)return new re.SampleProperty({rows:this.getNumber(n)});const r=e.sampleSpec().PERCENT_LITERAL();if(r)return new re.SampleProperty({percent:this.getNumber(r)});const i=e.sampleSpec().TRUE()!==void 0;return new re.SampleProperty({enable:i})}visitDocAnnotations(e){const n=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),r=new re.ModelAnnotation(n);return this.compilerFlags=r.getCompilerFlags(this.compilerFlags,this.msgLog),r}visitIgnoredObjectAnnotations(e){return this.contextError(e,"Object annotation not connected to any object"),new gF(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new gF(e.text)}visitDefExploreAnnotation(e){const n=this.getNotes(e);return new re.ObjectAnnotation(n)}visitSQID(e){const n=this.getModelEntryName(e);return this.astAt(new re.SQReference(n),e.id())}getSqExpr(e){const n=this.visit(e);return n instanceof re.SourceQueryElement?n:(this.contextError(e,`Expected a source/query expression, not '${n.elementType}'`),new pV)}visitSQExtendedSource(e){const n=this.getSqExpr(e.sqExpr()),r=new re.SQExtend(n,this.getSourceExtensions(e.exploreProperties()));return this.astAt(r,e)}visitSQParens(e){const n=this.getSqExpr(e.sqExpr());return this.astAt(n,e)}visitSQArrow(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new re.SQArrow(n,this.getVExpr(r));return this.astAt(i,e)}getVExpr(e){const n=this.visit(e);if(n instanceof re.View)return n;throw this.internalError(e,`Expected view, got a '${n.elementType}'`)}visitSegField(e){return new re.ReferenceView(this.getFieldPath(e.fieldPath(),re.ViewOrScalarFieldReference))}visitSegOps(e){return new re.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new re.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new re.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new re.SQRefine(n,this.getVExpr(r));return this.astAt(i,e)}visitSQTable(e){const n=this.visit(e.exploreTable());if(n instanceof JRe.TableSource){const r=new re.SQSource(n);return this.astAt(r,e)}return new pV}visitSQSQL(e){const n=new re.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(n,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new re.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}}g5.MalloyToAST=tOe;var m5={};Object.defineProperty(m5,"__esModule",{value:!0}),m5.MessageLog=void 0;class nOe{constructor(){this.rawLog=[]}getLog(){return this.rawLog}log(e){const n=e.message;if(n.endsWith("]")){const r=n.lastIndexOf("[");r>0&&(e.message=n.slice(0,r),e.errorTag=n.slice(r+1,-1))}this.rawLog.push(e)}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(n=>n.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}}m5.MessageLog=nOe;var y5={};Object.defineProperty(y5,"__esModule",{value:!0}),y5.Zone=void 0;class rOe{constructor(){this.location={},this.zone=new Map}get(e){const n=this.zone.get(e);if((n==null?void 0:n.status)==="present")return n.value}getEntry(e){const n=this.zone.get(e);return n?n.firstReference||!this.location[e]?n:{...n,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,n){this.zone.set(e,{status:"present",value:n})}reference(e,n){const r=this.zone.get(e);(r==null?void 0:r.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:n}),this.location[e]=n)}getUndefined(){const e=[];for(const[n,r]of this.zone)r.status==="reference"&&e.push(n);return e.length>0?e:void 0}updateFrom(e,n){if(e)for(const[r,i]of Object.entries(e))i!==void 0&&this.define(r,i);if(n)for(const[r,i]of Object.entries(n))this.zone.set(r,{status:"error",message:i})}}y5.Zone=rOe;var E5={};Object.defineProperty(E5,"__esModule",{value:!0}),E5.walkForDocumentSymbols=void 0;const iOe=dx,sOe=Pn;class oOe{constructor(e,n,r,i){this.translator=e,this.tokens=n,this.scopes=r,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const n=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=n)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const n=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=n)}enterSourceDefinition(e){const n=this.translator.rangeFromContext(e);this.scopes.push({range:n,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const n=this.popScope();n&&this.symbols.push(n)}enterDefExploreQuery(e){const n=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=n)}enterExploreQueryDef(e){const n={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},r=this.peekScope();r&&r.children.push(n),this.scopes.push(n),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const n=e.queryName();if(n)return n.id().text;let r,i=!1;const s={enterVArrow(u){u.vExpr().enterRule(s)},enterVSeg(u){u.segExpr().enterRule(o)}},o={enterSegField(u){const a=u.fieldPath().fieldName();i||(r??(r=a[a.length-1].id().text))},enterSegParen(u){u.vExpr().enterRule(s)},enterSegRefine(u){u._lhs.enterRule(o)},enterSegOps(){r=void 0,i=!0}};return e.vExpr().enterRule(s),r}handleNestEntry(e){const n=this.getNestDefName(e);if(n===void 0)return;const r={range:this.translator.rangeFromContext(e),name:n,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(r),r}enterNestDef(e){const n=this.handleNestEntry(e);n&&this.scopes.push(n)}exitNestDef(e){this.popScope()}enterFieldDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterQueryFieldEntry(e){var n;const r=(n=e.taggedRef())===null||n===void 0?void 0:n.fieldPath();if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const n={range:this.translator.rangeFromContext(e),name:e.joinNameDef().id().text,type:"join",children:[]},r=this.peekScope();r&&r.children.push(n)}enterImportStatement(e){const n=(0,sOe.getStringIfShort)(e.importURL());n&&this.scopes.push({range:this.translator.rangeFromContext(e),name:n,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const n=this.peekScope();if(n)for(const r of e.importItem()){const i={range:this.translator.rangeFromContext(e),name:r.text,type:"import_item",children:[]};n.children.push(i)}}}function uOe(t,e,n){const r=new oOe(t,e,[],[]),i=r;return iOe.ParseTreeWalker.DEFAULT.walk(i,n),r.symbols}E5.walkForDocumentSymbols=uOe;var A5={};Object.defineProperty(A5,"__esModule",{value:!0}),A5.walkForDocumentCompletions=void 0;const aOe=dx,lOe=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],cOe=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],fOe=["source","explore","query","sql"];class xOe{constructor(e,n,r){this.tokens=e,this.completions=n,this.position=r}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){const{start:n,end:r}=e,i=this.position.line>n.line||this.position.line===n.line&&this.position.character>=n.character,s=this.position.line<r.line||this.position.line===r.line&&this.position.character<=r.character;return i&&s}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.exploreStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of lOe)this.completions.push({type:"explore_property",text:`${r}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.queryStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of cOe)this.completions.push({type:"query_property",text:`${r}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.malloyStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of fOe)this.completions.push({type:"model_property",text:`${r}: `})}}}function dOe(t,e,n){const r=new xOe(t,[],n),i=r;return aOe.ParseTreeWalker.DEFAULT.walk(i,e),r.completions}A5.walkForDocumentCompletions=dOe;var v5={};Object.defineProperty(v5,"__esModule",{value:!0}),v5.walkForDocumentHelpContext=void 0;const hOe=K7;class pOe extends hOe.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let n=this.defaultResult();if(this.inRange(this.rangeOf(e))){n={type:this.type,token:e.start.text};const r=e.childCount;for(let i=0;i<r;i++){const o=e.getChild(i).accept(this);o&&(n=this.aggregateResult(n,o))}}return n}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,n){return n}}function gOe(t,e){return new pOe(e).visit(t)}v5.walkForDocumentHelpContext=gOe;var S5={},s3={};Object.defineProperty(s3,"__esModule",{value:!0}),s3.locationContainsPosition=void 0;function mOe(t,e){return t.range.start.line<=e.line&&t.range.end.line>=e.line&&(e.line!==t.range.start.line||e.character>=t.range.start.character)&&(e.line!==t.range.end.line||e.character<=t.range.end.character)}s3.locationContainsPosition=mOe,Object.defineProperty(S5,"__esModule",{value:!0}),S5.ReferenceList=void 0;const yOe=s3;class EOe{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let n=0,r=this.references.length;for(;n<r;){const i=Math.floor((n+r)/2),s=this.references[i].location.range.end;s.line<e.line||s.line===e.line&&s.character<e.character?n=i+1:r=i}return n}add(e){if(e.location.url!==this.sourceURL)return;const n=this.findIndexBefore(e.location.range.end);n<this.references.length&&this.isPositionEqual(e,this.references[n])||this.references.splice(n,0,e)}isPositionEqual(e,n){const r=e.location.range,i=n.location.range;return r.start.line===i.start.line&&r.start.character===i.start.character&&r.end.line===i.end.line&&r.end.character===i.end.character}find(e){const n=this.findIndexBefore(e);if(n===this.references.length)return;const r=this.references[n];if((0,yOe.locationContainsPosition)(r.location,e))return r}}S5.ReferenceList=EOe;var _5={};Object.defineProperty(_5,"__esModule",{value:!0}),_5.isNeedResponse=void 0;function AOe(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}_5.isNeedResponse=AOe;var C5={};Object.defineProperty(C5,"__esModule",{value:!0}),C5.walkForModelAnnotation=void 0;const vOe=dx;class SOe{constructor(e,n,r){this.translator=e,this.tokens=n,this.parseInfo=r,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}enterDocAnnotations(e){const n=e.DOC_ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}));this.notes.push(...n)}get annotation(){return{notes:this.notes}}}function _Oe(t,e,n){const r=new SOe(t,e,n),i=r;return vOe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.annotation}C5.walkForModelAnnotation=_Oe;var COe=N&&N.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),bOe=N&&N.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),TOe=N&&N.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&COe(e,t,n);return bOe(e,t),e};Object.defineProperty(Lu,"__esModule",{value:!0}),Lu.MalloyParserErrorHandler=Lu.MalloyTranslator=Lu.MalloyChildTranslator=Lu.MalloyTranslation=void 0;const gV=Lv,ROe=qS,OOe=F,mV=TOe(T4),NOe=g5,DOe=m5,FOe=El,mF=y5,wOe=E5,LOe=A5,IOe=v5,$Oe=S5,b5=_5,BOe=s3,yV=dl,kOe=C5;class POe extends ROe.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}class MOe{step(e){if(this.response)return this.response;if(e.urlIsFullPath===void 0)try{const s=new URL(e.sourceURL);e.urlIsFullPath=!0}catch(s){const o=s instanceof Error?s.message:"";e.urlIsFullPath=!1,e.root.logger.log({message:`Could not compute full path URL: ${o}`,severity:"error"})}if(!e.urlIsFullPath)return e.fatalResponse();const n=e.root.importZone.getEntry(e.sourceURL);if(n.status!=="present"){if(n.status==="error"){const s=n.message.includes(e.sourceURL)?`import error: ${n.message}`:`import '${e.sourceURL}' error: ${n.message}`,o=n.firstReference||e.defaultLocation();return e.root.logger.log({message:s,at:o,severity:"error"}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const r=n.value===""?`
1285
1285
  `:n.value;this.sourceInfo=this.getSourceInfo(r);let i;try{i=this.runParser(r,e)}catch(s){e.root.logger.log({message:`Malloy internal parser exception [${s.message}]`,severity:"error"}),i=void 0}return e.root.logger.hasErrors()?this.response={parse:i,...e.fatalResponse()}:this.response={parse:i},this.response}getSourceInfo(e){const n=/\r?\n/,r={at:[],lines:[],length:e.length};let i=e,s=0;for(;i!=="";){const o=i.match(n);if(o&&o.index!==void 0){r.lines.push(i.slice(0,o.index));const u=o.index+o[0].length;r.at.push({begin:s,end:s+u}),s+=u,i=i.slice(u)}else{r.lines.push(i),r.at.push({begin:s,end:s+i.length});break}}return r}runParser(e,n){const r=gV.CharStreams.fromString(e),i=new POe(r),s=new gV.CommonTokenStream(i),o=new OOe.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new AV(n,n.root.logger));const u=o[n.grammarRule];if(!u)throw new Error(`No such parse rule as ${n.grammarRule}`);return{root:u.call(o),tokenStream:s,sourceStream:r,sourceURL:n.sourceURL,importBaseURL:n.importBaseURL||n.sourceURL,rangeFromContext:a=>n.rangeFromContext(a),malloyVersion:"4.0.0"}}}class jOe{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){const n=this.parseStep.step(e);if(n.parse===void 0)return n;if(!this.parseReferences){this.parseReferences=(0,FOe.findReferences)(e,n.parse.tokenStream,n.parse.root);for(const o in this.parseReferences.tables)e.root.schemaZone.reference(o,{url:e.sourceURL,range:this.parseReferences.tables[o].firstReference});for(const o in this.parseReferences.urls){const u=this.parseReferences.urls[o];try{const a=decodeURI(new URL(o,e.importBaseURL||e.sourceURL).toString());e.addChild(a),e.imports.push({importURL:a,location:{url:e.sourceURL,range:u}}),e.root.importZone.reference(a,{url:e.sourceURL,range:u})}catch{e.root.logger.log({message:`Malformed URL '${o}'"`,at:{url:e.sourceURL,range:u},severity:"error"})}}}if(e.root.logger.hasErrors())return null;let r={};const i=e.root.schemaZone.getUndefined();if(i){const o={};for(const u of i){const a=this.parseReferences.tables[u];o[u]={connectionName:a.connectionName,tablePath:a.tablePath}}r={tables:o}}const s=e.root.importZone.getUndefined();if(s&&(r={...r,urls:s}),(0,b5.isNeedResponse)(r))return r;for(const o of e.childTranslators.values()){const u=o.importsAndTablesStep.step(o);if((0,b5.isNeedResponse)(u))return u}return null}}class UOe{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;const n=this.importStep.step(e);if(n)return n;const r=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;const i=r==null?void 0:r.parse;if(!i)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");const s=new NOe.MalloyToAST(i,e.root.logger,e.compilerFlags),o=s.visit(i.root);if(e.compilerFlags=s.compilerFlags,o.elementType==="unimplemented"&&o.log("INTERNAL COMPILER ERROR: Untranslated parse node"),!this.walked){for(const u of o.walk())u instanceof mV.Unimplemented&&u.log("INTERNAL COMPILER ERROR: Untranslated parse node");this.walked=!0}if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;for(const u of e.childTranslators.values()){const a=u.astStep.step(u);if((0,b5.isNeedResponse)(a))return a}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}}class qOe{constructor(e){this.parseStep=e}step(e){if(!this.response){const n=this.parseStep.step(e);if(n.parse){let r;try{r=(0,wOe.walkForDocumentSymbols)(e,n.parse.tokenStream,n.parse.root)}catch{}this.response={symbols:r,final:!0}}else return n}return this.response}}class HOe{constructor(e){this.parseStep=e}step(e,n){const r=this.parseStep.step(e);if(r.parse){let i=[];if(n!==void 0)try{i=(0,LOe.walkForDocumentCompletions)(r.parse.tokenStream,r.parse.root,n)}catch{}return{...r,completions:i}}else return r}}class zOe{constructor(e){this.parseStep=e}step(e,n){const r=this.parseStep.step(e);if(r.parse){let i;if(n!==void 0)try{i=(0,IOe.walkForDocumentHelpContext)(r.parse.root,n)}catch{}return{...r,helpContext:i}}else return r}}class QOe{constructor(e){this.parseStep=e}step(e,n){if(!this.response){const r=this.parseStep.step(e);if(!r.parse||r.final)return r;{const i=(0,kOe.walkForModelAnnotation)(e,r.parse.tokenStream,r.parse);this.response={modelAnnotation:{...i,inherits:n==null?void 0:n.annotation}}}}return this.response}}class GOe{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,n){if(this.response)return this.response;if(n&&!this.importedAnnotations){const i=yV.Tag.annotationToTag(n.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}const r=this.astStep.step(e);if((0,b5.isNeedResponse)(r))return r;if(!r.ast)return this.response=r,this.response;if(e.grammarRule==="malloyDocument")if(r.ast instanceof mV.Document){const i=r.ast;for(i.initModelDef(n);;){const s=i.compile();if(s.needs)return s.needs;e.modelDef=s.modelDef,e.queryList=s.queryList,e.sqlBlocks=s.sqlBlocks;break}}else e.root.logger.log({message:`'${e.sourceURL}' did not parse to malloy document`,at:e.defaultLocation(),severity:"error"});return e.root.logger.hasErrors()?this.response={fromSources:e.getDependencies(),...e.fatalResponse()}:this.response={translated:{modelDef:e.modelDef,queryList:e.queryList,sqlBlocks:e.sqlBlocks},fromSources:e.getDependencies(),...e.problemResponse(),final:!0},this.response}}class yF{constructor(e,n=null,r="malloyDocument"){this.sourceURL=e,this.importBaseURL=n,this.grammarRule=r,this.queryList=[],this.sqlBlocks=[],this.imports=[],this.compilerFlags=new yV.Tag,this.dialectAlreadyChecked={},this.allDialectsEnabled=!1,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new MOe,this.modelAnnotationStep=new QOe(this.parseStep),this.metadataStep=new qOe(this.parseStep),this.completionsStep=new HOe(this.parseStep),this.helpContextStep=new zOe(this.parseStep),this.importsAndTablesStep=new jOe(this.parseStep),this.astStep=new UOe(this.importsAndTablesStep),this.translateStep=new GOe(this.astStep),this.references=new $Oe.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new EV(e,this.root))}getDependencies(){const e=[this.sourceURL];for(const[n,r]of this.childTranslators)e.push(...r.getDependencies());return e}addReference(e){this.references.add(e)}referenceAt(e){return this.references.find(e)}fatalResponse(){return{final:!0,...this.problemResponse()}}problemResponse(){return{problems:this.problems()}}problems(){return[...this.root.logger.getLog()]}getLineMap(e){var n,r;if(e===this.sourceURL)return(n=this.parseStep.sourceInfo)===null||n===void 0?void 0:n.lines;const i=this.childTranslators.get(e);if(i)return(r=i.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines}codeAtLocation(e){const n=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return n[e.range.start.line].slice(e.range.start.character,e.range.end.character);let r="";r+=n[e.range.start.line].slice(e.range.start.character);for(let i=e.range.start.line+1;i<e.range.end.line;i++)r+=n[i];return r+=n[e.range.end.line].slice(0,e.range.end.character),r}prettyErrors(){let e="",n="";for(const r of this.root.logger.getLog()){let i=r.message,s=this.sourceURL;if(r.at){s=r.at.url;const o=r.at.range.start.line,u=r.at.range.start.character,a=this.getLineMap(r.at.url);if(a){const l=a[o];i=`line ${o+1}: ${r.message}
1286
1286
  | ${l}`,u>0&&(i=i+`
1287
1287
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}