@malloydata/render 0.0.199 → 0.0.200-dev241012235421

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.
@@ -1323,12 +1323,12 @@ ${r} ${s}: [`,o.length>0&&(i+=`
1323
1323
  ${r} `),i+="]")}return i}*walk(){for(const e of Object.keys(this.children)){const n=this.children[e];if(n instanceof su)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 new Error(`INTERNAL ERROR IN TRANSLATION: ${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.logError("experiment-not-enabled",{experimentId:e}),!1)}}Ge.MalloyElement=su;class y1e extends su{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Ge.Unimplemented=y1e;class tO extends su{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}}Ge.ModelEntryReference=tO;class E1e extends su{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Ge.ExperimentalExperiment=E1e;function iq(t){return t.execute!==void 0}Ge.isDocStatement=iq;function A1e(t){return t instanceof c1||iq(t)}Ge.isDocStatementOrDocStatementList=A1e;class sq extends su{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}}}Ge.ListOf=sq;class c1 extends sq{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=rq.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,rq.isNoteable)(n)&&n.extendNote(this.note),this.noteCursor+=1),n instanceof c1){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}}}Ge.DocStatementList=c1;const v1e="5a79a191-06bc-43cf-9b12-58741cd82970";function oq(t){const e=t.inherits?oq(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 S1e(t){const e=oq(t).join("");return(0,m1e.v5)(e,v1e)}class nO extends su{constructor(e){super(),this.elementType="document",this.globalNameSpace=new g1e.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new x1e.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new c1(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((0,NA.modelObjIsSource)(i)||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=S1e(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((0,NA.modelObjIsSource)(r)||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}`};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.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,NA.modelObjIsSource)(n.entry)&&this.checkExperimentalDialect(this,n.entry.dialect),this.documentModel[e]=n}checkExperimentalDialect(e,n){const r=this.translator();r&&r.firstReferenceToDialect(n)&&(0,nq.getDialect)(n).experimental&&!r.experimentalDialectEnabled(n)&&e.logError("experimental-dialect-not-enabled",{dialect:n})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const n=(0,nq.getDialect)(e),r=new p1e.DialectNameSpace(n);return this.dialectNameSpaces.set(e,r),r}}Ge.Document=nO;var wA={},ed={},wr={},Dl={};Object.defineProperty(Dl,"__esModule",{value:!0}),Dl.canMakeEntry=Dl.SpaceEntry=void 0;class _1e{}Dl.SpaceEntry=_1e;function C1e(t){return"makeEntry"in t}Dl.canMakeEntry=C1e,Object.defineProperty(wr,"__esModule",{value:!0}),wr.SpaceField=void 0;const T1e=Dl;class b1e extends T1e.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){const n={dataType:e.type,expressionType:"scalar",evalSpace:"input"};return e.expressionType&&(n.expressionType=e.expressionType),n.dataType==="sql native"&&e.type==="sql native"&&e.rawType&&(n.rawType=e.rawType),n}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}wr.SpaceField=b1e,Object.defineProperty(ed,"__esModule",{value:!0}),ed.ViewField=void 0;const R1e=wr;class O1e extends R1e.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){return{dataType:"turtle",expressionType:"scalar",evalSpace:"input"}}}ed.ViewField=O1e,Object.defineProperty(wA,"__esModule",{value:!0}),wA.ASTViewField=void 0;const D1e=ed;class N1e extends D1e.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)}}wA.ASTViewField=N1e,Object.defineProperty(l1,"__esModule",{value:!0}),l1.ViewFieldDeclaration=void 0;const w1e=Ge,F1e=Nr,L1e=Kx,I1e=wA;class $1e extends w1e.MalloyElement{constructor(e,n){super({view:n}),this.name=e,this.view=n,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=F1e.extendNoteMethod}makeEntry(e){const n=new I1e.ASTViewField(e,this,this.name);e.newEntry(this.name,this,n)}getFieldDef(e){const{pipeline:n,annotation:r}=this.view.pipelineComp(e),i=(0,L1e.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}}l1.ViewFieldDeclaration=$1e;var mn={};Object.defineProperty(mn,"__esModule",{value:!0}),mn.LegalRefinementStage=mn.QueryClass=void 0;var uq;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(uq||(mn.QueryClass=uq={}));var aq;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(aq||(mn.LegalRefinementStage=aq={})),Object.defineProperty(a1,"__esModule",{value:!0}),a1.NestFieldDeclaration=void 0;const B1e=Kx,k1e=l1,lq=mn;class P1e extends k1e.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=lq.LegalRefinementStage.Single,this.forceQueryClass=lq.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,B1e.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")}}a1.NestFieldDeclaration=P1e;var td={},Fr={};Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.ErrorFactory=void 0;const cq="~malformed~";class rO{static get structDef(){return{type:"table",name:cq,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:cq,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:rO.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}Fr.ErrorFactory=rO,Object.defineProperty(td,"__esModule",{value:!0}),td.DefineSourceList=td.DefineSource=void 0;const M1e=Fr,fq=Ge,j1e=Nr;class U1e extends fq.MalloyElement{constructor(e,n,r,i){super(),this.name=e,this.sourceExpr=n,this.exported=r,this.parameters=i,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=j1e.extendNoteMethod,n&&this.has({sourceExpr:n}),i&&this.has({parameters:i})}execute(e){var n;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`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=this.deduplicatedParameters(),s=r.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(i,s),M1e.ErrorFactory.didCreate(s))return;const o={...s,as:this.name,location:this.location};this.note&&(o.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:o,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},n=[];for(const r of this.parameters)r.name in e&&r.logError("parameter-name-conflict",`Cannot redefine parameter \`${r.name}\``),e[r.name]=!0,n.push(r);return n}validateParameterShadowing(e,n){for(const r of e)n.fields.find(i=>{var s;return((s=i.as)!==null&&s!==void 0?s:i.name)===r.name})&&r.logError("parameter-shadowing-field",`Illegal shadowing of field \`${r.name}\` by parameter with the same name`)}}td.DefineSource=U1e;class q1e extends fq.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}td.DefineSourceList=q1e;var nd={};Object.defineProperty(nd,"__esModule",{value:!0}),nd.DefineQueryList=nd.DefineQuery=void 0;const xq=Ge,H1e=Nr;class z1e extends xq.MalloyElement{constructor(e,n){super({queryExpr:n}),this.name=e,this.queryExpr=n,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=H1e.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("query-definition-from-non-query","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})}}nd.DefineQuery=z1e;class Q1e extends xq.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}nd.DefineQueryList=Q1e;var so={};Object.defineProperty(so,"__esModule",{value:!0}),so.Source=void 0;const G1e=Ge;class W1e extends G1e.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const n={};for(const r of e){const i=r.parameter();n[i.name]=i}return n}withParameters(e,n){return{...this.getSourceDef(e),parameters:this.packParameters(n)}}}so.Source=W1e;var f1={},rd={},FA={},Nl={};Object.defineProperty(Nl,"__esModule",{value:!0}),Nl.mergeFields=Nl.nameFromDef=void 0;function iO(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Nl.nameFromDef=iO;function V1e(t,e){if(t===void 0)return e;const n=new Set(e.map(i=>iO(i))),r=t.filter(i=>!n.has(iO(i)));return r.push(...e),r}Nl.mergeFields=V1e;var x1={},hr={},ou={};Object.defineProperty(ou,"__esModule",{value:!0}),ou.DefinedParameter=ou.AbstractParameter=ou.SpaceParam=void 0;const Y1e=Dl;class sO extends Y1e.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}ou.SpaceParam=sO;class J1e extends sO{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){var e;return{dataType:(e=this.parameter().type)!==null&&e!==void 0?e:"error",expressionType:"scalar",evalSpace:"constant"}}}ou.AbstractParameter=J1e;class X1e extends sO{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{dataType:this.paramDef.type,expressionType:"scalar",evalSpace:"input"}}}ou.DefinedParameter=X1e;var id={};Object.defineProperty(id,"__esModule",{value:!0}),id.StructSpaceFieldBase=void 0;const K1e=wr;class Z1e extends K1e.SpaceField{constructor(e){super(),this.sourceDef=e}fieldDef(){return this.sourceDef}get joinPathElement(){return{name:this.sourceDef.as||this.sourceDef.name,joinType:this.sourceDef.join,joinElementType:this.sourceDef.type}}typeDesc(){return{dataType:this.sourceDef.type,expressionType:"scalar",evalSpace:"input"}}}id.StructSpaceFieldBase=Z1e;var d1={};Object.defineProperty(d1,"__esModule",{value:!0}),d1.ColumnSpaceField=void 0;const ege=wr;class tge extends ege.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}d1.ColumnSpaceField=tge;var LA={};Object.defineProperty(LA,"__esModule",{value:!0}),LA.IRViewField=void 0;const nge=ed;class rge extends nge.ViewField{constructor(e,n){super(e),this.turtleDef=n}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}LA.IRViewField=rge,Object.defineProperty(hr,"__esModule",{value:!0}),hr.StaticSourceSpace=hr.StructSpaceField=hr.StaticSpace=void 0;const ige=Po,IA=oe,sge=ou,oge=wr,$A=id,uge=d1,age=LA;class oO{get dialect(){return this.fromStruct.dialect}constructor(e){this.fromStruct=e,this.type="fieldSpace"}dialectName(){return this.fromStruct.dialect}dialectObj(){try{return(0,ige.getDialect)(this.fromStruct.dialect)}catch{return}}defToSpaceField(e){return(0,IA.isJoined)(e)?new dq(e,this.fromStruct.dialect):(0,IA.isTurtleDef)(e)?new age.IRViewField(this,e):new uge.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((0,IA.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,n]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new sge.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(){const e={...this.fromStruct};return(0,IA.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const n=e[0],r=e.slice(1),i=this.entry(n.refString);if(!i)return{error:{message:`'${n}' is not defined`,code:"field-not-found"},found:i};if(i instanceof oge.SpaceField){const o=i.fieldDef();o&&n.addReference({type:i instanceof $A.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:n.location,text:n.refString})}const s=i instanceof $A.StructSpaceFieldBase?[{...i.joinPathElement,name:n.refString}]:[];if(r.length){if(i instanceof $A.StructSpaceFieldBase){const o=i.fieldSpace.lookup(r);return o.found?{...o,joinPath:[...s,...o.joinPath]}:o}return{error:{message:`'${n}' cannot contain a '${r[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:i,error:void 0,joinPath:s,isOutputField:!1}}isQueryFieldSpace(){return!1}}hr.StaticSpace=oO;class dq extends $A.StructSpaceFieldBase{constructor(e,n){super(e),this.parentDialect=n}get fieldSpace(){return new oO(this.sourceDef)}}hr.StructSpaceField=dq;class lge extends oO{constructor(e){super(e),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}hr.StaticSourceSpace=lge,Object.defineProperty(x1,"__esModule",{value:!0}),x1.JoinSpaceField=void 0;const cge=hr;class fge extends cge.StructSpaceField{constructor(e,n,r){super(n.structDef(e),r),this.parameterSpace=e,this.join=n}}x1.JoinSpaceField=fge;var sd={};Object.defineProperty(sd,"__esModule",{value:!0}),sd.ParameterSpace=void 0;const xge=ou;class dge{constructor(e){this.type="fieldSpace",this._map={};for(const n of e)this._map[n.name]=new xge.AbstractParameter(n)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const n=e[0];if(n===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const r=this.entry(n.refString);return r===void 0?{error:{message:`\`${n}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${n}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:r,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}}sd.ParameterSpace=dge;var hge=D&&D.__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]}),pge=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gge=D&&D.__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)&&hge(e,t,n);return pge(e,t),e};Object.defineProperty(FA,"__esModule",{value:!0}),FA.DynamicSpace=void 0;const mge=gge(oe),yge=Nl,Ege=Fr,Age=wr,vge=x1,Sge=ed,hq=ou,_ge=hr,Cge=id,Tge=sd;class bge extends _ge.StaticSpace{constructor(e){super(structuredClone(e)),this.completions=[],this.complete=!1,this.parameters=[],this.fromSource=e,this.final=void 0}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.entry(n.name)===void 0&&(this.parameters.push(n),this.setEntry(n.name,new hq.AbstractParameter(n)));return this}parameterSpace(){return new Tge.ParameterSpace(this.parameters)}newEntry(e,n,r){if(this.entry(e)){n.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,r)}renameEntry(e,n,r){this.dropEntry(e),this.setEntry(n,r)}addFieldDef(e){this.setEntry((0,yge.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.final===void 0){const e={};for(const[a,l]of this.entries())l instanceof hq.SpaceParam&&(e[a]=l.parameter());this.final={...this.fromSource,fields:[]},this.final.parameters=e;const n=[],r=[],i=[],s=[];for(const[a,l]of this.entries())l instanceof Cge.StructSpaceFieldBase?r.push([a,l]):l instanceof Sge.ViewField?i.push([a,l]):l instanceof Age.SpaceField&&n.push([a,l]);const o=[...n,...r,...i],u=this.parameterSpace();for(const[,a]of o)if(a instanceof vge.JoinSpaceField){const l=a.join.structDef(u);Ege.ErrorFactory.didCreate(l)||(this.final.fields.push(l),s.push([a.join,l]))}else{const l=a.fieldDef();l&&this.final.fields.push(l)}for(const[a,l]of s)a.fixupJoinOn(this,l)}return this.newTimezone&&mge.isSourceDef(this.final)&&(this.final.queryTimezone=this.newTimezone),this.isComplete(),this.final}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}FA.DynamicSpace=bge,Object.defineProperty(rd,"__esModule",{value:!0}),rd.RefinedSpace=void 0;const Rge=FA,Oge=Dl;class uO extends Rge.DynamicSpace{static filteredFrom(e,n,r){const i=new uO(e);if(n){const s=n.refs.list,o=i.entries();for(const u of s)o.find(([l])=>l===u.refString)===void 0&&(r!=null&&r.entry(u.refString)?u.logError(`${n.edit}-parameter`,`Illegal \`${n.edit}:\` of parameter`):u.logError("field-list-edit-not-found",`\`${u.refString}\` is not defined`));i.dropEntries();for(const[u,a]of o){const l=!!s.find(f=>f.refString===u),c=n.edit==="accept";l===c&&i.setEntry(u,a)}}return i}pushFields(...e){for(const n of e)(0,Oge.canMakeEntry)(n)?n.makeEntry(this):n.logError("unexpected-element-type",`Internal error, ${n.elementType} not expected in this context`)}}rd.RefinedSpace=uO;var wl={},Ki={};Object.defineProperty(Ki,"__esModule",{value:!0}),Ki.DefinitionList=void 0;const Dge=Ge,pq=Nr;class Nge extends Dge.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,pq.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,pq.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Ki.DefinitionList=Nge,Object.defineProperty(wl,"__esModule",{value:!0}),wl.DeclareFields=void 0;const wge=Ki,Fge=mn;class Lge extends wge.DefinitionList{constructor(e){super(e),this.elementType="declareFields",this.queryRefinementStage=Fge.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}}wl.DeclareFields=Lge;var oo={};Object.defineProperty(oo,"__esModule",{value:!0}),oo.Filter=oo.FilterElement=void 0;const gq=oe,mq=Ge,aO=mn;class Ige extends mq.MalloyElement{constructor(e,n){super({expr:e}),this.expr=e,this.exprSrc=n,this.elementType="filterElement"}filterCondition(e){const n=this.expr.getExpression(e);return n.dataType!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar"}):{node:"filterCondition",code:this.exprSrc,e:n.value,expressionType:n.expressionType}}}oo.FilterElement=Ige;let $ge=class extends mq.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=aO.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?aO.LegalRefinementStage.Tail:aO.LegalRefinementStage.Head}getFilterList(e){const n=[];for(const r of this.list){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,gq.expressionIsAggregate)(i.expressionType),o=(0,gq.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");continue}}else if(o){r.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");continue}else s&&r.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}n.push(i)}return n}};oo.Filter=$ge;var od={};Object.defineProperty(od,"__esModule",{value:!0}),od.FieldListEdit=void 0;const Bge=Ge;class kge extends Bge.MalloyElement{constructor(e,n){super({refs:n}),this.edit=e,this.refs=n,this.elementType="fieldListEdit"}}od.FieldListEdit=kge;var ud={};Object.defineProperty(ud,"__esModule",{value:!0}),ud.PrimaryKey=void 0;const Pge=Ge;class Mge extends Pge.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}ud.PrimaryKey=Mge;var ad={};Object.defineProperty(ad,"__esModule",{value:!0}),ad.Views=void 0;const jge=Ki;class Uge extends jge.DefinitionList{constructor(){super(...arguments),this.elementType="turtleDefList"}}ad.Views=Uge;var ld={};Object.defineProperty(ld,"__esModule",{value:!0}),ld.TimezoneStatement=void 0;const qge=Ge;class Hge extends qge.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)}}ld.TimezoneStatement=Hge;var Fl={};Object.defineProperty(Fl,"__esModule",{value:!0}),Fl.ModelAnnotation=Fl.ObjectAnnotation=void 0;const zge=Mo,Qge=Ge;class yq extends Qge.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Fl.ObjectAnnotation=yq;class Gge extends yq{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,n){const r=zge.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)}}Fl.ModelAnnotation=Gge;var Ll={},BA={};Object.defineProperty(BA,"__esModule",{value:!0}),BA.RenameSpaceField=void 0;const Wge=wr;class Vge extends Wge.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()}}BA.RenameSpaceField=Vge,Object.defineProperty(Ll,"__esModule",{value:!0}),Ll.Renames=Ll.RenameField=void 0;const Yge=BA,Eq=Ge,Jge=wr;class Xge extends Eq.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.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const n=this.oldName.getField(e);n.found?n.found instanceof Jge.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new Yge.RenameSpaceField(n.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}}Ll.RenameField=Xge;class Kge extends Eq.ListOf{constructor(){super(...arguments),this.elementType="renameFields"}}Ll.Renames=Kge;var Ti={};Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.JoinStatement=Ti.ExpressionJoin=Ti.KeyJoin=Ti.Join=void 0;const lO=oe,Zge=x1,eme=Ki,tme=Ge,nme=Nr,Aq=Fr,rme=mn;class cO extends tme.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=nme.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new Zge.JoinSpaceField(e.parameterSpace(),this,e.dialect))}getStructDefFromExpr(e){const n=this.sourceExpr.getSource();return n?n.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),Aq.ErrorFactory.structDef)}}Ti.Join=cO;class ime extends cO{constructor(e,n,r){super({name:e,sourceExpr:n,keyExpr:r}),this.name=e,this.sourceExpr=n,this.keyExpr=r,this.elementType="joinOnKey"}structDef(e){var n;const r=this.getStructDefFromExpr(e);if(!(0,lO.isJoinable)(r))throw this.internalError(`Cannot join struct type '${r.type}'`);const i={...r,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete i.as,this.note&&(i.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(i),i}fixupJoinOn(e,n){const r=this.keyExpr.getExpression(e);if((0,lO.isSourceDef)(n)&&n.primaryKey){const i=n.fields.find(s=>(s.as||s.name)===n.primaryKey);if(i)if(i.type===r.dataType){n.join="one",n.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,n.primaryKey]},right:r.value}};return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${r.dataType}/${i.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${i}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}Ti.KeyJoin=ime;class sme extends cO{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.logError("non-boolean-join-on","join conditions must be boolean expressions");return}n.onExpression=r.value}structDef(e){var n;const r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),Aq.ErrorFactory.joinDef;const i=r.getSourceDef(e);let s="left";if(this.inExperiment("join_types",!0)&&(s=this.matrixOperation),!(0,lO.isJoinable)(i))throw this.internalError(`Can't join struct type ${i.type}`);const o={...i,name:this.name.refString,join:this.joinType,matrixOperation:s,location:this.location};return delete o.as,this.note&&(o.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(o),o}}Ti.ExpressionJoin=sme;class ome extends eme.DefinitionList{constructor(e){super(e),this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=rme.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}}Ti.JoinStatement=ome,Object.defineProperty(f1,"__esModule",{value:!0}),f1.RefinedSource=void 0;const ume=oe,ame=rd,lme=wl,cme=oo,fme=od,xme=ud,dme=ad,hme=so,pme=ld,gme=Fl,mme=Ll,yme=sd,Eme=Ti;class Ame extends hme.Source{constructor(e,n){super({source:e,refinement:n}),this.source=e,this.refinement=n,this.elementType="refinedSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;let i,s;const o=[],u=[];let a;for(const m of this.refinement.list){if(m instanceof gme.ObjectAnnotation)continue;const g=m;if(m instanceof xme.PrimaryKey){if(i){const y="multiple-primary-keys";i.logError(y,"Primary key already defined"),m.logError(y,"Primary key redefined")}i=m}else if(m instanceof fme.FieldListEdit){if(s){const y="multiple-field-list-edits";s.logError(y,"Too many accept/except statements"),m.logError(y,"Too many accept/except statements")}s=m}else m instanceof lme.DeclareFields||m instanceof Eme.JoinStatement||m instanceof dme.Views||m instanceof mme.Renames?o.push(...m.list):m instanceof cme.Filter?u.push(m):m instanceof pme.TimezoneStatement?a=m.tz:g.logError("unexpected-source-property",`Unexpected source property: '${g.elementType}'`)}const l=n?new yme.ParameterSpace(n):void 0,c=structuredClone(this.source.getSourceDef(l));i&&(c.primaryKey=i.field.name);const f=ame.RefinedSpace.filteredFrom(c,s,l);if(a&&f.setTimezone(a),n&&f.addParameters(n),f.pushFields(...o),i){const m=i.field.getField(f);m.error&&i.logError(m.error.code,m.error.message)}const x=f.structDef(),h=x.filterList||[];let p=!1;for(const m of u)for(const g of m.list){const y=g.filterCondition(f);(0,ume.expressionIsCalculation)(y.expressionType)?g.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(h.push(y),p=!0)}return p?{...x,filterList:h}:((r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(x),x)}}f1.RefinedSource=Ame;var uu={};Object.defineProperty(uu,"__esModule",{value:!0}),uu.SourceQueryElement=void 0;const vme=Ge;class fO extends vme.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,n,r){return this.isErrorFree()&&this.logError(e,n,r),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const n of this.walk())if(n instanceof fO&&n.errored){e=!1;break}return e}}uu.SourceQueryElement=fO;var kA={},Lc={};Object.defineProperty(Lc,"__esModule",{value:!0}),Lc.QuerySource=void 0;const Sme=so,_me=W3;class Cme extends Sme.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,n){var r;const i=this.query.queryComp(!1),s={...i.outputStruct,name:`QuerySource-${(0,_me.v4)()}`,type:"query_source",query:i.query};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),{...s,parameters:this.packParameters(n)}}}Lc.QuerySource=Cme;var cd={},h1={};Object.defineProperty(h1,"__esModule",{value:!0}),h1.QueryBase=void 0;const Tme=Kx,bme=Ge;class Rme extends bme.MalloyElement{query(){const e=this.queryComp(!0).query;return{...e,pipeline:(0,Tme.detectAndRemovePartialStages)(e.pipeline,this)}}}h1.QueryBase=Rme,Object.defineProperty(cd,"__esModule",{value:!0}),cd.QueryArrow=void 0;const Ome=oe,Dme=so,vq=hr,Nme=h1;class wme extends Nme.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 Dme.Source){const l=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};r={type:"query",...l,pipeline:[],location:this.location},n=(0,Ome.refIsStructDef)(l.structRef)?l.structRef:this.source.getSourceDef(void 0),i=new vq.StaticSpace(n)}else{const l=this.source.queryComp(e);r=l.query,n=l.outputStruct,i=new vq.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}}}cd.QueryArrow=wme,Object.defineProperty(kA,"__esModule",{value:!0}),kA.SQArrow=void 0;const Fme=uu,Lme=Lc,Ime=cd;class $me extends Fme.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("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const n=new Ime.QueryArrow(e,this.operation);return this.has({query:n}),n}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const n=new Lme.QuerySource(e);return this.has({asSource:n}),n}}kA.SQArrow=$me;var PA={},fd={},Zi={};Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.getStructFieldDef=Zi.getFinalStruct=Zi.opOutputStruct=void 0;const Sq=pl,Bme=X0,MA=oe,_q=Fr;function Cq(t,e,n){const r=_q.ErrorFactory.didCreate(e)||(0,MA.structHasErrors)(e);(0,MA.isPartialSegment)(n)&&(n={...n,type:"reduce"});const i=(0,MA.segmentHasErrors)(n);if(!r&&!i)try{const s=Bme.Segment.nextStructDef(e,n);if((0,MA.isSourceDef)(s))return s;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1324
1324
  STRUCTDEF: ${(0,Sq.inspect)(s,{breakLength:72,depth:1/0})}`)}catch(s){t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: ${s.message}
1325
1325
  QUERY: ${(0,Sq.inspect)(n,{breakLength:72,depth:1/0})}`)}return _q.ErrorFactory.structDef}Zi.opOutputStruct=Cq;function kme(t,e,n){for(const r of n)e=Cq(t,e,r);return e}Zi.getFinalStruct=kme;function Pme(t,e){return t.fields.find(n=>(n.as||n.name)===e)}Zi.getStructFieldDef=Pme,Object.defineProperty(fd,"__esModule",{value:!0}),fd.QueryRefine=void 0;const Mme=hr,jme=Zi,Ume=h1;class qme extends Ume.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 Mme.StaticSpace(n.inputStruct),i=this.refinement.refine(r,n.query.pipeline,void 0);return{query:{...n.query,pipeline:i},outputStruct:(0,jme.getFinalStruct)(this.refinement,n.inputStruct,i),inputStruct:n.inputStruct}}}fd.QueryRefine=qme;var p1={},xd={},Jn={};Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.timeResult=Jn.resolution=Jn.castDateToTimestamp=Jn.castTimestampToDate=Jn.castTo=Jn.timeOffset=void 0;const Hme=oe;function zme(t,e,n,r,i){return{node:"delta",kids:{base:{...e,dataType:t},delta:r},op:n,units:i}}Jn.timeOffset=zme;function Qme(t,e,n,r=!1){const i={node:"cast",dstType:t,e,safe:r};return(0,Hme.isAtomicFieldType)(n)&&(i.srcType=n),i}Jn.castTo=Qme;function Gme(t,e=!1){return{node:"cast",dstType:"date",srcType:"timestamp",e:t,safe:e}}Jn.castTimestampToDate=Gme;function Wme(t,e=!1){return{node:"cast",dstType:"timestamp",srcType:"date",e:t,safe:e}}Jn.castDateToTimestamp=Wme;function Vme(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Jn.resolution=Vme;function Yme(t,e){return e?{...t,timeframe:e}:t}Jn.timeResult=Yme;var Ic={},st={},Jt={};Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.FT=void 0;const Jme=Ai;function $c(t,e="scalar",n="constant"){return{dataType:t,expressionType:e,evalSpace:n}}class pr{static in(e,n){return e?n.find(i=>pr.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=>pr.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,Jme.expressionIsScalar)(r.expressionType)||(i=`${r.expressionType} ${i}`),i}return"undefined"}).join(",")}}Jt.FT=pr,pr.nullT=$c("null"),pr.numberT=$c("number"),pr.stringT=$c("string"),pr.dateT=$c("date"),pr.timestampT=$c("timestamp"),pr.boolT=$c("boolean"),pr.anyAtomicT=[pr.numberT,pr.stringT,pr.dateT,pr.timestampT,pr.boolT],pr.aggregateBoolT=$c("boolean","aggregate");var dd={};Object.defineProperty(dd,"__esModule",{value:!0}),dd.isGranularResult=void 0;function Xme(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}dd.isGranularResult=Xme;var uo={};Object.defineProperty(uo,"__esModule",{value:!0}),uo.isComparison=uo.isEquality=uo.getExprNode=void 0;function Kme(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}uo.getExprNode=Kme;function Tq(t){return t==="="||t==="!="||t==="~"||t==="!~"}uo.isEquality=Tq;function Zme(t){return Tq(t)||t===">="||t==="<="||t===">"||t==="<"}uo.isComparison=Zme,Object.defineProperty(st,"__esModule",{value:!0}),st.applyBinary=st.getMorphicValue=st.ExprDuration=st.ExpressionDef=st.ATNodeType=void 0;const yn=oe,xO=Ci,Bc=Jt,jA=Jn,bq=dd,e3e=Ge,g1=uo;class t3e extends Error{}var dO;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(dO||(st.ATNodeType=dO={}));class Rq extends e3e.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Bc.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.dataType!=="error"&&!Bc.FT.in(n,this.legalChildTypes)?(n.dataType==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:n.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${Bc.FT.inspect(n)}`),!1):!0}apply(e,n,r,i=!1){return wq(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,yn.expressionIsAggregate)(e.expressionType)}atNodeType(){return dO.Value}atExpr(){return this}}st.ExpressionDef=Rq;class hO extends Rq{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[Bc.FT.timestampT,Bc.FT.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,yn.isTemporalField)(i.dataType)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!Bc.FT.typeEq(s,Bc.FT.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${s.dataType}`),(0,xO.errorFor)("illegal unit expression");let o;if((0,bq.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){const u=(0,jA.timeOffset)("timestamp",i.value,n,s.value,this.timeframe);return(0,jA.timeResult)({dataType:"timestamp",expressionType:(0,yn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,yn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u},o)}return(0,yn.isDateUnit)(this.timeframe)?(0,jA.timeResult)({dataType:"date",expressionType:(0,yn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,yn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,jA.timeOffset)("date",i.value,n,s.value,this.timeframe)},o):this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`)}return super.apply(e,n,r)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:{node:"error",message:"Duration is not a value"},evalSpace:"constant"}}}st.ExprDuration=hO;function Oq(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function n3e(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}st.getMorphicValue=n3e;function Dq(t,e,n,r){const i=(0,yn.isTemporalField)(e.dataType),s=(0,yn.isTemporalField)(r.dataType),o=(0,g1.getExprNode)(n);if(i&&s)if(e.dataType!==r.dataType){const u=Oq(e,"timestamp"),a=Oq(r,"timestamp");if(u&&a)return{node:o,kids:{left:u,right:u}}}else return{node:o,kids:{left:e.value,right:r.value}};if((i||s)&&e.dataType!=="null"&&r.dataType!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.dataType} to a ${r.dataType}`),{node:"false"}}function r3e(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.dataType==="string"&&t.dataType==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function i3e(t,e,n){const r=e==="!="||e==="!~",i=r?"is-not-null":"is-null";if(t.dataType==="null"||n.dataType==="null")return t.dataType!=="null"?{node:i,e:t.value}:n.dataType!=="null"?{node:i,e:n.value}:{node:r?"false":"true"}}function s3e(t,e,n,r){var i;const s=e.getExpression(t),o=r.getExpression(t),u=(0,g1.getExprNode)(n),a=m1("boolean",s,o);if(a)return a;if(s.dataType==="sql native"||o.dataType==="sql native"){const f=s.dataType==="null"||o.dataType==="null",x=s.rawType&&s.rawType===o.rawType;if(!(f||x)){const h=y1(e,s,r,o);if(h)return{...h,dataType:"boolean"}}}let c=Dq(e,s,n,o)||{node:u,kids:{left:s.value,right:o.value}};if(s.dataType!=="error"&&o.dataType!=="error")switch(n){case"~":case"!~":{if(s.dataType!=="string"||o.dataType!=="string"){let f=r3e(s,o);if(f)n[0]==="!"&&(f={node:"not",e:{...f}});else throw new t3e("Incompatible types for match('~') operator");c=f}break}case"=":case"!=":{c=(i=i3e(s,n,o))!==null&&i!==void 0?i:c;break}}return{dataType:"boolean",expressionType:(0,yn.maxExpressionType)(s.expressionType,o.expressionType),evalSpace:(0,yn.mergeEvalSpaces)(s.evalSpace,o.evalSpace),value:c}}function o3e(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=m1("boolean",i,s);if(o)return o;const u=(0,yn.maxExpressionType)(i.expressionType,s.expressionType),a=y1(e,i,r,s);if(a)return{...a,dataType:"boolean"};const l=Dq(e,i,n,s)||{node:(0,g1.getExprNode)(n),kids:{left:i.value,right:s.value}};return{dataType:"boolean",expressionType:u,evalSpace:(0,yn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function Nq(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=m1("number",i,s);if(o)return o;const u=y1(e,i,r,s);if(u)return u;const a=(0,yn.maxExpressionType)(i.expressionType,s.expressionType);if(i.dataType!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${n}' operator requires a number, not a '${i.dataType}'`);else if(s.dataType!=="number")r.logError("arithmetic-operation-type-mismatch",`The '${n}' operator requires a number, not a '${s.dataType}'`);else return{dataType:"number",expressionType:a,value:{node:n,kids:{left:i.value,right:s.value}},evalSpace:(0,yn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)};return(0,xO.errorFor)("numbers required")}function u3e(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=y1(e,i,r,s);if(o)return o;const u=(0,yn.isTemporalField)(i.dataType),a=m1(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.dataType!=="duration")if((0,bq.isGranularResult)(i))l=new hO(r,i.timeframe);else if(i.dataType==="date")l=new hO(r,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${s.dataType}'`);return l.apply(t,n,e)}return Nq(t,e,n,r)}function wq(t,e,n,r){if((0,g1.isEquality)(n))return s3e(t,e,n,r);if((0,g1.isComparison)(n))return o3e(t,e,n,r);if(n==="+"||n==="-")return u3e(t,e,n,r);if(n==="*")return Nq(t,e,n,r);if(n==="/"||n==="%"){const i=e.getExpression(t),s=r.getExpression(t),o=y1(e,i,r,s);if(o)return o;const u=m1("number",i,s);if(u)return u;if(i.dataType!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(s.dataType!=="number")r.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const a={node:n,kids:{left:i.value,right:s.value}};return{dataType:"number",expressionType:(0,yn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,yn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a}}return(0,xO.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${n} operator here`)}st.applyBinary=wq;function m1(t,...e){if(e.some(n=>n.dataType==="error"))return{dataType:t,expressionType:(0,yn.maxOfExpressionTypes)(e.map(n=>n.expressionType)),value:{node:"error",message:"cascading error"},evalSpace:(0,yn.mergeEvalSpaces)(...e.map(n=>n.evalSpace))}}function y1(t,e,n,r){const i={dataType:e.dataType,expressionType:(0,yn.maxExpressionType)(e.expressionType,r.expressionType),value:{node:"error",message:"sql-native unsupported"},evalSpace:(0,yn.mergeEvalSpaces)(e.evalSpace,r.evalSpace)};if(e.dataType==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),i.dataType=r.dataType,i;if(r.dataType==="sql native")return n.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}),i}Object.defineProperty(Ic,"__esModule",{value:!0}),Ic.ExprIdReference=void 0;const a3e=oe,l3e=st;class c3e extends l3e.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:{node:"outputField",name:this.refString}};const i={node:n.found.refType,path:this.fieldReference.path},s=(0,a3e.expressionIsAggregate)(r.expressionType)?"output":r.evalSpace;return{...r,value:i,evalSpace:s}}return this.loggedErrorExpr(n.error.code,n.error.message)}}Ic.ExprIdReference=c3e,Object.defineProperty(xd,"__esModule",{value:!0}),xd.NamedSource=void 0;const pO=oe,f3e=so,x3e=Fr,d3e=Jn,Fq=Ge,h3e=Ic,p3e=sd;class g3e extends f3e.Source{constructor(e,n,r){super(),this.ref=e,this.sourceArguments=n,this.args=r,this.elementType="namedSource",r&&this.has({args:r}),e instanceof Fq.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Fq.ModelEntryReference?this.ref.name:this.ref}structRef(e){const n=this.modelEntry(this.ref);return n&&!n.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,n,r){typeof this.ref=="string"?this.logError(e,n,r):this.ref.logError(e,n,r)}modelStruct(){var e;const n=this.modelEntry(this.ref),r=n==null?void 0:n.entry;if(!r){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(r.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(r.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,r.dialect),(0,pO.isSourceDef)(r))return{...r};this.logError("invalid-source-source",`Cannot construct a source from a ${r.type}`)}evaluateArgumentsForRef(e){const n=this.modelStruct();return n===void 0?{}:this.evaluateArguments(e,n.parameters,[])}evaluateArguments(e,n,r){var i,s;const o={...this.sourceArguments},u=new Set;for(const a of(i=this.args)!==null&&i!==void 0?i:[]){const l=(s=a.id)!==null&&s!==void 0?s:a.value instanceof h3e.ExprIdReference?a.value.fieldReference:void 0;if(l===void 0){a.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const c=l.outputName;if(u.has(c)){a.logError("duplicate-source-argument",`Cannot pass argument for \`${c}\` more than once`);continue}u.add(c);const f=(n??{})[c];if(!f)l.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${l.refString}\``);else{const x=e??new p3e.ParameterSpace(r??[]),h=a.value.getExpression(x);let p=h.value;h.dataType!==f.type&&(0,pO.isCastType)(f.type)&&(p=(0,d3e.castTo)(f.type,h.value,h.dataType,!0)),o[c]={...f,value:p}}}for(const a in n)a in o||((0,pO.paramHasValue)(n[a])?o[a]={...n[a]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${a}\``));return o}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;const i=this.modelStruct();if(!i){const a=x3e.ErrorFactory.structDef,l=`${this.refName}-undefined`;return a.name=a.name+l,a.dialect=a.dialect+l,a}const s={};for(const a of n??[]){const l=a.parameter();s[l.name]=l}const o=this.evaluateArguments(e,i.parameters,n),u={...i,parameters:s,arguments:o};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}xd.NamedSource=g3e;var E1={},UA={};Object.defineProperty(UA,"__esModule",{value:!0}),UA.QueryHeadStruct=void 0;const m3e=oe,y3e=so,E3e=xd;class A3e extends y3e.Source{constructor(e,n){super(),this.fromRef=e,this.sourceArguments=n,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,m3e.refIsStructDef)(this.fromRef))return this.fromRef;const n=new E3e.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:n}),n.getSourceDef(e)}}UA.QueryHeadStruct=A3e,Object.defineProperty(E1,"__esModule",{value:!0}),E1.QueryReference=void 0;const gO=Fr,v3e=Ge,S3e=UA,_3e=oe,C3e=Zi;class T3e extends v3e.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:gO.ErrorFactory.structDef,outputStruct:gO.ErrorFactory.structDef,query:gO.ErrorFactory.query}};if(!r)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),i();if(r.type==="query"){const s=new S3e.QueryHeadStruct(r.structRef,r.sourceArguments);this.has({queryHead:s});const o=s.getSourceDef(void 0),u=(0,C3e.getFinalStruct)(this,o,r.pipeline);return{query:e||(0,_3e.refIsStructDef)(r.structRef)?r:{...r,structRef:o},outputStruct:u,inputStruct:o}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}}E1.QueryReference=T3e,Object.defineProperty(p1,"__esModule",{value:!0}),p1.SQReference=void 0;const b3e=uu,R3e=Lc,O3e=xd,Lq=E1,Iq=Ai;class D3e extends b3e.SourceQueryElement{constructor(e,n){super({ref:e}),this.ref=e,this.args=n,this.elementType="sq-reference",n!==void 0&&this.has({args:n})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const n=new Lq.QueryReference(this.ref);return this.has({query:n}),n}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,Iq.modelObjIsSource)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const n=new Lq.QueryReference(this.ref);this.asSource=new R3e.QuerySource(n)}else if((0,Iq.modelObjIsSource)(e))this.asSource=new O3e.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}p1.SQReference=D3e,Object.defineProperty(PA,"__esModule",{value:!0}),PA.SQRefine=void 0;const N3e=uu,w3e=Lc,F3e=fd,L3e=p1;class I3e extends N3e.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 L3e.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const n=new F3e.QueryRefine(e,this.refine);return this.has({query:n}),n}}getSource(){const e=this.getQuery();if(e){const n=new w3e.QuerySource(e);return this.has({queryAsSource:n}),n}}}PA.SQRefine=I3e;var qA={},A1={};Object.defineProperty(A1,"__esModule",{value:!0}),A1.QueryRaw=void 0;const $3e=oe,B3e=Ge;class k3e extends B3e.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const n=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},r=(0,$3e.refIsStructDef)(n.structRef)?n.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...n,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:r,inputStruct:r}}query(){return this.queryComp(!0).query}}A1.QueryRaw=k3e;var v1={},HA={};Object.defineProperty(HA,"__esModule",{value:!0}),HA.makeSQLSentence=void 0;const P3e=oe,M3e=Rt;function j3e(t,e){return{name:`sql://${e}/${U3e(t)}`,connection:e,select:t}}HA.makeSQLSentence=j3e;function U3e(t){const e=t.map(n=>(0,P3e.isSegmentSQL)(n)?n.sql:JSON.stringify(n));return(0,M3e.generateHash)(e.join(";"))}Object.defineProperty(v1,"__esModule",{value:!0}),v1.SQLSource=void 0;const q3e=HA,H3e=so,zA=Fr;class z3e extends H3e.Source{constructor(e,n){super({connectionName:e,select:n}),this.connectionName=e,this.select=n,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSentence(){return this.requestBlock||(this.requestBlock=(0,q3e.makeSQLSentence)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return{structRef:this.getSourceDef()}}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.logError("invalid-connection-for-sql-source",`${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.sqlSentence(),s=(n=this.translator())===null||n===void 0?void 0:n.root.sqlQueryZone;if(!s){this.logError("failed-to-fetch-sql-source-schema","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)}getSourceDef(){var e;if(!this.validateConnectionName())return zA.ErrorFactory.structDef;const n=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!n)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),zA.ErrorFactory.structDef;const r=this.sqlSentence();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.logError("invalid-sql-source","Invalid SQL, "+s.join(`
1326
- `)),zA.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.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),zA.ErrorFactory.structDef}}v1.SQLSource=z3e,Object.defineProperty(qA,"__esModule",{value:!0}),qA.SQSource=void 0;const Q3e=uu,G3e=A1,W3e=v1;class V3e extends Q3e.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 W3e.SQLSource){const e=new G3e.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}qA.SQSource=V3e;var QA={};Object.defineProperty(QA,"__esModule",{value:!0}),QA.SQExtend=void 0;const Y3e=f1,J3e=uu;class X3e extends J3e.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 Y3e.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}QA.SQExtend=X3e;var GA={},ha={},S1={};Object.defineProperty(S1,"__esModule",{value:!0}),S1.BinaryBoolean=void 0;const $q=oe,K3e=Ci,Z3e=Jt,eye=uo,tye=st;class nye extends tye.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=[Z3e.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,$q.mergeEvalSpaces)(n.evalSpace,r.evalSpace);return{dataType:"boolean",expressionType:(0,$q.maxExpressionType)(n.expressionType,r.expressionType),value:{node:(0,eye.getExprNode)(this.op),kids:{left:n.value,right:r.value}},evalSpace:i}}return(0,K3e.errorFor)("logial required boolean")}}S1.BinaryBoolean=nye,Object.defineProperty(ha,"__esModule",{value:!0}),ha.ExprLegacyIn=ha.ExprEquality=ha.ExprCompare=void 0;const Bq=Ai,Qt=Jt,rye=st,iye=S1,sye={"~":[Qt.FT.stringT],"!~":[Qt.FT.stringT],"<":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],"<=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],"=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],"!=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],">=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],">":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT]};class kq extends iye.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="a<=>b",this.legalChildTypes=sye[n]}getExpression(e){return this.right.apply(e,this.op,this.left)}}ha.ExprCompare=kq;class oye extends kq{constructor(e,n,r){super(e,n,r),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,n,r){return super.apply(e,n,r,!0)}}ha.ExprEquality=oye;class uye extends rye.ExpressionDef{constructor(e,n,r){super(),this.expr=e,this.notIn=n,this.choices=r,this.elementType="in",this.has({expr:e,choices:r})}getExpression(e){const n=this.expr.getExpression(e);let{evalSpace:r,expressionType:i}=n;const s=this.choices.map(o=>{const u=o.getExpression(e);return i=(0,Bq.maxExpressionType)(i,u.expressionType),r=(0,Bq.mergeEvalSpaces)(r,u.evalSpace),u.value});return{dataType:"boolean",expressionType:i,evalSpace:r,value:{node:"in",not:this.notIn,kids:{e:n.value,oneOf:s}}}}}ha.ExprLegacyIn=uye;var _1={},hd={};Object.defineProperty(hd,"__esModule",{value:!0}),hd.ExprTime=void 0;const aye=oe,lye=st;class mO extends lye.ExpressionDef{constructor(e,n,r="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:r,value:n,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,n){let r=n.value;if(e!==n.dataType){const i={node:"cast",safe:!1,dstType:e,e:n.value};(0,aye.isTemporalField)(n.dataType)&&(i.srcType=n.dataType),r=i}return new mO(e,r,n.expressionType)}}hd.ExprTime=mO;var Il={};Object.defineProperty(Il,"__esModule",{value:!0}),Il.Range=void 0;const Pq=oe,cye=Ci,fye=st;class xye extends fye.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,Pq.maxExpressionType)(u.expressionType,a.expressionType),evalSpace:(0,Pq.mergeEvalSpaces)(u.evalSpace,a.evalSpace),value:{node:s,kids:{left:u.value,right: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.logError("range-as-value","A Range is not a value"),(0,cye.errorFor)("a range is not a value")}}Il.Range=xye,Object.defineProperty(_1,"__esModule",{value:!0}),_1.ExprGranularTime=void 0;const Mq=oe,dye=Ci,jq=Jt,Uq=Jn,hye=st,WA=hd,qq=Il;class pye extends hye.ExpressionDef{constructor(e,n,r){super({expr:e}),this.expr=e,this.units=n,this.truncate=r,this.elementType="granularTime",this.legalChildTypes=[jq.FT.timestampT,jq.FT.dateT]}granular(){return!0}getExpression(e){const n=this.units,r=this.expr.getExpression(e);if((0,Mq.isTemporalField)(r.dataType)){const s={...r,dataType:r.dataType,timeframe:n};return this.truncate&&(s.value={node:"trunc",e:{...r.value,dataType:r.dataType},units:n}),s}r.dataType!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${r.dataType}'`);const i=r.dataType==="error"?(0,Mq.isDateUnit)(n)?"date":"timestamp":r.dataType;return{...r,dataType:i,value:(0,dye.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const n=this.getExpression(e),r={node:"numberLiteral",literal:"1"};if(n.dataType==="timestamp"){const u=WA.ExprTime.fromValue("timestamp",n),a=new WA.ExprTime("timestamp",(0,Uq.timeOffset)("timestamp",n.value,"+",r,this.units),n.expressionType);return new qq.Range(u,a)}const i=new WA.ExprTime("date",n.value,n.expressionType),s=(0,Uq.timeOffset)("date",n.value,"+",r,this.units),o=new WA.ExprTime("date",s,n.expressionType);return new qq.Range(i,o)}}_1.ExprGranularTime=pye,Object.defineProperty(GA,"__esModule",{value:!0}),GA.Apply=void 0;const gye=ha,mye=dd,Hq=_1;class yye extends gye.ExprCompare{constructor(e,n){super(e,"=",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,mye.isGranularResult)(r)&&(n=new Hq.ExprGranularTime(this.right,r.timeframe,!1))}return n instanceof Hq.ExprGranularTime?n.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}GA.Apply=yye;var pd={};Object.defineProperty(pd,"__esModule",{value:!0}),pd.BinaryNumeric=void 0;const Eye=Jt,Aye=st;class vye extends Aye.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=[Eye.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}pd.BinaryNumeric=vye;var VA={};Object.defineProperty(VA,"__esModule",{value:!0}),VA.Boolean=void 0;const Sye=st,_ye=Jt;let Cye=class extends Sye.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{..._ye.FT.boolT,value:{node:this.value}}}};VA.Boolean=Cye;var $l={};Object.defineProperty($l,"__esModule",{value:!0}),$l.FunctionOrdering=$l.FunctionOrderBy=void 0;const yO=oe,zq=Ge,Tye=Ic;class bye extends zq.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.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const n=this.field.getExpression(e);return(0,yO.expressionIsAggregate)(n.expressionType)||((0,yO.expressionIsScalar)(n.expressionType)?(!(this.field instanceof Tye.ExprIdReference)||n.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:n.value,dir:this.dir}}getAggregateOrderBy(e,n){if(this.field){const r=this.field.getExpression(e);return(0,yO.expressionIsScalar)(r.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),n||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:r.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}$l.FunctionOrderBy=bye;class Rye extends zq.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))}}$l.FunctionOrdering=Rye;var YA={};Object.defineProperty(YA,"__esModule",{value:!0}),YA.ExprAddSub=void 0;const Oye=pd;class Dye extends Oye.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}YA.ExprAddSub=Dye;var pa={},ht={},C1={};Object.defineProperty(C1,"__esModule",{value:!0}),C1.ReferenceField=void 0;const Qq=wr;class Nye extends Qq.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){var n;if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.list.map(u=>u.name),s=((n=r.found)===null||n===void 0?void 0:n.refType)==="parameter"?{type:r.found.typeDesc().dataType,name:i[0],e:{node:"parameter",path:i}}:{type:"fieldref",path:i};this.queryFieldDef=s;const o=this.referenceTo;if(o instanceof Qq.SpaceField){const u=o.constructorFieldDef();if(u){const a=this.fieldRef.note;if(u.annotation||a){const l=a||{};u.annotation&&(l.inherits=u.annotation),this.queryFieldDef.annotation=l}}}}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"}}}C1.ReferenceField=Nye;var In={};Object.defineProperty(In,"__esModule",{value:!0}),In.typecheckGroupBy=In.typecheckAggregate=In.typecheckCalculate=In.typecheckDeclare=In.typecheckMeasure=In.typecheckDimension=In.typecheckIndex=In.typecheckProject=void 0;const En=Ai;function wye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="select-of-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="select-of-analytic";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}In.typecheckProject=wye;function Fye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a view",r="index-of-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="an analytic",r="index-of-analytic";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(r,`Cannot use ${n} field in an index operation`)}}In.typecheckIndex=Fye;function Lye(t,e){if(!(0,En.expressionIsScalar)(t.expressionType))if((0,En.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,En.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}In.typecheckDimension=Lye;function Iye(t,e){if(!(0,En.expressionIsAggregate)(t.expressionType))if((0,En.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,En.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}In.typecheckMeasure=Iye;function $ye(t,e){t.dataType==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,En.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}In.typecheckDeclare=$ye;function Bye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsAnalytic)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="calculate-of-view";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="calculate-of-aggregate";else if((0,En.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}In.typecheckCalculate=Bye;function kye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsAggregate)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="aggregate-of-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="aggregate-of-analytic";else if((0,En.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(i,`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}In.typecheckAggregate=kye;function Pye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="group-by-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="group-by-analytic";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}In.typecheckGroupBy=Pye,Object.defineProperty(ht,"__esModule",{value:!0}),ht.FieldReferences=ht.WildcardFieldReference=ht.ViewOrScalarFieldReference=ht.DimensionFieldReference=ht.MeasureFieldReference=ht.DeclareFieldReference=ht.ProjectFieldReference=ht.GroupByFieldReference=ht.AggregateFieldReference=ht.IndexFieldReference=ht.CalculateFieldReference=ht.ParameterFieldReference=ht.PartitionByFieldReference=ht.ExpressionFieldReference=ht.AcceptExceptFieldReference=ht.FieldReference=void 0;const Mye=C1,jye=Ki,Gq=Ge,Wq=Nr,Bl=In;class bi extends Gq.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=Wq.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.logError("output-name-conflict",`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new Mye.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}}ht.FieldReference=bi;class Uye extends bi{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}ht.AcceptExceptFieldReference=Uye;class qye extends bi{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}ht.ExpressionFieldReference=qye;class Hye extends bi{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}ht.PartitionByFieldReference=Hye;class zye extends bi{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}ht.ParameterFieldReference=zye;class Qye extends bi{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Bl.typecheckCalculate)(e,this)}}ht.CalculateFieldReference=Qye;class EO extends bi{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Bl.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return EO.indexOutputName(this.path)}}ht.IndexFieldReference=EO;class Gye extends bi{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Bl.typecheckAggregate)(e,this)}}ht.AggregateFieldReference=Gye;class Wye extends bi{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Bl.typecheckGroupBy)(e,this)}}ht.GroupByFieldReference=Wye;class Vye extends bi{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Bl.typecheckProject)(e,this)}}ht.ProjectFieldReference=Vye;class Yye extends bi{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Bl.typecheckDeclare)(e,this)}}ht.DeclareFieldReference=Yye;class Jye extends bi{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Bl.typecheckMeasure)(e,this)}}ht.MeasureFieldReference=Jye;class Xye extends bi{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Bl.typecheckDimension)(e,this)}}ht.DimensionFieldReference=Xye;class Kye extends bi{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}ht.ViewOrScalarFieldReference=Kye;class Zye extends Gq.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=Wq.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}.*`:"*"}}ht.WildcardFieldReference=Zye;class eEe extends jye.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}ht.FieldReferences=eEe,Object.defineProperty(pa,"__esModule",{value:!0}),pa.ExprAggregateFunction=void 0;const T1=oe,tEe=Rt,nEe=Ci,Vq=hr,rEe=Jt,iEe=ht,sEe=st,oEe=wr,uEe=Ic;class aEe extends sEe.ExpressionDef{constructor(e,n,r){super(),this.func=e,this.legalChildTypes=[rEe.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,i;const s=e.isQueryFieldSpace()?e.inputSpace():e;let o=this.expr,u=(n=this.expr)===null||n===void 0?void 0:n.getExpression(s),a=(r=this.source)===null||r===void 0?void 0:r.path,l=[];if(this.source){const f=this.source.getField(s);if(f.found){l=f.joinPath;const x=f.found,h=x.typeDesc();if(!(x instanceof Vq.StructSpaceField))if((0,T1.isAtomicFieldType)(h.dataType)){o=this.source,u={dataType:h.dataType,expressionType:h.expressionType,value:h.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:h.evalSpace},a=this.source.path;const p=this.getJoinUsage(s);(p.length===1||p.length>1&&p.slice(1).every(g=>lEe(g,p[0])))&&(a=p[0].map(g=>g.name),l=p[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${h.dataType}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(u===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,T1.expressionIsAggregate)(u.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(u.dataType==="error")){const f=this.getJoinUsage(s),x=this.source!==void 0||this.explicitSource;if(o&&!(!this.source&&f.every(p=>p.length===0))&&!this.isSymmetricFunction()){const p=vO(l,f),m=SO(this.elementType,p),g=x?m==null?void 0:m.message:"Join path is required for this calculation";if(g){const y=cEe(g,f,o,this.elementType),E=(i=m==null?void 0:m.code)!==null&&i!==void 0?i:"bad-join-usage";m?this.logError(E,y):this.logWarning(E,y)}}}if(this.typeCheck(this.expr||this,{...u,expressionType:"scalar"})){const f={node:"aggregate",function:this.func,e:u.value};return a&&a.length>0&&(f.structPath=a),{dataType:this.returns(u),expressionType:"aggregate",value:f,evalSpace:"output"}}return(0,nEe.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const n=[];if(this.source&&this.source.getField(e).found){const i={node:"field",path:this.source.path};n.push(...AO(e,i))}if(this.expr){const r=this.expr.getExpression(e).value;n.push(...AO(e,r))}return n}}pa.ExprAggregateFunction=aEe;function lEe(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 AO(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 Vq.StructSpaceField&&u.length>0){const l=r(a.fieldSpace,u);return{...l,joinPath:[{...a.joinPathElement,name:o},...l.joinPath]}}else if(a instanceof oEe.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,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const i of(0,tEe.exprWalk)(e))if(i.node==="field"){const s=r(t,i.path),o=s.def;if((0,T1.isAtomic)(o)&&!(0,T1.isJoined)(o))if((0,T1.hasExpression)(o)){const u=AO(s.fs,o.e);n.push(...u.map(a=>[...s.joinPath,...a]))}else n.push(s.joinPath)}else if(i.node==="source-reference")if(i.path){const s=r(t,i.path);n.push(s.joinPath)}else n.push([]);return n}function vO(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 SO(t,e){for(const n of e)for(const r of n){if(r.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${r.name}\``};if(r.joinElementType==="array"&&!r.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${r.name}\``};if(r.joinType==="many"&&!r.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${r.name}\``}}}function cEe(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=vO(i,e),o=SO(r,s),u=i.slice().reverse().findIndex(p=>p.joinType==="many"||p.joinType==="cross"),a=u===-1?0:i.length-u,l=i.slice(0,a),c=vO(l,e),f=SO(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 iEe.FieldReference?`${n.refString}.${r}()`:n instanceof uEe.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 JA={};Object.defineProperty(JA,"__esModule",{value:!0}),JA.ExprAlternationTree=void 0;const XA=oe,gd=st,fEe=uo;function _O(t){const e=t.atExpr();switch(e.atNodeType()){case gd.ATNodeType.And:case gd.ATNodeType.Partial:return;case gd.ATNodeType.Or:{if(e instanceof Yq){const n=_O(e.left);if(n){const r=_O(e.right);if(r)return[...n,...r]}}return}default:return e.granular()?void 0:[e]}}class Yq extends gd.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="alternation",this.elementType=`${n}alternation${n}`}equalityList(){return this.inList===void 0&&(this.inList=_O(this)||[]),this.inList}apply(e,n,r,i){if((0,fEe.isEquality)(n)){const u=this.equalityList();if(u.length>0&&(n==="="||n==="!=")){const a=r.getExpression(e),l=u.map(x=>x.getExpression(e));let{evalSpace:c,expressionType:f}=a;for(const x of l)c=(0,XA.mergeEvalSpaces)(c,x.evalSpace),f=(0,XA.maxExpressionType)(f,x.expressionType);return{dataType:"boolean",evalSpace:c,expressionType:f,value:{node:"in",not:n==="!=",kids:{e:a.value,oneOf:l.map(x=>x.value)}}}}u.length===0&&i&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${n} operator`)}const s=this.left.apply(e,n,r),o=this.right.apply(e,n,r);return{dataType:"boolean",expressionType:(0,XA.maxExpressionType)(s.expressionType,o.expressionType),evalSpace:(0,XA.mergeEvalSpaces)(s.evalSpace,o.evalSpace),value:{node:this.op==="&"?"and":"or",kids:{left:s.value,right:o.value}}}}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?gd.ATNodeType.Or:gd.ATNodeType.And}}JA.ExprAlternationTree=Yq;var md={};Object.defineProperty(md,"__esModule",{value:!0}),md.ExprAsymmetric=void 0;const xEe=pa;class dEe extends xEe.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}`}}}}md.ExprAsymmetric=dEe;var KA={};Object.defineProperty(KA,"__esModule",{value:!0}),KA.ExprAvg=void 0;const hEe=md;class pEe extends hEe.ExprAsymmetric{constructor(e,n,r){super("avg",e,n,r),this.has({source:n})}}KA.ExprAvg=pEe;var ZA={};Object.defineProperty(ZA,"__esModule",{value:!0}),ZA.ExprCast=void 0;const gEe=Jn,mEe=st;class yEe extends mEe.ExpressionDef{constructor(e,n,r=!1){super({expr:e}),this.expr=e,this.castType=n,this.safe=r,this.elementType="cast"}getExpression(e){const n=this.expr.getExpression(e);let r="error";if(typeof this.castType=="string")r=this.castType;else{const i=e.dialectObj();i&&(i.validateTypeName(this.castType.raw)?r=i.sqlTypeToMalloyType(this.castType.raw).type:this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${i.name} dialect`),this.safe&&!i.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return{dataType:r,expressionType:n.expressionType,value:(0,gEe.castTo)(this.castType,n.value,n.dataType,this.safe),evalSpace:n.evalSpace}}}ZA.ExprCast=yEe;var ev={};Object.defineProperty(ev,"__esModule",{value:!0}),ev.ExprCoalesce=void 0;const Jq=Ai,Xq=Jt,EEe=st;class AEe extends EEe.ExpressionDef{constructor(e,n){super({expr:e,altExpr:n}),this.expr=e,this.altExpr=n,this.elementType="coalesce expression",this.legalChildTypes=Xq.FT.anyAtomicT}getExpression(e){const n=this.expr.getExpression(e),r=this.altExpr.getExpression(e);return n.dataType==="null"?r:(Xq.FT.typeEq(n,r)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${n.dataType}, ${r.dataType})`),{...r,dataType:n.dataType==="error"?r.dataType:n.dataType,expressionType:(0,Jq.maxExpressionType)(n.expressionType,r.expressionType),value:{node:"coalesce",kids:{left:n.value,right:r.value}},evalSpace:(0,Jq.mergeEvalSpaces)(n.evalSpace,r.evalSpace)})}}ev.ExprCoalesce=AEe;var tv={};Object.defineProperty(tv,"__esModule",{value:!0}),tv.ExprCount=void 0;const vEe=pa;class SEe extends vEe.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={node:"aggregate",function:"count",e:{node:""}};return this.source&&(n.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:n,evalSpace:"output"}}}tv.ExprCount=SEe;var nv={};Object.defineProperty(nv,"__esModule",{value:!0}),nv.ExprCountDistinct=void 0;const rv=Jt,_Ee=pa;class CEe extends _Ee.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[rv.FT.numberT,rv.FT.stringT,rv.FT.dateT,rv.FT.timestampT]}}nv.ExprCountDistinct=CEe;var iv={},kl={};Object.defineProperty(kl,"__esModule",{value:!0}),kl.Limit=void 0;const TEe=Ge,bEe=mn;class REe extends TEe.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=bEe.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}kl.Limit=REe;var yd={};Object.defineProperty(yd,"__esModule",{value:!0}),yd.PartitionBy=void 0;const OEe=Ge;class DEe extends OEe.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}yd.PartitionBy=DEe;var b1={},Pl={};Object.defineProperty(Pl,"__esModule",{value:!0}),Pl.FieldName=void 0;const NEe=Ge;class wEe extends NEe.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])}}Pl.FieldName=wEe,Object.defineProperty(b1,"__esModule",{value:!0}),b1.ExprFunc=void 0;const es=oe,FEe=Ci,LEe=id,IEe=st,$Ee=Pl,Kq=Rt;class BEe extends IEe.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)}findFunctionDef(e){var n,r,i;const s=this.name.toLowerCase(),o=e?(r=(n=this.getDialectNamespace(e))===null||n===void 0?void 0:n.getEntry(s))===null||r===void 0?void 0:r.entry:void 0,u=o??((i=this.modelEntry(s))===null||i===void 0?void 0:i.entry);return u===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):u.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${u.type}) is not a function`),{found:void 0,error:"called non function"}):(u.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${u.name}' instead`),{found:u,error:void 0})}getPropsExpression(e,n){var r,i,s,o;const u=this.args.map(R=>R.getExpression(e));if(this.isRaw){let R="scalar",O;const I=[`${this.name}(`];for(const z of u)R=(0,es.maxExpressionType)(R,z.expressionType),O?I.push(","):O=z.dataType,I.push(z.value);return I.push(")"),{dataType:(i=(r=this.rawType)!==null&&r!==void 0?r:O)!==null&&i!==void 0?i:"number",expressionType:R,value:(0,Kq.composeSQLExpr)(I),evalSpace:(0,es.mergeEvalSpaces)(...u.map(z=>z.evalSpace))}}const a=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:l,error:c}=this.findFunctionDef(a);if(l===void 0)return(0,FEe.errorFor)(c);let f,x=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const R=this.source.getField(e).found;if(R){const O=R.typeDesc();if((0,es.isAtomicFieldType)(O.dataType))f={dataType:O.dataType,expressionType:O.expressionType,value:{node:"field",path:this.source.path},evalSpace:O.evalSpace},x=this.source.path.slice(0,-1);else if(!(R instanceof LEe.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${O.dataType}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const h=[...f?[f]:[],...u],p=kEe(l,h);if(p===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${h.map(R=>R.dataType).join(", ")})`);const{overload:m,expressionTypeErrors:g,evalSpaceErrors:y,nullabilityErrors:E}=p;for(const R of g){const O=R.argIndex-(f?1:0),I=(0,es.expressionIsScalar)(R.maxExpressionType)?"scalar":"scalar or aggregate";this.args[O].logError("invalid-function-argument-expression-type",`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must be ${I}, but received ${R.actualExpressionType}`)}for(const R of y){const O=R.argIndex-(f?1:0),I=R.maxEvalSpace==="literal"?"literal":R.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[O].logError("invalid-function-argument-evaluation-space",`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must be ${I}, but received ${R.actualEvalSpace}`)}for(const R of E){const O=R.argIndex-(f?1:0);this.args[O].logError("literal-null-function-argument",`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must not be a literal null`)}const A=m.returnType,v=(0,es.maxOfExpressionTypes)([A.expressionType,...h.map(R=>R.expressionType)]);if(!(0,es.expressionIsAggregate)(m.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${h.map(R=>R.dataType).join(", ")}) with source`);const _={node:"function_call",overload:m,name:this.name,kids:{args:h.map(R=>R.value)},expressionType:v,structPath:x};let S=_;if(n!=null&&n.orderBys&&n.orderBys.length>0){const R=(0,es.expressionIsAnalytic)(m.returnType.expressionType);if(R||this.inExperiment("aggregate_order_by",!0)||n.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),m.supportsOrderBy||R){const O=m.supportsOrderBy!=="only_default",I=n.orderBys.flatMap(j=>R?j.getAnalyticOrderBy(e):j.getAggregateOrderBy(e,O));_.kids.orderBy=I}else n.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((n==null?void 0:n.limit)!==void 0&&(m.supportsLimit?_.limit=n.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),n!=null&&n.partitionBys&&n.partitionBys.length>0){const R=[];for(const O of n.partitionBys)for(const I of O.partitionFields){const j=I.getField(e);j.found===void 0?I.logError("partition-by-not-found",`${I.refString} is not defined`):(0,es.expressionIsAnalytic)(j.found.typeDesc().expressionType)||(0,es.expressionIsUngroupedAggregate)(j.found.typeDesc().expressionType)?I.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):R.push(I.nameString)}_.partitionBy=R}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);const R=h[0].value;if(R.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${l.name}\``);else{const O=R.literal,I=PEe(O),j=I.filter(Y=>Y.type==="interpolation"&&Y.name.includes(".")).map(Y=>Y.type==="interpolation"?`\${${Y.name}}`:`\${${Y.value}}`);if(j.length>0){const Y=j.length===1?`'.' paths are not yet supported in sql interpolations, found ${j.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${j.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Y)}const z=[];for(const Y of I)if(Y.type==="string")z.push(Y.value);else if(Y.name==="TABLE")z.push({node:"source-reference"});else{const Q=new $Ee.FieldName(Y.name);this.has({name:Q});const se=e.lookup([Q]);if(se.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${se.error.message}`);se.found.refType==="parameter"?z.push({node:"parameter",path:[Y.name]}):z.push({node:"field",path:[Y.name]})}S=(0,Kq.composeSQLExpr)(z)}}if(A.dataType==="any")return this.loggedErrorExpr("function-returns-any",`Invalid return type ${A.dataType} for function '${this.name}'`);const C=(0,es.mergeEvalSpaces)(...h.map(R=>R.evalSpace)),T=C==="constant"?"constant":(0,es.expressionIsScalar)(v)?C:"output";return{dataType:A.dataType,expressionType:v,value:S,evalSpace:T}}}b1.ExprFunc=BEe;function kEe(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,es.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")||(0,es.expressionIsAnalytic)(n.returnType.expressionType)&&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 PEe(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(iv,"__esModule",{value:!0}),iv.ExprProps=void 0;const MEe=oe,jEe=Ci,UEe=Jt,qEe=$l,HEe=kl,zEe=yd,QEe=st,GEe=b1;class WEe extends QEe.ExpressionDef{constructor(e,n){super({expr:e,statements:n}),this.expr=e,this.statements=n,this.elementType="expression with props",this.legalChildTypes=UEe.FT.anyAtomicT}getFilteredExpression(e,n,r){if(r.length>0){if(!this.expr.supportsWhere(n))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),n;const i=[];for(const s of r){const o=s.getFilterList(e);if(o.find(u=>(0,MEe.expressionIsCalculation)(u.expressionType)))return s.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),n;i.push(...o)}return this.typeCheck(this.expr,{...n,expressionType:"scalar"})?{...n,value:{node:"filteredExpr",kids:{e:n.value,filterList:i}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${n.expressionType}' data`),(0,jEe.errorFor)("cannot filter type"))}return n}getExpression(e){const n=[];let r;const i=[],s=[];for(const u of this.statements)u instanceof zEe.PartitionBy?this.expr.canSupportPartitionBy()?n.push(u):u.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):u instanceof HEe.Limit?r?u.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?r=u:u.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):u instanceof qEe.FunctionOrdering?this.expr.canSupportOrderBy()?i.push(u):u.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):s.push(u);const o=this.expr instanceof GEe.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:n,limit:r,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}}iv.ExprProps=WEe;var sv={};Object.defineProperty(sv,"__esModule",{value:!0}),sv.ExprLogicalOp=void 0;const VEe=S1,Zq=Jt;class YEe extends VEe.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[Zq.FT.boolT,Zq.FT.aggregateBoolT]}}sv.ExprLogicalOp=YEe;var ov={};Object.defineProperty(ov,"__esModule",{value:!0}),ov.ExprMax=void 0;const uv=Jt,JEe=pa;class XEe extends JEe.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[uv.FT.numberT,uv.FT.stringT,uv.FT.dateT,uv.FT.timestampT]}returns(e){return e.dataType}}ov.ExprMax=XEe;var av={};Object.defineProperty(av,"__esModule",{value:!0}),av.ExprMin=void 0;const lv=Jt,KEe=pa;class ZEe extends KEe.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[lv.FT.numberT,lv.FT.stringT,lv.FT.dateT,lv.FT.timestampT]}returns(e){return e.dataType}}av.ExprMin=ZEe;var cv={};Object.defineProperty(cv,"__esModule",{value:!0}),cv.ExprMinus=void 0;const eAe=Ci,eH=Jt,tAe=st;class nAe extends tAe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[eH.FT.numberT]}getExpression(e){const n=this.expr.getExpression(e);return eH.FT.typeIn(n,this.legalChildTypes)?{...n,dataType:"number",value:{node:"unary-",e:n.value}}:(0,eAe.errorFor)("negate requires number")}}cv.ExprMinus=nAe;var fv={};Object.defineProperty(fv,"__esModule",{value:!0}),fv.ExprMulDiv=void 0;const rAe=pd;class iAe extends rAe.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}fv.ExprMulDiv=iAe;var xv={},R1={};Object.defineProperty(R1,"__esModule",{value:!0}),R1.Unary=void 0;const sAe=st;class oAe extends sAe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}R1.Unary=oAe,Object.defineProperty(xv,"__esModule",{value:!0}),xv.ExprNot=void 0;const tH=Jt,uAe=R1;class aAe extends uAe.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[tH.FT.boolT,tH.FT.nullT]}getExpression(e){const n=this.expr.getExpression(e),r=this.typeCheck(this.expr,n);return{...n,dataType:"boolean",value:{node:"not",e:r?n.value:{node:"false"}}}}}xv.ExprNot=aAe;var dv={};Object.defineProperty(dv,"__esModule",{value:!0}),dv.ExprNow=void 0;const lAe=st;class cAe extends lAe.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now"}}}}dv.ExprNow=cAe;var hv={};Object.defineProperty(hv,"__esModule",{value:!0}),hv.ExprNULL=void 0;const fAe=st;class xAe extends fAe.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:{node:"null"},expressionType:"scalar",evalSpace:"literal"}}}hv.ExprNULL=xAe;var pv={};Object.defineProperty(pv,"__esModule",{value:!0}),pv.ExprNumber=void 0;const dAe=Jt,hAe=st;class pAe extends hAe.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...dAe.FT.numberT,evalSpace:"literal",value:{node:"numberLiteral",literal:this.n}}}}pv.ExprNumber=pAe;var gv={};Object.defineProperty(gv,"__esModule",{value:!0}),gv.ExprParens=void 0;const CO=st;class gAe extends CO.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:{node:"()",e:n.value}}}apply(e,n,r,i){return this.expr.atNodeType()===CO.ATNodeType.Or?this.expr.apply(e,n,r,i):(0,CO.applyBinary)(e,r,n,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}gv.ExprParens=gAe;var mv={};Object.defineProperty(mv,"__esModule",{value:!0}),mv.ExprRegEx=void 0;const mAe=st;class yAe extends mAe.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:{node:"regexpLiteral",literal:this.regex},evalSpace:"literal"}}}mv.ExprRegEx=yAe;var yv={};Object.defineProperty(yv,"__esModule",{value:!0}),yv.ExprString=void 0;const EAe=st,AAe=Jt;class vAe extends EAe.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...AAe.FT.stringT,value:{node:"stringLiteral",literal:this.value},evalSpace:"literal"}}}yv.ExprString=vAe;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.ExprSum=void 0;const SAe=md;class _Ae extends SAe.ExprAsymmetric{constructor(e,n,r){super("sum",e,n,r),this.has({source:n})}}Ev.ExprSum=_Ae;var Av={};Object.defineProperty(Av,"__esModule",{value:!0}),Av.ExprTimeExtract=void 0;const kc=oe,nH=Ci,TO=st,CAe=Il;class O1 extends TO.ExpressionDef{static extractor(e){const n=O1.pluralMap[e];if(n)return n;if((0,kc.isExtractUnit)(e))return e}constructor(e,n){super({args:n}),this.extractText=e,this.args=n,this.elementType="timeExtract"}getExpression(e){const n=O1.extractor(this.extractText);if(n){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${n} requires one argument`);const r=this.args[0];if(r instanceof CAe.Range){let i=r.first.getExpression(e),s=r.last.getExpression(e);const o=(0,kc.maxExpressionType)(i.expressionType,s.expressionType),u=(0,kc.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:u,value:(0,nH.errorFor)("extract from error").value};if(!(0,kc.isTemporalField)(i.dataType))return r.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${n} from '${i.dataType}'`);if(!(0,kc.isTemporalField)(s.dataType))return r.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${n} from '${s.dataType}'`);let a=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(a="timestamp",i.dataType==="date"){const c=(0,TO.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{const c=(0,TO.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return r.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${i.dataType} to ${s.dataType}`)}return["week","month","quarter","year"].includes(n)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${n}'`):(0,kc.isTimestampUnit)(n)?{dataType:"number",expressionType:o,evalSpace:u,value:{node:"timeDiff",units:n,kids:{left:{...i.value,dataType:a},right:{...s.value,dataType:a}}}}:this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${n} from a range`)}else{const i=r.getExpression(e);return(0,kc.isTemporalField)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:{node:"extract",e:{...i.value,dataType:i.dataType},units:n}}:(i.dataType!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,nH.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}Av.ExprTimeExtract=O1,O1.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var vv={},ao={},Sv={};Object.defineProperty(Sv,"__esModule",{value:!0}),Sv.QueryInputSpace=void 0;const TAe=Ti,bAe=rd;class RAe extends bAe.RefinedSpace{constructor(e,n){super(e),this.queryOutput=n,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof TAe.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}}Sv.QueryInputSpace=RAe;var OAe=D&&D.__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]}),DAe=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),NAe=D&&D.__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)&&OAe(e,t,n);return DAe(e,t),e};Object.defineProperty(ao,"__esModule",{value:!0}),ao.ReduceFieldSpace=ao.QuerySpace=ao.QueryOperationSpace=void 0;const _v=NAe(oe),bO=Nl,wAe=Pl,FAe=wr,LAe=ht,IAe=rd,$Ae=d1,BAe=hr,kAe=Sv;class rH extends IAe.RefinedSpace{constructor(e,n,r,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=r,this.astEl=i,this.expandedWild={},this.exprSpace=new kAe.QueryInputSpace(e.structDef(),this),n&&this.addRefineFromFields(n)}logError(e,n,r){return this.astEl&&this.astEl.logError(e,n,r),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 BAe.StructSpaceField)r=l.fieldSpace;else{u.logError("invalid-wildcard-source",`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.logError("wildcard-source-not-defined",`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries())if(!e.except.has(u)&&a.refType!=="parameter")if(this.entry(u)){const l=(n=this.expandedWild[u])===null||n===void 0?void 0:n.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{const l=a.typeDesc();_v.isAtomicFieldType(l.dataType)&&_v.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)}}ao.QueryOperationSpace=rH;class iH extends rH{addRefineFromFields(e){var n;if(_v.isQuerySegment(e))for(const r of e.queryFields)if(r.type==="fieldref"){const i=this.exprSpace.lookup(r.path.map(s=>new wAe.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 $Ae.ColumnSpaceField(r))}pushFields(...e){for(const n of e)n instanceof LAe.WildcardFieldReference?this.addWild(n):super.pushFields(n)}canContain(e){return!0}queryFieldDefs(){const e=[];for(const[n,r]of this.entries())if(r instanceof FAe.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)&&!MAe(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){const n=this.getPipeSegment(e);if(_v.isQuerySegment(n))return n;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","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,bO.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,bO.nameFromDef)(u)===s);o&&r.push(o)}n.extendSource=(0,bO.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}}ao.QuerySpace=iH;class PAe extends iH{constructor(){super(...arguments),this.segmentType="reduce"}}ao.ReduceFieldSpace=PAe;function MAe(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}Object.defineProperty(vv,"__esModule",{value:!0}),vv.ExprUngroup=void 0;const sH=oe,jAe=ao,UAe=Jt,qAe=st;class HAe extends qAe.ExpressionDef{constructor(e,n,r){super({expr:n,fields:r}),this.control=e,this.expr=n,this.fields=r,this.legalChildTypes=UAe.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){const n=this.expr.getExpression(e);if(!(0,sH.expressionIsAggregate)(n.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,sH.expressionIsUngroupedAggregate)(n.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const r={node: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 jAe.QuerySpace){u=u.nestParent;continue}break}if(a){const l=s?"exclude()":"all()";o.logError("ungroup-field-not-in-output",`${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.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}vv.ExprUngroup=HAe;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.ForRange=void 0;const oH=Ai,uH=Ci,aH=Jt,Tv=Jn,zAe=st,bv=hd,lH=Il;class QAe extends zAe.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=[aH.FT.timestampT,aH.FT.dateT]}apply(e,n,r){const i=this.from.getExpression(e),s=r.getExpression(e);if(!this.typeCheck(r,s))return(0,uH.errorFor)("no time for range");const o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,oH.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,oH.maxExpressionType)(i.expressionType,s.expressionType),value:(0,uH.errorFor)("for not number").value};const u=this.timeframe.text;let a=(0,Tv.resolution)(u);if(i.dataType==="timestamp"&&(a="timestamp"),s.dataType==="date"&&a==="date"){const p=this.from,m=(0,Tv.timeOffset)("date",i.value,"+",o.value,u),g=new bv.ExprTime("date",m);return new lH.Range(p,g).apply(e,n,r)}const l=bv.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,Tv.castDateToTimestamp)(f),c=new bv.ExprTime("timestamp",f,i.expressionType)}const x=(0,Tv.timeOffset)("timestamp",f,"+",o.value,u),h=new bv.ExprTime("timestamp",x,i.expressionType);return new lH.Range(c,h).apply(e,n,l)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Cv.ForRange=QAe;var Xn={},Ri={};Object.defineProperty(Ri,"__esModule",{value:!0});class Pc extends Error{}class GAe extends Pc{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class WAe extends Pc{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class VAe extends Pc{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class D1 extends Pc{}class cH extends Pc{constructor(e){super(`Invalid unit ${e}`)}}class Rs extends Pc{}class Ml extends Pc{constructor(){super("Zone is an abstract class")}}const Pe="numeric",lo="short",ts="long",RO={year:Pe,month:Pe,day:Pe},fH={year:Pe,month:lo,day:Pe},YAe={year:Pe,month:lo,day:Pe,weekday:lo},xH={year:Pe,month:ts,day:Pe},dH={year:Pe,month:ts,day:Pe,weekday:ts},hH={hour:Pe,minute:Pe},pH={hour:Pe,minute:Pe,second:Pe},gH={hour:Pe,minute:Pe,second:Pe,timeZoneName:lo},mH={hour:Pe,minute:Pe,second:Pe,timeZoneName:ts},yH={hour:Pe,minute:Pe,hourCycle:"h23"},EH={hour:Pe,minute:Pe,second:Pe,hourCycle:"h23"},AH={hour:Pe,minute:Pe,second:Pe,hourCycle:"h23",timeZoneName:lo},vH={hour:Pe,minute:Pe,second:Pe,hourCycle:"h23",timeZoneName:ts},SH={year:Pe,month:Pe,day:Pe,hour:Pe,minute:Pe},_H={year:Pe,month:Pe,day:Pe,hour:Pe,minute:Pe,second:Pe},CH={year:Pe,month:lo,day:Pe,hour:Pe,minute:Pe},TH={year:Pe,month:lo,day:Pe,hour:Pe,minute:Pe,second:Pe},JAe={year:Pe,month:lo,day:Pe,weekday:lo,hour:Pe,minute:Pe},bH={year:Pe,month:ts,day:Pe,hour:Pe,minute:Pe,timeZoneName:lo},RH={year:Pe,month:ts,day:Pe,hour:Pe,minute:Pe,second:Pe,timeZoneName:lo},OH={year:Pe,month:ts,day:Pe,weekday:ts,hour:Pe,minute:Pe,timeZoneName:ts},DH={year:Pe,month:ts,day:Pe,weekday:ts,hour:Pe,minute:Pe,second:Pe,timeZoneName:ts};function vt(t){return typeof t>"u"}function Mc(t){return typeof t=="number"}function Rv(t){return typeof t=="number"&&t%1===0}function XAe(t){return typeof t=="string"}function KAe(t){return Object.prototype.toString.call(t)==="[object Date]"}function NH(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function ZAe(t){return Array.isArray(t)?t:[t]}function wH(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 eve(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function Ed(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ga(t,e,n){return Rv(t)&&t>=e&&t<=n}function tve(t,e){return t-e*Math.floor(t/e)}function On(t,e=2){const n=t<0;let r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function jl(t){if(!(vt(t)||t===null||t===""))return parseInt(t,10)}function jc(t){if(!(vt(t)||t===null||t===""))return parseFloat(t)}function OO(t){if(!(vt(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function DO(t,e,n=!1){const r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function N1(t){return t%4===0&&(t%100!==0||t%400===0)}function w1(t){return N1(t)?366:365}function Ov(t,e){const n=tve(e-1,12)+1,r=t+(e-n)/12;return n===2?N1(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function NO(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 Dv(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 wO(t){return t>99?t:t>60?1900+t:2e3+t}function FH(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 Nv(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 LH(t){const e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new Rs(`Invalid unit value ${t}`);return e}function wv(t,e){const n={};for(const r in t)if(Ed(t,r)){const i=t[r];if(i==null)continue;n[e(r)]=LH(i)}return n}function F1(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}${On(n,2)}:${On(r,2)}`;case"narrow":return`${i}${n}${r>0?`:${r}`:""}`;case"techie":return`${i}${On(n,2)}${On(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Fv(t){return eve(t,["hour","minute","second","millisecond"])}const IH=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,nve=["January","February","March","April","May","June","July","August","September","October","November","December"],$H=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],rve=["J","F","M","A","M","J","J","A","S","O","N","D"];function BH(t){switch(t){case"narrow":return[...rve];case"short":return[...$H];case"long":return[...nve];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 kH=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],PH=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],ive=["M","T","W","T","F","S","S"];function MH(t){switch(t){case"narrow":return[...ive];case"short":return[...PH];case"long":return[...kH];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const jH=["AM","PM"],sve=["Before Christ","Anno Domini"],ove=["BC","AD"],uve=["B","A"];function UH(t){switch(t){case"narrow":return[...uve];case"short":return[...ove];case"long":return[...sve];default:return null}}function ave(t){return jH[t.hour<12?0:1]}function lve(t,e){return MH(e)[t.weekday-1]}function cve(t,e){return BH(e)[t.month-1]}function fve(t,e){return UH(e)[t.year<0?0:1]}function xve(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 qH(t,e){let n="";for(const r of t)r.literal?n+=r.val:n+=e(r.val);return n}const dve={D:RO,DD:fH,DDD:xH,DDDD:dH,t:hH,tt:pH,ttt:gH,tttt:mH,T:yH,TT:EH,TTT:AH,TTTT:vH,f:SH,ff:CH,fff:bH,ffff:OH,F:_H,FF:TH,FFF:RH,FFFF:DH};class Oi{static create(e,n={}){return new Oi(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 dve[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 On(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?ave(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),a=(h,p)=>r?cve(e,h):s(p?{month:h}:{month:h,day:"numeric"},"month"),l=(h,p)=>r?lve(e,h):s(p?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),c=h=>{const p=Oi.macroTokenToFormatOpts(h);return p?this.formatWithSystemDefault(e,p):h},f=h=>r?fve(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 qH(Oi.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=Oi.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 qH(s,i(u))}}class co{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}let Ad=class{get type(){throw new Ml}get name(){throw new Ml}get ianaName(){return this.name}get isUniversal(){throw new Ml}offsetName(e,n){throw new Ml}formatOffset(e,n){throw new Ml}offset(e){throw new Ml}equals(e){throw new Ml}get isValid(){throw new Ml}},FO=null;class Lv extends Ad{static get instance(){return FO===null&&(FO=new Lv),FO}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return FH(e,n,r)}formatOffset(e,n){return F1(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}let Iv={};function hve(t){return Iv[t]||(Iv[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"})),Iv[t]}const pve={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function gve(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 mve(t,e){const n=t.formatToParts(e),r=[];for(let i=0;i<n.length;i++){const{type:s,value:o}=n[i],u=pve[s];s==="era"?r[u]=o:vt(u)||(r[u]=parseInt(o,10))}return r}let $v={};class au extends Ad{static create(e){return $v[e]||($v[e]=new au(e)),$v[e]}static resetCache(){$v={},Iv={}}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=au.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return FH(e,n,r,this.name)}formatOffset(e,n){return F1(this.offset(e),n)}offset(e){const n=new Date(e);if(isNaN(n))return NaN;const r=hve(this.name);let[i,s,o,u,a,l,c]=r.formatToParts?mve(r,n):gve(r,n);u==="BC"&&(i=-Math.abs(i)+1);const x=NO({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 LO=null;class Lr extends Ad{static get utcInstance(){return LO===null&&(LO=new Lr(0)),LO}static instance(e){return e===0?Lr.utcInstance:new Lr(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Lr(Nv(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${F1(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${F1(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return F1(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 HH extends Ad{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 Ul(t,e){if(vt(t)||t===null)return e;if(t instanceof Ad)return t;if(XAe(t)){const n=t.toLowerCase();return n==="local"||n==="system"?e:n==="utc"||n==="gmt"?Lr.utcInstance:Lr.parseSpecifier(n)||au.create(t)}else return Mc(t)?Lr.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new HH(t)}let zH=()=>Date.now(),QH="system",GH=null,WH=null,VH=null,YH;class Dn{static get now(){return zH}static set now(e){zH=e}static set defaultZone(e){QH=e}static get defaultZone(){return Ul(QH,Lv.instance)}static get defaultLocale(){return GH}static set defaultLocale(e){GH=e}static get defaultNumberingSystem(){return WH}static set defaultNumberingSystem(e){WH=e}static get defaultOutputCalendar(){return VH}static set defaultOutputCalendar(e){VH=e}static get throwOnInvalid(){return YH}static set throwOnInvalid(e){YH=e}static resetCaches(){cn.resetCache(),au.resetCache()}}let JH={};function yve(t,e={}){const n=JSON.stringify([t,e]);let r=JH[n];return r||(r=new Intl.ListFormat(t,e),JH[n]=r),r}let IO={};function $O(t,e={}){const n=JSON.stringify([t,e]);let r=IO[n];return r||(r=new Intl.DateTimeFormat(t,e),IO[n]=r),r}let BO={};function Eve(t,e={}){const n=JSON.stringify([t,e]);let r=BO[n];return r||(r=new Intl.NumberFormat(t,e),BO[n]=r),r}let kO={};function Ave(t,e={}){const{base:n,...r}=e,i=JSON.stringify([t,r]);let s=kO[i];return s||(s=new Intl.RelativeTimeFormat(t,e),kO[i]=s),s}let L1=null;function vve(){return L1||(L1=new Intl.DateTimeFormat().resolvedOptions().locale,L1)}function Sve(t){const e=t.indexOf("-u-");if(e===-1)return[t];{let n;const r=t.substring(0,e);try{n=$O(t).resolvedOptions()}catch{n=$O(r).resolvedOptions()}const{numberingSystem:i,calendar:s}=n;return[r,i,s]}}function _ve(t,e,n){return(n||e)&&(t+="-u",n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Cve(t){const e=[];for(let n=1;n<=12;n++){const r=ut.utc(2016,n,1);e.push(t(r))}return e}function Tve(t){const e=[];for(let n=1;n<=7;n++){const r=ut.utc(2016,11,13+n);e.push(t(r))}return e}function Bv(t,e,n,r,i){const s=t.listingMode(n);return s==="error"?null:s==="en"?r(e):i(e)}function bve(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 Rve{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=Eve(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):DO(e,3);return On(n,this.padTo)}}}class Ove{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&&au.create(u).valid?(i=u,this.dt=e):(i="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:ut.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=$O(n,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}}class Dve{constructor(e,n,r){this.opts={style:"long",...r},!n&&NH()&&(this.rtf=Ave(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):xve(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}class cn{static fromOpts(e){return cn.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,n,r,i=!1){const s=e||Dn.defaultLocale,o=s||(i?"en-US":vve()),u=n||Dn.defaultNumberingSystem,a=r||Dn.defaultOutputCalendar;return new cn(o,u,a,s)}static resetCache(){L1=null,IO={},BO={},kO={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r}={}){return cn.create(e,n,r)}constructor(e,n,r,i){const[s,o,u]=Sve(e);this.locale=s,this.numberingSystem=n||o||null,this.outputCalendar=r||u||null,this.intl=_ve(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=bve(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:cn.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 Bv(this,e,r,BH,()=>{const i=n?{month:e,day:"numeric"}:{month:e},s=n?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=Cve(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,n=!1,r=!0){return Bv(this,e,r,MH,()=>{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]=Tve(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return Bv(this,void 0,e,()=>jH,()=>{if(!this.meridiemCache){const n={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ut.utc(2016,11,13,9),ut.utc(2016,11,13,19)].map(r=>this.extract(r,n,"dayperiod"))}return this.meridiemCache})}eras(e,n=!0){return Bv(this,e,n,UH,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[ut.utc(-40,1,1),ut.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 Rve(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Ove(e,this.intl,n)}relFormatter(e={}){return new Dve(this.intl,this.isEnglish(),e)}listFormatter(e={}){return yve(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 vd(...t){const e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function Sd(...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 _d(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 XH(...t){return(e,n)=>{const r={};let i;for(i=0;i<t.length;i++)r[t[i]]=jl(e[n+i]);return[r,null,n+i]}}const KH=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Nve=`(?:${KH.source}?(?:\\[(${IH.source})\\])?)?`,PO=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ZH=RegExp(`${PO.source}${Nve}`),MO=RegExp(`(?:T${ZH.source})?`),wve=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Fve=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Lve=/(\d{4})-?(\d{3})/,Ive=XH("weekYear","weekNumber","weekDay"),$ve=XH("year","ordinal"),Bve=/(\d{4})-(\d\d)-(\d\d)/,ez=RegExp(`${PO.source} ?(?:${KH.source}|(${IH.source}))?`),kve=RegExp(`(?: ${ez.source})?`);function Cd(t,e,n){const r=t[e];return vt(r)?n:jl(r)}function Pve(t,e){return[{year:Cd(t,e),month:Cd(t,e+1,1),day:Cd(t,e+2,1)},null,e+3]}function Td(t,e){return[{hours:Cd(t,e,0),minutes:Cd(t,e+1,0),seconds:Cd(t,e+2,0),milliseconds:OO(t[e+3])},null,e+4]}function I1(t,e){const n=!t[e]&&!t[e+1],r=Nv(t[e+1],t[e+2]),i=n?null:Lr.instance(r);return[{},i,e+3]}function $1(t,e){const n=t[e]?au.create(t[e]):null;return[{},n,e+1]}const Mve=RegExp(`^T?${PO.source}$`),jve=/^-?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 Uve(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(jc(n)),months:x(jc(r)),weeks:x(jc(i)),days:x(jc(s)),hours:x(jc(o)),minutes:x(jc(u)),seconds:x(jc(a),a==="-0"),milliseconds:x(OO(l),f)}]}const qve={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 jO(t,e,n,r,i,s,o){const u={year:e.length===2?wO(jl(e)):jl(e),month:$H.indexOf(n)+1,day:jl(r),hour:jl(i),minute:jl(s)};return o&&(u.second=jl(o)),t&&(u.weekday=t.length>3?kH.indexOf(t)+1:PH.indexOf(t)+1),u}const Hve=/^(?:(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 zve(t){const[,e,n,r,i,s,o,u,a,l,c,f]=t,x=jO(e,i,r,n,s,o,u);let h;return a?h=qve[a]:l?h=0:h=Nv(c,f),[x,new Lr(h)]}function Qve(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Gve=/^(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$/,Wve=/^(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$/,Vve=/^(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 tz(t){const[,e,n,r,i,s,o,u]=t;return[jO(e,i,r,n,s,o,u),Lr.utcInstance]}function Yve(t){const[,e,n,r,i,s,o,u]=t;return[jO(e,u,n,r,i,s,o),Lr.utcInstance]}const Jve=vd(wve,MO),Xve=vd(Fve,MO),Kve=vd(Lve,MO),Zve=vd(ZH),nz=Sd(Pve,Td,I1,$1),e4e=Sd(Ive,Td,I1,$1),t4e=Sd($ve,Td,I1,$1),n4e=Sd(Td,I1,$1);function r4e(t){return _d(t,[Jve,nz],[Xve,e4e],[Kve,t4e],[Zve,n4e])}function i4e(t){return _d(Qve(t),[Hve,zve])}function s4e(t){return _d(t,[Gve,tz],[Wve,tz],[Vve,Yve])}function o4e(t){return _d(t,[jve,Uve])}const u4e=Sd(Td);function a4e(t){return _d(t,[Mve,u4e])}const l4e=vd(Bve,kve),c4e=vd(ez),f4e=Sd(Td,I1,$1);function x4e(t){return _d(t,[l4e,nz],[c4e,f4e])}const d4e="Invalid Duration",rz={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}},h4e={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},...rz},Os=146097/400,bd=146097/4800,p4e={years:{quarters:4,months:12,weeks:Os/7,days:Os,hours:Os*24,minutes:Os*24*60,seconds:Os*24*60*60,milliseconds:Os*24*60*60*1e3},quarters:{months:3,weeks:Os/28,days:Os/4,hours:Os*24/4,minutes:Os*24*60/4,seconds:Os*24*60*60/4,milliseconds:Os*24*60*60*1e3/4},months:{weeks:bd/7,days:bd,hours:bd*24,minutes:bd*24*60,seconds:bd*24*60*60,milliseconds:bd*24*60*60*1e3},...rz},Uc=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],g4e=Uc.slice(0).reverse();function qc(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 St(r)}function m4e(t){return t<0?Math.floor(t):Math.ceil(t)}function iz(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?m4e(o):Math.trunc(o);r[i]+=a,e[n]-=a*s}function y4e(t,e){g4e.reduce((n,r)=>vt(e[r])?n:(n&&iz(t,e,n,e,r),r),null)}class St{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||cn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n?p4e:h4e,this.isLuxonDuration=!0}static fromMillis(e,n){return St.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new Rs(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new St({values:wv(e,St.normalizeUnit),loc:cn.fromObject(n),conversionAccuracy:n.conversionAccuracy})}static fromDurationLike(e){if(Mc(e))return St.fromMillis(e);if(St.isDuration(e))return e;if(typeof e=="object")return St.fromObject(e);throw new Rs(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[r]=o4e(e);return r?St.fromObject(r,n):St.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[r]=a4e(e);return r?St.fromObject(r,n):St.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new Rs("need to specify a reason the Duration is invalid");const r=e instanceof co?e:new co(e,n);if(Dn.throwOnInvalid)throw new VAe(r);return new St({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 cH(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?Oi.create(this.loc,r).formatDurationFromString(this,e):d4e}toHuman(e={}){const n=Uc.map(r=>{const i=this.values[r];return vt(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+=DO(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=St.fromDurationLike(e),r={};for(const i of Uc)(Ed(n.values,i)||Ed(this.values,i))&&(r[i]=n.get(i)+this.get(i));return qc(this,{values:r},!0)}minus(e){if(!this.isValid)return this;const n=St.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]=LH(e(this.values[r],r));return qc(this,{values:n},!0)}get(e){return this[St.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...wv(e,St.normalizeUnit)};return qc(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),qc(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return y4e(this.matrix,e),qc(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>St.normalizeUnit(o));const n={},r={},i=this.toObject();let s;for(const o of Uc)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;Mc(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)Uc.indexOf(l)>Uc.indexOf(o)&&iz(this.matrix,i,l,n,o)}else Mc(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 qc(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 qc(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 Uc)if(!n(this.values[r],e.values[r]))return!1;return!0}}const B1="Invalid Interval";function E4e(t,e){return!t||!t.isValid?fn.invalid("missing or invalid start"):!e||!e.isValid?fn.invalid("missing or invalid end"):e<t?fn.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 fn{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 Rs("need to specify a reason the Interval is invalid");const r=e instanceof co?e:new co(e,n);if(Dn.throwOnInvalid)throw new WAe(r);return new fn({invalid:r})}static fromDateTimes(e,n){const r=j1(e),i=j1(n),s=E4e(r,i);return s??new fn({start:r,end:i})}static after(e,n){const r=St.fromDurationLike(n),i=j1(e);return fn.fromDateTimes(i,i.plus(r))}static before(e,n){const r=St.fromDurationLike(n),i=j1(e);return fn.fromDateTimes(i.minus(r),i)}static fromISO(e,n){const[r,i]=(e||"").split("/",2);if(r&&i){let s,o;try{s=ut.fromISO(r,n),o=s.isValid}catch{o=!1}let u,a;try{u=ut.fromISO(i,n),a=u.isValid}catch{a=!1}if(o&&a)return fn.fromDateTimes(s,u);if(o){const l=St.fromISO(i,n);if(l.isValid)return fn.after(s,l)}else if(a){const l=St.fromISO(r,n);if(l.isValid)return fn.before(u,l)}}return fn.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?fn.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(j1).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(fn.fromDateTimes(i,u)),i=u,s+=1}return r}splitBy(e){const n=St.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(fn.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:fn.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 fn.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(fn.fromDateTimes(n,a.time)),n=null);return fn.merge(i)}difference(...e){return fn.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:B1}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:B1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:B1}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:B1}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:B1}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):St.invalid(this.invalidReason)}mapEndpoints(e){return fn.fromDateTimes(e(this.s),e(this.e))}}let k1=class{static hasDST(e=Dn.defaultZone){const n=ut.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return au.isValidZone(e)}static normalizeZone(e){return Ul(e,Dn.defaultZone)}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||cn.create(n,r,s)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||cn.create(n,r,s)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||cn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||cn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return cn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return cn.create(n,null,"gregory").eras(e)}static features(){return{relative:NH()}}};function sz(t,e){const n=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(St.fromMillis(r).as("days"))}function A4e(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=sz(u,a);return(l-l%7)/7}],["days",sz]],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 v4e(t,e,n,r){let[i,s,o,u]=A4e(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=St.fromObject(s,r);return l.length>0?St.fromMillis(a,r).shiftTo(...l).plus(c):c}const UO={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},oz={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]},S4e=UO.hanidec.replace(/[\[|\]]/g,"").split("");function _4e(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(UO.hanidec)!==-1)e+=S4e.indexOf(t[n]);else for(const i in oz){const[s,o]=oz[i];r>=s&&r<=o&&(e+=r-s)}}return parseInt(e,10)}else return e}function fo({numberingSystem:t},e=""){return new RegExp(`${UO[t||"latn"]}${e}`)}const C4e="missing Intl.DateTimeFormat.formatToParts support";function Ft(t,e=n=>n){return{regex:t,deser:([n])=>e(_4e(n))}}const uz="[  ]",az=new RegExp(uz,"g");function T4e(t){return t.replace(/\./g,"\\.?").replace(az,uz)}function lz(t){return t.replace(/\./g,"").replace(az," ").toLowerCase()}function xo(t,e){return t===null?null:{regex:RegExp(t.map(T4e).join("|")),deser:([n])=>t.findIndex(r=>lz(n)===lz(r))+e}}function cz(t,e){return{regex:t,deser:([,n,r])=>Nv(n,r),groups:e}}function qO(t){return{regex:t,deser:([e])=>e}}function b4e(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function R4e(t,e){const n=fo(e),r=fo(e,"{2}"),i=fo(e,"{3}"),s=fo(e,"{4}"),o=fo(e,"{6}"),u=fo(e,"{1,2}"),a=fo(e,"{1,3}"),l=fo(e,"{1,6}"),c=fo(e,"{1,9}"),f=fo(e,"{2,4}"),x=fo(e,"{4,6}"),h=g=>({regex:RegExp(b4e(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,wO);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 qO(c);case"uu":return qO(u);case"uuu":return Ft(n);case"a":return xo(e.meridiems(),0);case"kkkk":return Ft(s);case"kk":return Ft(f,wO);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 cz(new RegExp(`([+-]${u.source})(?::(${r.source}))?`),2);case"ZZZ":return cz(new RegExp(`([+-]${u.source})(${r.source})?`),2);case"z":return qO(/[a-z_+-/]{1,256}?/i);default:return h(g)}})(t)||{invalidReason:C4e};return m.token=t,m}const O4e={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 D4e(t,e,n){const{type:r,value:i}=t;if(r==="literal")return{literal:!0,val:i};const s=n[r];let o=O4e[r];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function N4e(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function w4e(t,e,n){const r=t.match(e);if(r){const i={};let s=1;for(const o in n)if(Ed(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 F4e(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 vt(t.z)||(n=au.create(t.z)),vt(t.Z)||(n||(n=new Lr(t.Z)),r=t.Z),vt(t.q)||(t.M=(t.q-1)*3+1),vt(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),vt(t.u)||(t.S=OO(t.u)),[Object.keys(t).reduce((s,o)=>{const u=e(o);return u&&(s[u]=t[o]),s},{}),n,r]}let HO=null;function L4e(){return HO||(HO=ut.fromMillis(1555555555555)),HO}function I4e(t,e){if(t.literal)return t;const n=Oi.macroTokenToFormatOpts(t.val);if(!n)return t;const s=Oi.create(e,n).formatDateTimeParts(L4e()).map(o=>D4e(o,e,n));return s.includes(void 0)?t:s}function $4e(t,e){return Array.prototype.concat(...t.map(n=>I4e(n,e)))}function fz(t,e,n){const r=$4e(Oi.parseFormat(n),t),i=r.map(o=>R4e(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:r,invalidReason:s.invalidReason};{const[o,u]=N4e(i),a=RegExp(o,"i"),[l,c]=w4e(e,a,u),[f,x,h]=c?F4e(c):[null,null,void 0];if(Ed(c,"a")&&Ed(c,"H"))throw new D1("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 B4e(t,e,n){const{result:r,zone:i,specificOffset:s,invalidReason:o}=fz(t,e,n);return[r,i,s,o]}const xz=[0,31,59,90,120,151,181,212,243,273,304,334],dz=[0,31,60,91,121,152,182,213,244,274,305,335];function Ds(t,e){return new co("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function hz(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 pz(t,e,n){return n+(N1(t)?dz:xz)[e-1]}function gz(t,e){const n=N1(t)?dz:xz,r=n.findIndex(s=>s<e),i=e-n[r];return{month:r+1,day:i}}function zO(t){const{year:e,month:n,day:r}=t,i=pz(e,n,r),s=hz(e,n,r);let o=Math.floor((i-s+10)/7),u;return o<1?(u=e-1,o=Dv(u)):o>Dv(e)?(u=e+1,o=1):u=e,{weekYear:u,weekNumber:o,weekday:s,...Fv(t)}}function mz(t){const{weekYear:e,weekNumber:n,weekday:r}=t,i=hz(e,1,4),s=w1(e);let o=n*7+r-i-3,u;o<1?(u=e-1,o+=w1(u)):o>s?(u=e+1,o-=w1(e)):u=e;const{month:a,day:l}=gz(u,o);return{year:u,month:a,day:l,...Fv(t)}}function QO(t){const{year:e,month:n,day:r}=t,i=pz(e,n,r);return{year:e,ordinal:i,...Fv(t)}}function yz(t){const{year:e,ordinal:n}=t,{month:r,day:i}=gz(e,n);return{year:e,month:r,day:i,...Fv(t)}}function k4e(t){const e=Rv(t.weekYear),n=ga(t.weekNumber,1,Dv(t.weekYear)),r=ga(t.weekday,1,7);return e?n?r?!1:Ds("weekday",t.weekday):Ds("week",t.week):Ds("weekYear",t.weekYear)}function P4e(t){const e=Rv(t.year),n=ga(t.ordinal,1,w1(t.year));return e?n?!1:Ds("ordinal",t.ordinal):Ds("year",t.year)}function Ez(t){const e=Rv(t.year),n=ga(t.month,1,12),r=ga(t.day,1,Ov(t.year,t.month));return e?n?r?!1:Ds("day",t.day):Ds("month",t.month):Ds("year",t.year)}function Az(t){const{hour:e,minute:n,second:r,millisecond:i}=t,s=ga(e,0,23)||e===24&&n===0&&r===0&&i===0,o=ga(n,0,59),u=ga(r,0,59),a=ga(i,0,999);return s?o?u?a?!1:Ds("millisecond",i):Ds("second",r):Ds("minute",n):Ds("hour",e)}const GO="Invalid DateTime",vz=864e13;function kv(t){return new co("unsupported zone",`the zone "${t.name}" is not supported`)}function WO(t){return t.weekData===null&&(t.weekData=zO(t.c)),t.weekData}function P1(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new ut({...n,...e,old:n})}function Sz(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 _z(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 Pv(t,e,n){return Sz(NO(t),e,n)}function Cz(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,Ov(r,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=St.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=NO(s);let[a,l]=Sz(u,n,t.zone);return o!==0&&(a+=o,l=t.zone.offset(a)),{ts:a,o:l}}function M1(t,e,n,r,i,s){const{setZone:o,zone:u}=n;if(t&&Object.keys(t).length!==0){const a=e||u,l=ut.fromObject(t,{...n,zone:a,specificOffset:s});return o?l:l.setZone(u)}else return ut.invalid(new co("unparsable",`the input "${i}" can't be parsed as ${r}`))}function Mv(t,e,n=!0){return t.isValid?Oi.create(cn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function VO(t,e){const n=t.c.year>9999||t.c.year<0;let r="";return n&&t.c.year>=0&&(r+="+"),r+=On(t.c.year,n?6:4),e?(r+="-",r+=On(t.c.month),r+="-",r+=On(t.c.day)):(r+=On(t.c.month),r+=On(t.c.day)),r}function Tz(t,e,n,r,i,s){let o=On(t.c.hour);return e?(o+=":",o+=On(t.c.minute),(t.c.second!==0||!n)&&(o+=":")):o+=On(t.c.minute),(t.c.second!==0||!n)&&(o+=On(t.c.second),(t.c.millisecond!==0||!r)&&(o+=".",o+=On(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=On(Math.trunc(-t.o/60)),o+=":",o+=On(Math.trunc(-t.o%60))):(o+="+",o+=On(Math.trunc(t.o/60)),o+=":",o+=On(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}const bz={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},M4e={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},j4e={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Rz=["year","month","day","hour","minute","second","millisecond"],U4e=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],q4e=["year","ordinal","hour","minute","second","millisecond"];function Oz(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 cH(t);return e}function Dz(t,e){const n=Ul(e.zone,Dn.defaultZone),r=cn.fromObject(e),i=Dn.now();let s,o;if(vt(t.year))s=i;else{for(const l of Rz)vt(t[l])&&(t[l]=bz[l]);const u=Ez(t)||Az(t);if(u)return ut.invalid(u);const a=n.offset(i);[s,o]=Pv(t,a,n)}return new ut({ts:s,zone:n,loc:r,o})}function Nz(t,e,n){const r=vt(n.round)?!0:n.round,i=(o,u)=>(o=DO(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 wz(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 ut{constructor(e){const n=e.zone||Dn.defaultZone;let r=e.invalid||(Number.isNaN(e.ts)?new co("invalid input"):null)||(n.isValid?null:kv(n));this.ts=vt(e.ts)?Dn.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=_z(this.ts,u),r=Number.isNaN(i.year)?new co("invalid input"):null,i=r?null:i,s=r?null:u}this._zone=n,this.loc=e.loc||cn.create(),this.invalid=r,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new ut({})}static local(){const[e,n]=wz(arguments),[r,i,s,o,u,a,l]=n;return Dz({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static utc(){const[e,n]=wz(arguments),[r,i,s,o,u,a,l]=n;return e.zone=Lr.utcInstance,Dz({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static fromJSDate(e,n={}){const r=KAe(e)?e.valueOf():NaN;if(Number.isNaN(r))return ut.invalid("invalid input");const i=Ul(n.zone,Dn.defaultZone);return i.isValid?new ut({ts:r,zone:i,loc:cn.fromObject(n)}):ut.invalid(kv(i))}static fromMillis(e,n={}){if(Mc(e))return e<-vz||e>vz?ut.invalid("Timestamp out of range"):new ut({ts:e,zone:Ul(n.zone,Dn.defaultZone),loc:cn.fromObject(n)});throw new Rs(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(Mc(e))return new ut({ts:e*1e3,zone:Ul(n.zone,Dn.defaultZone),loc:cn.fromObject(n)});throw new Rs("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const r=Ul(n.zone,Dn.defaultZone);if(!r.isValid)return ut.invalid(kv(r));const i=Dn.now(),s=vt(n.specificOffset)?r.offset(i):n.specificOffset,o=wv(e,Oz),u=!vt(o.ordinal),a=!vt(o.year),l=!vt(o.month)||!vt(o.day),c=a||l,f=o.weekYear||o.weekNumber,x=cn.fromObject(n);if((c||u)&&f)throw new D1("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&u)throw new D1("Can't mix ordinal dates with month/day");const h=f||o.weekday&&!c;let p,m,g=_z(i,s);h?(p=U4e,m=M4e,g=zO(g)):u?(p=q4e,m=j4e,g=QO(g)):(p=Rz,m=bz);let y=!1;for(const T of p){const R=o[T];vt(R)?y?o[T]=m[T]:o[T]=g[T]:y=!0}const E=h?k4e(o):u?P4e(o):Ez(o),A=E||Az(o);if(A)return ut.invalid(A);const v=h?mz(o):u?yz(o):o,[_,S]=Pv(v,s,r),C=new ut({ts:_,zone:r,o:S,loc:x});return o.weekday&&c&&e.weekday!==C.weekday?ut.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${C.toISO()}`):C}static fromISO(e,n={}){const[r,i]=r4e(e);return M1(r,i,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[r,i]=i4e(e);return M1(r,i,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[r,i]=s4e(e);return M1(r,i,n,"HTTP",n)}static fromFormat(e,n,r={}){if(vt(e)||vt(n))throw new Rs("fromFormat requires an input string and a format");const{locale:i=null,numberingSystem:s=null}=r,o=cn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[u,a,l,c]=B4e(o,e,n);return c?ut.invalid(c):M1(u,a,r,`format ${n}`,e,l)}static fromString(e,n,r={}){return ut.fromFormat(e,n,r)}static fromSQL(e,n={}){const[r,i]=x4e(e);return M1(r,i,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new Rs("need to specify a reason the DateTime is invalid");const r=e instanceof co?e:new co(e,n);if(Dn.throwOnInvalid)throw new GAe(r);return new ut({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?WO(this).weekYear:NaN}get weekNumber(){return this.isValid?WO(this).weekNumber:NaN}get weekday(){return this.isValid?WO(this).weekday:NaN}get ordinal(){return this.isValid?QO(this.c).ordinal:NaN}get monthShort(){return this.isValid?k1.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?k1.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?k1.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?k1.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 N1(this.year)}get daysInMonth(){return Ov(this.year,this.month)}get daysInYear(){return this.isValid?w1(this.year):NaN}get weeksInWeekYear(){return this.isValid?Dv(this.weekYear):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:r,calendar:i}=Oi.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:i}}toUTC(e=0,n={}){return this.setZone(Lr.instance(e),n)}toLocal(){return this.setZone(Dn.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=Ul(e,Dn.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]=Pv(o,s,e)}return P1(this,{ts:i,zone:e})}else return ut.invalid(kv(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return P1(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=wv(e,Oz),r=!vt(n.weekYear)||!vt(n.weekNumber)||!vt(n.weekday),i=!vt(n.ordinal),s=!vt(n.year),o=!vt(n.month)||!vt(n.day),u=s||o,a=n.weekYear||n.weekNumber;if((u||i)&&a)throw new D1("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new D1("Can't mix ordinal dates with month/day");let l;r?l=mz({...zO(this.c),...n}):vt(n.ordinal)?(l={...this.toObject(),...n},vt(n.day)&&(l.day=Math.min(Ov(l.year,l.month),l.day))):l=yz({...QO(this.c),...n});const[c,f]=Pv(l,this.o,this.zone);return P1(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;const n=St.fromDurationLike(e);return P1(this,Cz(this,n))}minus(e){if(!this.isValid)return this;const n=St.fromDurationLike(e).negate();return P1(this,Cz(this,n))}startOf(e){if(!this.isValid)return this;const n={},r=St.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?Oi.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):GO}toLocaleString(e=RO,n={}){return this.isValid?Oi.create(this.loc.clone(n),e).formatDateTime(this):GO}toLocaleParts(e={}){return this.isValid?Oi.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=VO(this,o);return u+="T",u+=Tz(this,o,n,r,i,s),u}toISODate({format:e="extended"}={}){return this.isValid?VO(this,e==="extended"):null}toISOWeekDate(){return Mv(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":"")+Tz(this,o==="extended",n,e,r,s):null}toRFC2822(){return Mv(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Mv(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?VO(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")),Mv(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():GO}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 St.invalid("created by diffing an invalid DateTime");const i={locale:this.locale,numberingSystem:this.numberingSystem,...r},s=ZAe(n).map(St.normalizeUnit),o=e.valueOf()>this.valueOf(),u=o?this:e,a=o?e:this,l=v4e(u,a,s,i);return o?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(ut.now(),e,n)}until(e){return this.isValid?fn.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||ut.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),Nz(n,this.plus(r),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?Nz(e.base||ut.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(ut.isDateTime))throw new Rs("min requires all arguments be DateTimes");return wH(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(ut.isDateTime))throw new Rs("max requires all arguments be DateTimes");return wH(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){const{locale:i=null,numberingSystem:s=null}=r,o=cn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return fz(o,e,n)}static fromStringExplain(e,n,r={}){return ut.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return RO}static get DATE_MED(){return fH}static get DATE_MED_WITH_WEEKDAY(){return YAe}static get DATE_FULL(){return xH}static get DATE_HUGE(){return dH}static get TIME_SIMPLE(){return hH}static get TIME_WITH_SECONDS(){return pH}static get TIME_WITH_SHORT_OFFSET(){return gH}static get TIME_WITH_LONG_OFFSET(){return mH}static get TIME_24_SIMPLE(){return yH}static get TIME_24_WITH_SECONDS(){return EH}static get TIME_24_WITH_SHORT_OFFSET(){return AH}static get TIME_24_WITH_LONG_OFFSET(){return vH}static get DATETIME_SHORT(){return SH}static get DATETIME_SHORT_WITH_SECONDS(){return _H}static get DATETIME_MED(){return CH}static get DATETIME_MED_WITH_SECONDS(){return TH}static get DATETIME_MED_WITH_WEEKDAY(){return JAe}static get DATETIME_FULL(){return bH}static get DATETIME_FULL_WITH_SECONDS(){return RH}static get DATETIME_HUGE(){return OH}static get DATETIME_HUGE_WITH_SECONDS(){return DH}}function j1(t){if(ut.isDateTime(t))return t;if(t&&t.valueOf&&Mc(t.valueOf()))return ut.fromJSDate(t);if(t&&typeof t=="object")return ut.fromObject(t);throw new Rs(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const H4e="2.5.2";var Fz=Ri.DateTime=ut;Ri.Duration=St,Ri.FixedOffsetZone=Lr,Ri.IANAZone=au,Ri.Info=k1,Ri.Interval=fn,Ri.InvalidZone=HH,Ri.Settings=Dn,Ri.SystemZone=Lv,Ri.VERSION=H4e,Ri.Zone=Ad,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.LiteralYear=Xn.LiteralQuarter=Xn.LiteralMonth=Xn.LiteralWeek=Xn.LiteralDay=Xn.LiteralHour=Xn.LiteralTimestamp=Xn.TimeFormatError=void 0;const ql=Ri,z4e=oe,Q4e=Il,Lz=hd,YO=st;class G4e extends Error{}Xn.TimeFormatError=G4e;function Hc(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 Iz="yyyy",$z=`${Iz}-LL`,Ns=`${$z}-dd`,Bz=`${Ns} HH`,kz=`${Bz}:mm`,JO=`${kz}:ss`;class Pz extends YO.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={node:"timeLiteral",literal:e,dataType: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 XO extends Pz{constructor(e,n){super(e,n,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let n;const r=Hc(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=ql.DateTime.fromFormat(e,JO);if(s.isValid)return new XO(r,n);if(s=ql.DateTime.fromFormat(e,kz),s.isValid){r.text=r.text+":00",n="minute";const o=s.plus({minute:1}).toFormat(JO);return new KO(r,n,"timestamp",o)}}}Xn.LiteralTimestamp=XO;class KO extends Pz{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,YO.getMorphicValue)(i,"timestamp"),a=(0,YO.getMorphicValue)(s,"timestamp");if(u&&a)i=u,s=a;else return super.apply(e,n,r)}if((0,z4e.isTemporalField)(o.dataType)){const u=o.dataType;return new Q4e.Range(new Lz.ExprTime(u,i.value),new Lz.ExprTime(u,s.value)).apply(e,n,r)}}return super.apply(e,n,r)}}class ZO extends KO{constructor(e,n){super(e,"hour","timestamp",n),this.elementType="literal:hour"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,Bz);if(i.isValid)return n.text=n.text+":00:00",r=i.plus({hour:1}).toFormat(JO),new ZO(n,r)}}Xn.LiteralHour=ZO;class U1 extends KO{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 eD extends U1{constructor(e,n){super(e,"day",n),this.elementType="literal:day"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,Ns);if(i.isValid)return r=i.plus({day:1}).toFormat(Ns),new eD(n,r)}}Xn.LiteralDay=eD;class tD extends U1{constructor(e,n){super(e,"week",n),this.elementType="literal:week"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=n.text.slice(0,10),s=ql.DateTime.fromFormat(i,Ns);if(s.isValid&&s.weekday===7){const u=s.plus({days:7});return n.text=s.toFormat(Ns),r=u.toFormat(Ns),new tD(n,r)}}}Xn.LiteralWeek=tD;class nD extends U1{constructor(e,n){super(e,"month",n),this.elementType="literal:month"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,$z);if(i.isValid){const s=i.plus({months:1});return n.text=i.toFormat(Ns),r=s.toFormat(Ns),new nD(n,r)}}}Xn.LiteralMonth=nD;class rD extends U1{constructor(e,n){super(e,"quarter",n),this.elementType="literal:quarter"}static parse(e){const n=Hc(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=ql.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));const u=o.plus({quarter:1});return n.text=o.toFormat(Ns),r=u.toFormat(Ns),new rD(n,r)}}}Xn.LiteralQuarter=rD;class iD extends U1{constructor(e,n){super(e,"year",n),this.elementType="literal:year"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,Iz);if(i.isValid){const s=i.plus({year:1});return n.text=i.toFormat(Ns),r=s.toFormat(Ns),new iD(n,r)}}}Xn.LiteralYear=iD;var jv={};Object.defineProperty(jv,"__esModule",{value:!0}),jv.PartialCompare=void 0;const Mz=st;class W4e extends Mz.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.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return Mz.ATNodeType.Partial}}jv.PartialCompare=W4e;var Rd={};Object.defineProperty(Rd,"__esModule",{value:!0}),Rd.PickWhen=Rd.Pick=void 0;const lu=oe,Od=Jt,V4e=st,Y4e=Ge;function Uv(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class J4e extends V4e.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={node:"case",kids:{caseWhen:[],caseThen:[]}};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,lu.maxExpressionType)(o,(0,lu.maxExpressionType)(f.expressionType,x.expressionType)),u=(0,lu.mergeEvalSpaces)(u,f.evalSpace,x.evalSpace),s&&!Od.FT.typeEq(s,x,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:x.dataType,returnType:s.dataType});s=Uv(s,x),i.kids.caseWhen.push(f.value),i.kids.caseThen.push(x.value)}const l=(this.elsePick||r).getExpression(e);return s=Uv(s,l),Od.FT.typeEq(s,l,!0)?(i.kids.caseElse=l.value,{dataType:s.dataType,expressionType:(0,lu.maxExpressionType)(o,l.expressionType),evalSpace:(0,lu.mergeEvalSpaces)(u,l.evalSpace),value:i}):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:l.dataType,returnType:s.dataType}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:l.dataType,returnType:s.dataType})}getExpression(e){const n={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const r=[];for(const a of this.choices){if(a.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");a.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply"),r.push({pick:a.pick.getExpression(e),when:a.when.getExpression(e)})}let i,s="scalar",o="constant";for(const a of r){if(!Od.FT.typeEq(a.when,Od.FT.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:a.when.dataType});if(i&&!Od.FT.typeEq(i,a.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:a.pick.dataType,returnType:i.dataType});i=Uv(i,a.pick),s=(0,lu.maxExpressionType)(s,(0,lu.maxExpressionType)(a.pick.expressionType,a.when.expressionType)),o=(0,lu.mergeEvalSpaces)(o,a.pick.evalSpace,a.when.evalSpace),n.kids.caseWhen.push(a.when.value),n.kids.caseThen.push(a.pick.value)}const u=this.elsePick.getExpression(e);return s=(0,lu.maxExpressionType)(s,u.expressionType),o=(0,lu.mergeEvalSpaces)(o,u.evalSpace),i=Uv(i,u),Od.FT.typeEq(i,u,!0)?(n.kids.caseElse=u.value,{dataType:i.dataType,expressionType:s,value:n,evalSpace:o}):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.dataType,returnType:i.dataType})}}Rd.Pick=J4e;class X4e extends Y4e.MalloyElement{constructor(e,n){super({when:n}),this.pick=e,this.when=n,this.elementType="caseWhen",this.has({pick:e})}}Rd.PickWhen=X4e;var Dd={};Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.CaseWhen=Dd.Case=void 0;const K4e=st,Z4e=Ge,q1=Jt,zc=Ai;function jz(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class eSe extends K4e.ExpressionDef{constructor(e,n,r){super({choices:n}),this.value=e,this.choices=n,this.elseValue=r,this.elementType="case",this.has({elseValue:r,value:e})}getExpression(e){var n;const r={node:"case",kids:{caseWhen:[],caseThen:[]}};let i="scalar",s="constant",o;this.value&&(o=this.value.getExpression(e),i=(0,zc.maxExpressionType)(i,o.expressionType),s=(0,zc.mergeEvalSpaces)(s,o.evalSpace),r.kids.caseValue=o.value);const u=[];for(const l of this.choices){const c=l.when.getExpression(e),f=l.then.getExpression(e);u.push({when:c,then:f})}let a;for(const l of u){if(o!==void 0){if(!q1.FT.typeEq(l.when,o))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:l.when.dataType,valueType:o.dataType})}else if(!q1.FT.typeEq(l.when,q1.FT.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:l.when.dataType});if(a&&!q1.FT.typeEq(a,l.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:l.then.dataType,returnType:a.dataType});a=jz(a,l.then),i=(0,zc.maxExpressionType)(i,(0,zc.maxExpressionType)(l.then.expressionType,l.when.expressionType)),s=(0,zc.mergeEvalSpaces)(s,l.then.evalSpace,l.when.evalSpace),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.then.value)}if(this.elseValue){const l=this.elseValue.getExpression(e);if(a&&!q1.FT.typeEq(a,l,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:l.dataType,returnType:a.dataType});a=jz(a,l),i=(0,zc.maxExpressionType)(i,l.expressionType),s=(0,zc.mergeEvalSpaces)(s,l.evalSpace),r.kids.caseElse=l.value}return{value:r,dataType:(n=a==null?void 0:a.dataType)!==null&&n!==void 0?n:"null",expressionType:i,evalSpace:s}}}Dd.Case=eSe;class tSe extends Z4e.MalloyElement{constructor(e,n){super({when:e,then:n}),this.when=e,this.then=n,this.elementType="caseWhen"}}Dd.CaseWhen=tSe;var Nd={};Object.defineProperty(Nd,"__esModule",{value:!0}),Nd.RecordLiteral=Nd.RecordElement=void 0;const Uz=Ai,nSe=st,rSe=Ge;class iSe extends rSe.MalloyElement{constructor(e,n){super(),this.key=e,this.value=n,this.elementType="record element",this.has({value:n})}}Nd.RecordElement=iSe;class sSe extends nSe.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){const n={node:"recordLiteral",kids:{}};let r="scalar";for(const i of this.pairs){const s=i.value.getExpression(e),o={dataType:"error",...s.value};o.dataType==="error"&&(0,Uz.isAtomicFieldType)(s.dataType)&&(o.dataType=s.dataType),o.dataType==="error"&&s.dataType!=="error"&&this.logError("illegal-record-property-type",`Type '${s.dataType}' not a legal record value`),n.kids[i.key]=o,r=(0,Uz.maxExpressionType)(s.expressionType,r)}return{dataType:"record",value:n,expressionType:r,evalSpace:"literal"}}}Nd.RecordLiteral=sSe;var qv={};Object.defineProperty(qv,"__esModule",{value:!0}),qv.Timeframe=void 0;const oSe=oe,uSe=Ge;class aSe extends uSe.MalloyElement{constructor(e){super(),this.elementType="timeframe";let n=e.toLowerCase();n.endsWith("s")&&(n=n.slice(0,-1)),this.text=(0,oSe.isTimestampUnit)(n)?n:"second"}}qv.Timeframe=aSe;var Hv={};Object.defineProperty(Hv,"__esModule",{value:!0}),Hv.TopBy=void 0;const lSe=oe,qz=st,cSe=Ge;class fSe extends cSe.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof qz.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof qz.ExpressionDef){const n=this.by.getExpression(e);return(0,lSe.expressionIsAggregate)(n.expressionType)||this.logError("top-by-non-aggregate","top by expression must be an aggregate"),{by:"expression",e:n.value}}return{by:"name",name:this.by}}}Hv.TopBy=fSe;var Hl={};Object.defineProperty(Hl,"__esModule",{value:!0}),Hl.ImportStatement=Hl.ImportSelect=Hl.ImportSourceName=void 0;const sD=Ge;class xSe extends sD.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}Hl.ImportSourceName=xSe;class dSe extends sD.MalloyElement{constructor(e,n){super(),this.text=e,this.from=n,this.elementType="importName",n&&this.has({from:n})}}Hl.ImportSelect=dSe;class hSe extends sD.ListOf{constructor(e,n){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,n).toString())}catch{this.logError("invalid-import-url","Invalid URL 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.logError("no-translator-for-import","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.logError("name-conflict-on-selective-import",`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.logError("selective-import-not-found",`Cannot find '${o.text}', not imported`)}else for(const[s,o]of Object.entries(n.getChildExports(this.fullURL)))e.getEntry(s)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else r.status==="error"?this.logError("failed-import",`import failed: '${r.message}'`):this.logError("failed-import",`import failed with status: '${r.status}'`)}}}Hl.ImportStatement=hSe;var H1={};Object.defineProperty(H1,"__esModule",{value:!0}),H1.ExtendBlock=void 0;const pSe=Ge,gSe=mn;class mSe extends pSe.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=gSe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)for(const r of n.list)e.inputFS.extendSource(r)}}H1.ExtendBlock=mSe;var zv={};Object.defineProperty(zv,"__esModule",{value:!0}),zv.Argument=void 0;const ySe=Ge;class ESe extends ySe.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}zv.Argument=ESe;var Qv={};Object.defineProperty(Qv,"__esModule",{value:!0}),Qv.HasParameter=void 0;const Hz=oe,ASe=Ge;class vSe extends ASe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,Hz.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const n=this.default.constantValue();return this.type&&this.type!==n.dataType&&n.dataType!=="null"&&n.dataType!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),n.dataType==="null"?this.type?{value:n.value,name:this.name,type:this.type}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:n.value,name:this.name,type:"error"}):!(0,Hz.isCastType)(n.dataType)&&n.dataType!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${n.dataType}\``),{value:n.value,name:this.name,type:"error"}):{value:n.value,name:this.name,type:n.dataType}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}Qv.HasParameter=vSe;var Gv={};Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.AnonymousQuery=void 0;const SSe=Ge,_Se=Nr;class CSe extends SSe.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=_Se.extendNoteMethod,this.has({queryExpr:e})}execute(e){const n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("non-query-used-as-query","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)}}Gv.AnonymousQuery=CSe;var zl={};Object.defineProperty(zl,"__esModule",{value:!0}),zl.View=void 0;const TSe=Ge;let bSe=class extends TSe.MalloyElement{pipeline(e,n){return this.pipelineComp(e,n).pipeline}};zl.View=bSe;var Wv={};Object.defineProperty(Wv,"__esModule",{value:!0}),Wv.ViewArrow=void 0;const RSe=hr,OSe=zl;class DSe extends OSe.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 RSe.StaticSpace(n.outputStruct),i=this.operation.pipelineComp(r);return{pipeline:[...n.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,n,r){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Wv.ViewArrow=DSe;var Vv={},z1={};Object.defineProperty(z1,"__esModule",{value:!0}),z1.refine=void 0;const oD=Ai,uD=Nl;function NSe(t,e,n){var r,i;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const s={...e[0]},o=n;if((0,oD.isRawSegment)(s))t.logError("refinement-of-raw-query","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.logError("mismatched-view-types-for-refinement",`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.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.logError("limit-overridden-in-refinement","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,oD.isQuerySegment)(o)&&(0,oD.isQuerySegment)(s)){const u=[],a=[],l=new Map(s.queryFields.map(c=>[(0,uD.nameFromDef)(c),c]));for(const c of o.queryFields)l.has((0,uD.nameFromDef)(c))?u.push(c):a.push(c);s.queryFields=[...s.queryFields,...a],u.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${u.map(uD.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}z1.refine=NSe,Object.defineProperty(Vv,"__esModule",{value:!0}),Vv.ViewRefine=void 0;const wSe=Fr,FSe=Zi,LSe=z1,ISe=zl;class $Se extends ISe.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,FSe.getFinalStruct)(this.refinement,e.structDef(),i):wSe.ErrorFactory.structDef}}refine(e,n,r){const i=this.pipeline(e,r);return i.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),n):(0,LSe.refine)(this,n,i[0])}getImplicitName(){return this.base.getImplicitName()}}Vv.ViewRefine=$Se;var Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.ReferenceView=void 0;const aD=oe,zz=Fr,BSe=Zi,kSe=wr,PSe=z1,MSe=zl;class jSe extends MSe.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:zz.ErrorFactory.structDef,outputStruct:zz.ErrorFactory.structDef,pipeline:[],error:!0}};if(!r.found)return this.logError("view-not-found",`\`${this.reference.refString}\` is not defined`),i();if(!(r.found instanceof kSe.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,aD.isAtomicFieldType)(s.type)){const o={type:"reduce",queryFields:[this.reference.refToField]},u=this.reference.nameString,a={...(0,aD.sourceBase)(e.structDef()),type:"query_result",name:u,fields:[s]};return{pipeline:[o],name:u,outputStruct:a}}else return(0,aD.isTurtleDef)(s)?this.reference.list.length>1?(n?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,BSe.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(n?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.logError("nest-of-source","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.logError("refinement-with-multistage-view",`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,PSe.refine)(this,n,i):n}getImplicitName(){return this.reference.nameString}}Yv.ReferenceView=jSe;var Jv={},Q1={},Xv={},G1={};Object.defineProperty(G1,"__esModule",{value:!0}),G1.Index=void 0;const USe=Ge,qSe=mn;let HSe=class extends USe.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=qSe.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};G1.Index=HSe;var W1={};Object.defineProperty(W1,"__esModule",{value:!0}),W1.SampleProperty=void 0;const zSe=Ge,Qz=mn;class QSe extends zSe.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=Qz.LegalRefinementStage.Tail,this.forceQueryClass=Qz.QueryClass.Index}sampling(){return this.sample}}W1.SampleProperty=QSe;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.IndexFieldSpace=void 0;const Gz=oe,lD=ht,GSe=wr,WSe=ao,VSe=C1,YSe=hr;class JSe extends WSe.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const n of e)n instanceof lD.FieldReference?super.pushFields(n):n instanceof lD.WildcardFieldReference?this.addWild(n):n.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};const n=[];for(const[r,i]of this.entries())if(i instanceof GSe.SpaceField){const s=this.expandedWild[r];if(s){n.push({type:"fieldref",path:s});continue}if(i instanceof VSe.ReferenceField){const o=i.fieldRef,u=o.getField(this.exprSpace);u.error?o.logError(u.error.code,u.error.message):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 YSe.StructSpaceField)r=l.fieldSpace;else{u.logError("invalid-wildcard-source",`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.logError("wildcard-source-not-found",`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries()){if(e.except.has(u)||a.refType==="parameter")continue;const l=lD.IndexFieldReference.indexOutputName([...i,u]);if(this.entry(l)){const c=(n=this.expandedWild[l])===null||n===void 0?void 0:n.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=a.typeDesc(),f=c.dataType;(0,Gz.isAtomicFieldType)(f)&&f!=="record"&&f!=="array"&&(0,Gz.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)}}Kv.IndexFieldSpace=JSe,Object.defineProperty(Xv,"__esModule",{value:!0}),Xv.IndexBuilder=void 0;const cD=oe,XSe=Fr,KSe=oo,ZSe=G1,e_e=kl,t_e=W1,n_e=Kv;class r_e{constructor(e,n,r,i){this.filters=[],this.type="index",this.resultFS=new n_e.IndexFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof KSe.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof e_e.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof ZSe.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof t_e.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}finalize(e){if(e&&!(0,cD.isIndexSegment)(e)&&!(0,cD.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),XSe.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,cD.isIndexSegment)(e)&&(e!=null&&e.sample)&&(n.sample=e.sample),this.sample&&(n.sample=this.sample),n}}Xv.IndexBuilder=r_e;var Zv={},V1={};Object.defineProperty(V1,"__esModule",{value:!0}),V1.GroupBy=void 0;const i_e=Ki,Wz=mn;class s_e extends i_e.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=Wz.LegalRefinementStage.Single,this.forceQueryClass=Wz.QueryClass.Grouping}}V1.GroupBy=s_e;var e4={};Object.defineProperty(e4,"__esModule",{value:!0}),e4.ProjectFieldSpace=void 0;const fD=oe,o_e=ao;class u_e extends o_e.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,fD.expressionIsAggregate)(e.expressionType)?!1:(0,fD.expressionInvolvesAggregate)(e.expressionType)&&(0,fD.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}e4.ProjectFieldSpace=u_e;var Ql={},Qc={};Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.Ordering=Qc.OrderBy=void 0;const a_e=oe,Vz=Pl,Yz=Ge,l_e=mn;class c_e extends Yz.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e instanceof Vz.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 Vz.FieldName&&e.isQueryFieldSpace()){const i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.logError(s.error.code,s.error.message),(!s.found||!s.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,a_e.expressionIsAnalytic)((n=s.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const r={field:this.modelField};return this.dir&&(r.dir=this.dir),r}}Qc.OrderBy=c_e;class f_e extends Yz.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=l_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(n=>n.getOrderBy(e))}}Qc.Ordering=f_e;var Y1={};Object.defineProperty(Y1,"__esModule",{value:!0}),Y1.Top=void 0;const Jz=oe,x_e=Pl,d_e=Ge,h_e=mn;let p_e=class extends d_e.MalloyElement{constructor(e,n){super(),this.limit=e,this.by=n,this.elementType="top",this.queryRefinementStage=h_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:n})}getBy(e){var n;if(this.by)if(this.by instanceof x_e.FieldName){if(e.isQueryFieldSpace()){const r=e.outputSpace(),i=this.by.getField(r);i.error&&this.by.logError(i.error.code,i.error.message),(!i.found||!i.isOutputField)&&this.by.logError("top-by-not-found-in-output",`Unknown field ${this.by.refString} in output space`),(0,Jz.expressionIsAnalytic)((n=i.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.by.logError("top-by-analytic",`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,Jz.expressionIsAggregate)(r.expressionType)&&this.by.logError("top-by-aggregate","top by expression must not be an aggregate"),r.evalSpace==="output"&&this.by.logError("top-by-not-in-output","top by expression must be an output expression"),{by:"expression",e:r.value}}}};Y1.Top=p_e,Object.defineProperty(Ql,"__esModule",{value:!0}),Ql.ReduceBuilder=Ql.QuerySegmentBuilder=void 0;const Xz=oe,g_e=Fr,m_e=oo,y_e=kl,Kz=Qc,Zz=Y1,E_e=ao,A_e=Ki;class eQ{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof A_e.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof m_e.Filter){const n=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(n))}else e instanceof Zz.Top?(this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.logError("ordering-already-specified","Query operation is already sorted"):this.order=e)):e instanceof y_e.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Kz.Ordering&&(this.order?e.logError("ordering-already-specified","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 Zz.Top){const i=this.order.getBy(this.inputFS);i&&(n.by=i)}this.order instanceof Kz.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])}}Ql.QuerySegmentBuilder=eQ;class v_e extends eQ{constructor(e,n,r,i){super(),this.type="grouping",this.resultFS=new E_e.ReduceFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let n;if(e)if((0,Xz.isReduceSegment)(e)||(0,Xz.isPartialSegment)(e))n=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),g_e.ErrorFactory.reduceSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}Ql.ReduceBuilder=v_e,Object.defineProperty(Zv,"__esModule",{value:!0}),Zv.ProjectBuilder=void 0;const tQ=oe,S_e=Fr,__e=V1,C_e=e4,T_e=Ql;class b_e extends T_e.QuerySegmentBuilder{constructor(e,n,r,i){super(),this.type="project",this.resultFS=new C_e.ProjectFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof __e.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let n;if(e)if((0,tQ.isProjectSegment)(e)||(0,tQ.isPartialSegment)(e))n=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),S_e.ErrorFactory.projectSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}Zv.ProjectBuilder=b_e;var t4={};Object.defineProperty(t4,"__esModule",{value:!0}),t4.PartialBuilder=void 0;const R_e=Ai,O_e=Ql;class D_e extends O_e.ReduceBuilder{finalize(e){const n=super.finalize(e);if((0,R_e.isQuerySegment)(n))return{...n,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${n.type}`)}}t4.PartialBuilder=D_e,Object.defineProperty(Q1,"__esModule",{value:!0}),Q1.QOpDesc=void 0;const N_e=Xv,w_e=Zv,F_e=Ql,L_e=Ge,I_e=Zi,$_e=hr,Gc=mn,B_e=t4;class k_e extends L_e.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let n,r=!1;this.refineThis&&(this.refineThis.type==="reduce"?n=Gc.QueryClass.Grouping:this.refineThis.type==="project"?n=Gc.QueryClass.Project:this.refineThis.type==="index"&&(n=Gc.QueryClass.Index));for(const i of this.list)i.forceQueryClass&&(n?n!==i.forceQueryClass&&i.logError(`illegal-${n}-operation`,`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.logError("ambiguous-view-type",{}),n=Gc.QueryClass.Project),this.opClass=n,n}refineFrom(e){this.refineThis=e}getBuilder(e,n,r){switch(this.computeType()){case Gc.QueryClass.Grouping:return new F_e.ReduceBuilder(e,this.refineThis,n,r);case Gc.QueryClass.Project:return new w_e.ProjectBuilder(e,this.refineThis,n,r);case Gc.QueryClass.Index:return new N_e.IndexBuilder(e,this.refineThis,n,r);case void 0:return new B_e.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 $_e.StaticSourceSpace((0,I_e.opOutputStruct)(this,e.structDef(),i))}}}Q1.QOpDesc=k_e,Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.QOpDescView=void 0;const P_e=oe,M_e=hr,nQ=Q1,j_e=Zi,xD=mn,U_e=zl;class q_e extends U_e.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,P_e.isRawSegment)(i)?(this.logError("refinement-of-raw-query","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 nQ.QOpDesc([]),o=new nQ.QOpDesc([]);for(const u of this.operation.list)switch(u.queryRefinementStage){case xD.LegalRefinementStage.Head:s.push(u);break;case xD.LegalRefinementStage.Single:u.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case xD.LegalRefinementStage.Tail:o.push(u);break;default:u.logError("illegal-refinement-operation","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,j_e.getFinalStruct)(this,e.structDef(),i.slice(-1));i[u]=this.getOp(new M_e.StaticSourceSpace(a),void 0,o,i[u])}return i}getImplicitName(){}}Jv.QOpDescView=q_e;var xn={};Object.defineProperty(xn,"__esModule",{value:!0}),xn.FieldDefinitionValue=xn.DefSpace=xn.DimensionFieldDeclaration=xn.MeasureFieldDeclaration=xn.DeclareFieldDeclaration=xn.ProjectFieldDeclaration=xn.GroupByFieldDeclaration=xn.AggregateFieldDeclaration=xn.CalculateFieldDeclaration=xn.AtomicFieldDeclaration=void 0;const rQ=oe,H_e=Jt,z_e=dd,Q_e=Ge,Wc=In,G_e=Nr,W_e=wr;class Gl extends Q_e.MalloyElement{constructor(e,n,r){super({expr:e}),this.expr=e,this.defineName=n,this.exprSrc=r,this.isNoteableObj=!0,this.extendNote=G_e.extendNoteMethod}fieldDef(e,n){return this.queryFieldDef(new dD(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 u=this.executesInOutputSpace()?i():e;r=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${n}', ${u.message}`),{name:n,type:"error"}}let s=r.dataType;if(s==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),s="number"),(0,rQ.isAtomicFieldType)(s)&&s!=="error"){this.typecheckExprValue(r);let u;switch(s){case"date":case"timestamp":{const a={name:n,type:s,location:this.location,e:r.value};(0,z_e.isGranularResult)(r)&&(a.timeframe=r.timeframe),u=a;break}case"json":case"boolean":case"string":case"number":case"sql native":{u={type:s,name:n,location:this.location,e:r.value};break}case"record":{const a=[];u={type:"record",name:n,location:this.location,join:"one",fields:a,e:r.value,dialect:e.dialectName()};break}case"array":throw this.internalError("Cannot return an array result from a query (yet)")}return r.expressionType&&(u.expressionType=r.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof dD&&e.foundCircle)&&r.dataType!=="error"){const u=H_e.FT.inspect(r);this.logError("invalid-type-for-field-definition",`Cannot define '${n}', unexpected type: ${u}`)}return{name:n,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new iQ(e,this))}}xn.AtomicFieldDeclaration=Gl;class V_e extends Gl{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}xn.CalculateFieldDeclaration=V_e;class Y_e extends Gl{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckAggregate)(e,this)}}xn.AggregateFieldDeclaration=Y_e;class J_e extends Gl{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckGroupBy)(e,this)}}xn.GroupByFieldDeclaration=J_e;class X_e extends Gl{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckProject)(e,this)}}xn.ProjectFieldDeclaration=X_e;class K_e extends Gl{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckDeclare)(e,this)}}xn.DeclareFieldDeclaration=K_e;class Z_e extends Gl{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckMeasure)(e,this)}}xn.MeasureFieldDeclaration=Z_e;class e5e extends Gl{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckDimension)(e,this)}}xn.DimensionFieldDeclaration=e5e;class dD{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:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}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")}}xn.DefSpace=dD;class iQ extends W_e.SpaceField{constructor(e,n){super(),this.space=e,this.exprDef=n,this.fieldName=n.defineName}get name(){return this.fieldName}fieldDef(){let e=this.defInSource;return e===void 0&&(this.defInSource=e,e=this.exprDef.fieldDef(this.space,this.name)),e}getQueryFieldDef(e){if(!this.defInQuery){const n=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=n}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,rQ.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}xn.FieldDefinitionValue=iQ;var n4={};Object.defineProperty(n4,"__esModule",{value:!0}),n4.Aggregate=void 0;const t5e=Ki,sQ=mn;let n5e=class extends t5e.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=sQ.LegalRefinementStage.Single,this.forceQueryClass=sQ.QueryClass.Grouping}};n4.Aggregate=n5e;var r4={};Object.defineProperty(r4,"__esModule",{value:!0}),r4.Calculate=void 0;const r5e=Ki,i5e=mn;class s5e extends r5e.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=i5e.LegalRefinementStage.Single}}r4.Calculate=s5e;var J1={};Object.defineProperty(J1,"__esModule",{value:!0}),J1.Dimensions=void 0;const o5e=wl;class u5e extends o5e.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}J1.Dimensions=u5e;var X1={};Object.defineProperty(X1,"__esModule",{value:!0}),X1.Measures=void 0;const a5e=wl;class l5e extends a5e.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}X1.Measures=l5e;var i4={};Object.defineProperty(i4,"__esModule",{value:!0}),i4.Nests=void 0;const c5e=Ki,oQ=mn;class f5e extends c5e.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=oQ.LegalRefinementStage.Single,this.forceQueryClass=oQ.QueryClass.Grouping}}i4.Nests=f5e;var s4={};Object.defineProperty(s4,"__esModule",{value:!0}),s4.ProjectStatement=void 0;const x5e=Ki,uQ=mn;class d5e extends x5e.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=uQ.QueryClass.Project,this.queryRefinementStage=uQ.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}s4.ProjectStatement=d5e;var Wl={},ma={};Object.defineProperty(ma,"__esModule",{value:!0}),ma.findReferences=ma.deprecatedParseTableURI=ma.constructTableKey=void 0;const h5e=dl,hD=nn;function pD(t){const e=(0,hD.getStringIfShort)(t);if(e)return e;const n=[],r=t.string().sqlString();if(r){for(const i of(0,hD.getStringParts)(r))typeof i=="string"&&n.push(i);return n.join("")}return""}class p5e{constructor(e,n){this.trans=e,this.tokens=n,this.needTables={},this.needImports={}}registerTableReference(e,n,r){const i=aQ(e,n);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:n,firstReference:r})}enterTableMethod(e){const n=(0,hD.getId)(e.connectionId()),r=pD(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(n,r,i)}enterTableFunction(e){const n=pD(e.tableURI()),{connectionName:r,tablePath:i}=lQ(n),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const n=pD(e);this.needImports[n]||(this.needImports[n]=this.trans.rangeFromContext(e))}}function aQ(t,e){return t===void 0?e:`${t}:${e}`}ma.constructTableKey=aQ;function lQ(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,n,r]=e;return{connectionName:n,tablePath:r}}else return{tablePath:t}}ma.deprecatedParseTableURI=lQ;function g5e(t,e,n){const r=new p5e(t,e),i=r;return h5e.ParseTreeWalker.DEFAULT.walk(i,n),{tables:r.needTables,urls:r.needImports}}ma.findReferences=g5e,Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.TableFunctionSource=Wl.TableMethodSource=Wl.TableSource=void 0;const cQ=ma,m5e=so,fQ=Fr;class gD extends m5e.Source{getSourceDef(){var e,n,r;const i=this.getTableInfo();if(i===void 0)return fQ.ErrorFactory.structDef;const{tablePath:s,connectionName:o}=i,u=(0,cQ.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.logError("failed-to-fetch-table-schema",l),fQ.ErrorFactory.structDef}}Wl.TableSource=gD;class y5e extends gD{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.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}Wl.TableMethodSource=y5e;class E5e extends gD{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,cQ.deprecatedParseTableURI)(this.tableURI)}}Wl.TableFunctionSource=E5e;var o4={};Object.defineProperty(o4,"__esModule",{value:!0}),o4.SQLString=void 0;const A5e=Ge,xQ=uu;class v5e extends A5e.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(S5e)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof xQ.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","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("failed-to-expand-sql-source","Cannot expand into a query")}return e}}o4.SQLString=v5e;function S5e(t){return t instanceof xQ.SourceQueryElement}var u4={};Object.defineProperty(u4,"__esModule",{value:!0}),u4.SourceDesc=void 0;const _5e=Ge;class C5e extends _5e.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}u4.SourceDesc=C5e;var a4={};Object.defineProperty(a4,"__esModule",{value:!0}),a4.isSourceProperty=void 0;const T5e=oo,b5e=wl,R5e=od,O5e=Ll,D5e=ud,N5e=ad,w5e=ld,F5e=Fl,L5e=Ti;function I5e(t){return t instanceof T5e.Filter||t instanceof L5e.JoinStatement||t instanceof b5e.DeclareFields||t instanceof R5e.FieldListEdit||t instanceof O5e.Renames||t instanceof D5e.PrimaryKey||t instanceof F5e.ObjectAnnotation||t instanceof N5e.Views||t instanceof w5e.TimezoneStatement}a4.isSourceProperty=I5e;var l4={};Object.defineProperty(l4,"__esModule",{value:!0}),l4.isFieldCollectionMember=void 0;const $5e=xn,dQ=ht;function B5e(t){return t instanceof dQ.FieldReference||t instanceof dQ.WildcardFieldReference||t instanceof $5e.AtomicFieldDeclaration}l4.isFieldCollectionMember=B5e;var c4={};Object.defineProperty(c4,"__esModule",{value:!0}),c4.isQueryElement=void 0;const k5e=cd,P5e=fd,M5e=E1,j5e=A1;function U5e(t){return t instanceof k5e.QueryArrow||t instanceof P5e.QueryRefine||t instanceof M5e.QueryReference||t instanceof j5e.QueryRaw}c4.isQueryElement=U5e;var hQ={};Object.defineProperty(hQ,"__esModule",{value:!0});var f4={};Object.defineProperty(f4,"__esModule",{value:!0}),f4.isQueryProperty=void 0;function q5e(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}f4.isQueryProperty=q5e;var x4={};Object.defineProperty(x4,"__esModule",{value:!0}),x4.isQueryExtendProperty=void 0;const H5e=J1,z5e=Ti,Q5e=X1;function G5e(t){return t instanceof H5e.Dimensions||t instanceof Q5e.Measures||t instanceof z5e.JoinStatement}x4.isQueryExtendProperty=G5e;var d4={};Object.defineProperty(d4,"__esModule",{value:!0}),d4.isFieldPropStatement=void 0;const W5e=$l,V5e=oo,Y5e=kl,J5e=yd;function X5e(t){return t instanceof V5e.Filter||t instanceof Y5e.Limit||t instanceof J5e.PartitionBy||t instanceof W5e.FunctionOrdering}d4.isFieldPropStatement=X5e,function(t){var e=D&&D.__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=D&&D.__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(a1,t),n(td,t),n(nd,t),n(so,t),n(f1,t),n(uu,t),n(kA,t),n(PA,t),n(qA,t),n(p1,t),n(QA,t),n(od,t),n(ud,t),n(Ll,t),n(ad,t),n(ld,t),n(GA,t),n(pd,t),n(VA,t),n($l,t),n(YA,t),n(pa,t),n(JA,t),n(md,t),n(KA,t),n(ZA,t),n(ev,t),n(ha,t),n(tv,t),n(nv,t),n(iv,t),n(b1,t),n(_1,t),n(Ic,t),n(sv,t),n(ov,t),n(av,t),n(cv,t),n(fv,t),n(xv,t),n(dv,t),n(hv,t),n(pv,t),n(gv,t),n(mv,t),n(yv,t),n(Ev,t),n(Av,t),n(vv,t),n(Cv,t),n(Xn,t),n(jv,t),n(yd,t),n(Rd,t),n(Dd,t),n(Nd,t),n(Il,t),n(qv,t),n(Hv,t),n(R1,t),n(Hl,t),n(H1,t),n(zv,t),n(Qv,t),n(Gv,t),n(fd,t),n(cd,t),n(zl,t),n(Wv,t),n(Vv,t),n(Yv,t),n(Jv,t),n(xn,t),n(ht,t),n(n4,t),n(r4,t),n(wl,t),n(J1,t),n(H1,t),n(oo,t),n(V1,t),n(G1,t),n(Ti,t),n(l1,t),n(kl,t),n(X1,t),n(a1,t),n(i4,t),n(Qc,t),n(s4,t),n(Q1,t),n(W1,t),n(Y1,t),n(xd,t),n(Lc,t),n(v1,t),n(Wl,t),n(o4,t),n(Fl,t),n(uo,t),n(u4,t),n(a4,t),n(st,t),n(l4,t),n(Pl,t),n(Ge,t),n(c4,t),n(hQ,t),n(f4,t),n(x4,t),n(d4,t)}(RA);var h4={},wd={};Object.defineProperty(wd,"__esModule",{value:!0}),wd.ConstantExpression=wd.ConstantFieldSpace=void 0;const K5e=st;class pQ{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}}wd.ConstantFieldSpace=pQ;class Z5e extends K5e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new pQ),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,n,r){return this.expr.apply(e,n,r)}requestExpression(e){return this.expr.requestExpression(e)}}wd.ConstantExpression=Z5e;var eCe=D&&D.__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]}),tCe=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),nCe=D&&D.__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)&&eCe(e,t,n);return tCe(e,t),e};Object.defineProperty(h4,"__esModule",{value:!0}),h4.MalloyToAST=void 0;const gQ=CE,rCe=f2,Z=nCe(RA),mD=OA,mQ=Qn,iCe=RA,$n=nn,yD=oe,sCe=Mo,oCe=wd;class yQ extends Z.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class ED extends Z.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const uCe=["##! m4warnings=error"];class aCe extends rCe.AbstractParseTreeVisitor{constructor(e,n,r){super(),this.parseInfo=e,this.msgLog=n,this.compilerFlags=r;for(const i of uCe){const s=sCe.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,n){return this.contextError(e,"internal-translator-error",{message:n}),new Error(`Internal Translator Error: ${n}`)}astError(e,n,r,i){this.msgLog.log((0,mD.makeLogMessage)(n,r,{at:e.location,...i}))}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new mQ.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,n,r,i){this.msgLog.log((0,mD.makeLogMessage)(n,r,{at:this.getLocation(e),...i}))}warnWithReplacement(e,n,r,i){this.msgLog.log((0,mD.makeLogMessage)(e,n,{at:{url:this.parseInfo.sourceURL,range:r},severity:"warn",replacement:i}))}inExperiment(e,n){const r=this.compilerFlags.tag("experimental");return r&&(r.bare()||r.has(e))?!0:(this.contextError(n,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,n,r){const i=this.m4Severity();i&&this.contextError(e,n,r,{severity:i})}only(e,n,r){const i=[];for(const s of e){const o=n(s);o?i.push(o):s instanceof ED||this.astError(s,"unexpected-statement-in-translation",`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 Z.FieldName((0,$n.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new Z.ModelEntryReference((0,$n.getId)(e)),e.id())}defaultResult(){return new Z.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 mQ.Interval(n,r.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){const n=this.getFieldExpr(e),r=new Z.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 Z.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","Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new Z.Filter([n])}getPlainStringFrom(e){const[n,r]=(0,$n.getPlainString)(e);for(const i of r)i instanceof gQ.ParserRuleContext&&this.contextError(i,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return n||""}makeSqlString(e,n){for(const r of e.sqlInterpolation())r.CLOSE_CODE()&&this.m4advisory(r,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const r of(0,$n.getStringParts)(e))r instanceof gQ.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,"failed-to-parse-time-literal","Time data parse error"),r=new Z.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=>Z.isDocStatementOrDocStatementList(r)&&r,"statement");return new Z.Document(n)}visitDefineSourceStatement(e){const r=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new Z.DefineSourceList(r);return s.extendNote({blockNotes:i}),s}getSourceParameter(e){const n=e.fieldExpr(),r=n?this.astAt(new oCe.ConstantExpression(this.getFieldExpr(n)),n):void 0,i=e.malloyType(),s=i?this.getMalloyType(i):void 0;return this.astAt(new Z.HasParameter({name:(0,$n.getId)(e.parameterNameDef()),type:s,default:r}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(n=>this.getSourceParameter(n)))}visitSourceDefinition(e){const n=this.visit(e.sqExplore()),r=this.getSourceParameters(e.sourceParameters()),i=new Z.DefineSource((0,$n.getId)(e.sourceNameDef()),n instanceof Z.SourceQueryElement?n:void 0,!0,r),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,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=>Z.isSourceProperty(s)&&s,"source property"),i=new Z.SourceDesc(r);return n&&i.push(this.getFilterShortcut(n)),i}visitTableFunction(e){const n=this.getPlainStringFrom(e.tableURI()),r=this.astAt(new Z.TableFunctionSource(n),e);return this.m4advisory(e,"table-function","`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.getPlainStringFrom(e.tablePath());return this.astAt(new Z.TableMethodSource(r,i),e)}visitSqlSource(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=new Z.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);const o=e.shortString();o&&i.push((0,$n.getShortString)(o));const u=new Z.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 Z.Join&&(n.push(s),s instanceof Z.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):s instanceof Z.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const r=new Z.JoinStatement(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 Z.Join&&(r.push(s),s instanceof Z.ExpressionJoin&&(s.joinType="one"));const i=new Z.JoinStatement(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 Z.Join&&(r.push(s),s instanceof Z.ExpressionJoin?s.joinType="cross":s.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const i=new Z.JoinStatement(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return this.only(e.joinDef().map(n=>this.visit(n)),n=>n instanceof Z.Join&&n,"join")}getJoinFrom(e){const n=e.isExplore(),r=this.getModelEntryName(e.joinNameDef());if(n){const s=this.getSqExpr(n.sqExpr()),o=this.getNotes(n._before_is).concat(this.getNotes(n._after_is));return{joinFrom:s,notes:o,joinAs:r}}const i=e.sourceArguments();return i?{joinFrom:this.astAt(new Z.SQReference(r,this.getSQArguments(i)),e),notes:[],joinAs:r}:{joinAs:r,joinFrom:new Z.SQReference(r),notes:[]}}visitQueryJoinStatement(e){const n=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"join-statement-in-view","Joins in queries are deprecated, move into an `extend:` block."),n}visitJoinOn(e){var n;const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=new Z.ExpressionJoin(r,i),u=e.joinExpression(),a=((n=e.matrixOperation())===null||n===void 0?void 0:n.text.toLocaleLowerCase())||"left";return(0,yD.isMatrixOperation)(a)?o.matrixOperation=a:this.contextError(e,"unknown-matrix-operation","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{joinAs:n,joinFrom:r,notes:i}=this.getJoinFrom(e.joinFrom()),s=this.getFieldExpr(e.fieldExpr()),o=new Z.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,$n.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(),Z.DimensionFieldDeclaration),r=new Z.Dimensions(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitDefMeasures(e){const n=this.getFieldDefs(e.defList().fieldDef(),Z.MeasureFieldDeclaration),r=new Z.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(Z.isQueryExtendProperty(s))n.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);const i=new Z.ExtendBlock(n);return this.astAt(i,e)}visitDeclareStatement(e){const n=this.getFieldDefs(e.defList().fieldDef(),Z.DeclareFieldDeclaration),r=new Z.DeclareFields(n),i=this.astAt(r,e);return this.m4advisory(e,"declare","`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 Z.RenameField((0,$n.getId)(n),this.getFieldName(r));return this.astAt(i,e)}visitDefExploreRename(e){const r=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new Z.Renames(r);return this.astAt(i,e)}visitFilterClauseList(e){return new Z.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 Z.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,"query-in-source","Use view: inside of a source instead of query:"),n}visitDefExplorePrimaryKey(e){const n=new Z.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(n,e)}visitFieldNameList(e){const n=e.fieldName().map(r=>new Z.AcceptExceptFieldReference([this.getFieldName(r)]));return new Z.FieldReferences(n)}visitDefExploreEditField(e){const n=e.ACCEPT()?"accept":"except";return new Z.FieldListEdit(n,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const n=this.getPlainStringFrom(e),r=this.astAt(new Z.TimezoneStatement(n),e.string());return r.isValid||this.astError(r,"invalid-timezone",{timezone:r.tz}),this.astAt(r,e)}visitQueryProperties(e){const n=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>Z.isQueryProperty(i)&&i,"query statement"),r=e.filterShortcut();return r&&n.push(this.getFilterShortcut(r)),new Z.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 Z.FieldReference||i instanceof Z.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){const n=new Z.Aggregate(this.getQueryItems(e.queryFieldList(),Z.AggregateFieldDeclaration,Z.AggregateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitGroupByStatement(e){const n=new Z.GroupBy(this.getQueryItems(e.queryFieldList(),Z.GroupByFieldDeclaration,Z.GroupByFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCalculateStatement(e){const n=new Z.Calculate(this.getQueryItems(e.queryFieldList(),Z.CalculateFieldDeclaration,Z.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(),Z.ExpressionFieldReference);let u;const a=i.timeframe();a&&(u=new Z.ExprGranularTime(new Z.ExprIdReference(o),this.visitTimeframe(a).text,!0));const l=i.aggregate();if(l){const f=l.text.toLowerCase();if(f==="sum")u=new Z.ExprSum(void 0,o);else return this.contextError(l,"invalid-reference-only-aggregation",`\`${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,Z.ProjectFieldDeclaration,Z.ProjectFieldReference));return this.astAt(new Z.ProjectStatement(n),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","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,Z.ProjectFieldReference):void 0,s=this.astAt(new Z.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,$n.getId)(a));return s}visitIndexFields(e){const n=e.indexElement().map(r=>{const i=r.fieldPath();if(!i)return this.astAt(new Z.WildcardFieldReference(void 0),e);const s=this.getFieldPath(i,Z.IndexFieldReference);return r.STAR()?this.astAt(new Z.WildcardFieldReference(s),e):this.astAt(s,e)});return new Z.FieldReferences(n)}visitIndexStatement(e){const n=this.visitIndexFields(e.indexFields()),r=new Z.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 Z.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 Z.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 Z.FunctionOrdering(n),e)}visitOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.INTEGER_LITERAL();if(r)return new Z.OrderBy(this.getNumber(r),n);const i=e.fieldName();if(i)return new Z.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 Z.Ordering(n),e)}visitTopStatement(e){const n=e.bySpec(),r=this.getNumber(e.INTEGER_LITERAL());let i;if(n){this.m4advisory(n,"top-by","by clause of top statement unupported. Use order_by instead");const s=n.fieldName();if(s){const u=this.getFieldName(s);i=new Z.Top(r,u)}const o=n.fieldExpr();o&&(i=new Z.Top(r,this.getFieldExpr(o)))}return i||(i=new Z.Top(r,void 0)),this.astAt(i,e)}visitTopLevelQueryDefs(e){const n=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),r=this.getNotes(e.tags()),i=new Z.DefineQueryList(n);return i.extendNote({blockNotes:r}),i}visitTopLevelQueryDef(e){const n=(0,$n.getId)(e.queryName()),r=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(r instanceof Z.SourceQueryElement){const s=new Z.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 Z.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","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 Z.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 Z.Nests(this.only(e.nestEntry().map(n=>this.visit(n)),n=>n instanceof Z.NestFieldDeclaration&&n,"query"))}visitNestDef(e){const n=e.queryName();let r;const i=this.getVExpr(e.vExpr());if(n)r=(0,$n.getId)(n);else{const u=i.getImplicitName();u===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),r=u??"__unnamed__"}const s=new Z.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,$n.getId)(e.exploreQueryNameDef()),r=new Z.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 Z.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new Z.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 Z.ExprLogicalOp(n,"or",r)}visitExprLogicalAnd(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new Z.ExprLogicalOp(n,"and",r)}visitExprOrTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new Z.ExprAlternationTree(n,"|",r),e)}visitExprAndTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new Z.ExprAlternationTree(n,"&",r),e)}visitExprCoalesce(e){const n=this.getFieldExpr(e.fieldExpr()[0]),r=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new Z.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(Z.isComparison(i))return this.astAt(new Z.PartialCompare(i,r),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return r}visitExprString(e){const n=this.getPlainStringFrom(e);return new Z.ExprString(n)}visitExprRegex(e){const n=e.HACKY_REGEX().text;return new Z.ExprRegEx(n.slice(2,-1))}visitExprNow(e){return new Z.ExprNow}visitExprNumber(e){return new Z.ExprNumber(e.text)}visitExprFieldPath(e){const n=new Z.ExprIdReference(this.getFieldPath(e.fieldPath(),Z.ExpressionFieldReference));return this.astAt(n,e)}visitExprNULL(e){return new Z.ExprNULL}visitExprExpr(e){return new Z.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new Z.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 Z.ExprAddSub(n,i,r)}visitExprMulDiv(e){const n=e.STAR()?"*":e.SLASH()?"/":"%";return new Z.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const n=e.compareOp().text,r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));if(Z.isEquality(n))return this.astAt(new Z.ExprEquality(r,n,i),e);if(Z.isComparison(n))return this.astAt(new Z.ExprCompare(r,n,i),e);throw this.internalError(e,`untranslatable comparison operator '${n}'`)}visitExprUngroup(e){const n=e.fieldName().map(i=>this.getFieldName(i)),r=e.ungroup().text.toLowerCase();return this.astAt(new Z.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,Z.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,"count-expression-with-locality","Expression illegal inside path.count()"),new Z.ExprCount(i);const u=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(u)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s));else{const a=this.astAt(new Z.ExprIdReference(r),n);return s==="min"?new Z.ExprMin(a):new Z.ExprMax(a)}else{if(s==="avg")return new Z.ExprAvg(u,i);if(s==="sum")return new Z.ExprSum(u,i);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${s}`)}return new Z.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,"wildcard-in-aggregate",`* illegal inside ${s}()`),s==="count")return this.astAt(r?new Z.ExprCountDistinct(r):new Z.ExprCount,e);if(s==="min"){if(r)return new Z.ExprMin(r);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s))}else if(s==="max"){if(r)return new Z.ExprMax(r);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s))}else{if(r===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(s)),new Z.ExprNULL;const o=e.SOURCE_KW()!==void 0;if(s==="avg")return new Z.ExprAvg(r,i,o);if(s==="sum")return new Z.ExprSum(r,i,o)}return new Z.ExprNULL}visitExprApply(e){return new Z.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new Z.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new Z.ExprCast(this.getFieldExpr(e.fieldExpr()),n)}getMalloyType(e){const n=e.text;if((0,yD.isCastType)(n))return n;throw this.internalError(e,`unknown type '${n}'`)}getMalloyOrSQLType(e){const n=e.malloyType();if(n)return this.getMalloyType(n);const r=e.string();if(r)return{raw:this.getPlainStringFrom({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 Z.ExprCast(this.getFieldExpr(e.fieldExpr()),n,!0)}visitExprTimeTrunc(e){return new Z.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new Z.Timeframe(e.text)}visitExprForRange(e){const n=this.getFieldExpr(e._startAt),r=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new Z.ForRange(n,r,i)}visitExprAggFunc(e){const n=e.argumentList(),r=n?this.allFieldExpressions(n.fieldExpr()):[],i=(0,$n.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,Z.ExpressionFieldReference):void 0,u=s&&o?this.astAt(o,s):void 0;return Z.ExprTimeExtract.extractor(i)?this.astAt(new Z.ExprTimeExtract(i,r),e):this.astAt(new Z.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,yD.isCastType)(u)?a=u:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${u}'`),a=void 0));let l=(0,$n.getOptionalId)(e)||((r=e.timeframe())===null||r===void 0?void 0:r.text);return l===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),l="FUNCTION_NAME_ERROR"),Z.ExprTimeExtract.extractor(l)?this.astAt(new Z.ExprTimeExtract(l,s),e):this.astAt(new Z.ExprFunc(l,s,o,a),e)}visitExprDuration(e){return new Z.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const n=e._valueExpr,r=n?this.getFieldExpr(n):void 0,i=e.caseWhen(),s=i.map(a=>new Z.CaseWhen(this.getFieldExpr(a._condition),this.getFieldExpr(a._result))),o=e._caseElse,u=o?this.getFieldExpr(o):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.parseInfo.rangeFromContext(e),`${[...n?[`${this.getSourceCode(n)} ?`]:[],...i.map(a=>`pick ${this.getSourceCode(a._result)} when ${this.getSourceCode(a._condition)}`),o?`else ${o.text}`:"else null"].join(" ")}`),new Z.Case(r,s,u)}visitPickStatement(e){const n=e.pick().map(r=>{let i;return r._pickValue&&(i=this.getFieldExpr(r._pickValue)),new Z.PickWhen(i,this.getFieldExpr(r._pickWhen))});return e.ELSE()?new Z.Pick(n,this.getFieldExpr(e._pickElse)):new Z.Pick(n)}visitExprFieldProps(e){const n=this.only(e.fieldProperties().fieldPropertyStatement().map(r=>this.visit(r)),r=>Z.isFieldPropStatement(r)&&r,"field property statement");return new Z.ExprProps(this.getFieldExpr(e.fieldExpr()),n)}visitPartitionByStatement(e){return this.astAt(new Z.PartitionBy(e.id().map(n=>this.astAt(new Z.PartitionByFieldReference([this.astAt(new Z.FieldName((0,$n.idToStr)(n)),n)]),n))),e)}visitLiteralTimestamp(e){return this.parseTime(e,Z.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,Z.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,Z.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,Z.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,Z.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,Z.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,Z.LiteralYear.parse)}visitImportStatement(e){const n=this.getPlainStringFrom(e.importURL()),r=this.astAt(new Z.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 Z.ImportSourceName((0,$n.idToStr)(o[1])),o[1]):void 0;r.push(this.astAt(new Z.ImportSelect((0,$n.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 Z.SampleProperty({rows:this.getNumber(n)});const r=e.sampleSpec().PERCENT_LITERAL();if(r)return new Z.SampleProperty({percent:this.getNumber(r)});const i=e.sampleSpec().TRUE()!==void 0;return new Z.SampleProperty({enable:i})}visitDocAnnotations(e){const n=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),r=new Z.ModelAnnotation(n);return this.compilerFlags=r.getCompilerFlags(this.compilerFlags,this.msgLog),r}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new ED(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new ED(e.text)}visitDefExploreAnnotation(e){const n=this.getNotes(e);return new Z.ObjectAnnotation(n)}getSQArgument(e){const n=e.argumentId(),r=n?this.astAt(new Z.PartitionByFieldReference([this.astAt(new Z.FieldName((0,$n.idToStr)(n.id())),n)]),n):void 0;return this.astAt(new Z.Argument({id:r,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(n=>this.getSQArgument(n))}visitSQID(e){const n=this.getModelEntryName(e),r=this.getSQArguments(e.sourceArguments());return this.astAt(new Z.SQReference(n,r),e.id())}getSqExpr(e){const n=this.visit(e);return n instanceof Z.SourceQueryElement?n:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${n.elementType}'`),new yQ)}visitSQExtendedSource(e){const n=this.getSqExpr(e.sqExpr()),r=new Z.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 Z.SQArrow(n,this.getVExpr(r));return this.astAt(i,e)}getVExpr(e){const n=this.visit(e);if(n instanceof Z.View)return n;throw this.internalError(e,`Expected view, got a '${n.elementType}'`)}visitSegField(e){return new Z.ReferenceView(this.getFieldPath(e.fieldPath(),Z.ViewOrScalarFieldReference))}visitSegOps(e){return new Z.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new Z.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new Z.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new Z.SQRefine(n,this.getVExpr(r));return this.astAt(i,e)}visitSQTable(e){const n=this.visit(e.exploreTable());if(n instanceof iCe.TableSource){const r=new Z.SQSource(n);return this.astAt(r,e)}return new yQ}visitSQSQL(e){const n=new Z.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(n,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new Z.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitExprWarnLike(e){let n="~";const r=e.fieldExpr(0),i=e.fieldExpr(1),s=this.parseInfo.rangeFromContext(e);return e.NOT()?(n="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",s,`${this.getSourceCode(r)} !~ ${this.getSourceCode(i)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",s,`${this.getSourceCode(r)} ~ ${this.getSourceCode(i)}`),this.astAt(new Z.ExprCompare(this.getFieldExpr(r),n,this.getFieldExpr(i)),e)}visitExprWarnNullCmp(e){let n="=";const r=e.fieldExpr(),i=this.parseInfo.rangeFromContext(e);e.NOT()?(n="!=",this.warnWithReplacement("sql-is-not-null","Use '!= NULL' to check for NULL instead of 'IS NOT NULL'",i,`${this.getSourceCode(r)} != null`)):this.warnWithReplacement("sql-is-null","Use '= NULL' to check for NULL instead of 'IS NULL'",i,`${this.getSourceCode(r)} = null`);const s=new Z.ExprNULL;return this.astAt(new Z.ExprCompare(this.getFieldExpr(r),n,s),e)}visitExprWarnIn(e){const n=this.getFieldExpr(e.fieldExpr()),r=!!e.NOT(),i=e.fieldExprList().fieldExpr(),s=this.astAt(new Z.ExprLegacyIn(n,r,i.map(o=>this.getFieldExpr(o))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${r?" NOT":""} IN (a,b,c)`,this.parseInfo.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${r?"!=":"="} (${i.map(o=>this.getSourceCode(o)).join(" | ")})`),s}}h4.MalloyToAST=aCe;var p4={};Object.defineProperty(p4,"__esModule",{value:!0}),p4.Zone=void 0;class lCe{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})}}p4.Zone=lCe;var g4={};Object.defineProperty(g4,"__esModule",{value:!0}),g4.walkForDocumentSymbols=void 0;const cCe=dl,fCe=nn;class xCe{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.joinFrom().joinNameDef().id().text,type:"join",children:[]},r=this.peekScope();r&&r.children.push(n)}enterImportStatement(e){const n=(0,fCe.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 dCe(t,e,n){const r=new xCe(t,e,[],[]),i=r;return cCe.ParseTreeWalker.DEFAULT.walk(i,n),r.symbols}g4.walkForDocumentSymbols=dCe;var m4={};Object.defineProperty(m4,"__esModule",{value:!0}),m4.walkForDocumentCompletions=void 0;const hCe=dl,pCe=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],gCe=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],mCe=["source","explore","query","sql"];class yCe{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 pCe)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 gCe)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 mCe)this.completions.push({type:"model_property",text:`${r}: `})}}}function ECe(t,e,n){const r=new yCe(t,[],n),i=r;return hCe.ParseTreeWalker.DEFAULT.walk(i,e),r.completions}m4.walkForDocumentCompletions=ECe;var y4={};Object.defineProperty(y4,"__esModule",{value:!0}),y4.walkForDocumentHelpContext=void 0;const ACe=vb;class vCe extends ACe.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 SCe(t,e){return new vCe(e).visit(t)}y4.walkForDocumentHelpContext=SCe;var E4={},K1={};Object.defineProperty(K1,"__esModule",{value:!0}),K1.locationContainsPosition=void 0;function _Ce(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)}K1.locationContainsPosition=_Ce,Object.defineProperty(E4,"__esModule",{value:!0}),E4.ReferenceList=void 0;const CCe=K1;class TCe{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,CCe.locationContainsPosition)(r.location,e))return r}}E4.ReferenceList=TCe;var A4={};Object.defineProperty(A4,"__esModule",{value:!0}),A4.isNeedResponse=void 0;function bCe(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}A4.isNeedResponse=bCe;var v4={};Object.defineProperty(v4,"__esModule",{value:!0}),v4.walkForModelAnnotation=void 0;const RCe=dl;class OCe{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 DCe(t,e,n){const r=new OCe(t,e,n),i=r;return RCe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.annotation}v4.walkForModelAnnotation=DCe;var S4={};Object.defineProperty(S4,"__esModule",{value:!0}),S4.walkForTablePath=void 0;const EQ=nn,NCe=dl;class wCe{constructor(e,n){this.translator=e,this.tokens=n,this.pathInfos=[]}enterTableMethod(e){const n=(0,EQ.getId)(e.connectionId()),[r,i]=(0,EQ.getPlainString)(e.tablePath(),!0);r!==void 0&&this.pathInfos.push({connectionId:n,tablePath:r,range:this.translator.rangeFromContext(e)})}}function FCe(t,e,n){const r=new wCe(t,e),i=r;return NCe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.pathInfos}S4.walkForTablePath=FCe;var LCe=D&&D.__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]}),ICe=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$Ce=D&&D.__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)&&LCe(e,t,n);return ICe(e,t),e};Object.defineProperty(eu,"__esModule",{value:!0}),eu.MalloyParserErrorHandler=eu.MalloyTranslator=eu.MalloyChildTranslator=eu.MalloyTranslation=void 0;const AQ=CE,BCe=oe,kCe=jE,PCe=F,vQ=$Ce(RA),MCe=h4,AD=OA,jCe=ma,vD=p4,UCe=g4,qCe=m4,HCe=y4,zCe=E4,_4=A4,QCe=K1,SQ=Mo,GCe=v4,WCe=S4;class VCe extends kCe.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}class YCe{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.logError("failed-to-compute-absolute-import-url",`Could not compute full path URL: ${o}`)}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.firstReference||e.defaultLocation();return e.root.logError("import-error",{message:n.message,url:e.sourceURL},{at:s}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const r=n.value===""?`
1326
+ `)),zA.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.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),zA.ErrorFactory.structDef}}v1.SQLSource=z3e,Object.defineProperty(qA,"__esModule",{value:!0}),qA.SQSource=void 0;const Q3e=uu,G3e=A1,W3e=v1;class V3e extends Q3e.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 W3e.SQLSource){const e=new G3e.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}qA.SQSource=V3e;var QA={};Object.defineProperty(QA,"__esModule",{value:!0}),QA.SQExtend=void 0;const Y3e=f1,J3e=uu;class X3e extends J3e.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 Y3e.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}QA.SQExtend=X3e;var GA={},ha={},S1={};Object.defineProperty(S1,"__esModule",{value:!0}),S1.BinaryBoolean=void 0;const $q=oe,K3e=Ci,Z3e=Jt,eye=uo,tye=st;class nye extends tye.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=[Z3e.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,$q.mergeEvalSpaces)(n.evalSpace,r.evalSpace);return{dataType:"boolean",expressionType:(0,$q.maxExpressionType)(n.expressionType,r.expressionType),value:{node:(0,eye.getExprNode)(this.op),kids:{left:n.value,right:r.value}},evalSpace:i}}return(0,K3e.errorFor)("logial required boolean")}}S1.BinaryBoolean=nye,Object.defineProperty(ha,"__esModule",{value:!0}),ha.ExprLegacyIn=ha.ExprEquality=ha.ExprCompare=void 0;const Bq=Ai,Qt=Jt,rye=st,iye=S1,sye={"~":[Qt.FT.stringT],"!~":[Qt.FT.stringT],"<":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],"<=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],"=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],"!=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],">=":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT],">":[Qt.FT.numberT,Qt.FT.stringT,Qt.FT.dateT,Qt.FT.timestampT]};class kq extends iye.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="a<=>b",this.legalChildTypes=sye[n]}getExpression(e){return this.right.apply(e,this.op,this.left)}}ha.ExprCompare=kq;class oye extends kq{constructor(e,n,r){super(e,n,r),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,n,r){return super.apply(e,n,r,!0)}}ha.ExprEquality=oye;class uye extends rye.ExpressionDef{constructor(e,n,r){super(),this.expr=e,this.notIn=n,this.choices=r,this.elementType="in",this.has({expr:e,choices:r})}getExpression(e){const n=this.expr.getExpression(e);let{evalSpace:r,expressionType:i}=n;const s=this.choices.map(o=>{const u=o.getExpression(e);return i=(0,Bq.maxExpressionType)(i,u.expressionType),r=(0,Bq.mergeEvalSpaces)(r,u.evalSpace),u.value});return{dataType:"boolean",expressionType:i,evalSpace:r,value:{node:"in",not:this.notIn,kids:{e:n.value,oneOf:s}}}}}ha.ExprLegacyIn=uye;var _1={},hd={};Object.defineProperty(hd,"__esModule",{value:!0}),hd.ExprTime=void 0;const aye=oe,lye=st;class mO extends lye.ExpressionDef{constructor(e,n,r="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:r,value:n,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,n){let r=n.value;if(e!==n.dataType){const i={node:"cast",safe:!1,dstType:e,e:n.value};(0,aye.isTemporalField)(n.dataType)&&(i.srcType=n.dataType),r=i}return new mO(e,r,n.expressionType)}}hd.ExprTime=mO;var Il={};Object.defineProperty(Il,"__esModule",{value:!0}),Il.Range=void 0;const Pq=oe,cye=Ci,fye=st;class xye extends fye.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,Pq.maxExpressionType)(u.expressionType,a.expressionType),evalSpace:(0,Pq.mergeEvalSpaces)(u.evalSpace,a.evalSpace),value:{node:s,kids:{left:u.value,right: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.logError("range-as-value","A Range is not a value"),(0,cye.errorFor)("a range is not a value")}}Il.Range=xye,Object.defineProperty(_1,"__esModule",{value:!0}),_1.ExprGranularTime=void 0;const Mq=oe,dye=Ci,jq=Jt,Uq=Jn,hye=st,WA=hd,qq=Il;class pye extends hye.ExpressionDef{constructor(e,n,r){super({expr:e}),this.expr=e,this.units=n,this.truncate=r,this.elementType="granularTime",this.legalChildTypes=[jq.FT.timestampT,jq.FT.dateT]}granular(){return!0}getExpression(e){const n=this.units,r=this.expr.getExpression(e);if((0,Mq.isTemporalField)(r.dataType)){const s={...r,dataType:r.dataType,timeframe:n};return this.truncate&&(s.value={node:"trunc",e:{...r.value,dataType:r.dataType},units:n}),s}r.dataType!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${r.dataType}'`);const i=r.dataType==="error"?(0,Mq.isDateUnit)(n)?"date":"timestamp":r.dataType;return{...r,dataType:i,value:(0,dye.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const n=this.getExpression(e),r={node:"numberLiteral",literal:"1"};if(n.dataType==="timestamp"){const u=WA.ExprTime.fromValue("timestamp",n),a=new WA.ExprTime("timestamp",(0,Uq.timeOffset)("timestamp",n.value,"+",r,this.units),n.expressionType);return new qq.Range(u,a)}const i=new WA.ExprTime("date",n.value,n.expressionType),s=(0,Uq.timeOffset)("date",n.value,"+",r,this.units),o=new WA.ExprTime("date",s,n.expressionType);return new qq.Range(i,o)}}_1.ExprGranularTime=pye,Object.defineProperty(GA,"__esModule",{value:!0}),GA.Apply=void 0;const gye=ha,mye=dd,Hq=_1;class yye extends gye.ExprCompare{constructor(e,n){super(e,"=",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,mye.isGranularResult)(r)&&(n=new Hq.ExprGranularTime(this.right,r.timeframe,!1))}return n instanceof Hq.ExprGranularTime?n.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}GA.Apply=yye;var pd={};Object.defineProperty(pd,"__esModule",{value:!0}),pd.BinaryNumeric=void 0;const Eye=Jt,Aye=st;class vye extends Aye.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=[Eye.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}pd.BinaryNumeric=vye;var VA={};Object.defineProperty(VA,"__esModule",{value:!0}),VA.Boolean=void 0;const Sye=st,_ye=Jt;let Cye=class extends Sye.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{..._ye.FT.boolT,value:{node:this.value}}}};VA.Boolean=Cye;var $l={};Object.defineProperty($l,"__esModule",{value:!0}),$l.FunctionOrdering=$l.FunctionOrderBy=void 0;const yO=oe,zq=Ge,Tye=Ic;class bye extends zq.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.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const n=this.field.getExpression(e);return(0,yO.expressionIsAggregate)(n.expressionType)||((0,yO.expressionIsScalar)(n.expressionType)?(!(this.field instanceof Tye.ExprIdReference)||n.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:n.value,dir:this.dir}}getAggregateOrderBy(e,n){if(this.field){const r=this.field.getExpression(e);return(0,yO.expressionIsScalar)(r.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),n||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:r.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}$l.FunctionOrderBy=bye;class Rye extends zq.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))}}$l.FunctionOrdering=Rye;var YA={};Object.defineProperty(YA,"__esModule",{value:!0}),YA.ExprAddSub=void 0;const Oye=pd;class Dye extends Oye.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}YA.ExprAddSub=Dye;var pa={},ht={},C1={};Object.defineProperty(C1,"__esModule",{value:!0}),C1.ReferenceField=void 0;const Qq=wr;class Nye extends Qq.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){var n;if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.list.map(u=>u.name),s=((n=r.found)===null||n===void 0?void 0:n.refType)==="parameter"?{type:r.found.typeDesc().dataType,name:i[0],e:{node:"parameter",path:i}}:{type:"fieldref",path:i};this.queryFieldDef=s;const o=this.referenceTo;if(o instanceof Qq.SpaceField){const u=o.constructorFieldDef();if(u){const a=this.fieldRef.note;if(u.annotation||a){const l=a||{};u.annotation&&(l.inherits=u.annotation),this.queryFieldDef.annotation=l}}}}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"}}}C1.ReferenceField=Nye;var In={};Object.defineProperty(In,"__esModule",{value:!0}),In.typecheckGroupBy=In.typecheckAggregate=In.typecheckCalculate=In.typecheckDeclare=In.typecheckMeasure=In.typecheckDimension=In.typecheckIndex=In.typecheckProject=void 0;const En=Ai;function wye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="select-of-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="select-of-analytic";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}In.typecheckProject=wye;function Fye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a view",r="index-of-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="an analytic",r="index-of-analytic";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(r,`Cannot use ${n} field in an index operation`)}}In.typecheckIndex=Fye;function Lye(t,e){if(!(0,En.expressionIsScalar)(t.expressionType))if((0,En.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,En.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}In.typecheckDimension=Lye;function Iye(t,e){if(!(0,En.expressionIsAggregate)(t.expressionType))if((0,En.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,En.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}In.typecheckMeasure=Iye;function $ye(t,e){t.dataType==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,En.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}In.typecheckDeclare=$ye;function Bye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsAnalytic)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="calculate-of-view";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="calculate-of-aggregate";else if((0,En.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}In.typecheckCalculate=Bye;function kye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsAggregate)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="aggregate-of-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="aggregate-of-analytic";else if((0,En.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(i,`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}In.typecheckAggregate=kye;function Pye(t,e){if(t.dataType==="turtle"||!(0,En.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.dataType==="turtle")n="a nest",r="a view",i="group-by-view";else if((0,En.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="group-by-analytic";else if((0,En.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}In.typecheckGroupBy=Pye,Object.defineProperty(ht,"__esModule",{value:!0}),ht.FieldReferences=ht.WildcardFieldReference=ht.ViewOrScalarFieldReference=ht.DimensionFieldReference=ht.MeasureFieldReference=ht.DeclareFieldReference=ht.ProjectFieldReference=ht.GroupByFieldReference=ht.AggregateFieldReference=ht.IndexFieldReference=ht.CalculateFieldReference=ht.ParameterFieldReference=ht.PartitionByFieldReference=ht.ExpressionFieldReference=ht.AcceptExceptFieldReference=ht.FieldReference=void 0;const Mye=C1,jye=Ki,Gq=Ge,Wq=Nr,Bl=In;class bi extends Gq.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=Wq.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.logError("output-name-conflict",`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new Mye.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}}ht.FieldReference=bi;class Uye extends bi{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}ht.AcceptExceptFieldReference=Uye;class qye extends bi{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}ht.ExpressionFieldReference=qye;class Hye extends bi{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}ht.PartitionByFieldReference=Hye;class zye extends bi{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}ht.ParameterFieldReference=zye;class Qye extends bi{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Bl.typecheckCalculate)(e,this)}}ht.CalculateFieldReference=Qye;class EO extends bi{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Bl.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return EO.indexOutputName(this.path)}}ht.IndexFieldReference=EO;class Gye extends bi{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Bl.typecheckAggregate)(e,this)}}ht.AggregateFieldReference=Gye;class Wye extends bi{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Bl.typecheckGroupBy)(e,this)}}ht.GroupByFieldReference=Wye;class Vye extends bi{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Bl.typecheckProject)(e,this)}}ht.ProjectFieldReference=Vye;class Yye extends bi{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Bl.typecheckDeclare)(e,this)}}ht.DeclareFieldReference=Yye;class Jye extends bi{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Bl.typecheckMeasure)(e,this)}}ht.MeasureFieldReference=Jye;class Xye extends bi{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Bl.typecheckDimension)(e,this)}}ht.DimensionFieldReference=Xye;class Kye extends bi{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}ht.ViewOrScalarFieldReference=Kye;class Zye extends Gq.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=Wq.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}.*`:"*"}}ht.WildcardFieldReference=Zye;class eEe extends jye.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}ht.FieldReferences=eEe,Object.defineProperty(pa,"__esModule",{value:!0}),pa.ExprAggregateFunction=void 0;const T1=oe,tEe=Rt,nEe=Ci,Vq=hr,rEe=Jt,iEe=ht,sEe=st,oEe=wr,uEe=Ic;class aEe extends sEe.ExpressionDef{constructor(e,n,r){super(),this.func=e,this.legalChildTypes=[rEe.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,i;const s=e.isQueryFieldSpace()?e.inputSpace():e;let o=this.expr,u=(n=this.expr)===null||n===void 0?void 0:n.getExpression(s),a=(r=this.source)===null||r===void 0?void 0:r.path,l=[];if(this.source){const f=this.source.getField(s);if(f.found){l=f.joinPath;const x=f.found,h=x.typeDesc();if(!(x instanceof Vq.StructSpaceField))if((0,T1.isAtomicFieldType)(h.dataType)){o=this.source,u={dataType:h.dataType,expressionType:h.expressionType,value:h.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:h.evalSpace},a=this.source.path;const p=this.getJoinUsage(s);(p.length===1||p.length>1&&p.slice(1).every(g=>lEe(g,p[0])))&&(a=p[0].map(g=>g.name),l=p[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${h.dataType}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(u===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,T1.expressionIsAggregate)(u.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(u.dataType==="error")){const f=this.getJoinUsage(s),x=this.source!==void 0||this.explicitSource;if(o&&!(!this.source&&f.every(p=>p.length===0))&&!this.isSymmetricFunction()){const p=vO(l,f),m=SO(this.elementType,p),g=x?m==null?void 0:m.message:"Join path is required for this calculation";if(g){const y=cEe(g,f,o,this.elementType),E=(i=m==null?void 0:m.code)!==null&&i!==void 0?i:"bad-join-usage";m?this.logError(E,y):this.logWarning(E,y)}}}if(this.typeCheck(this.expr||this,{...u,expressionType:"scalar"})){const f={node:"aggregate",function:this.func,e:u.value};return a&&a.length>0&&(f.structPath=a),{dataType:this.returns(u),expressionType:"aggregate",value:f,evalSpace:"output"}}return(0,nEe.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const n=[];if(this.source&&this.source.getField(e).found){const i={node:"field",path:this.source.path};n.push(...AO(e,i))}if(this.expr){const r=this.expr.getExpression(e).value;n.push(...AO(e,r))}return n}}pa.ExprAggregateFunction=aEe;function lEe(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 AO(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 Vq.StructSpaceField&&u.length>0){const l=r(a.fieldSpace,u);return{...l,joinPath:[{...a.joinPathElement,name:o},...l.joinPath]}}else if(a instanceof oEe.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,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const i of(0,tEe.exprWalk)(e))if(i.node==="field"){const s=r(t,i.path),o=s.def;if((0,T1.isAtomic)(o)&&!(0,T1.isJoined)(o))if((0,T1.hasExpression)(o)){const u=AO(s.fs,o.e);n.push(...u.map(a=>[...s.joinPath,...a]))}else n.push(s.joinPath)}else if(i.node==="source-reference")if(i.path){const s=r(t,i.path);n.push(s.joinPath)}else n.push([]);return n}function vO(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 SO(t,e){for(const n of e)for(const r of n){if(r.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${r.name}\``};if(r.joinElementType==="array"&&!r.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${r.name}\``};if(r.joinType==="many"&&!r.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${r.name}\``}}}function cEe(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=vO(i,e),o=SO(r,s),u=i.slice().reverse().findIndex(p=>p.joinType==="many"||p.joinType==="cross"),a=u===-1?0:i.length-u,l=i.slice(0,a),c=vO(l,e),f=SO(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 iEe.FieldReference?`${n.refString}.${r}()`:n instanceof uEe.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 JA={};Object.defineProperty(JA,"__esModule",{value:!0}),JA.ExprAlternationTree=void 0;const XA=oe,gd=st,fEe=uo;function _O(t){const e=t.atExpr();switch(e.atNodeType()){case gd.ATNodeType.And:case gd.ATNodeType.Partial:return;case gd.ATNodeType.Or:{if(e instanceof Yq){const n=_O(e.left);if(n){const r=_O(e.right);if(r)return[...n,...r]}}return}default:return e.granular()?void 0:[e]}}class Yq extends gd.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="alternation",this.elementType=`${n}alternation${n}`}equalityList(){return this.inList===void 0&&(this.inList=_O(this)||[]),this.inList}apply(e,n,r,i){if((0,fEe.isEquality)(n)){const u=this.equalityList();if(u.length>0&&(n==="="||n==="!=")){const a=r.getExpression(e),l=u.map(x=>x.getExpression(e));let{evalSpace:c,expressionType:f}=a;for(const x of l)c=(0,XA.mergeEvalSpaces)(c,x.evalSpace),f=(0,XA.maxExpressionType)(f,x.expressionType);return{dataType:"boolean",evalSpace:c,expressionType:f,value:{node:"in",not:n==="!=",kids:{e:a.value,oneOf:l.map(x=>x.value)}}}}u.length===0&&i&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${n} operator`)}const s=this.left.apply(e,n,r),o=this.right.apply(e,n,r);return{dataType:"boolean",expressionType:(0,XA.maxExpressionType)(s.expressionType,o.expressionType),evalSpace:(0,XA.mergeEvalSpaces)(s.evalSpace,o.evalSpace),value:{node:this.op==="&"?"and":"or",kids:{left:s.value,right:o.value}}}}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?gd.ATNodeType.Or:gd.ATNodeType.And}}JA.ExprAlternationTree=Yq;var md={};Object.defineProperty(md,"__esModule",{value:!0}),md.ExprAsymmetric=void 0;const xEe=pa;class dEe extends xEe.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}`}}}}md.ExprAsymmetric=dEe;var KA={};Object.defineProperty(KA,"__esModule",{value:!0}),KA.ExprAvg=void 0;const hEe=md;class pEe extends hEe.ExprAsymmetric{constructor(e,n,r){super("avg",e,n,r),this.has({source:n})}}KA.ExprAvg=pEe;var ZA={};Object.defineProperty(ZA,"__esModule",{value:!0}),ZA.ExprCast=void 0;const gEe=Jn,mEe=st;class yEe extends mEe.ExpressionDef{constructor(e,n,r=!1){super({expr:e}),this.expr=e,this.castType=n,this.safe=r,this.elementType="cast"}getExpression(e){const n=this.expr.getExpression(e);let r="error";if(typeof this.castType=="string")r=this.castType;else{const i=e.dialectObj();i&&(i.validateTypeName(this.castType.raw)?r=i.sqlTypeToMalloyType(this.castType.raw).type:this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${i.name} dialect`),this.safe&&!i.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return{dataType:r,expressionType:n.expressionType,value:(0,gEe.castTo)(this.castType,n.value,n.dataType,this.safe),evalSpace:n.evalSpace}}}ZA.ExprCast=yEe;var ev={};Object.defineProperty(ev,"__esModule",{value:!0}),ev.ExprCoalesce=void 0;const Jq=Ai,Xq=Jt,EEe=st;class AEe extends EEe.ExpressionDef{constructor(e,n){super({expr:e,altExpr:n}),this.expr=e,this.altExpr=n,this.elementType="coalesce expression",this.legalChildTypes=Xq.FT.anyAtomicT}getExpression(e){const n=this.expr.getExpression(e),r=this.altExpr.getExpression(e);return n.dataType==="null"?r:(Xq.FT.typeEq(n,r)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${n.dataType}, ${r.dataType})`),{...r,dataType:n.dataType==="error"?r.dataType:n.dataType,expressionType:(0,Jq.maxExpressionType)(n.expressionType,r.expressionType),value:{node:"coalesce",kids:{left:n.value,right:r.value}},evalSpace:(0,Jq.mergeEvalSpaces)(n.evalSpace,r.evalSpace)})}}ev.ExprCoalesce=AEe;var tv={};Object.defineProperty(tv,"__esModule",{value:!0}),tv.ExprCount=void 0;const vEe=pa;class SEe extends vEe.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={node:"aggregate",function:"count",e:{node:""}};return this.source&&(n.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:n,evalSpace:"output"}}}tv.ExprCount=SEe;var nv={};Object.defineProperty(nv,"__esModule",{value:!0}),nv.ExprCountDistinct=void 0;const rv=Jt,_Ee=pa;class CEe extends _Ee.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[rv.FT.numberT,rv.FT.stringT,rv.FT.dateT,rv.FT.timestampT]}}nv.ExprCountDistinct=CEe;var iv={},kl={};Object.defineProperty(kl,"__esModule",{value:!0}),kl.Limit=void 0;const TEe=Ge,bEe=mn;class REe extends TEe.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=bEe.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}kl.Limit=REe;var yd={};Object.defineProperty(yd,"__esModule",{value:!0}),yd.PartitionBy=void 0;const OEe=Ge;class DEe extends OEe.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}yd.PartitionBy=DEe;var b1={},Pl={};Object.defineProperty(Pl,"__esModule",{value:!0}),Pl.FieldName=void 0;const NEe=Ge;class wEe extends NEe.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])}}Pl.FieldName=wEe,Object.defineProperty(b1,"__esModule",{value:!0}),b1.ExprFunc=void 0;const es=oe,FEe=Ci,LEe=id,IEe=st,$Ee=Pl,Kq=Rt;class BEe extends IEe.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)}findFunctionDef(e){var n,r,i;const s=this.name.toLowerCase(),o=e?(r=(n=this.getDialectNamespace(e))===null||n===void 0?void 0:n.getEntry(s))===null||r===void 0?void 0:r.entry:void 0,u=o??((i=this.modelEntry(s))===null||i===void 0?void 0:i.entry);return u===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):u.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${u.type}) is not a function`),{found:void 0,error:"called non function"}):(u.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${u.name}' instead`),{found:u,error:void 0})}getPropsExpression(e,n){var r,i,s,o;const u=this.args.map(R=>R.getExpression(e));if(this.isRaw){let R="scalar",O;const I=[`${this.name}(`];for(const z of u)R=(0,es.maxExpressionType)(R,z.expressionType),O?I.push(","):O=z.dataType,I.push(z.value);return I.push(")"),{dataType:(i=(r=this.rawType)!==null&&r!==void 0?r:O)!==null&&i!==void 0?i:"number",expressionType:R,value:(0,Kq.composeSQLExpr)(I),evalSpace:(0,es.mergeEvalSpaces)(...u.map(z=>z.evalSpace))}}const a=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:l,error:c}=this.findFunctionDef(a);if(l===void 0)return(0,FEe.errorFor)(c);let f,x=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const R=this.source.getField(e).found;if(R){const O=R.typeDesc();if((0,es.isAtomicFieldType)(O.dataType))f={dataType:O.dataType,expressionType:O.expressionType,value:{node:"field",path:this.source.path},evalSpace:O.evalSpace},x=this.source.path.slice(0,-1);else if(!(R instanceof LEe.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${O.dataType}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const h=[...f?[f]:[],...u],p=kEe(l,h);if(p===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${h.map(R=>R.dataType).join(", ")})`);const{overload:m,expressionTypeErrors:g,evalSpaceErrors:y,nullabilityErrors:E}=p;for(const R of g){const O=R.argIndex-(f?1:0),I=(0,es.expressionIsScalar)(R.maxExpressionType)?"scalar":"scalar or aggregate";this.args[O].logError("invalid-function-argument-expression-type",`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must be ${I}, but received ${R.actualExpressionType}`)}for(const R of y){const O=R.argIndex-(f?1:0),I=R.maxEvalSpace==="literal"?"literal":R.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[O].logError("invalid-function-argument-evaluation-space",`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must be ${I}, but received ${R.actualEvalSpace}`)}for(const R of E){const O=R.argIndex-(f?1:0);this.args[O].logError("literal-null-function-argument",`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must not be a literal null`)}const A=m.returnType,v=(0,es.maxOfExpressionTypes)([A.expressionType,...h.map(R=>R.expressionType)]);if(!(0,es.expressionIsAggregate)(m.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${h.map(R=>R.dataType).join(", ")}) with source`);const _={node:"function_call",overload:m,name:this.name,kids:{args:h.map(R=>R.value)},expressionType:v,structPath:x};let S=_;if(n!=null&&n.orderBys&&n.orderBys.length>0){const R=(0,es.expressionIsAnalytic)(m.returnType.expressionType);if(R||this.inExperiment("aggregate_order_by",!0)||n.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),m.supportsOrderBy||R){const O=m.supportsOrderBy!=="only_default",I=n.orderBys.flatMap(j=>R?j.getAnalyticOrderBy(e):j.getAggregateOrderBy(e,O));_.kids.orderBy=I}else n.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((n==null?void 0:n.limit)!==void 0&&(m.supportsLimit?_.limit=n.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),n!=null&&n.partitionBys&&n.partitionBys.length>0){const R=[];for(const O of n.partitionBys)for(const I of O.partitionFields){const j=I.getField(e);j.found===void 0?I.logError("partition-by-not-found",`${I.refString} is not defined`):(0,es.expressionIsAnalytic)(j.found.typeDesc().expressionType)||(0,es.expressionIsUngroupedAggregate)(j.found.typeDesc().expressionType)?I.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):R.push(I.nameString)}_.partitionBy=R}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);const R=h[0].value;if(R.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${l.name}\``);else{const O=R.literal,I=PEe(O),j=I.filter(Y=>Y.type==="interpolation"&&Y.name.includes(".")).map(Y=>Y.type==="interpolation"?`\${${Y.name}}`:`\${${Y.value}}`);if(j.length>0){const Y=j.length===1?`'.' paths are not yet supported in sql interpolations, found ${j.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${j.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Y)}const z=[];for(const Y of I)if(Y.type==="string")z.push(Y.value);else if(Y.name==="TABLE")z.push({node:"source-reference"});else{const Q=new $Ee.FieldName(Y.name);this.has({name:Q});const se=e.lookup([Q]);if(se.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${se.error.message}`);se.found.refType==="parameter"?z.push({node:"parameter",path:[Y.name]}):z.push({node:"field",path:[Y.name]})}S=(0,Kq.composeSQLExpr)(z)}}if(A.dataType==="any")return this.loggedErrorExpr("function-returns-any",`Invalid return type ${A.dataType} for function '${this.name}'`);const C=(0,es.mergeEvalSpaces)(...h.map(R=>R.evalSpace)),T=C==="constant"?"constant":(0,es.expressionIsScalar)(v)?C:"output";return{dataType:A.dataType,expressionType:v,value:S,evalSpace:T}}}b1.ExprFunc=BEe;function kEe(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,es.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")||(0,es.expressionIsAnalytic)(n.returnType.expressionType)&&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 PEe(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(iv,"__esModule",{value:!0}),iv.ExprProps=void 0;const MEe=oe,jEe=Ci,UEe=Jt,qEe=$l,HEe=kl,zEe=yd,QEe=st,GEe=b1;class WEe extends QEe.ExpressionDef{constructor(e,n){super({expr:e,statements:n}),this.expr=e,this.statements=n,this.elementType="expression with props",this.legalChildTypes=UEe.FT.anyAtomicT}getFilteredExpression(e,n,r){if(r.length>0){if(!this.expr.supportsWhere(n))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),n;const i=[];for(const s of r){const o=s.getFilterList(e);if(o.find(u=>(0,MEe.expressionIsCalculation)(u.expressionType)))return s.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),n;i.push(...o)}return this.typeCheck(this.expr,{...n,expressionType:"scalar"})?{...n,value:{node:"filteredExpr",kids:{e:n.value,filterList:i}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${n.expressionType}' data`),(0,jEe.errorFor)("cannot filter type"))}return n}getExpression(e){const n=[];let r;const i=[],s=[];for(const u of this.statements)u instanceof zEe.PartitionBy?this.expr.canSupportPartitionBy()?n.push(u):u.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):u instanceof HEe.Limit?r?u.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?r=u:u.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):u instanceof qEe.FunctionOrdering?this.expr.canSupportOrderBy()?i.push(u):u.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):s.push(u);const o=this.expr instanceof GEe.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:n,limit:r,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}}iv.ExprProps=WEe;var sv={};Object.defineProperty(sv,"__esModule",{value:!0}),sv.ExprLogicalOp=void 0;const VEe=S1,Zq=Jt;class YEe extends VEe.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[Zq.FT.boolT,Zq.FT.aggregateBoolT]}}sv.ExprLogicalOp=YEe;var ov={};Object.defineProperty(ov,"__esModule",{value:!0}),ov.ExprMax=void 0;const uv=Jt,JEe=pa;class XEe extends JEe.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[uv.FT.numberT,uv.FT.stringT,uv.FT.dateT,uv.FT.timestampT]}returns(e){return e.dataType}}ov.ExprMax=XEe;var av={};Object.defineProperty(av,"__esModule",{value:!0}),av.ExprMin=void 0;const lv=Jt,KEe=pa;class ZEe extends KEe.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[lv.FT.numberT,lv.FT.stringT,lv.FT.dateT,lv.FT.timestampT]}returns(e){return e.dataType}}av.ExprMin=ZEe;var cv={};Object.defineProperty(cv,"__esModule",{value:!0}),cv.ExprMinus=void 0;const eAe=Ci,eH=Jt,tAe=st;class nAe extends tAe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[eH.FT.numberT]}getExpression(e){const n=this.expr.getExpression(e);return eH.FT.typeIn(n,this.legalChildTypes)?{...n,dataType:"number",value:{node:"unary-",e:n.value}}:(0,eAe.errorFor)("negate requires number")}}cv.ExprMinus=nAe;var fv={};Object.defineProperty(fv,"__esModule",{value:!0}),fv.ExprMulDiv=void 0;const rAe=pd;class iAe extends rAe.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}fv.ExprMulDiv=iAe;var xv={},R1={};Object.defineProperty(R1,"__esModule",{value:!0}),R1.Unary=void 0;const sAe=st;class oAe extends sAe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}R1.Unary=oAe,Object.defineProperty(xv,"__esModule",{value:!0}),xv.ExprNot=void 0;const tH=Jt,uAe=R1;class aAe extends uAe.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[tH.FT.boolT,tH.FT.nullT]}getExpression(e){const n=this.expr.getExpression(e),r=this.typeCheck(this.expr,n);return{...n,dataType:"boolean",value:{node:"not",e:r?n.value:{node:"false"}}}}}xv.ExprNot=aAe;var dv={};Object.defineProperty(dv,"__esModule",{value:!0}),dv.ExprNow=void 0;const lAe=st;class cAe extends lAe.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now"}}}}dv.ExprNow=cAe;var hv={};Object.defineProperty(hv,"__esModule",{value:!0}),hv.ExprNULL=void 0;const fAe=st;class xAe extends fAe.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:{node:"null"},expressionType:"scalar",evalSpace:"literal"}}}hv.ExprNULL=xAe;var pv={};Object.defineProperty(pv,"__esModule",{value:!0}),pv.ExprNumber=void 0;const dAe=Jt,hAe=st;class pAe extends hAe.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...dAe.FT.numberT,evalSpace:"literal",value:{node:"numberLiteral",literal:this.n}}}}pv.ExprNumber=pAe;var gv={};Object.defineProperty(gv,"__esModule",{value:!0}),gv.ExprParens=void 0;const CO=st;class gAe extends CO.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:{node:"()",e:n.value}}}apply(e,n,r,i){return this.expr.atNodeType()===CO.ATNodeType.Or?this.expr.apply(e,n,r,i):(0,CO.applyBinary)(e,r,n,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}gv.ExprParens=gAe;var mv={};Object.defineProperty(mv,"__esModule",{value:!0}),mv.ExprRegEx=void 0;const mAe=st;class yAe extends mAe.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:{node:"regexpLiteral",literal:this.regex},evalSpace:"literal"}}}mv.ExprRegEx=yAe;var yv={};Object.defineProperty(yv,"__esModule",{value:!0}),yv.ExprString=void 0;const EAe=st,AAe=Jt;class vAe extends EAe.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...AAe.FT.stringT,value:{node:"stringLiteral",literal:this.value},evalSpace:"literal"}}}yv.ExprString=vAe;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.ExprSum=void 0;const SAe=md;class _Ae extends SAe.ExprAsymmetric{constructor(e,n,r){super("sum",e,n,r),this.has({source:n})}}Ev.ExprSum=_Ae;var Av={};Object.defineProperty(Av,"__esModule",{value:!0}),Av.ExprTimeExtract=void 0;const kc=oe,nH=Ci,TO=st,CAe=Il;class O1 extends TO.ExpressionDef{static extractor(e){const n=O1.pluralMap[e];if(n)return n;if((0,kc.isExtractUnit)(e))return e}constructor(e,n){super({args:n}),this.extractText=e,this.args=n,this.elementType="timeExtract"}getExpression(e){const n=O1.extractor(this.extractText);if(n){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${n} requires one argument`);const r=this.args[0];if(r instanceof CAe.Range){let i=r.first.getExpression(e),s=r.last.getExpression(e);const o=(0,kc.maxExpressionType)(i.expressionType,s.expressionType),u=(0,kc.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:u,value:(0,nH.errorFor)("extract from error").value};if(!(0,kc.isTemporalField)(i.dataType))return r.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${n} from '${i.dataType}'`);if(!(0,kc.isTemporalField)(s.dataType))return r.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${n} from '${s.dataType}'`);let a=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(a="timestamp",i.dataType==="date"){const c=(0,TO.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{const c=(0,TO.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return r.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${i.dataType} to ${s.dataType}`)}return["week","month","quarter","year"].includes(n)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${n}'`):(0,kc.isTimestampUnit)(n)?{dataType:"number",expressionType:o,evalSpace:u,value:{node:"timeDiff",units:n,kids:{left:{...i.value,dataType:a},right:{...s.value,dataType:a}}}}:this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${n} from a range`)}else{const i=r.getExpression(e);return(0,kc.isTemporalField)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:{node:"extract",e:{...i.value,dataType:i.dataType},units:n}}:(i.dataType!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,nH.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}Av.ExprTimeExtract=O1,O1.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var vv={},ao={},Sv={};Object.defineProperty(Sv,"__esModule",{value:!0}),Sv.QueryInputSpace=void 0;const TAe=Ti,bAe=rd;class RAe extends bAe.RefinedSpace{constructor(e,n){super(e),this.queryOutput=n,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof TAe.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}}Sv.QueryInputSpace=RAe;var OAe=D&&D.__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]}),DAe=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),NAe=D&&D.__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)&&OAe(e,t,n);return DAe(e,t),e};Object.defineProperty(ao,"__esModule",{value:!0}),ao.ReduceFieldSpace=ao.QuerySpace=ao.QueryOperationSpace=void 0;const _v=NAe(oe),bO=Nl,wAe=Pl,FAe=wr,LAe=ht,IAe=rd,$Ae=d1,BAe=hr,kAe=Sv;class rH extends IAe.RefinedSpace{constructor(e,n,r,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=r,this.astEl=i,this.expandedWild={},this.exprSpace=new kAe.QueryInputSpace(e.structDef(),this),n&&this.addRefineFromFields(n)}logError(e,n,r){return this.astEl&&this.astEl.logError(e,n,r),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 BAe.StructSpaceField)r=l.fieldSpace;else{u.logError("invalid-wildcard-source",`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.logError("wildcard-source-not-defined",`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries())if(!e.except.has(u)&&a.refType!=="parameter")if(this.entry(u)){const l=(n=this.expandedWild[u])===null||n===void 0?void 0:n.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{const l=a.typeDesc();_v.isAtomicFieldType(l.dataType)&&_v.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)}}ao.QueryOperationSpace=rH;class iH extends rH{addRefineFromFields(e){var n;if(_v.isQuerySegment(e))for(const r of e.queryFields)if(r.type==="fieldref"){const i=this.exprSpace.lookup(r.path.map(s=>new wAe.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 $Ae.ColumnSpaceField(r))}pushFields(...e){for(const n of e)n instanceof LAe.WildcardFieldReference?this.addWild(n):super.pushFields(n)}canContain(e){return!0}queryFieldDefs(){const e=[];for(const[n,r]of this.entries())if(r instanceof FAe.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)&&!MAe(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){const n=this.getPipeSegment(e);if(_v.isQuerySegment(n))return n;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","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,bO.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,bO.nameFromDef)(u)===s);o&&r.push(o)}n.extendSource=(0,bO.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}}ao.QuerySpace=iH;class PAe extends iH{constructor(){super(...arguments),this.segmentType="reduce"}}ao.ReduceFieldSpace=PAe;function MAe(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}Object.defineProperty(vv,"__esModule",{value:!0}),vv.ExprUngroup=void 0;const sH=oe,jAe=ao,UAe=Jt,qAe=st;class HAe extends qAe.ExpressionDef{constructor(e,n,r){super({expr:n,fields:r}),this.control=e,this.expr=n,this.fields=r,this.legalChildTypes=UAe.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){const n=this.expr.getExpression(e);if(!(0,sH.expressionIsAggregate)(n.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,sH.expressionIsUngroupedAggregate)(n.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const r={node: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 jAe.QuerySpace){u=u.nestParent;continue}break}if(a){const l=s?"exclude()":"all()";o.logError("ungroup-field-not-in-output",`${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.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}vv.ExprUngroup=HAe;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.ForRange=void 0;const oH=Ai,uH=Ci,aH=Jt,Tv=Jn,zAe=st,bv=hd,lH=Il;class QAe extends zAe.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=[aH.FT.timestampT,aH.FT.dateT]}apply(e,n,r){const i=this.from.getExpression(e),s=r.getExpression(e);if(!this.typeCheck(r,s))return(0,uH.errorFor)("no time for range");const o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,oH.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,oH.maxExpressionType)(i.expressionType,s.expressionType),value:(0,uH.errorFor)("for not number").value};const u=this.timeframe.text;let a=(0,Tv.resolution)(u);if(i.dataType==="timestamp"&&(a="timestamp"),s.dataType==="date"&&a==="date"){const p=this.from,m=(0,Tv.timeOffset)("date",i.value,"+",o.value,u),g=new bv.ExprTime("date",m);return new lH.Range(p,g).apply(e,n,r)}const l=bv.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,Tv.castDateToTimestamp)(f),c=new bv.ExprTime("timestamp",f,i.expressionType)}const x=(0,Tv.timeOffset)("timestamp",f,"+",o.value,u),h=new bv.ExprTime("timestamp",x,i.expressionType);return new lH.Range(c,h).apply(e,n,l)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Cv.ForRange=QAe;var Xn={},Ri={};Object.defineProperty(Ri,"__esModule",{value:!0});class Pc extends Error{}class GAe extends Pc{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class WAe extends Pc{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class VAe extends Pc{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class D1 extends Pc{}class cH extends Pc{constructor(e){super(`Invalid unit ${e}`)}}class Rs extends Pc{}class Ml extends Pc{constructor(){super("Zone is an abstract class")}}const Pe="numeric",lo="short",ts="long",RO={year:Pe,month:Pe,day:Pe},fH={year:Pe,month:lo,day:Pe},YAe={year:Pe,month:lo,day:Pe,weekday:lo},xH={year:Pe,month:ts,day:Pe},dH={year:Pe,month:ts,day:Pe,weekday:ts},hH={hour:Pe,minute:Pe},pH={hour:Pe,minute:Pe,second:Pe},gH={hour:Pe,minute:Pe,second:Pe,timeZoneName:lo},mH={hour:Pe,minute:Pe,second:Pe,timeZoneName:ts},yH={hour:Pe,minute:Pe,hourCycle:"h23"},EH={hour:Pe,minute:Pe,second:Pe,hourCycle:"h23"},AH={hour:Pe,minute:Pe,second:Pe,hourCycle:"h23",timeZoneName:lo},vH={hour:Pe,minute:Pe,second:Pe,hourCycle:"h23",timeZoneName:ts},SH={year:Pe,month:Pe,day:Pe,hour:Pe,minute:Pe},_H={year:Pe,month:Pe,day:Pe,hour:Pe,minute:Pe,second:Pe},CH={year:Pe,month:lo,day:Pe,hour:Pe,minute:Pe},TH={year:Pe,month:lo,day:Pe,hour:Pe,minute:Pe,second:Pe},JAe={year:Pe,month:lo,day:Pe,weekday:lo,hour:Pe,minute:Pe},bH={year:Pe,month:ts,day:Pe,hour:Pe,minute:Pe,timeZoneName:lo},RH={year:Pe,month:ts,day:Pe,hour:Pe,minute:Pe,second:Pe,timeZoneName:lo},OH={year:Pe,month:ts,day:Pe,weekday:ts,hour:Pe,minute:Pe,timeZoneName:ts},DH={year:Pe,month:ts,day:Pe,weekday:ts,hour:Pe,minute:Pe,second:Pe,timeZoneName:ts};function vt(t){return typeof t>"u"}function Mc(t){return typeof t=="number"}function Rv(t){return typeof t=="number"&&t%1===0}function XAe(t){return typeof t=="string"}function KAe(t){return Object.prototype.toString.call(t)==="[object Date]"}function NH(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function ZAe(t){return Array.isArray(t)?t:[t]}function wH(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 eve(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function Ed(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ga(t,e,n){return Rv(t)&&t>=e&&t<=n}function tve(t,e){return t-e*Math.floor(t/e)}function On(t,e=2){const n=t<0;let r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function jl(t){if(!(vt(t)||t===null||t===""))return parseInt(t,10)}function jc(t){if(!(vt(t)||t===null||t===""))return parseFloat(t)}function OO(t){if(!(vt(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function DO(t,e,n=!1){const r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function N1(t){return t%4===0&&(t%100!==0||t%400===0)}function w1(t){return N1(t)?366:365}function Ov(t,e){const n=tve(e-1,12)+1,r=t+(e-n)/12;return n===2?N1(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function NO(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 Dv(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 wO(t){return t>99?t:t>60?1900+t:2e3+t}function FH(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 Nv(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 LH(t){const e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new Rs(`Invalid unit value ${t}`);return e}function wv(t,e){const n={};for(const r in t)if(Ed(t,r)){const i=t[r];if(i==null)continue;n[e(r)]=LH(i)}return n}function F1(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}${On(n,2)}:${On(r,2)}`;case"narrow":return`${i}${n}${r>0?`:${r}`:""}`;case"techie":return`${i}${On(n,2)}${On(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Fv(t){return eve(t,["hour","minute","second","millisecond"])}const IH=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,nve=["January","February","March","April","May","June","July","August","September","October","November","December"],$H=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],rve=["J","F","M","A","M","J","J","A","S","O","N","D"];function BH(t){switch(t){case"narrow":return[...rve];case"short":return[...$H];case"long":return[...nve];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 kH=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],PH=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],ive=["M","T","W","T","F","S","S"];function MH(t){switch(t){case"narrow":return[...ive];case"short":return[...PH];case"long":return[...kH];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const jH=["AM","PM"],sve=["Before Christ","Anno Domini"],ove=["BC","AD"],uve=["B","A"];function UH(t){switch(t){case"narrow":return[...uve];case"short":return[...ove];case"long":return[...sve];default:return null}}function ave(t){return jH[t.hour<12?0:1]}function lve(t,e){return MH(e)[t.weekday-1]}function cve(t,e){return BH(e)[t.month-1]}function fve(t,e){return UH(e)[t.year<0?0:1]}function xve(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 qH(t,e){let n="";for(const r of t)r.literal?n+=r.val:n+=e(r.val);return n}const dve={D:RO,DD:fH,DDD:xH,DDDD:dH,t:hH,tt:pH,ttt:gH,tttt:mH,T:yH,TT:EH,TTT:AH,TTTT:vH,f:SH,ff:CH,fff:bH,ffff:OH,F:_H,FF:TH,FFF:RH,FFFF:DH};class Oi{static create(e,n={}){return new Oi(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 dve[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 On(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?ave(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),a=(h,p)=>r?cve(e,h):s(p?{month:h}:{month:h,day:"numeric"},"month"),l=(h,p)=>r?lve(e,h):s(p?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),c=h=>{const p=Oi.macroTokenToFormatOpts(h);return p?this.formatWithSystemDefault(e,p):h},f=h=>r?fve(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 qH(Oi.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=Oi.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 qH(s,i(u))}}class co{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}let Ad=class{get type(){throw new Ml}get name(){throw new Ml}get ianaName(){return this.name}get isUniversal(){throw new Ml}offsetName(e,n){throw new Ml}formatOffset(e,n){throw new Ml}offset(e){throw new Ml}equals(e){throw new Ml}get isValid(){throw new Ml}},FO=null;class Lv extends Ad{static get instance(){return FO===null&&(FO=new Lv),FO}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return FH(e,n,r)}formatOffset(e,n){return F1(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}let Iv={};function hve(t){return Iv[t]||(Iv[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"})),Iv[t]}const pve={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function gve(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 mve(t,e){const n=t.formatToParts(e),r=[];for(let i=0;i<n.length;i++){const{type:s,value:o}=n[i],u=pve[s];s==="era"?r[u]=o:vt(u)||(r[u]=parseInt(o,10))}return r}let $v={};class au extends Ad{static create(e){return $v[e]||($v[e]=new au(e)),$v[e]}static resetCache(){$v={},Iv={}}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=au.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return FH(e,n,r,this.name)}formatOffset(e,n){return F1(this.offset(e),n)}offset(e){const n=new Date(e);if(isNaN(n))return NaN;const r=hve(this.name);let[i,s,o,u,a,l,c]=r.formatToParts?mve(r,n):gve(r,n);u==="BC"&&(i=-Math.abs(i)+1);const x=NO({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 LO=null;class Lr extends Ad{static get utcInstance(){return LO===null&&(LO=new Lr(0)),LO}static instance(e){return e===0?Lr.utcInstance:new Lr(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Lr(Nv(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${F1(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${F1(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return F1(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 HH extends Ad{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 Ul(t,e){if(vt(t)||t===null)return e;if(t instanceof Ad)return t;if(XAe(t)){const n=t.toLowerCase();return n==="local"||n==="system"?e:n==="utc"||n==="gmt"?Lr.utcInstance:Lr.parseSpecifier(n)||au.create(t)}else return Mc(t)?Lr.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new HH(t)}let zH=()=>Date.now(),QH="system",GH=null,WH=null,VH=null,YH;class Dn{static get now(){return zH}static set now(e){zH=e}static set defaultZone(e){QH=e}static get defaultZone(){return Ul(QH,Lv.instance)}static get defaultLocale(){return GH}static set defaultLocale(e){GH=e}static get defaultNumberingSystem(){return WH}static set defaultNumberingSystem(e){WH=e}static get defaultOutputCalendar(){return VH}static set defaultOutputCalendar(e){VH=e}static get throwOnInvalid(){return YH}static set throwOnInvalid(e){YH=e}static resetCaches(){cn.resetCache(),au.resetCache()}}let JH={};function yve(t,e={}){const n=JSON.stringify([t,e]);let r=JH[n];return r||(r=new Intl.ListFormat(t,e),JH[n]=r),r}let IO={};function $O(t,e={}){const n=JSON.stringify([t,e]);let r=IO[n];return r||(r=new Intl.DateTimeFormat(t,e),IO[n]=r),r}let BO={};function Eve(t,e={}){const n=JSON.stringify([t,e]);let r=BO[n];return r||(r=new Intl.NumberFormat(t,e),BO[n]=r),r}let kO={};function Ave(t,e={}){const{base:n,...r}=e,i=JSON.stringify([t,r]);let s=kO[i];return s||(s=new Intl.RelativeTimeFormat(t,e),kO[i]=s),s}let L1=null;function vve(){return L1||(L1=new Intl.DateTimeFormat().resolvedOptions().locale,L1)}function Sve(t){const e=t.indexOf("-u-");if(e===-1)return[t];{let n;const r=t.substring(0,e);try{n=$O(t).resolvedOptions()}catch{n=$O(r).resolvedOptions()}const{numberingSystem:i,calendar:s}=n;return[r,i,s]}}function _ve(t,e,n){return(n||e)&&(t+="-u",n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Cve(t){const e=[];for(let n=1;n<=12;n++){const r=ut.utc(2016,n,1);e.push(t(r))}return e}function Tve(t){const e=[];for(let n=1;n<=7;n++){const r=ut.utc(2016,11,13+n);e.push(t(r))}return e}function Bv(t,e,n,r,i){const s=t.listingMode(n);return s==="error"?null:s==="en"?r(e):i(e)}function bve(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 Rve{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=Eve(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):DO(e,3);return On(n,this.padTo)}}}class Ove{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&&au.create(u).valid?(i=u,this.dt=e):(i="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:ut.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=$O(n,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}}class Dve{constructor(e,n,r){this.opts={style:"long",...r},!n&&NH()&&(this.rtf=Ave(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):xve(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}class cn{static fromOpts(e){return cn.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,n,r,i=!1){const s=e||Dn.defaultLocale,o=s||(i?"en-US":vve()),u=n||Dn.defaultNumberingSystem,a=r||Dn.defaultOutputCalendar;return new cn(o,u,a,s)}static resetCache(){L1=null,IO={},BO={},kO={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r}={}){return cn.create(e,n,r)}constructor(e,n,r,i){const[s,o,u]=Sve(e);this.locale=s,this.numberingSystem=n||o||null,this.outputCalendar=r||u||null,this.intl=_ve(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=bve(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:cn.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 Bv(this,e,r,BH,()=>{const i=n?{month:e,day:"numeric"}:{month:e},s=n?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=Cve(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,n=!1,r=!0){return Bv(this,e,r,MH,()=>{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]=Tve(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return Bv(this,void 0,e,()=>jH,()=>{if(!this.meridiemCache){const n={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ut.utc(2016,11,13,9),ut.utc(2016,11,13,19)].map(r=>this.extract(r,n,"dayperiod"))}return this.meridiemCache})}eras(e,n=!0){return Bv(this,e,n,UH,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[ut.utc(-40,1,1),ut.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 Rve(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Ove(e,this.intl,n)}relFormatter(e={}){return new Dve(this.intl,this.isEnglish(),e)}listFormatter(e={}){return yve(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 vd(...t){const e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function Sd(...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 _d(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 XH(...t){return(e,n)=>{const r={};let i;for(i=0;i<t.length;i++)r[t[i]]=jl(e[n+i]);return[r,null,n+i]}}const KH=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Nve=`(?:${KH.source}?(?:\\[(${IH.source})\\])?)?`,PO=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ZH=RegExp(`${PO.source}${Nve}`),MO=RegExp(`(?:T${ZH.source})?`),wve=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Fve=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Lve=/(\d{4})-?(\d{3})/,Ive=XH("weekYear","weekNumber","weekDay"),$ve=XH("year","ordinal"),Bve=/(\d{4})-(\d\d)-(\d\d)/,ez=RegExp(`${PO.source} ?(?:${KH.source}|(${IH.source}))?`),kve=RegExp(`(?: ${ez.source})?`);function Cd(t,e,n){const r=t[e];return vt(r)?n:jl(r)}function Pve(t,e){return[{year:Cd(t,e),month:Cd(t,e+1,1),day:Cd(t,e+2,1)},null,e+3]}function Td(t,e){return[{hours:Cd(t,e,0),minutes:Cd(t,e+1,0),seconds:Cd(t,e+2,0),milliseconds:OO(t[e+3])},null,e+4]}function I1(t,e){const n=!t[e]&&!t[e+1],r=Nv(t[e+1],t[e+2]),i=n?null:Lr.instance(r);return[{},i,e+3]}function $1(t,e){const n=t[e]?au.create(t[e]):null;return[{},n,e+1]}const Mve=RegExp(`^T?${PO.source}$`),jve=/^-?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 Uve(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(jc(n)),months:x(jc(r)),weeks:x(jc(i)),days:x(jc(s)),hours:x(jc(o)),minutes:x(jc(u)),seconds:x(jc(a),a==="-0"),milliseconds:x(OO(l),f)}]}const qve={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 jO(t,e,n,r,i,s,o){const u={year:e.length===2?wO(jl(e)):jl(e),month:$H.indexOf(n)+1,day:jl(r),hour:jl(i),minute:jl(s)};return o&&(u.second=jl(o)),t&&(u.weekday=t.length>3?kH.indexOf(t)+1:PH.indexOf(t)+1),u}const Hve=/^(?:(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 zve(t){const[,e,n,r,i,s,o,u,a,l,c,f]=t,x=jO(e,i,r,n,s,o,u);let h;return a?h=qve[a]:l?h=0:h=Nv(c,f),[x,new Lr(h)]}function Qve(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Gve=/^(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$/,Wve=/^(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$/,Vve=/^(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 tz(t){const[,e,n,r,i,s,o,u]=t;return[jO(e,i,r,n,s,o,u),Lr.utcInstance]}function Yve(t){const[,e,n,r,i,s,o,u]=t;return[jO(e,u,n,r,i,s,o),Lr.utcInstance]}const Jve=vd(wve,MO),Xve=vd(Fve,MO),Kve=vd(Lve,MO),Zve=vd(ZH),nz=Sd(Pve,Td,I1,$1),e4e=Sd(Ive,Td,I1,$1),t4e=Sd($ve,Td,I1,$1),n4e=Sd(Td,I1,$1);function r4e(t){return _d(t,[Jve,nz],[Xve,e4e],[Kve,t4e],[Zve,n4e])}function i4e(t){return _d(Qve(t),[Hve,zve])}function s4e(t){return _d(t,[Gve,tz],[Wve,tz],[Vve,Yve])}function o4e(t){return _d(t,[jve,Uve])}const u4e=Sd(Td);function a4e(t){return _d(t,[Mve,u4e])}const l4e=vd(Bve,kve),c4e=vd(ez),f4e=Sd(Td,I1,$1);function x4e(t){return _d(t,[l4e,nz],[c4e,f4e])}const d4e="Invalid Duration",rz={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}},h4e={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},...rz},Os=146097/400,bd=146097/4800,p4e={years:{quarters:4,months:12,weeks:Os/7,days:Os,hours:Os*24,minutes:Os*24*60,seconds:Os*24*60*60,milliseconds:Os*24*60*60*1e3},quarters:{months:3,weeks:Os/28,days:Os/4,hours:Os*24/4,minutes:Os*24*60/4,seconds:Os*24*60*60/4,milliseconds:Os*24*60*60*1e3/4},months:{weeks:bd/7,days:bd,hours:bd*24,minutes:bd*24*60,seconds:bd*24*60*60,milliseconds:bd*24*60*60*1e3},...rz},Uc=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],g4e=Uc.slice(0).reverse();function qc(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 St(r)}function m4e(t){return t<0?Math.floor(t):Math.ceil(t)}function iz(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?m4e(o):Math.trunc(o);r[i]+=a,e[n]-=a*s}function y4e(t,e){g4e.reduce((n,r)=>vt(e[r])?n:(n&&iz(t,e,n,e,r),r),null)}class St{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||cn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n?p4e:h4e,this.isLuxonDuration=!0}static fromMillis(e,n){return St.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new Rs(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new St({values:wv(e,St.normalizeUnit),loc:cn.fromObject(n),conversionAccuracy:n.conversionAccuracy})}static fromDurationLike(e){if(Mc(e))return St.fromMillis(e);if(St.isDuration(e))return e;if(typeof e=="object")return St.fromObject(e);throw new Rs(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[r]=o4e(e);return r?St.fromObject(r,n):St.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[r]=a4e(e);return r?St.fromObject(r,n):St.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new Rs("need to specify a reason the Duration is invalid");const r=e instanceof co?e:new co(e,n);if(Dn.throwOnInvalid)throw new VAe(r);return new St({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 cH(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?Oi.create(this.loc,r).formatDurationFromString(this,e):d4e}toHuman(e={}){const n=Uc.map(r=>{const i=this.values[r];return vt(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+=DO(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=St.fromDurationLike(e),r={};for(const i of Uc)(Ed(n.values,i)||Ed(this.values,i))&&(r[i]=n.get(i)+this.get(i));return qc(this,{values:r},!0)}minus(e){if(!this.isValid)return this;const n=St.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]=LH(e(this.values[r],r));return qc(this,{values:n},!0)}get(e){return this[St.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...wv(e,St.normalizeUnit)};return qc(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),qc(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return y4e(this.matrix,e),qc(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>St.normalizeUnit(o));const n={},r={},i=this.toObject();let s;for(const o of Uc)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;Mc(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)Uc.indexOf(l)>Uc.indexOf(o)&&iz(this.matrix,i,l,n,o)}else Mc(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 qc(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 qc(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 Uc)if(!n(this.values[r],e.values[r]))return!1;return!0}}const B1="Invalid Interval";function E4e(t,e){return!t||!t.isValid?fn.invalid("missing or invalid start"):!e||!e.isValid?fn.invalid("missing or invalid end"):e<t?fn.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 fn{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 Rs("need to specify a reason the Interval is invalid");const r=e instanceof co?e:new co(e,n);if(Dn.throwOnInvalid)throw new WAe(r);return new fn({invalid:r})}static fromDateTimes(e,n){const r=j1(e),i=j1(n),s=E4e(r,i);return s??new fn({start:r,end:i})}static after(e,n){const r=St.fromDurationLike(n),i=j1(e);return fn.fromDateTimes(i,i.plus(r))}static before(e,n){const r=St.fromDurationLike(n),i=j1(e);return fn.fromDateTimes(i.minus(r),i)}static fromISO(e,n){const[r,i]=(e||"").split("/",2);if(r&&i){let s,o;try{s=ut.fromISO(r,n),o=s.isValid}catch{o=!1}let u,a;try{u=ut.fromISO(i,n),a=u.isValid}catch{a=!1}if(o&&a)return fn.fromDateTimes(s,u);if(o){const l=St.fromISO(i,n);if(l.isValid)return fn.after(s,l)}else if(a){const l=St.fromISO(r,n);if(l.isValid)return fn.before(u,l)}}return fn.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?fn.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(j1).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(fn.fromDateTimes(i,u)),i=u,s+=1}return r}splitBy(e){const n=St.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(fn.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:fn.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 fn.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(fn.fromDateTimes(n,a.time)),n=null);return fn.merge(i)}difference(...e){return fn.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:B1}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:B1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:B1}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:B1}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:B1}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):St.invalid(this.invalidReason)}mapEndpoints(e){return fn.fromDateTimes(e(this.s),e(this.e))}}let k1=class{static hasDST(e=Dn.defaultZone){const n=ut.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return au.isValidZone(e)}static normalizeZone(e){return Ul(e,Dn.defaultZone)}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||cn.create(n,r,s)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||cn.create(n,r,s)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||cn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||cn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return cn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return cn.create(n,null,"gregory").eras(e)}static features(){return{relative:NH()}}};function sz(t,e){const n=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(St.fromMillis(r).as("days"))}function A4e(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=sz(u,a);return(l-l%7)/7}],["days",sz]],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 v4e(t,e,n,r){let[i,s,o,u]=A4e(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=St.fromObject(s,r);return l.length>0?St.fromMillis(a,r).shiftTo(...l).plus(c):c}const UO={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},oz={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]},S4e=UO.hanidec.replace(/[\[|\]]/g,"").split("");function _4e(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(UO.hanidec)!==-1)e+=S4e.indexOf(t[n]);else for(const i in oz){const[s,o]=oz[i];r>=s&&r<=o&&(e+=r-s)}}return parseInt(e,10)}else return e}function fo({numberingSystem:t},e=""){return new RegExp(`${UO[t||"latn"]}${e}`)}const C4e="missing Intl.DateTimeFormat.formatToParts support";function Ft(t,e=n=>n){return{regex:t,deser:([n])=>e(_4e(n))}}const uz="[  ]",az=new RegExp(uz,"g");function T4e(t){return t.replace(/\./g,"\\.?").replace(az,uz)}function lz(t){return t.replace(/\./g,"").replace(az," ").toLowerCase()}function xo(t,e){return t===null?null:{regex:RegExp(t.map(T4e).join("|")),deser:([n])=>t.findIndex(r=>lz(n)===lz(r))+e}}function cz(t,e){return{regex:t,deser:([,n,r])=>Nv(n,r),groups:e}}function qO(t){return{regex:t,deser:([e])=>e}}function b4e(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function R4e(t,e){const n=fo(e),r=fo(e,"{2}"),i=fo(e,"{3}"),s=fo(e,"{4}"),o=fo(e,"{6}"),u=fo(e,"{1,2}"),a=fo(e,"{1,3}"),l=fo(e,"{1,6}"),c=fo(e,"{1,9}"),f=fo(e,"{2,4}"),x=fo(e,"{4,6}"),h=g=>({regex:RegExp(b4e(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,wO);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 qO(c);case"uu":return qO(u);case"uuu":return Ft(n);case"a":return xo(e.meridiems(),0);case"kkkk":return Ft(s);case"kk":return Ft(f,wO);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 cz(new RegExp(`([+-]${u.source})(?::(${r.source}))?`),2);case"ZZZ":return cz(new RegExp(`([+-]${u.source})(${r.source})?`),2);case"z":return qO(/[a-z_+-/]{1,256}?/i);default:return h(g)}})(t)||{invalidReason:C4e};return m.token=t,m}const O4e={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 D4e(t,e,n){const{type:r,value:i}=t;if(r==="literal")return{literal:!0,val:i};const s=n[r];let o=O4e[r];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function N4e(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function w4e(t,e,n){const r=t.match(e);if(r){const i={};let s=1;for(const o in n)if(Ed(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 F4e(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 vt(t.z)||(n=au.create(t.z)),vt(t.Z)||(n||(n=new Lr(t.Z)),r=t.Z),vt(t.q)||(t.M=(t.q-1)*3+1),vt(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),vt(t.u)||(t.S=OO(t.u)),[Object.keys(t).reduce((s,o)=>{const u=e(o);return u&&(s[u]=t[o]),s},{}),n,r]}let HO=null;function L4e(){return HO||(HO=ut.fromMillis(1555555555555)),HO}function I4e(t,e){if(t.literal)return t;const n=Oi.macroTokenToFormatOpts(t.val);if(!n)return t;const s=Oi.create(e,n).formatDateTimeParts(L4e()).map(o=>D4e(o,e,n));return s.includes(void 0)?t:s}function $4e(t,e){return Array.prototype.concat(...t.map(n=>I4e(n,e)))}function fz(t,e,n){const r=$4e(Oi.parseFormat(n),t),i=r.map(o=>R4e(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:r,invalidReason:s.invalidReason};{const[o,u]=N4e(i),a=RegExp(o,"i"),[l,c]=w4e(e,a,u),[f,x,h]=c?F4e(c):[null,null,void 0];if(Ed(c,"a")&&Ed(c,"H"))throw new D1("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 B4e(t,e,n){const{result:r,zone:i,specificOffset:s,invalidReason:o}=fz(t,e,n);return[r,i,s,o]}const xz=[0,31,59,90,120,151,181,212,243,273,304,334],dz=[0,31,60,91,121,152,182,213,244,274,305,335];function Ds(t,e){return new co("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function hz(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 pz(t,e,n){return n+(N1(t)?dz:xz)[e-1]}function gz(t,e){const n=N1(t)?dz:xz,r=n.findIndex(s=>s<e),i=e-n[r];return{month:r+1,day:i}}function zO(t){const{year:e,month:n,day:r}=t,i=pz(e,n,r),s=hz(e,n,r);let o=Math.floor((i-s+10)/7),u;return o<1?(u=e-1,o=Dv(u)):o>Dv(e)?(u=e+1,o=1):u=e,{weekYear:u,weekNumber:o,weekday:s,...Fv(t)}}function mz(t){const{weekYear:e,weekNumber:n,weekday:r}=t,i=hz(e,1,4),s=w1(e);let o=n*7+r-i-3,u;o<1?(u=e-1,o+=w1(u)):o>s?(u=e+1,o-=w1(e)):u=e;const{month:a,day:l}=gz(u,o);return{year:u,month:a,day:l,...Fv(t)}}function QO(t){const{year:e,month:n,day:r}=t,i=pz(e,n,r);return{year:e,ordinal:i,...Fv(t)}}function yz(t){const{year:e,ordinal:n}=t,{month:r,day:i}=gz(e,n);return{year:e,month:r,day:i,...Fv(t)}}function k4e(t){const e=Rv(t.weekYear),n=ga(t.weekNumber,1,Dv(t.weekYear)),r=ga(t.weekday,1,7);return e?n?r?!1:Ds("weekday",t.weekday):Ds("week",t.week):Ds("weekYear",t.weekYear)}function P4e(t){const e=Rv(t.year),n=ga(t.ordinal,1,w1(t.year));return e?n?!1:Ds("ordinal",t.ordinal):Ds("year",t.year)}function Ez(t){const e=Rv(t.year),n=ga(t.month,1,12),r=ga(t.day,1,Ov(t.year,t.month));return e?n?r?!1:Ds("day",t.day):Ds("month",t.month):Ds("year",t.year)}function Az(t){const{hour:e,minute:n,second:r,millisecond:i}=t,s=ga(e,0,23)||e===24&&n===0&&r===0&&i===0,o=ga(n,0,59),u=ga(r,0,59),a=ga(i,0,999);return s?o?u?a?!1:Ds("millisecond",i):Ds("second",r):Ds("minute",n):Ds("hour",e)}const GO="Invalid DateTime",vz=864e13;function kv(t){return new co("unsupported zone",`the zone "${t.name}" is not supported`)}function WO(t){return t.weekData===null&&(t.weekData=zO(t.c)),t.weekData}function P1(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new ut({...n,...e,old:n})}function Sz(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 _z(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 Pv(t,e,n){return Sz(NO(t),e,n)}function Cz(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,Ov(r,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=St.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=NO(s);let[a,l]=Sz(u,n,t.zone);return o!==0&&(a+=o,l=t.zone.offset(a)),{ts:a,o:l}}function M1(t,e,n,r,i,s){const{setZone:o,zone:u}=n;if(t&&Object.keys(t).length!==0){const a=e||u,l=ut.fromObject(t,{...n,zone:a,specificOffset:s});return o?l:l.setZone(u)}else return ut.invalid(new co("unparsable",`the input "${i}" can't be parsed as ${r}`))}function Mv(t,e,n=!0){return t.isValid?Oi.create(cn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function VO(t,e){const n=t.c.year>9999||t.c.year<0;let r="";return n&&t.c.year>=0&&(r+="+"),r+=On(t.c.year,n?6:4),e?(r+="-",r+=On(t.c.month),r+="-",r+=On(t.c.day)):(r+=On(t.c.month),r+=On(t.c.day)),r}function Tz(t,e,n,r,i,s){let o=On(t.c.hour);return e?(o+=":",o+=On(t.c.minute),(t.c.second!==0||!n)&&(o+=":")):o+=On(t.c.minute),(t.c.second!==0||!n)&&(o+=On(t.c.second),(t.c.millisecond!==0||!r)&&(o+=".",o+=On(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=On(Math.trunc(-t.o/60)),o+=":",o+=On(Math.trunc(-t.o%60))):(o+="+",o+=On(Math.trunc(t.o/60)),o+=":",o+=On(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}const bz={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},M4e={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},j4e={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Rz=["year","month","day","hour","minute","second","millisecond"],U4e=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],q4e=["year","ordinal","hour","minute","second","millisecond"];function Oz(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 cH(t);return e}function Dz(t,e){const n=Ul(e.zone,Dn.defaultZone),r=cn.fromObject(e),i=Dn.now();let s,o;if(vt(t.year))s=i;else{for(const l of Rz)vt(t[l])&&(t[l]=bz[l]);const u=Ez(t)||Az(t);if(u)return ut.invalid(u);const a=n.offset(i);[s,o]=Pv(t,a,n)}return new ut({ts:s,zone:n,loc:r,o})}function Nz(t,e,n){const r=vt(n.round)?!0:n.round,i=(o,u)=>(o=DO(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 wz(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 ut{constructor(e){const n=e.zone||Dn.defaultZone;let r=e.invalid||(Number.isNaN(e.ts)?new co("invalid input"):null)||(n.isValid?null:kv(n));this.ts=vt(e.ts)?Dn.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=_z(this.ts,u),r=Number.isNaN(i.year)?new co("invalid input"):null,i=r?null:i,s=r?null:u}this._zone=n,this.loc=e.loc||cn.create(),this.invalid=r,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new ut({})}static local(){const[e,n]=wz(arguments),[r,i,s,o,u,a,l]=n;return Dz({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static utc(){const[e,n]=wz(arguments),[r,i,s,o,u,a,l]=n;return e.zone=Lr.utcInstance,Dz({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static fromJSDate(e,n={}){const r=KAe(e)?e.valueOf():NaN;if(Number.isNaN(r))return ut.invalid("invalid input");const i=Ul(n.zone,Dn.defaultZone);return i.isValid?new ut({ts:r,zone:i,loc:cn.fromObject(n)}):ut.invalid(kv(i))}static fromMillis(e,n={}){if(Mc(e))return e<-vz||e>vz?ut.invalid("Timestamp out of range"):new ut({ts:e,zone:Ul(n.zone,Dn.defaultZone),loc:cn.fromObject(n)});throw new Rs(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(Mc(e))return new ut({ts:e*1e3,zone:Ul(n.zone,Dn.defaultZone),loc:cn.fromObject(n)});throw new Rs("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const r=Ul(n.zone,Dn.defaultZone);if(!r.isValid)return ut.invalid(kv(r));const i=Dn.now(),s=vt(n.specificOffset)?r.offset(i):n.specificOffset,o=wv(e,Oz),u=!vt(o.ordinal),a=!vt(o.year),l=!vt(o.month)||!vt(o.day),c=a||l,f=o.weekYear||o.weekNumber,x=cn.fromObject(n);if((c||u)&&f)throw new D1("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&u)throw new D1("Can't mix ordinal dates with month/day");const h=f||o.weekday&&!c;let p,m,g=_z(i,s);h?(p=U4e,m=M4e,g=zO(g)):u?(p=q4e,m=j4e,g=QO(g)):(p=Rz,m=bz);let y=!1;for(const T of p){const R=o[T];vt(R)?y?o[T]=m[T]:o[T]=g[T]:y=!0}const E=h?k4e(o):u?P4e(o):Ez(o),A=E||Az(o);if(A)return ut.invalid(A);const v=h?mz(o):u?yz(o):o,[_,S]=Pv(v,s,r),C=new ut({ts:_,zone:r,o:S,loc:x});return o.weekday&&c&&e.weekday!==C.weekday?ut.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${C.toISO()}`):C}static fromISO(e,n={}){const[r,i]=r4e(e);return M1(r,i,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[r,i]=i4e(e);return M1(r,i,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[r,i]=s4e(e);return M1(r,i,n,"HTTP",n)}static fromFormat(e,n,r={}){if(vt(e)||vt(n))throw new Rs("fromFormat requires an input string and a format");const{locale:i=null,numberingSystem:s=null}=r,o=cn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[u,a,l,c]=B4e(o,e,n);return c?ut.invalid(c):M1(u,a,r,`format ${n}`,e,l)}static fromString(e,n,r={}){return ut.fromFormat(e,n,r)}static fromSQL(e,n={}){const[r,i]=x4e(e);return M1(r,i,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new Rs("need to specify a reason the DateTime is invalid");const r=e instanceof co?e:new co(e,n);if(Dn.throwOnInvalid)throw new GAe(r);return new ut({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?WO(this).weekYear:NaN}get weekNumber(){return this.isValid?WO(this).weekNumber:NaN}get weekday(){return this.isValid?WO(this).weekday:NaN}get ordinal(){return this.isValid?QO(this.c).ordinal:NaN}get monthShort(){return this.isValid?k1.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?k1.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?k1.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?k1.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 N1(this.year)}get daysInMonth(){return Ov(this.year,this.month)}get daysInYear(){return this.isValid?w1(this.year):NaN}get weeksInWeekYear(){return this.isValid?Dv(this.weekYear):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:r,calendar:i}=Oi.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:i}}toUTC(e=0,n={}){return this.setZone(Lr.instance(e),n)}toLocal(){return this.setZone(Dn.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=Ul(e,Dn.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]=Pv(o,s,e)}return P1(this,{ts:i,zone:e})}else return ut.invalid(kv(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return P1(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=wv(e,Oz),r=!vt(n.weekYear)||!vt(n.weekNumber)||!vt(n.weekday),i=!vt(n.ordinal),s=!vt(n.year),o=!vt(n.month)||!vt(n.day),u=s||o,a=n.weekYear||n.weekNumber;if((u||i)&&a)throw new D1("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new D1("Can't mix ordinal dates with month/day");let l;r?l=mz({...zO(this.c),...n}):vt(n.ordinal)?(l={...this.toObject(),...n},vt(n.day)&&(l.day=Math.min(Ov(l.year,l.month),l.day))):l=yz({...QO(this.c),...n});const[c,f]=Pv(l,this.o,this.zone);return P1(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;const n=St.fromDurationLike(e);return P1(this,Cz(this,n))}minus(e){if(!this.isValid)return this;const n=St.fromDurationLike(e).negate();return P1(this,Cz(this,n))}startOf(e){if(!this.isValid)return this;const n={},r=St.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?Oi.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):GO}toLocaleString(e=RO,n={}){return this.isValid?Oi.create(this.loc.clone(n),e).formatDateTime(this):GO}toLocaleParts(e={}){return this.isValid?Oi.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=VO(this,o);return u+="T",u+=Tz(this,o,n,r,i,s),u}toISODate({format:e="extended"}={}){return this.isValid?VO(this,e==="extended"):null}toISOWeekDate(){return Mv(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":"")+Tz(this,o==="extended",n,e,r,s):null}toRFC2822(){return Mv(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Mv(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?VO(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")),Mv(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():GO}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 St.invalid("created by diffing an invalid DateTime");const i={locale:this.locale,numberingSystem:this.numberingSystem,...r},s=ZAe(n).map(St.normalizeUnit),o=e.valueOf()>this.valueOf(),u=o?this:e,a=o?e:this,l=v4e(u,a,s,i);return o?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(ut.now(),e,n)}until(e){return this.isValid?fn.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||ut.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),Nz(n,this.plus(r),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?Nz(e.base||ut.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(ut.isDateTime))throw new Rs("min requires all arguments be DateTimes");return wH(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(ut.isDateTime))throw new Rs("max requires all arguments be DateTimes");return wH(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){const{locale:i=null,numberingSystem:s=null}=r,o=cn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return fz(o,e,n)}static fromStringExplain(e,n,r={}){return ut.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return RO}static get DATE_MED(){return fH}static get DATE_MED_WITH_WEEKDAY(){return YAe}static get DATE_FULL(){return xH}static get DATE_HUGE(){return dH}static get TIME_SIMPLE(){return hH}static get TIME_WITH_SECONDS(){return pH}static get TIME_WITH_SHORT_OFFSET(){return gH}static get TIME_WITH_LONG_OFFSET(){return mH}static get TIME_24_SIMPLE(){return yH}static get TIME_24_WITH_SECONDS(){return EH}static get TIME_24_WITH_SHORT_OFFSET(){return AH}static get TIME_24_WITH_LONG_OFFSET(){return vH}static get DATETIME_SHORT(){return SH}static get DATETIME_SHORT_WITH_SECONDS(){return _H}static get DATETIME_MED(){return CH}static get DATETIME_MED_WITH_SECONDS(){return TH}static get DATETIME_MED_WITH_WEEKDAY(){return JAe}static get DATETIME_FULL(){return bH}static get DATETIME_FULL_WITH_SECONDS(){return RH}static get DATETIME_HUGE(){return OH}static get DATETIME_HUGE_WITH_SECONDS(){return DH}}function j1(t){if(ut.isDateTime(t))return t;if(t&&t.valueOf&&Mc(t.valueOf()))return ut.fromJSDate(t);if(t&&typeof t=="object")return ut.fromObject(t);throw new Rs(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const H4e="2.5.2";var Fz=Ri.DateTime=ut;Ri.Duration=St,Ri.FixedOffsetZone=Lr,Ri.IANAZone=au,Ri.Info=k1,Ri.Interval=fn,Ri.InvalidZone=HH,Ri.Settings=Dn,Ri.SystemZone=Lv,Ri.VERSION=H4e,Ri.Zone=Ad,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.LiteralYear=Xn.LiteralQuarter=Xn.LiteralMonth=Xn.LiteralWeek=Xn.LiteralDay=Xn.LiteralHour=Xn.LiteralTimestamp=Xn.TimeFormatError=void 0;const ql=Ri,z4e=oe,Q4e=Il,Lz=hd,YO=st;class G4e extends Error{}Xn.TimeFormatError=G4e;function Hc(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 Iz="yyyy",$z=`${Iz}-LL`,Ns=`${$z}-dd`,Bz=`${Ns} HH`,kz=`${Bz}:mm`,JO=`${kz}:ss`;class Pz extends YO.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={node:"timeLiteral",literal:e,dataType: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 XO extends Pz{constructor(e,n){super(e,n,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let n;const r=Hc(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=ql.DateTime.fromFormat(e,JO);if(s.isValid)return new XO(r,n);if(s=ql.DateTime.fromFormat(e,kz),s.isValid){r.text=r.text+":00",n="minute";const o=s.plus({minute:1}).toFormat(JO);return new KO(r,n,"timestamp",o)}}}Xn.LiteralTimestamp=XO;class KO extends Pz{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,YO.getMorphicValue)(i,"timestamp"),a=(0,YO.getMorphicValue)(s,"timestamp");if(u&&a)i=u,s=a;else return super.apply(e,n,r)}if((0,z4e.isTemporalField)(o.dataType)){const u=o.dataType;return new Q4e.Range(new Lz.ExprTime(u,i.value),new Lz.ExprTime(u,s.value)).apply(e,n,r)}}return super.apply(e,n,r)}}class ZO extends KO{constructor(e,n){super(e,"hour","timestamp",n),this.elementType="literal:hour"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,Bz);if(i.isValid)return n.text=n.text+":00:00",r=i.plus({hour:1}).toFormat(JO),new ZO(n,r)}}Xn.LiteralHour=ZO;class U1 extends KO{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 eD extends U1{constructor(e,n){super(e,"day",n),this.elementType="literal:day"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,Ns);if(i.isValid)return r=i.plus({day:1}).toFormat(Ns),new eD(n,r)}}Xn.LiteralDay=eD;class tD extends U1{constructor(e,n){super(e,"week",n),this.elementType="literal:week"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=n.text.slice(0,10),s=ql.DateTime.fromFormat(i,Ns);if(s.isValid&&s.weekday===7){const u=s.plus({days:7});return n.text=s.toFormat(Ns),r=u.toFormat(Ns),new tD(n,r)}}}Xn.LiteralWeek=tD;class nD extends U1{constructor(e,n){super(e,"month",n),this.elementType="literal:month"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,$z);if(i.isValid){const s=i.plus({months:1});return n.text=i.toFormat(Ns),r=s.toFormat(Ns),new nD(n,r)}}}Xn.LiteralMonth=nD;class rD extends U1{constructor(e,n){super(e,"quarter",n),this.elementType="literal:quarter"}static parse(e){const n=Hc(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=ql.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));const u=o.plus({quarter:1});return n.text=o.toFormat(Ns),r=u.toFormat(Ns),new rD(n,r)}}}Xn.LiteralQuarter=rD;class iD extends U1{constructor(e,n){super(e,"year",n),this.elementType="literal:year"}static parse(e){const n=Hc(e,!1);let r=n.text;const i=ql.DateTime.fromFormat(n.text,Iz);if(i.isValid){const s=i.plus({year:1});return n.text=i.toFormat(Ns),r=s.toFormat(Ns),new iD(n,r)}}}Xn.LiteralYear=iD;var jv={};Object.defineProperty(jv,"__esModule",{value:!0}),jv.PartialCompare=void 0;const Mz=st;class W4e extends Mz.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.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return Mz.ATNodeType.Partial}}jv.PartialCompare=W4e;var Rd={};Object.defineProperty(Rd,"__esModule",{value:!0}),Rd.PickWhen=Rd.Pick=void 0;const lu=oe,Od=Jt,V4e=st,Y4e=Ge;function Uv(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class J4e extends V4e.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={node:"case",kids:{caseWhen:[],caseThen:[]}};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,lu.maxExpressionType)(o,(0,lu.maxExpressionType)(f.expressionType,x.expressionType)),u=(0,lu.mergeEvalSpaces)(u,f.evalSpace,x.evalSpace),s&&!Od.FT.typeEq(s,x,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:x.dataType,returnType:s.dataType});s=Uv(s,x),i.kids.caseWhen.push(f.value),i.kids.caseThen.push(x.value)}const l=(this.elsePick||r).getExpression(e);return s=Uv(s,l),Od.FT.typeEq(s,l,!0)?(i.kids.caseElse=l.value,{dataType:s.dataType,expressionType:(0,lu.maxExpressionType)(o,l.expressionType),evalSpace:(0,lu.mergeEvalSpaces)(u,l.evalSpace),value:i}):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:l.dataType,returnType:s.dataType}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:l.dataType,returnType:s.dataType})}getExpression(e){const n={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const r=[];for(const a of this.choices){if(a.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");a.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply"),r.push({pick:a.pick.getExpression(e),when:a.when.getExpression(e)})}let i,s="scalar",o="constant";for(const a of r){if(!Od.FT.typeEq(a.when,Od.FT.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:a.when.dataType});if(i&&!Od.FT.typeEq(i,a.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:a.pick.dataType,returnType:i.dataType});i=Uv(i,a.pick),s=(0,lu.maxExpressionType)(s,(0,lu.maxExpressionType)(a.pick.expressionType,a.when.expressionType)),o=(0,lu.mergeEvalSpaces)(o,a.pick.evalSpace,a.when.evalSpace),n.kids.caseWhen.push(a.when.value),n.kids.caseThen.push(a.pick.value)}const u=this.elsePick.getExpression(e);return s=(0,lu.maxExpressionType)(s,u.expressionType),o=(0,lu.mergeEvalSpaces)(o,u.evalSpace),i=Uv(i,u),Od.FT.typeEq(i,u,!0)?(n.kids.caseElse=u.value,{dataType:i.dataType,expressionType:s,value:n,evalSpace:o}):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.dataType,returnType:i.dataType})}}Rd.Pick=J4e;class X4e extends Y4e.MalloyElement{constructor(e,n){super({when:n}),this.pick=e,this.when=n,this.elementType="caseWhen",this.has({pick:e})}}Rd.PickWhen=X4e;var Dd={};Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.CaseWhen=Dd.Case=void 0;const K4e=st,Z4e=Ge,q1=Jt,zc=Ai;function jz(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class eSe extends K4e.ExpressionDef{constructor(e,n,r){super({choices:n}),this.value=e,this.choices=n,this.elseValue=r,this.elementType="case",this.has({elseValue:r,value:e})}getExpression(e){var n;const r={node:"case",kids:{caseWhen:[],caseThen:[]}};let i="scalar",s="constant",o;this.value&&(o=this.value.getExpression(e),i=(0,zc.maxExpressionType)(i,o.expressionType),s=(0,zc.mergeEvalSpaces)(s,o.evalSpace),r.kids.caseValue=o.value);const u=[];for(const l of this.choices){const c=l.when.getExpression(e),f=l.then.getExpression(e);u.push({when:c,then:f})}let a;for(const l of u){if(o!==void 0){if(!q1.FT.typeEq(l.when,o))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:l.when.dataType,valueType:o.dataType})}else if(!q1.FT.typeEq(l.when,q1.FT.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:l.when.dataType});if(a&&!q1.FT.typeEq(a,l.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:l.then.dataType,returnType:a.dataType});a=jz(a,l.then),i=(0,zc.maxExpressionType)(i,(0,zc.maxExpressionType)(l.then.expressionType,l.when.expressionType)),s=(0,zc.mergeEvalSpaces)(s,l.then.evalSpace,l.when.evalSpace),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.then.value)}if(this.elseValue){const l=this.elseValue.getExpression(e);if(a&&!q1.FT.typeEq(a,l,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:l.dataType,returnType:a.dataType});a=jz(a,l),i=(0,zc.maxExpressionType)(i,l.expressionType),s=(0,zc.mergeEvalSpaces)(s,l.evalSpace),r.kids.caseElse=l.value}return{value:r,dataType:(n=a==null?void 0:a.dataType)!==null&&n!==void 0?n:"null",expressionType:i,evalSpace:s}}}Dd.Case=eSe;class tSe extends Z4e.MalloyElement{constructor(e,n){super({when:e,then:n}),this.when=e,this.then=n,this.elementType="caseWhen"}}Dd.CaseWhen=tSe;var Nd={};Object.defineProperty(Nd,"__esModule",{value:!0}),Nd.RecordLiteral=Nd.RecordElement=void 0;const Uz=Ai,nSe=st,rSe=Ge;class iSe extends rSe.MalloyElement{constructor(e,n){super(),this.key=e,this.value=n,this.elementType="record element",this.has({value:n})}}Nd.RecordElement=iSe;class sSe extends nSe.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){const n={node:"recordLiteral",kids:{}};let r="scalar";for(const i of this.pairs){const s=i.value.getExpression(e),o={dataType:"error",...s.value};o.dataType==="error"&&(0,Uz.isAtomicFieldType)(s.dataType)&&(o.dataType=s.dataType),o.dataType==="error"&&s.dataType!=="error"&&this.logError("illegal-record-property-type",`Type '${s.dataType}' not a legal record value`),n.kids[i.key]=o,r=(0,Uz.maxExpressionType)(s.expressionType,r)}return{dataType:"record",value:n,expressionType:r,evalSpace:"literal"}}}Nd.RecordLiteral=sSe;var qv={};Object.defineProperty(qv,"__esModule",{value:!0}),qv.Timeframe=void 0;const oSe=oe,uSe=Ge;class aSe extends uSe.MalloyElement{constructor(e){super(),this.elementType="timeframe";let n=e.toLowerCase();n.endsWith("s")&&(n=n.slice(0,-1)),this.text=(0,oSe.isTimestampUnit)(n)?n:"second"}}qv.Timeframe=aSe;var Hv={};Object.defineProperty(Hv,"__esModule",{value:!0}),Hv.TopBy=void 0;const lSe=oe,qz=st,cSe=Ge;class fSe extends cSe.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof qz.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof qz.ExpressionDef){const n=this.by.getExpression(e);return(0,lSe.expressionIsAggregate)(n.expressionType)||this.logError("top-by-non-aggregate","top by expression must be an aggregate"),{by:"expression",e:n.value}}return{by:"name",name:this.by}}}Hv.TopBy=fSe;var Hl={};Object.defineProperty(Hl,"__esModule",{value:!0}),Hl.ImportStatement=Hl.ImportSelect=Hl.ImportSourceName=void 0;const sD=Ge;class xSe extends sD.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}Hl.ImportSourceName=xSe;class dSe extends sD.MalloyElement{constructor(e,n){super(),this.text=e,this.from=n,this.elementType="importName",n&&this.has({from:n})}}Hl.ImportSelect=dSe;class hSe extends sD.ListOf{constructor(e,n){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,n).toString())}catch{this.logError("invalid-import-url","Invalid URL 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.logError("no-translator-for-import","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.logError("name-conflict-on-selective-import",`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.logError("selective-import-not-found",`Cannot find '${o.text}', not imported`)}else for(const[s,o]of Object.entries(n.getChildExports(this.fullURL)))e.getEntry(s)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else r.status==="error"?this.logError("failed-import",`import failed: '${r.message}'`):this.logError("failed-import",`import failed with status: '${r.status}'`)}}}Hl.ImportStatement=hSe;var H1={};Object.defineProperty(H1,"__esModule",{value:!0}),H1.ExtendBlock=void 0;const pSe=Ge,gSe=mn;class mSe extends pSe.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=gSe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)for(const r of n.list)e.inputFS.extendSource(r)}}H1.ExtendBlock=mSe;var zv={};Object.defineProperty(zv,"__esModule",{value:!0}),zv.Argument=void 0;const ySe=Ge;class ESe extends ySe.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}zv.Argument=ESe;var Qv={};Object.defineProperty(Qv,"__esModule",{value:!0}),Qv.HasParameter=void 0;const Hz=oe,ASe=Ge;class vSe extends ASe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,Hz.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const n=this.default.constantValue();return this.type&&this.type!==n.dataType&&n.dataType!=="null"&&n.dataType!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),n.dataType==="null"?this.type?{value:n.value,name:this.name,type:this.type}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:n.value,name:this.name,type:"error"}):!(0,Hz.isCastType)(n.dataType)&&n.dataType!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${n.dataType}\``),{value:n.value,name:this.name,type:"error"}):{value:n.value,name:this.name,type:n.dataType}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}Qv.HasParameter=vSe;var Gv={};Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.AnonymousQuery=void 0;const SSe=Ge,_Se=Nr;class CSe extends SSe.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=_Se.extendNoteMethod,this.has({queryExpr:e})}execute(e){const n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("non-query-used-as-query","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)}}Gv.AnonymousQuery=CSe;var zl={};Object.defineProperty(zl,"__esModule",{value:!0}),zl.View=void 0;const TSe=Ge;let bSe=class extends TSe.MalloyElement{pipeline(e,n){return this.pipelineComp(e,n).pipeline}};zl.View=bSe;var Wv={};Object.defineProperty(Wv,"__esModule",{value:!0}),Wv.ViewArrow=void 0;const RSe=hr,OSe=zl;class DSe extends OSe.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 RSe.StaticSpace(n.outputStruct),i=this.operation.pipelineComp(r);return{pipeline:[...n.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,n,r){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Wv.ViewArrow=DSe;var Vv={},z1={};Object.defineProperty(z1,"__esModule",{value:!0}),z1.refine=void 0;const oD=Ai,uD=Nl;function NSe(t,e,n){var r,i;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const s={...e[0]},o=n;if((0,oD.isRawSegment)(s))t.logError("refinement-of-raw-query","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.logError("mismatched-view-types-for-refinement",`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.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.logError("limit-overridden-in-refinement","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,oD.isQuerySegment)(o)&&(0,oD.isQuerySegment)(s)){const u=[],a=[],l=new Map(s.queryFields.map(c=>[(0,uD.nameFromDef)(c),c]));for(const c of o.queryFields)l.has((0,uD.nameFromDef)(c))?u.push(c):a.push(c);s.queryFields=[...s.queryFields,...a],u.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${u.map(uD.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}z1.refine=NSe,Object.defineProperty(Vv,"__esModule",{value:!0}),Vv.ViewRefine=void 0;const wSe=Fr,FSe=Zi,LSe=z1,ISe=zl;class $Se extends ISe.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,FSe.getFinalStruct)(this.refinement,e.structDef(),i):wSe.ErrorFactory.structDef}}refine(e,n,r){const i=this.pipeline(e,r);return i.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),n):(0,LSe.refine)(this,n,i[0])}getImplicitName(){return this.base.getImplicitName()}}Vv.ViewRefine=$Se;var Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.ReferenceView=void 0;const aD=oe,zz=Fr,BSe=Zi,kSe=wr,PSe=z1,MSe=zl;class jSe extends MSe.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:zz.ErrorFactory.structDef,outputStruct:zz.ErrorFactory.structDef,pipeline:[],error:!0}};if(!r.found)return this.logError("view-not-found",`\`${this.reference.refString}\` is not defined`),i();if(!(r.found instanceof kSe.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,aD.isAtomic)(s)){const o={type:"reduce",queryFields:[this.reference.refToField]},u=this.reference.nameString,a={...(0,aD.sourceBase)(e.structDef()),type:"query_result",name:u,fields:[s]};return{pipeline:[o],name:u,outputStruct:a}}else return(0,aD.isTurtleDef)(s)?this.reference.list.length>1?(n?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,BSe.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(n?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.logError("nest-of-source","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.logError("refinement-with-multistage-view",`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,PSe.refine)(this,n,i):n}getImplicitName(){return this.reference.nameString}}Yv.ReferenceView=jSe;var Jv={},Q1={},Xv={},G1={};Object.defineProperty(G1,"__esModule",{value:!0}),G1.Index=void 0;const USe=Ge,qSe=mn;let HSe=class extends USe.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=qSe.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};G1.Index=HSe;var W1={};Object.defineProperty(W1,"__esModule",{value:!0}),W1.SampleProperty=void 0;const zSe=Ge,Qz=mn;class QSe extends zSe.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=Qz.LegalRefinementStage.Tail,this.forceQueryClass=Qz.QueryClass.Index}sampling(){return this.sample}}W1.SampleProperty=QSe;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.IndexFieldSpace=void 0;const Gz=oe,lD=ht,GSe=wr,WSe=ao,VSe=C1,YSe=hr;class JSe extends WSe.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const n of e)n instanceof lD.FieldReference?super.pushFields(n):n instanceof lD.WildcardFieldReference?this.addWild(n):n.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};const n=[];for(const[r,i]of this.entries())if(i instanceof GSe.SpaceField){const s=this.expandedWild[r];if(s){n.push({type:"fieldref",path:s});continue}if(i instanceof VSe.ReferenceField){const o=i.fieldRef,u=o.getField(this.exprSpace);u.error?o.logError(u.error.code,u.error.message):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 YSe.StructSpaceField)r=l.fieldSpace;else{u.logError("invalid-wildcard-source",`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.logError("wildcard-source-not-found",`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries()){if(e.except.has(u)||a.refType==="parameter")continue;const l=lD.IndexFieldReference.indexOutputName([...i,u]);if(this.entry(l)){const c=(n=this.expandedWild[l])===null||n===void 0?void 0:n.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=a.typeDesc(),f=c.dataType;(0,Gz.isAtomicFieldType)(f)&&f!=="record"&&f!=="array"&&(0,Gz.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)}}Kv.IndexFieldSpace=JSe,Object.defineProperty(Xv,"__esModule",{value:!0}),Xv.IndexBuilder=void 0;const cD=oe,XSe=Fr,KSe=oo,ZSe=G1,e_e=kl,t_e=W1,n_e=Kv;class r_e{constructor(e,n,r,i){this.filters=[],this.type="index",this.resultFS=new n_e.IndexFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof KSe.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof e_e.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof ZSe.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof t_e.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}finalize(e){if(e&&!(0,cD.isIndexSegment)(e)&&!(0,cD.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),XSe.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,cD.isIndexSegment)(e)&&(e!=null&&e.sample)&&(n.sample=e.sample),this.sample&&(n.sample=this.sample),n}}Xv.IndexBuilder=r_e;var Zv={},V1={};Object.defineProperty(V1,"__esModule",{value:!0}),V1.GroupBy=void 0;const i_e=Ki,Wz=mn;class s_e extends i_e.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=Wz.LegalRefinementStage.Single,this.forceQueryClass=Wz.QueryClass.Grouping}}V1.GroupBy=s_e;var e4={};Object.defineProperty(e4,"__esModule",{value:!0}),e4.ProjectFieldSpace=void 0;const fD=oe,o_e=ao;class u_e extends o_e.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,fD.expressionIsAggregate)(e.expressionType)?!1:(0,fD.expressionInvolvesAggregate)(e.expressionType)&&(0,fD.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}e4.ProjectFieldSpace=u_e;var Ql={},Qc={};Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.Ordering=Qc.OrderBy=void 0;const a_e=oe,Vz=Pl,Yz=Ge,l_e=mn;class c_e extends Yz.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e instanceof Vz.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 Vz.FieldName&&e.isQueryFieldSpace()){const i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.logError(s.error.code,s.error.message),(!s.found||!s.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,a_e.expressionIsAnalytic)((n=s.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const r={field:this.modelField};return this.dir&&(r.dir=this.dir),r}}Qc.OrderBy=c_e;class f_e extends Yz.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=l_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(n=>n.getOrderBy(e))}}Qc.Ordering=f_e;var Y1={};Object.defineProperty(Y1,"__esModule",{value:!0}),Y1.Top=void 0;const Jz=oe,x_e=Pl,d_e=Ge,h_e=mn;let p_e=class extends d_e.MalloyElement{constructor(e,n){super(),this.limit=e,this.by=n,this.elementType="top",this.queryRefinementStage=h_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:n})}getBy(e){var n;if(this.by)if(this.by instanceof x_e.FieldName){if(e.isQueryFieldSpace()){const r=e.outputSpace(),i=this.by.getField(r);i.error&&this.by.logError(i.error.code,i.error.message),(!i.found||!i.isOutputField)&&this.by.logError("top-by-not-found-in-output",`Unknown field ${this.by.refString} in output space`),(0,Jz.expressionIsAnalytic)((n=i.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.by.logError("top-by-analytic",`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,Jz.expressionIsAggregate)(r.expressionType)&&this.by.logError("top-by-aggregate","top by expression must not be an aggregate"),r.evalSpace==="output"&&this.by.logError("top-by-not-in-output","top by expression must be an output expression"),{by:"expression",e:r.value}}}};Y1.Top=p_e,Object.defineProperty(Ql,"__esModule",{value:!0}),Ql.ReduceBuilder=Ql.QuerySegmentBuilder=void 0;const Xz=oe,g_e=Fr,m_e=oo,y_e=kl,Kz=Qc,Zz=Y1,E_e=ao,A_e=Ki;class eQ{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof A_e.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof m_e.Filter){const n=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(n))}else e instanceof Zz.Top?(this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.logError("ordering-already-specified","Query operation is already sorted"):this.order=e)):e instanceof y_e.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Kz.Ordering&&(this.order?e.logError("ordering-already-specified","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 Zz.Top){const i=this.order.getBy(this.inputFS);i&&(n.by=i)}this.order instanceof Kz.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])}}Ql.QuerySegmentBuilder=eQ;class v_e extends eQ{constructor(e,n,r,i){super(),this.type="grouping",this.resultFS=new E_e.ReduceFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let n;if(e)if((0,Xz.isReduceSegment)(e)||(0,Xz.isPartialSegment)(e))n=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),g_e.ErrorFactory.reduceSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}Ql.ReduceBuilder=v_e,Object.defineProperty(Zv,"__esModule",{value:!0}),Zv.ProjectBuilder=void 0;const tQ=oe,S_e=Fr,__e=V1,C_e=e4,T_e=Ql;class b_e extends T_e.QuerySegmentBuilder{constructor(e,n,r,i){super(),this.type="project",this.resultFS=new C_e.ProjectFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof __e.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let n;if(e)if((0,tQ.isProjectSegment)(e)||(0,tQ.isPartialSegment)(e))n=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),S_e.ErrorFactory.projectSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}Zv.ProjectBuilder=b_e;var t4={};Object.defineProperty(t4,"__esModule",{value:!0}),t4.PartialBuilder=void 0;const R_e=Ai,O_e=Ql;class D_e extends O_e.ReduceBuilder{finalize(e){const n=super.finalize(e);if((0,R_e.isQuerySegment)(n))return{...n,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${n.type}`)}}t4.PartialBuilder=D_e,Object.defineProperty(Q1,"__esModule",{value:!0}),Q1.QOpDesc=void 0;const N_e=Xv,w_e=Zv,F_e=Ql,L_e=Ge,I_e=Zi,$_e=hr,Gc=mn,B_e=t4;class k_e extends L_e.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let n,r=!1;this.refineThis&&(this.refineThis.type==="reduce"?n=Gc.QueryClass.Grouping:this.refineThis.type==="project"?n=Gc.QueryClass.Project:this.refineThis.type==="index"&&(n=Gc.QueryClass.Index));for(const i of this.list)i.forceQueryClass&&(n?n!==i.forceQueryClass&&i.logError(`illegal-${n}-operation`,`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.logError("ambiguous-view-type",{}),n=Gc.QueryClass.Project),this.opClass=n,n}refineFrom(e){this.refineThis=e}getBuilder(e,n,r){switch(this.computeType()){case Gc.QueryClass.Grouping:return new F_e.ReduceBuilder(e,this.refineThis,n,r);case Gc.QueryClass.Project:return new w_e.ProjectBuilder(e,this.refineThis,n,r);case Gc.QueryClass.Index:return new N_e.IndexBuilder(e,this.refineThis,n,r);case void 0:return new B_e.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 $_e.StaticSourceSpace((0,I_e.opOutputStruct)(this,e.structDef(),i))}}}Q1.QOpDesc=k_e,Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.QOpDescView=void 0;const P_e=oe,M_e=hr,nQ=Q1,j_e=Zi,xD=mn,U_e=zl;class q_e extends U_e.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,P_e.isRawSegment)(i)?(this.logError("refinement-of-raw-query","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 nQ.QOpDesc([]),o=new nQ.QOpDesc([]);for(const u of this.operation.list)switch(u.queryRefinementStage){case xD.LegalRefinementStage.Head:s.push(u);break;case xD.LegalRefinementStage.Single:u.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case xD.LegalRefinementStage.Tail:o.push(u);break;default:u.logError("illegal-refinement-operation","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,j_e.getFinalStruct)(this,e.structDef(),i.slice(-1));i[u]=this.getOp(new M_e.StaticSourceSpace(a),void 0,o,i[u])}return i}getImplicitName(){}}Jv.QOpDescView=q_e;var xn={};Object.defineProperty(xn,"__esModule",{value:!0}),xn.FieldDefinitionValue=xn.DefSpace=xn.DimensionFieldDeclaration=xn.MeasureFieldDeclaration=xn.DeclareFieldDeclaration=xn.ProjectFieldDeclaration=xn.GroupByFieldDeclaration=xn.AggregateFieldDeclaration=xn.CalculateFieldDeclaration=xn.AtomicFieldDeclaration=void 0;const rQ=oe,H_e=Jt,z_e=dd,Q_e=Ge,Wc=In,G_e=Nr,W_e=wr;class Gl extends Q_e.MalloyElement{constructor(e,n,r){super({expr:e}),this.expr=e,this.defineName=n,this.exprSrc=r,this.isNoteableObj=!0,this.extendNote=G_e.extendNoteMethod}fieldDef(e,n){return this.queryFieldDef(new dD(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 u=this.executesInOutputSpace()?i():e;r=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${n}', ${u.message}`),{name:n,type:"error"}}let s=r.dataType;if(s==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),s="number"),(0,rQ.isAtomicFieldType)(s)&&s!=="error"){this.typecheckExprValue(r);let u;switch(s){case"date":case"timestamp":{const a={name:n,type:s,location:this.location,e:r.value};(0,z_e.isGranularResult)(r)&&(a.timeframe=r.timeframe),u=a;break}case"json":case"boolean":case"string":case"number":case"sql native":{u={type:s,name:n,location:this.location,e:r.value};break}case"record":{const a=[];u={type:"record",name:n,location:this.location,join:"one",fields:a,e:r.value,dialect:e.dialectName()};break}case"array":throw this.internalError("Cannot return an array result from a query (yet)")}return r.expressionType&&(u.expressionType=r.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof dD&&e.foundCircle)&&r.dataType!=="error"){const u=H_e.FT.inspect(r);this.logError("invalid-type-for-field-definition",`Cannot define '${n}', unexpected type: ${u}`)}return{name:n,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new iQ(e,this))}}xn.AtomicFieldDeclaration=Gl;class V_e extends Gl{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}xn.CalculateFieldDeclaration=V_e;class Y_e extends Gl{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckAggregate)(e,this)}}xn.AggregateFieldDeclaration=Y_e;class J_e extends Gl{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckGroupBy)(e,this)}}xn.GroupByFieldDeclaration=J_e;class X_e extends Gl{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckProject)(e,this)}}xn.ProjectFieldDeclaration=X_e;class K_e extends Gl{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckDeclare)(e,this)}}xn.DeclareFieldDeclaration=K_e;class Z_e extends Gl{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckMeasure)(e,this)}}xn.MeasureFieldDeclaration=Z_e;class e5e extends Gl{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Wc.typecheckDimension)(e,this)}}xn.DimensionFieldDeclaration=e5e;class dD{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:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}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")}}xn.DefSpace=dD;class iQ extends W_e.SpaceField{constructor(e,n){super(),this.space=e,this.exprDef=n,this.fieldName=n.defineName}get name(){return this.fieldName}fieldDef(){let e=this.defInSource;return e===void 0&&(this.defInSource=e,e=this.exprDef.fieldDef(this.space,this.name)),e}getQueryFieldDef(e){if(!this.defInQuery){const n=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=n}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,rQ.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}xn.FieldDefinitionValue=iQ;var n4={};Object.defineProperty(n4,"__esModule",{value:!0}),n4.Aggregate=void 0;const t5e=Ki,sQ=mn;let n5e=class extends t5e.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=sQ.LegalRefinementStage.Single,this.forceQueryClass=sQ.QueryClass.Grouping}};n4.Aggregate=n5e;var r4={};Object.defineProperty(r4,"__esModule",{value:!0}),r4.Calculate=void 0;const r5e=Ki,i5e=mn;class s5e extends r5e.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=i5e.LegalRefinementStage.Single}}r4.Calculate=s5e;var J1={};Object.defineProperty(J1,"__esModule",{value:!0}),J1.Dimensions=void 0;const o5e=wl;class u5e extends o5e.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}J1.Dimensions=u5e;var X1={};Object.defineProperty(X1,"__esModule",{value:!0}),X1.Measures=void 0;const a5e=wl;class l5e extends a5e.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}X1.Measures=l5e;var i4={};Object.defineProperty(i4,"__esModule",{value:!0}),i4.Nests=void 0;const c5e=Ki,oQ=mn;class f5e extends c5e.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=oQ.LegalRefinementStage.Single,this.forceQueryClass=oQ.QueryClass.Grouping}}i4.Nests=f5e;var s4={};Object.defineProperty(s4,"__esModule",{value:!0}),s4.ProjectStatement=void 0;const x5e=Ki,uQ=mn;class d5e extends x5e.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=uQ.QueryClass.Project,this.queryRefinementStage=uQ.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}s4.ProjectStatement=d5e;var Wl={},ma={};Object.defineProperty(ma,"__esModule",{value:!0}),ma.findReferences=ma.deprecatedParseTableURI=ma.constructTableKey=void 0;const h5e=dl,hD=nn;function pD(t){const e=(0,hD.getStringIfShort)(t);if(e)return e;const n=[],r=t.string().sqlString();if(r){for(const i of(0,hD.getStringParts)(r))typeof i=="string"&&n.push(i);return n.join("")}return""}class p5e{constructor(e,n){this.trans=e,this.tokens=n,this.needTables={},this.needImports={}}registerTableReference(e,n,r){const i=aQ(e,n);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:n,firstReference:r})}enterTableMethod(e){const n=(0,hD.getId)(e.connectionId()),r=pD(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(n,r,i)}enterTableFunction(e){const n=pD(e.tableURI()),{connectionName:r,tablePath:i}=lQ(n),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const n=pD(e);this.needImports[n]||(this.needImports[n]=this.trans.rangeFromContext(e))}}function aQ(t,e){return t===void 0?e:`${t}:${e}`}ma.constructTableKey=aQ;function lQ(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,n,r]=e;return{connectionName:n,tablePath:r}}else return{tablePath:t}}ma.deprecatedParseTableURI=lQ;function g5e(t,e,n){const r=new p5e(t,e),i=r;return h5e.ParseTreeWalker.DEFAULT.walk(i,n),{tables:r.needTables,urls:r.needImports}}ma.findReferences=g5e,Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.TableFunctionSource=Wl.TableMethodSource=Wl.TableSource=void 0;const cQ=ma,m5e=so,fQ=Fr;class gD extends m5e.Source{getSourceDef(){var e,n,r;const i=this.getTableInfo();if(i===void 0)return fQ.ErrorFactory.structDef;const{tablePath:s,connectionName:o}=i,u=(0,cQ.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.logError("failed-to-fetch-table-schema",l),fQ.ErrorFactory.structDef}}Wl.TableSource=gD;class y5e extends gD{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.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}Wl.TableMethodSource=y5e;class E5e extends gD{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,cQ.deprecatedParseTableURI)(this.tableURI)}}Wl.TableFunctionSource=E5e;var o4={};Object.defineProperty(o4,"__esModule",{value:!0}),o4.SQLString=void 0;const A5e=Ge,xQ=uu;class v5e extends A5e.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(S5e)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof xQ.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","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("failed-to-expand-sql-source","Cannot expand into a query")}return e}}o4.SQLString=v5e;function S5e(t){return t instanceof xQ.SourceQueryElement}var u4={};Object.defineProperty(u4,"__esModule",{value:!0}),u4.SourceDesc=void 0;const _5e=Ge;class C5e extends _5e.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}u4.SourceDesc=C5e;var a4={};Object.defineProperty(a4,"__esModule",{value:!0}),a4.isSourceProperty=void 0;const T5e=oo,b5e=wl,R5e=od,O5e=Ll,D5e=ud,N5e=ad,w5e=ld,F5e=Fl,L5e=Ti;function I5e(t){return t instanceof T5e.Filter||t instanceof L5e.JoinStatement||t instanceof b5e.DeclareFields||t instanceof R5e.FieldListEdit||t instanceof O5e.Renames||t instanceof D5e.PrimaryKey||t instanceof F5e.ObjectAnnotation||t instanceof N5e.Views||t instanceof w5e.TimezoneStatement}a4.isSourceProperty=I5e;var l4={};Object.defineProperty(l4,"__esModule",{value:!0}),l4.isFieldCollectionMember=void 0;const $5e=xn,dQ=ht;function B5e(t){return t instanceof dQ.FieldReference||t instanceof dQ.WildcardFieldReference||t instanceof $5e.AtomicFieldDeclaration}l4.isFieldCollectionMember=B5e;var c4={};Object.defineProperty(c4,"__esModule",{value:!0}),c4.isQueryElement=void 0;const k5e=cd,P5e=fd,M5e=E1,j5e=A1;function U5e(t){return t instanceof k5e.QueryArrow||t instanceof P5e.QueryRefine||t instanceof M5e.QueryReference||t instanceof j5e.QueryRaw}c4.isQueryElement=U5e;var hQ={};Object.defineProperty(hQ,"__esModule",{value:!0});var f4={};Object.defineProperty(f4,"__esModule",{value:!0}),f4.isQueryProperty=void 0;function q5e(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}f4.isQueryProperty=q5e;var x4={};Object.defineProperty(x4,"__esModule",{value:!0}),x4.isQueryExtendProperty=void 0;const H5e=J1,z5e=Ti,Q5e=X1;function G5e(t){return t instanceof H5e.Dimensions||t instanceof Q5e.Measures||t instanceof z5e.JoinStatement}x4.isQueryExtendProperty=G5e;var d4={};Object.defineProperty(d4,"__esModule",{value:!0}),d4.isFieldPropStatement=void 0;const W5e=$l,V5e=oo,Y5e=kl,J5e=yd;function X5e(t){return t instanceof V5e.Filter||t instanceof Y5e.Limit||t instanceof J5e.PartitionBy||t instanceof W5e.FunctionOrdering}d4.isFieldPropStatement=X5e,function(t){var e=D&&D.__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=D&&D.__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(a1,t),n(td,t),n(nd,t),n(so,t),n(f1,t),n(uu,t),n(kA,t),n(PA,t),n(qA,t),n(p1,t),n(QA,t),n(od,t),n(ud,t),n(Ll,t),n(ad,t),n(ld,t),n(GA,t),n(pd,t),n(VA,t),n($l,t),n(YA,t),n(pa,t),n(JA,t),n(md,t),n(KA,t),n(ZA,t),n(ev,t),n(ha,t),n(tv,t),n(nv,t),n(iv,t),n(b1,t),n(_1,t),n(Ic,t),n(sv,t),n(ov,t),n(av,t),n(cv,t),n(fv,t),n(xv,t),n(dv,t),n(hv,t),n(pv,t),n(gv,t),n(mv,t),n(yv,t),n(Ev,t),n(Av,t),n(vv,t),n(Cv,t),n(Xn,t),n(jv,t),n(yd,t),n(Rd,t),n(Dd,t),n(Nd,t),n(Il,t),n(qv,t),n(Hv,t),n(R1,t),n(Hl,t),n(H1,t),n(zv,t),n(Qv,t),n(Gv,t),n(fd,t),n(cd,t),n(zl,t),n(Wv,t),n(Vv,t),n(Yv,t),n(Jv,t),n(xn,t),n(ht,t),n(n4,t),n(r4,t),n(wl,t),n(J1,t),n(H1,t),n(oo,t),n(V1,t),n(G1,t),n(Ti,t),n(l1,t),n(kl,t),n(X1,t),n(a1,t),n(i4,t),n(Qc,t),n(s4,t),n(Q1,t),n(W1,t),n(Y1,t),n(xd,t),n(Lc,t),n(v1,t),n(Wl,t),n(o4,t),n(Fl,t),n(uo,t),n(u4,t),n(a4,t),n(st,t),n(l4,t),n(Pl,t),n(Ge,t),n(c4,t),n(hQ,t),n(f4,t),n(x4,t),n(d4,t)}(RA);var h4={},wd={};Object.defineProperty(wd,"__esModule",{value:!0}),wd.ConstantExpression=wd.ConstantFieldSpace=void 0;const K5e=st;class pQ{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}}wd.ConstantFieldSpace=pQ;class Z5e extends K5e.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new pQ),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,n,r){return this.expr.apply(e,n,r)}requestExpression(e){return this.expr.requestExpression(e)}}wd.ConstantExpression=Z5e;var eCe=D&&D.__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]}),tCe=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),nCe=D&&D.__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)&&eCe(e,t,n);return tCe(e,t),e};Object.defineProperty(h4,"__esModule",{value:!0}),h4.MalloyToAST=void 0;const gQ=CE,rCe=f2,Z=nCe(RA),mD=OA,mQ=Qn,iCe=RA,$n=nn,yD=oe,sCe=Mo,oCe=wd;class yQ extends Z.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class ED extends Z.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const uCe=["##! m4warnings=error"];class aCe extends rCe.AbstractParseTreeVisitor{constructor(e,n,r){super(),this.parseInfo=e,this.msgLog=n,this.compilerFlags=r;for(const i of uCe){const s=sCe.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,n){return this.contextError(e,"internal-translator-error",{message:n}),new Error(`Internal Translator Error: ${n}`)}astError(e,n,r,i){this.msgLog.log((0,mD.makeLogMessage)(n,r,{at:e.location,...i}))}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new mQ.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,n,r,i){this.msgLog.log((0,mD.makeLogMessage)(n,r,{at:this.getLocation(e),...i}))}warnWithReplacement(e,n,r,i){this.msgLog.log((0,mD.makeLogMessage)(e,n,{at:{url:this.parseInfo.sourceURL,range:r},severity:"warn",replacement:i}))}inExperiment(e,n){const r=this.compilerFlags.tag("experimental");return r&&(r.bare()||r.has(e))?!0:(this.contextError(n,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,n,r){const i=this.m4Severity();i&&this.contextError(e,n,r,{severity:i})}only(e,n,r){const i=[];for(const s of e){const o=n(s);o?i.push(o):s instanceof ED||this.astError(s,"unexpected-statement-in-translation",`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 Z.FieldName((0,$n.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new Z.ModelEntryReference((0,$n.getId)(e)),e.id())}defaultResult(){return new Z.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 mQ.Interval(n,r.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){const n=this.getFieldExpr(e),r=new Z.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 Z.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","Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new Z.Filter([n])}getPlainStringFrom(e){const[n,r]=(0,$n.getPlainString)(e);for(const i of r)i instanceof gQ.ParserRuleContext&&this.contextError(i,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return n||""}makeSqlString(e,n){for(const r of e.sqlInterpolation())r.CLOSE_CODE()&&this.m4advisory(r,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const r of(0,$n.getStringParts)(e))r instanceof gQ.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,"failed-to-parse-time-literal","Time data parse error"),r=new Z.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=>Z.isDocStatementOrDocStatementList(r)&&r,"statement");return new Z.Document(n)}visitDefineSourceStatement(e){const r=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new Z.DefineSourceList(r);return s.extendNote({blockNotes:i}),s}getSourceParameter(e){const n=e.fieldExpr(),r=n?this.astAt(new oCe.ConstantExpression(this.getFieldExpr(n)),n):void 0,i=e.malloyType(),s=i?this.getMalloyType(i):void 0;return this.astAt(new Z.HasParameter({name:(0,$n.getId)(e.parameterNameDef()),type:s,default:r}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(n=>this.getSourceParameter(n)))}visitSourceDefinition(e){const n=this.visit(e.sqExplore()),r=this.getSourceParameters(e.sourceParameters()),i=new Z.DefineSource((0,$n.getId)(e.sourceNameDef()),n instanceof Z.SourceQueryElement?n:void 0,!0,r),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,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=>Z.isSourceProperty(s)&&s,"source property"),i=new Z.SourceDesc(r);return n&&i.push(this.getFilterShortcut(n)),i}visitTableFunction(e){const n=this.getPlainStringFrom(e.tableURI()),r=this.astAt(new Z.TableFunctionSource(n),e);return this.m4advisory(e,"table-function","`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.getPlainStringFrom(e.tablePath());return this.astAt(new Z.TableMethodSource(r,i),e)}visitSqlSource(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=new Z.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);const o=e.shortString();o&&i.push((0,$n.getShortString)(o));const u=new Z.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 Z.Join&&(n.push(s),s instanceof Z.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):s instanceof Z.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const r=new Z.JoinStatement(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 Z.Join&&(r.push(s),s instanceof Z.ExpressionJoin&&(s.joinType="one"));const i=new Z.JoinStatement(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 Z.Join&&(r.push(s),s instanceof Z.ExpressionJoin?s.joinType="cross":s.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const i=new Z.JoinStatement(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return this.only(e.joinDef().map(n=>this.visit(n)),n=>n instanceof Z.Join&&n,"join")}getJoinFrom(e){const n=e.isExplore(),r=this.getModelEntryName(e.joinNameDef());if(n){const s=this.getSqExpr(n.sqExpr()),o=this.getNotes(n._before_is).concat(this.getNotes(n._after_is));return{joinFrom:s,notes:o,joinAs:r}}const i=e.sourceArguments();return i?{joinFrom:this.astAt(new Z.SQReference(r,this.getSQArguments(i)),e),notes:[],joinAs:r}:{joinAs:r,joinFrom:new Z.SQReference(r),notes:[]}}visitQueryJoinStatement(e){const n=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"join-statement-in-view","Joins in queries are deprecated, move into an `extend:` block."),n}visitJoinOn(e){var n;const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=new Z.ExpressionJoin(r,i),u=e.joinExpression(),a=((n=e.matrixOperation())===null||n===void 0?void 0:n.text.toLocaleLowerCase())||"left";return(0,yD.isMatrixOperation)(a)?o.matrixOperation=a:this.contextError(e,"unknown-matrix-operation","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{joinAs:n,joinFrom:r,notes:i}=this.getJoinFrom(e.joinFrom()),s=this.getFieldExpr(e.fieldExpr()),o=new Z.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,$n.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(),Z.DimensionFieldDeclaration),r=new Z.Dimensions(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitDefMeasures(e){const n=this.getFieldDefs(e.defList().fieldDef(),Z.MeasureFieldDeclaration),r=new Z.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(Z.isQueryExtendProperty(s))n.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);const i=new Z.ExtendBlock(n);return this.astAt(i,e)}visitDeclareStatement(e){const n=this.getFieldDefs(e.defList().fieldDef(),Z.DeclareFieldDeclaration),r=new Z.DeclareFields(n),i=this.astAt(r,e);return this.m4advisory(e,"declare","`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 Z.RenameField((0,$n.getId)(n),this.getFieldName(r));return this.astAt(i,e)}visitDefExploreRename(e){const r=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new Z.Renames(r);return this.astAt(i,e)}visitFilterClauseList(e){return new Z.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 Z.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,"query-in-source","Use view: inside of a source instead of query:"),n}visitDefExplorePrimaryKey(e){const n=new Z.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(n,e)}visitFieldNameList(e){const n=e.fieldName().map(r=>new Z.AcceptExceptFieldReference([this.getFieldName(r)]));return new Z.FieldReferences(n)}visitDefExploreEditField(e){const n=e.ACCEPT()?"accept":"except";return new Z.FieldListEdit(n,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const n=this.getPlainStringFrom(e),r=this.astAt(new Z.TimezoneStatement(n),e.string());return r.isValid||this.astError(r,"invalid-timezone",{timezone:r.tz}),this.astAt(r,e)}visitQueryProperties(e){const n=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>Z.isQueryProperty(i)&&i,"query statement"),r=e.filterShortcut();return r&&n.push(this.getFilterShortcut(r)),new Z.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 Z.FieldReference||i instanceof Z.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){const n=new Z.Aggregate(this.getQueryItems(e.queryFieldList(),Z.AggregateFieldDeclaration,Z.AggregateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitGroupByStatement(e){const n=new Z.GroupBy(this.getQueryItems(e.queryFieldList(),Z.GroupByFieldDeclaration,Z.GroupByFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCalculateStatement(e){const n=new Z.Calculate(this.getQueryItems(e.queryFieldList(),Z.CalculateFieldDeclaration,Z.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(),Z.ExpressionFieldReference);let u;const a=i.timeframe();a&&(u=new Z.ExprGranularTime(new Z.ExprIdReference(o),this.visitTimeframe(a).text,!0));const l=i.aggregate();if(l){const f=l.text.toLowerCase();if(f==="sum")u=new Z.ExprSum(void 0,o);else return this.contextError(l,"invalid-reference-only-aggregation",`\`${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,Z.ProjectFieldDeclaration,Z.ProjectFieldReference));return this.astAt(new Z.ProjectStatement(n),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","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,Z.ProjectFieldReference):void 0,s=this.astAt(new Z.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,$n.getId)(a));return s}visitIndexFields(e){const n=e.indexElement().map(r=>{const i=r.fieldPath();if(!i)return this.astAt(new Z.WildcardFieldReference(void 0),e);const s=this.getFieldPath(i,Z.IndexFieldReference);return r.STAR()?this.astAt(new Z.WildcardFieldReference(s),e):this.astAt(s,e)});return new Z.FieldReferences(n)}visitIndexStatement(e){const n=this.visitIndexFields(e.indexFields()),r=new Z.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 Z.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 Z.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 Z.FunctionOrdering(n),e)}visitOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.INTEGER_LITERAL();if(r)return new Z.OrderBy(this.getNumber(r),n);const i=e.fieldName();if(i)return new Z.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 Z.Ordering(n),e)}visitTopStatement(e){const n=e.bySpec(),r=this.getNumber(e.INTEGER_LITERAL());let i;if(n){this.m4advisory(n,"top-by","by clause of top statement unupported. Use order_by instead");const s=n.fieldName();if(s){const u=this.getFieldName(s);i=new Z.Top(r,u)}const o=n.fieldExpr();o&&(i=new Z.Top(r,this.getFieldExpr(o)))}return i||(i=new Z.Top(r,void 0)),this.astAt(i,e)}visitTopLevelQueryDefs(e){const n=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),r=this.getNotes(e.tags()),i=new Z.DefineQueryList(n);return i.extendNote({blockNotes:r}),i}visitTopLevelQueryDef(e){const n=(0,$n.getId)(e.queryName()),r=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(r instanceof Z.SourceQueryElement){const s=new Z.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 Z.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","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 Z.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 Z.Nests(this.only(e.nestEntry().map(n=>this.visit(n)),n=>n instanceof Z.NestFieldDeclaration&&n,"query"))}visitNestDef(e){const n=e.queryName();let r;const i=this.getVExpr(e.vExpr());if(n)r=(0,$n.getId)(n);else{const u=i.getImplicitName();u===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),r=u??"__unnamed__"}const s=new Z.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,$n.getId)(e.exploreQueryNameDef()),r=new Z.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 Z.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new Z.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 Z.ExprLogicalOp(n,"or",r)}visitExprLogicalAnd(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new Z.ExprLogicalOp(n,"and",r)}visitExprOrTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new Z.ExprAlternationTree(n,"|",r),e)}visitExprAndTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new Z.ExprAlternationTree(n,"&",r),e)}visitExprCoalesce(e){const n=this.getFieldExpr(e.fieldExpr()[0]),r=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new Z.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(Z.isComparison(i))return this.astAt(new Z.PartialCompare(i,r),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return r}visitExprString(e){const n=this.getPlainStringFrom(e);return new Z.ExprString(n)}visitExprRegex(e){const n=e.HACKY_REGEX().text;return new Z.ExprRegEx(n.slice(2,-1))}visitExprNow(e){return new Z.ExprNow}visitExprNumber(e){return new Z.ExprNumber(e.text)}visitExprFieldPath(e){const n=new Z.ExprIdReference(this.getFieldPath(e.fieldPath(),Z.ExpressionFieldReference));return this.astAt(n,e)}visitExprNULL(e){return new Z.ExprNULL}visitExprExpr(e){return new Z.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new Z.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 Z.ExprAddSub(n,i,r)}visitExprMulDiv(e){const n=e.STAR()?"*":e.SLASH()?"/":"%";return new Z.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const n=e.compareOp().text,r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));if(Z.isEquality(n))return this.astAt(new Z.ExprEquality(r,n,i),e);if(Z.isComparison(n))return this.astAt(new Z.ExprCompare(r,n,i),e);throw this.internalError(e,`untranslatable comparison operator '${n}'`)}visitExprUngroup(e){const n=e.fieldName().map(i=>this.getFieldName(i)),r=e.ungroup().text.toLowerCase();return this.astAt(new Z.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,Z.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,"count-expression-with-locality","Expression illegal inside path.count()"),new Z.ExprCount(i);const u=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(u)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s));else{const a=this.astAt(new Z.ExprIdReference(r),n);return s==="min"?new Z.ExprMin(a):new Z.ExprMax(a)}else{if(s==="avg")return new Z.ExprAvg(u,i);if(s==="sum")return new Z.ExprSum(u,i);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${s}`)}return new Z.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,"wildcard-in-aggregate",`* illegal inside ${s}()`),s==="count")return this.astAt(r?new Z.ExprCountDistinct(r):new Z.ExprCount,e);if(s==="min"){if(r)return new Z.ExprMin(r);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s))}else if(s==="max"){if(r)return new Z.ExprMax(r);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s))}else{if(r===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(s)),new Z.ExprNULL;const o=e.SOURCE_KW()!==void 0;if(s==="avg")return new Z.ExprAvg(r,i,o);if(s==="sum")return new Z.ExprSum(r,i,o)}return new Z.ExprNULL}visitExprApply(e){return new Z.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new Z.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new Z.ExprCast(this.getFieldExpr(e.fieldExpr()),n)}getMalloyType(e){const n=e.text;if((0,yD.isCastType)(n))return n;throw this.internalError(e,`unknown type '${n}'`)}getMalloyOrSQLType(e){const n=e.malloyType();if(n)return this.getMalloyType(n);const r=e.string();if(r)return{raw:this.getPlainStringFrom({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 Z.ExprCast(this.getFieldExpr(e.fieldExpr()),n,!0)}visitExprTimeTrunc(e){return new Z.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new Z.Timeframe(e.text)}visitExprForRange(e){const n=this.getFieldExpr(e._startAt),r=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new Z.ForRange(n,r,i)}visitExprAggFunc(e){const n=e.argumentList(),r=n?this.allFieldExpressions(n.fieldExpr()):[],i=(0,$n.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,Z.ExpressionFieldReference):void 0,u=s&&o?this.astAt(o,s):void 0;return Z.ExprTimeExtract.extractor(i)?this.astAt(new Z.ExprTimeExtract(i,r),e):this.astAt(new Z.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,yD.isCastType)(u)?a=u:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${u}'`),a=void 0));let l=(0,$n.getOptionalId)(e)||((r=e.timeframe())===null||r===void 0?void 0:r.text);return l===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),l="FUNCTION_NAME_ERROR"),Z.ExprTimeExtract.extractor(l)?this.astAt(new Z.ExprTimeExtract(l,s),e):this.astAt(new Z.ExprFunc(l,s,o,a),e)}visitExprDuration(e){return new Z.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const n=e._valueExpr,r=n?this.getFieldExpr(n):void 0,i=e.caseWhen(),s=i.map(a=>new Z.CaseWhen(this.getFieldExpr(a._condition),this.getFieldExpr(a._result))),o=e._caseElse,u=o?this.getFieldExpr(o):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.parseInfo.rangeFromContext(e),`${[...n?[`${this.getSourceCode(n)} ?`]:[],...i.map(a=>`pick ${this.getSourceCode(a._result)} when ${this.getSourceCode(a._condition)}`),o?`else ${o.text}`:"else null"].join(" ")}`),new Z.Case(r,s,u)}visitPickStatement(e){const n=e.pick().map(r=>{let i;return r._pickValue&&(i=this.getFieldExpr(r._pickValue)),new Z.PickWhen(i,this.getFieldExpr(r._pickWhen))});return e.ELSE()?new Z.Pick(n,this.getFieldExpr(e._pickElse)):new Z.Pick(n)}visitExprFieldProps(e){const n=this.only(e.fieldProperties().fieldPropertyStatement().map(r=>this.visit(r)),r=>Z.isFieldPropStatement(r)&&r,"field property statement");return new Z.ExprProps(this.getFieldExpr(e.fieldExpr()),n)}visitPartitionByStatement(e){return this.astAt(new Z.PartitionBy(e.id().map(n=>this.astAt(new Z.PartitionByFieldReference([this.astAt(new Z.FieldName((0,$n.idToStr)(n)),n)]),n))),e)}visitLiteralTimestamp(e){return this.parseTime(e,Z.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,Z.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,Z.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,Z.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,Z.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,Z.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,Z.LiteralYear.parse)}visitImportStatement(e){const n=this.getPlainStringFrom(e.importURL()),r=this.astAt(new Z.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 Z.ImportSourceName((0,$n.idToStr)(o[1])),o[1]):void 0;r.push(this.astAt(new Z.ImportSelect((0,$n.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 Z.SampleProperty({rows:this.getNumber(n)});const r=e.sampleSpec().PERCENT_LITERAL();if(r)return new Z.SampleProperty({percent:this.getNumber(r)});const i=e.sampleSpec().TRUE()!==void 0;return new Z.SampleProperty({enable:i})}visitDocAnnotations(e){const n=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),r=new Z.ModelAnnotation(n);return this.compilerFlags=r.getCompilerFlags(this.compilerFlags,this.msgLog),r}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new ED(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new ED(e.text)}visitDefExploreAnnotation(e){const n=this.getNotes(e);return new Z.ObjectAnnotation(n)}getSQArgument(e){const n=e.argumentId(),r=n?this.astAt(new Z.PartitionByFieldReference([this.astAt(new Z.FieldName((0,$n.idToStr)(n.id())),n)]),n):void 0;return this.astAt(new Z.Argument({id:r,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(n=>this.getSQArgument(n))}visitSQID(e){const n=this.getModelEntryName(e),r=this.getSQArguments(e.sourceArguments());return this.astAt(new Z.SQReference(n,r),e.id())}getSqExpr(e){const n=this.visit(e);return n instanceof Z.SourceQueryElement?n:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${n.elementType}'`),new yQ)}visitSQExtendedSource(e){const n=this.getSqExpr(e.sqExpr()),r=new Z.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 Z.SQArrow(n,this.getVExpr(r));return this.astAt(i,e)}getVExpr(e){const n=this.visit(e);if(n instanceof Z.View)return n;throw this.internalError(e,`Expected view, got a '${n.elementType}'`)}visitSegField(e){return new Z.ReferenceView(this.getFieldPath(e.fieldPath(),Z.ViewOrScalarFieldReference))}visitSegOps(e){return new Z.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new Z.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new Z.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new Z.SQRefine(n,this.getVExpr(r));return this.astAt(i,e)}visitSQTable(e){const n=this.visit(e.exploreTable());if(n instanceof iCe.TableSource){const r=new Z.SQSource(n);return this.astAt(r,e)}return new yQ}visitSQSQL(e){const n=new Z.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(n,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new Z.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitExprWarnLike(e){let n="~";const r=e.fieldExpr(0),i=e.fieldExpr(1),s=this.parseInfo.rangeFromContext(e);return e.NOT()?(n="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",s,`${this.getSourceCode(r)} !~ ${this.getSourceCode(i)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",s,`${this.getSourceCode(r)} ~ ${this.getSourceCode(i)}`),this.astAt(new Z.ExprCompare(this.getFieldExpr(r),n,this.getFieldExpr(i)),e)}visitExprWarnNullCmp(e){let n="=";const r=e.fieldExpr(),i=this.parseInfo.rangeFromContext(e);e.NOT()?(n="!=",this.warnWithReplacement("sql-is-not-null","Use '!= NULL' to check for NULL instead of 'IS NOT NULL'",i,`${this.getSourceCode(r)} != null`)):this.warnWithReplacement("sql-is-null","Use '= NULL' to check for NULL instead of 'IS NULL'",i,`${this.getSourceCode(r)} = null`);const s=new Z.ExprNULL;return this.astAt(new Z.ExprCompare(this.getFieldExpr(r),n,s),e)}visitExprWarnIn(e){const n=this.getFieldExpr(e.fieldExpr()),r=!!e.NOT(),i=e.fieldExprList().fieldExpr(),s=this.astAt(new Z.ExprLegacyIn(n,r,i.map(o=>this.getFieldExpr(o))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${r?" NOT":""} IN (a,b,c)`,this.parseInfo.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${r?"!=":"="} (${i.map(o=>this.getSourceCode(o)).join(" | ")})`),s}}h4.MalloyToAST=aCe;var p4={};Object.defineProperty(p4,"__esModule",{value:!0}),p4.Zone=void 0;class lCe{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})}}p4.Zone=lCe;var g4={};Object.defineProperty(g4,"__esModule",{value:!0}),g4.walkForDocumentSymbols=void 0;const cCe=dl,fCe=nn;class xCe{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.joinFrom().joinNameDef().id().text,type:"join",children:[]},r=this.peekScope();r&&r.children.push(n)}enterImportStatement(e){const n=(0,fCe.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 dCe(t,e,n){const r=new xCe(t,e,[],[]),i=r;return cCe.ParseTreeWalker.DEFAULT.walk(i,n),r.symbols}g4.walkForDocumentSymbols=dCe;var m4={};Object.defineProperty(m4,"__esModule",{value:!0}),m4.walkForDocumentCompletions=void 0;const hCe=dl,pCe=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],gCe=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],mCe=["source","explore","query","sql"];class yCe{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 pCe)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 gCe)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 mCe)this.completions.push({type:"model_property",text:`${r}: `})}}}function ECe(t,e,n){const r=new yCe(t,[],n),i=r;return hCe.ParseTreeWalker.DEFAULT.walk(i,e),r.completions}m4.walkForDocumentCompletions=ECe;var y4={};Object.defineProperty(y4,"__esModule",{value:!0}),y4.walkForDocumentHelpContext=void 0;const ACe=vb;class vCe extends ACe.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 SCe(t,e){return new vCe(e).visit(t)}y4.walkForDocumentHelpContext=SCe;var E4={},K1={};Object.defineProperty(K1,"__esModule",{value:!0}),K1.locationContainsPosition=void 0;function _Ce(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)}K1.locationContainsPosition=_Ce,Object.defineProperty(E4,"__esModule",{value:!0}),E4.ReferenceList=void 0;const CCe=K1;class TCe{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,CCe.locationContainsPosition)(r.location,e))return r}}E4.ReferenceList=TCe;var A4={};Object.defineProperty(A4,"__esModule",{value:!0}),A4.isNeedResponse=void 0;function bCe(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}A4.isNeedResponse=bCe;var v4={};Object.defineProperty(v4,"__esModule",{value:!0}),v4.walkForModelAnnotation=void 0;const RCe=dl;class OCe{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 DCe(t,e,n){const r=new OCe(t,e,n),i=r;return RCe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.annotation}v4.walkForModelAnnotation=DCe;var S4={};Object.defineProperty(S4,"__esModule",{value:!0}),S4.walkForTablePath=void 0;const EQ=nn,NCe=dl;class wCe{constructor(e,n){this.translator=e,this.tokens=n,this.pathInfos=[]}enterTableMethod(e){const n=(0,EQ.getId)(e.connectionId()),[r,i]=(0,EQ.getPlainString)(e.tablePath(),!0);r!==void 0&&this.pathInfos.push({connectionId:n,tablePath:r,range:this.translator.rangeFromContext(e)})}}function FCe(t,e,n){const r=new wCe(t,e),i=r;return NCe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.pathInfos}S4.walkForTablePath=FCe;var LCe=D&&D.__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]}),ICe=D&&D.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$Ce=D&&D.__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)&&LCe(e,t,n);return ICe(e,t),e};Object.defineProperty(eu,"__esModule",{value:!0}),eu.MalloyParserErrorHandler=eu.MalloyTranslator=eu.MalloyChildTranslator=eu.MalloyTranslation=void 0;const AQ=CE,BCe=oe,kCe=jE,PCe=F,vQ=$Ce(RA),MCe=h4,AD=OA,jCe=ma,vD=p4,UCe=g4,qCe=m4,HCe=y4,zCe=E4,_4=A4,QCe=K1,SQ=Mo,GCe=v4,WCe=S4;class VCe extends kCe.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}class YCe{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.logError("failed-to-compute-absolute-import-url",`Could not compute full path URL: ${o}`)}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.firstReference||e.defaultLocation();return e.root.logError("import-error",{message:n.message,url:e.sourceURL},{at:s}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const r=n.value===""?`
1327
1327
  `:n.value;this.sourceInfo=this.getSourceInfo(r);let i;try{i=this.runParser(r,e)}catch(s){e.root.logError("parse-exception",{message:s.message}),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=AQ.CharStreams.fromString(e),i=new VCe(r),s=new AQ.CommonTokenStream(i),o=new PCe.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new CQ(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 JCe{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,jCe.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.logError("invalid-import-url",`Malformed URL '${o}'"`,{at:{url:e.sourceURL,range:u}})}}}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,_4.isNeedResponse)(r))return r;for(const o of e.childTranslators.values()){const u=o.importsAndTablesStep.step(o);if((0,_4.isNeedResponse)(u))return u}return null}}class XCe{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 MCe.MalloyToAST(i,e.root.logger,e.compilerFlags),o=s.visit(i.root);if(e.compilerFlags=s.compilerFlags,o.elementType==="unimplemented"&&o.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node"),!this.walked){for(const u of o.walk())u instanceof vQ.Unimplemented&&u.logError("untranslated-parse-node","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,_4.isNeedResponse)(a))return a}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}}class KCe{constructor(e){this.parseStep=e}step(e){if(!this.response){const n=this.parseStep.step(e);if(n.parse){let r;try{r=(0,UCe.walkForDocumentSymbols)(e,n.parse.tokenStream,n.parse.root)}catch{}this.response={symbols:r,final:!0}}else return n}return this.response}}class ZCe{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,qCe.walkForDocumentCompletions)(r.parse.tokenStream,r.parse.root,n)}catch{}return{...r,completions:i}}else return r}}class eTe{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,HCe.walkForDocumentHelpContext)(r.parse.root,n)}catch{}return{...r,helpContext:i}}else return r}}class tTe{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,GCe.walkForModelAnnotation)(e,r.parse.tokenStream,r.parse);this.response={modelAnnotation:{...i,inherits:n==null?void 0:n.annotation}}}}return this.response}}class nTe{constructor(e){this.parseStep=e}step(e){if(!this.response){const n=this.parseStep.step(e);if(n.parse){const r=(0,WCe.walkForTablePath)(e,n.parse.tokenStream,n.parse);this.response={pathInfo:r}}else return n}return this.response}}class rTe{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,n){if(this.response)return this.response;if(n&&!this.importedAnnotations){const i=SQ.Tag.annotationToTag(n.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}const r=this.astStep.step(e);if((0,_4.isNeedResponse)(r))return r;if(!r.ast)return this.response=r,this.response;if(e.grammarRule==="malloyDocument")if(r.ast instanceof vQ.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.logError("parsed-non-malloy-document",{url:e.sourceURL},{at:e.defaultLocation()});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 SD{constructor(e,n=null,r="malloyDocument"){this.sourceURL=e,this.importBaseURL=n,this.grammarRule=r,this.queryList=[],this.sqlBlocks=[],this.imports=[],this.compilerFlags=new SQ.Tag,this.dialectAlreadyChecked={},this.allDialectsEnabled=!1,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new YCe,this.modelAnnotationStep=new tTe(this.parseStep),this.metadataStep=new KCe(this.parseStep),this.completionsStep=new ZCe(this.parseStep),this.helpContextStep=new eTe(this.parseStep),this.importsAndTablesStep=new JCe(this.parseStep),this.astStep=new XCe(this.importsAndTablesStep),this.tablePathInfoStep=new nTe(this.parseStep),this.translateStep=new rTe(this.astStep),this.references=new zCe.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new _Q(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}
1328
1328
  | ${l}`,u>0&&(i=i+`
1329
1329
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1330
1330
  `+i,n=s),e!==""?e=`${e}
1331
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,BCe.modelObjIsSource)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,QCe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}eu.MalloyTranslation=SD;class _Q extends SD{constructor(e,n){super(e),this.root=n}}eu.MalloyChildTranslator=_Q;class iTe extends SD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new vD.Zone,this.importZone=new vD.Zone,this.sqlQueryZone=new vD.Zone,this.root=this,this.logger=new AD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,AD.makeLogMessage)(e,n,{severity:"error",...r})),e}}eu.MalloyTranslator=iTe;class CQ{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,AD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}eu.MalloyParserErrorHandler=CQ;var Fd={};Object.defineProperty(Fd,"__esModule",{value:!0}),Fd.exploreQueryWalkerBuilder=Fd.ExploreQueryWalker=void 0;const sTe=dl;class TQ{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Fd.ExploreQueryWalker=TQ;function oTe(t,e){const n=new TQ(t),r=n;return sTe.ParseTreeWalker.DEFAULT.walk(r,e),n}Fd.exploreQueryWalkerBuilder=oTe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=eu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Fd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(W6);var Oe={},C4={};Object.defineProperty(C4,"__esModule",{value:!0}),C4.MALLOY_VERSION=void 0,C4.MALLOY_VERSION="0.0.199",Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.PreparedResultMaterializer=Oe.QueryMaterializer=Oe.ModelMaterializer=Oe.SingleConnectionRuntime=Oe.ConnectionRuntime=Oe.Runtime=Oe.ExploreField=Oe.JoinRelationship=Oe.QueryField=Oe.Query=Oe.StringField=Oe.UnsupportedField=Oe.JSONField=Oe.BooleanField=Oe.NumberField=Oe.TimestampField=Oe.DateField=Oe.TimestampTimeframe=Oe.DateTimeframe=Oe.AtomicField=Oe.AtomicFieldType=Oe.Explore=Oe.SourceRelationship=Oe.FixedConnectionMap=Oe.InMemoryURLReader=Oe.EmptyURLReader=Oe.PreparedResult=Oe.DocumentCompletion=Oe.DocumentSymbol=Oe.DocumentPosition=Oe.DocumentRange=Oe.DocumentTablePath=Oe.Parse=Oe.PreparedQuery=Oe.Model=Oe.MalloyError=Oe.Malloy=void 0;const uTe=W6,gr=Ai,bQ=Ri,An=Mo,_D=lx,aTe=C4;class Nn{static get version(){return aTe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new uTe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new OQ(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Nn._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>Nn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new Z1(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new Z1(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new RQ(`Error(s) compiling model:
1331
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,BCe.modelObjIsSource)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,QCe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}eu.MalloyTranslation=SD;class _Q extends SD{constructor(e,n){super(e),this.root=n}}eu.MalloyChildTranslator=_Q;class iTe extends SD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new vD.Zone,this.importZone=new vD.Zone,this.sqlQueryZone=new vD.Zone,this.root=this,this.logger=new AD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,AD.makeLogMessage)(e,n,{severity:"error",...r})),e}}eu.MalloyTranslator=iTe;class CQ{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,AD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}eu.MalloyParserErrorHandler=CQ;var Fd={};Object.defineProperty(Fd,"__esModule",{value:!0}),Fd.exploreQueryWalkerBuilder=Fd.ExploreQueryWalker=void 0;const sTe=dl;class TQ{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Fd.ExploreQueryWalker=TQ;function oTe(t,e){const n=new TQ(t),r=n;return sTe.ParseTreeWalker.DEFAULT.walk(r,e),n}Fd.exploreQueryWalkerBuilder=oTe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=eu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Fd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(W6);var Oe={},C4={};Object.defineProperty(C4,"__esModule",{value:!0}),C4.MALLOY_VERSION=void 0,C4.MALLOY_VERSION="0.0.200",Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.PreparedResultMaterializer=Oe.QueryMaterializer=Oe.ModelMaterializer=Oe.SingleConnectionRuntime=Oe.ConnectionRuntime=Oe.Runtime=Oe.ExploreField=Oe.JoinRelationship=Oe.QueryField=Oe.Query=Oe.StringField=Oe.UnsupportedField=Oe.JSONField=Oe.BooleanField=Oe.NumberField=Oe.TimestampField=Oe.DateField=Oe.TimestampTimeframe=Oe.DateTimeframe=Oe.AtomicField=Oe.AtomicFieldType=Oe.Explore=Oe.SourceRelationship=Oe.FixedConnectionMap=Oe.InMemoryURLReader=Oe.EmptyURLReader=Oe.PreparedResult=Oe.DocumentCompletion=Oe.DocumentSymbol=Oe.DocumentPosition=Oe.DocumentRange=Oe.DocumentTablePath=Oe.Parse=Oe.PreparedQuery=Oe.Model=Oe.MalloyError=Oe.Malloy=void 0;const uTe=W6,gr=Ai,bQ=Ri,An=Mo,_D=lx,aTe=C4;class Nn{static get version(){return aTe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new uTe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new OQ(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Nn._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>Nn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new Z1(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new Z1(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new RQ(`Error(s) compiling model:
1332
1332
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const A=await e.readURL(new URL(E)),v={[E]:A};m.update({urls:v})}catch(A){m.update({errors:{urls:{[E]:A.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const A in g.tables){const{connectionName:v,tablePath:_}=g.tables[A],S=E.get(v);S===void 0?E.set(v,{[A]:_}):S[A]=_}for(const[A,v]of E)try{const _=await n.lookupConnection(A),{schemas:S,errors:C}=await Nn.safelyFetchTableSchema(_,v,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:S,errors:{tables:C}})}catch(_){const S={},C={};for(const T in v)C[T]=_.toString();m.update({tables:S,errors:{tables:C}})}}if(g.compileSQL){const E=g.compileSQL,A=E.connection;try{const v=await n.lookupConnection(A),_=Nn.compileSQLBlock(v.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),S=await v.fetchSchemaForSQLStruct(_,{refreshTimestamp:p,modelAnnotation:y});S.error&&m.update({errors:{compileSQL:{[_.name]:S.error}}}),S.structDef&&m.update({compileSQL:{[_.name]:S.structDef}})}catch(v){const _={};_[E.name]=v.toString(),m.update({errors:{compileSQL:_}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,gr.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new gr.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new rg({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new rg({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new ns(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new Yc(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=Nn;class RQ extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=RQ;let Z1=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return An.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return An.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new Ld(n,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new Ld(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Ld(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,gr.modelObjIsSource)(n))return new ns(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(gr.modelObjIsSource).map(e=>new ns(e))}get namedQueries(){const e=n=>n.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}};Oe.Model=Z1;class Ld{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=An.Tag.annotationToTag(this._modelDef.annotation).tag;return e=An.Tag.addModelScope(e,n),An.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return An.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new gr.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new eg({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,gr.modelObjIsSource)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Ld;class OQ{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new T4(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new DQ(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new NQ(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=OQ;class DQ{constructor(e){this._range=Id.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}Oe.DocumentTablePath=DQ;class Id{constructor(e,n){this._start=e,this._end=n}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new Id(new CD(e.start.line,e.start.character),new CD(e.end.line,e.end.character))}}Oe.DocumentRange=Id;class CD{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Oe.DocumentPosition=CD;class T4{constructor(e){this._range=Id.fromJSON(e.range),this._lensRange=e.lensRange?Id.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new T4(n))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}Oe.DocumentSymbol=T4;class NQ{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=NQ;class eg{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new eg(e,n)}tagParse(e){const n=An.Tag.annotationToTag(this.modelDef.annotation).tag;return e=An.Tag.addModelScope(e,n),An.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return An.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return An.Tag.annotationToTag(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new ns(n,this.sourceExplore)}catch{return new ns(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,gr.modelObjIsSource)(n))return new ns(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=eg;class wQ{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=wQ;class lTe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Oe.InMemoryURLReader=lTe;class tg{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new tg(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=tg;var FQ;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(FQ||(Oe.SourceRelationship=FQ={}));class TD{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ns}isQuery(){return this instanceof FD}}class ns extends TD{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,gr.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return An.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return An.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=An.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Ld(r,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new Z1(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,gr.isJoined)(r))return[i,new LD(r,this,s)];if(r.type==="turtle")return[i,new FD(r,this,s)];if(r.type==="string")return[i,new wD(r,this,s)];if(r.type==="number")return[i,new b4(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new b4({...r,type:"number"},this,s)]:[i,new bD(r,this,s)];if(r.type==="timestamp")return[i,new RD(r,this,s)];if(r.type==="boolean")return[i,new OD(r,this,s)];if(r.type==="json")return[i,new DD(r,this,s)];if(r.type==="sql native")return[i,new ND(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof LD}get filters(){var e;return(0,gr.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,gr.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ns.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ns.fromJSON(e.sourceExplore):void 0;return new ns(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=ns;var cu;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(cu||(Oe.AtomicFieldType=cu={}));class Vl extends TD{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return cu.String;case"boolean":return cu.Boolean;case"date":return cu.Date;case"timestamp":return cu.Timestamp;case"number":return cu.Number;case"json":return cu.Json;case"sql native":return cu.NativeUnsupported;case"error":return cu.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=An.Tag.addModelScope(e,this.parent.modelTag),An.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return An.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,gr.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,gr.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof wD}isNumber(){return this instanceof b4}isDate(){return this instanceof bD}isBoolean(){return this instanceof OD}isJSON(){return this instanceof DD}isTimestamp(){return this instanceof RD}isUnsupported(){return this instanceof ND}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Oe.AtomicField=Vl;var Vc;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Vc||(Oe.DateTimeframe=Vc={}));var fu;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(fu||(Oe.TimestampTimeframe=fu={}));class bD extends Vl{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Vc.Day;case"week":return Vc.Week;case"month":return Vc.Month;case"quarter":return Vc.Quarter;case"year":return Vc.Year}}}Oe.DateField=bD;class RD extends Vl{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return fu.Day;case"week":return fu.Week;case"month":return fu.Month;case"quarter":return fu.Quarter;case"year":return fu.Year;case"second":return fu.Second;case"hour":return fu.Hour;case"minute":return fu.Minute}}}Oe.TimestampField=RD;class b4 extends Vl{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=b4;class OD extends Vl{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=OD;class DD extends Vl{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=DD;class ND extends Vl{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=ND;class wD extends Vl{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=wD;class LQ extends TD{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Oe.Query=LQ;class FD extends LQ{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=An.Tag.addModelScope(e,this.parent.modelTag),An.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return An.Tag.annotationToTaglines(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}Oe.QueryField=FD;var $d;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})($d||(Oe.JoinRelationship=$d={}));class LD extends ns{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,gr.isJoined)(this.structDef))switch(this.structDef.join){case"one":return $d.OneToOne;case"many":case"cross":return $d.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===$d.OneToOne}get isArray(){return this.joinRelationship!==$d.OneToOne}tagParse(e){return e=An.Tag.addModelScope(e,this._parentExplore.modelTag),An.Tag.annotationToTag(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}Oe.ExploreField=LD;class ID{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&(GQ(s)?n=s:hTe(s)?r=s:WQ(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new wQ),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new ng(this,async()=>{const s=e instanceof URL?await Nn.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):Nn.parse({source:e,eventStream:this.eventStream,options:n});return Nn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new ng(this,async()=>new Z1(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}Oe.Runtime=ID;class cTe extends ID{constructor(e,n){if(n===void 0){const r=e;super(tg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,tg.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=cTe;class fTe extends ID{constructor(...e){let n,r,i;for(const s of e)GQ(s)&&(n=s),pTe(s)&&(r=s),WQ(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,_D.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,_D.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,_D.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=fTe;class R4{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new IQ(this.runtime,e,n)}makeExploreMaterializer(e,n){return new BQ(this.runtime,e,n)}makePreparedResultMaterializer(e){return new $Q(this.runtime,e)}}class ng extends R4{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await Nn.parse({url:e,urlReader:s,options:n}):Nn.parse({source:e,options:n}),a=await this.getModel();return(await Nn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new ng(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await Nn.parse({url:e,urlReader:r,options:n}):Nn.parse({source:e,options:n}),o=await this.getModel();return await Nn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new gr.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,gr.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,gr.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1333
1333
  run: ${e}
1334
1334
  -> ${o}