@malloydata/render 0.0.121-dev240202151424 → 0.0.121

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.
@@ -63861,13 +63861,6 @@ QUERY: ${(0, util_1.inspect)(opDesc, { breakLength: 72, depth: Infinity })}`);
63861
63861
  throw new Error("Expected field to have definition");
63862
63862
  }
63863
63863
  if ((0, malloy_types_1.isAtomicFieldType)(fieldDef.type)) {
63864
- if (!this.inExperiment("scalar_lenses", true)) {
63865
- if (forRefinement) {
63866
- this.reference.log(`Cannot use scalar field \`${this.reference.refString}\` as a refinement; use \`scalar_lenses\` experiment to enable this behavior`);
63867
- } else {
63868
- this.reference.log(`Cannot use scalar field \`${this.reference.refString}\` as a view; use \`scalar_lenses\` experiment to enable this behavior`);
63869
- }
63870
- }
63871
63864
  const newSegment = {
63872
63865
  type: "reduce",
63873
63866
  queryFields: [this.reference.refToField]
@@ -674,7 +674,7 @@ ${n} ${s}: [`,o.length>0&&(i+=`
674
674
  `)+`
675
675
  ${n} `),i+="]")}return i}*walk(){for(let e of Object.keys(this.children)){let r=this.children[e];if(r instanceof t)yield r;else for(let n of r)yield n}}varInfo(){let e="";for(let[r,n]of Object.entries(this))r!=="elementType"&&(typeof n=="boolean"?e+=n?` ${r}`:` !${r}`:(typeof n=="string"||typeof n=="number")&&(e+=` ${r}=${n}`));return e}internalError(e){return this.log(`INTERNAL ERROR IN TRANSLATION: ${e}`),new Error(e)}needs(e){for(let r of this.walk()){let n=r.needs(e);if(n)return n}}inExperiment(e,r=!1){var n;let i=(n=this.translator())===null||n===void 0?void 0:n.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(r||this.log(`Experimental flag '${e}' is not set, feature not available`),!1)}};$n.MalloyElement=Rp;var aY=class extends Rp{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}};$n.Unimplemented=aY;var KC=class extends Rp{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}};$n.ModelEntryReference=KC;var uY=class extends Rp{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}};$n.ExperimentalExperiment=uY;function Jge(t){return t.execute!==void 0}$n.isDocStatement=Jge;function WJe(t){return t instanceof XC||Jge(t)}$n.isDocStatementOrDocStatementList=WJe;var cL=class extends Rp{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(let r of this.elements){let n=r.needs(e);if(n)return n}}};$n.ListOf=cL;var XC=class t extends cL{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Xge.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){let r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Xge.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof t){let n=r.executeList(e);if(n)return n}else{let n=r.needs(e);if(n)return n;r.execute(e)}this.execCursor+=1}}};$n.DocStatementList=XC;var YJe="5a79a191-06bc-43cf-9b12-58741cd82970";function Zge(t){let e=t.inherits?Zge(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(r=>r.text)),t.notes&&e.push(...t.notes.map(r=>r.text)),e}function KJe(t){let e=Zge(t).join("");return(0,VJe.v5)(e,YJe)}var JC=class extends Rp{constructor(e){super(),this.elementType="document",this.globalNameSpace=new QJe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new GJe.Tag({}),this.modelAnnotationTodoList=[],this.statements=new XC(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(let[r,n]of Object.entries(e.contents)){let i=structuredClone(n);if(i.type==="struct"||i.type==="query"||i.type==="function"){let s=e.exports.includes(r);this.setEntry(r,{entry:i,exported:s})}}}this.didInitModel=!0}}compile(){let e=this.statements.executeList(this),r=this.modelDef();if(e===void 0){for(let i of this.queryList)i.modelAnnotation===void 0&&r.annotation&&(i.modelAnnotation=r.annotation);for(let i of this.sqlBlocks)i.modelAnnotation===void 0&&r.annotation&&(i.modelAnnotation=r.annotation)}if(r.annotation)for(let i of this.modelAnnotationTodoList)i.modelAnnotation||(i.modelAnnotation=r.annotation);return{modelDef:r,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()){let e={...this.annotation,id:""};return e.id=KJe(e),e}}modelDef(){let e={name:"",exports:[],contents:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(let r in this.documentModel){let n=this.documentModel[r].entry;if(n.type==="struct"||n.type==="query"){this.documentModel[r].exported&&e.exports.push(r);let i=structuredClone(n);i.modelAnnotation===void 0&&e.annotation&&(i.modelAnnotation=e.annotation),e.contents[r]=i}}return e}defineSQL(e,r){let n={...e,as:`$${this.sqlBlocks.length}`,declaredSQLBlock:!0};if(r){if(this.getEntry(r))return!1;n.as=r,this.setEntry(r,{entry:n})}return this.sqlBlocks.push(n),!0}getEntry(e){var r;return(r=this.globalNameSpace.getEntry(e))!==null&&r!==void 0?r:this.documentModel[e]}setEntry(e,r){this.globalNameSpace.getEntry(e)!==void 0&&this.log(`Cannot redefine '${e}', which is in global namespace`),this.documentModel[e]=r}};$n.Document=JC});var fL=v(yA=>{"use strict";Object.defineProperty(yA,"__esModule",{value:!0});yA.canMakeEntry=yA.SpaceEntry=void 0;var lY=class{};yA.SpaceEntry=lY;function XJe(t){return"makeEntry"in t}yA.canMakeEntry=XJe});var ua=v(xL=>{"use strict";Object.defineProperty(xL,"__esModule",{value:!0});xL.SpaceField=void 0;var JJe=Ke(),ZJe=fL(),cY=class extends ZJe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){let r={dataType:e.type,expressionType:"scalar",evalSpace:"input"};return(0,JJe.isFieldTypeDef)(e)&&e.expressionType&&(r.expressionType=e.expressionType),r.dataType==="unsupported"&&e.type==="unsupported"&&e.rawType&&(r.rawType=e.rawType),r}getQueryFieldDef(e){}fieldDef(){}};xL.SpaceField=cY});var hL=v(dL=>{"use strict";Object.defineProperty(dL,"__esModule",{value:!0});dL.ViewField=void 0;var eZe=ua(),fY=class extends eZe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){return{dataType:"turtle",expressionType:"scalar",evalSpace:"input"}}};dL.ViewField=fY});var e3e=v(pL=>{"use strict";Object.defineProperty(pL,"__esModule",{value:!0});pL.ASTViewField=void 0;var tZe=hL(),xY=class extends tZe.ViewField{constructor(e,r,n){super(e),this.view=r,this.name=n}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.view.getFieldDef(this.inSpace)}};pL.ASTViewField=xY});var hY=v(mL=>{"use strict";Object.defineProperty(mL,"__esModule",{value:!0});mL.ViewFieldDeclaration=void 0;var rZe=mt(),nZe=Vc(),iZe=Z9(),sZe=e3e(),dY=class extends rZe.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=nZe.extendNoteMethod}makeEntry(e){let r=new sZe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getFieldDef(e){let{pipeline:r,annotation:n}=this.view.pipelineComp(e),i=(0,iZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:n},location:this.location}}};mL.ViewFieldDeclaration=dY});var Ii=v(EA=>{"use strict";Object.defineProperty(EA,"__esModule",{value:!0});EA.LegalRefinementStage=EA.QueryClass=void 0;var t3e;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(t3e||(EA.QueryClass=t3e={}));var r3e;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(r3e||(EA.LegalRefinementStage=r3e={}))});var mY=v(gL=>{"use strict";Object.defineProperty(gL,"__esModule",{value:!0});gL.NestFieldDeclaration=void 0;var oZe=Z9(),aZe=hY(),n3e=Ii(),pY=class extends aZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=n3e.LegalRefinementStage.Single,this.forceQueryClass=n3e.QueryClass.Grouping}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(e.isQueryFieldSpace()){let{pipeline:r,annotation:n}=this.view.pipelineComp(e,e.outputSpace()),i=(0,oZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:n},location:this.location}}throw this.internalError("Unexpected namespace for nest")}};gL.NestFieldDeclaration=pY});var la=v(yL=>{"use strict";Object.defineProperty(yL,"__esModule",{value:!0});yL.ErrorFactory=void 0;var i3e={type:"struct",name:"~malformed~",dialect:"~malformed~",structSource:{type:"table",tablePath:"//undefined_error_table_path"},structRelationship:{type:"basetable",connectionName:"//undefined_error_connection"},fields:[]},gY=class t{static get structDef(){return{...i3e}}static isErrorStructDef(e){return e.name.includes(i3e.name)}static get query(){return{structRef:t.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}};yL.ErrorFactory=gY});var EY=v(EL=>{"use strict";Object.defineProperty(EL,"__esModule",{value:!0});EL.HasParameter=void 0;var uZe=Ke(),lZe=mt(),yY=class extends lZe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,this.isCondition=e.isCondition,e.type&&(0,uZe.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e,r;let n=this.name,i=this.type||"string";if(this.isCondition){let o=((e=this.default)===null||e===void 0?void 0:e.constantCondition(i).value)||null;return{type:i,name:n,condition:o}}return{value:((r=this.default)===null||r===void 0?void 0:r.constantValue().value)||null,type:i,name:this.name,constant:!1}}};EL.HasParameter=yY});var o3e=v(SA=>{"use strict";Object.defineProperty(SA,"__esModule",{value:!0});SA.DefineSourceList=SA.DefineSource=void 0;var cZe=la(),fZe=EY(),s3e=mt(),xZe=Vc(),SY=class extends s3e.MalloyElement{constructor(e,r,n,i){if(super(),this.name=e,this.sourceExpr=r,this.exported=n,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=xZe.extendNoteMethod,r&&this.has({sourceExpr:r}),i){this.parameters=[];for(let s of i)s instanceof fZe.HasParameter?this.parameters.push(s):this.log(`Unexpected element type in define statement: ${s.elementType}`);this.has({parameters:this.parameters})}}execute(e){var r;if(e.modelEntry(this.name))this.log(`Cannot redefine '${this.name}'`);else{let n=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(n===void 0)return;let i=n.withParameters(this.parameters);if(cZe.ErrorFactory.isErrorStructDef(i))return;let s={...i,as:this.name,location:this.location};this.note&&(s.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:this.exported})}}};SA.DefineSource=SY;var AY=class extends s3e.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}};SA.DefineSourceList=AY});var u3e=v(AA=>{"use strict";Object.defineProperty(AA,"__esModule",{value:!0});AA.DefineQueryList=AA.DefineQuery=void 0;var a3e=mt(),dZe=Vc(),vY=class extends a3e.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=dZe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.log(`'${this.name}' is already defined, cannot redefine`);return}let n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("Cannot define a query from this expression");return}let i={...n.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})}};AA.DefineQuery=vY;var _Y=class extends a3e.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}};AA.DefineQueryList=_Y});var Px=v(SL=>{"use strict";Object.defineProperty(SL,"__esModule",{value:!0});SL.Source=void 0;var hZe=mt(),bY=class extends hZe.MalloyElement{structRef(){return this.structDef()}withParameters(e){let r=this.structDef();if(e){let n={...r.parameters||{}};for(let i of e){let s=i.parameter();n[s.name]=s}return{...r,parameters:n}}return r}};SL.Source=bY});var AL=v(vA=>{"use strict";Object.defineProperty(vA,"__esModule",{value:!0});vA.mergeFields=vA.nameFromDef=void 0;function TY(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}vA.nameFromDef=TY;function pZe(t,e){if(t===void 0)return e;let r=new Set(e.map(i=>TY(i))),n=t.filter(i=>!r.has(TY(i)));return n.push(...e),n}vA.mergeFields=pZe});var vL=v(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});Op.DefinedParameter=Op.AbstractParameter=Op.SpaceParam=void 0;var mZe=fL(),ZC=class extends mZe.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}};Op.SpaceParam=ZC;var CY=class extends ZC{constructor(e){super(),this.astParam=e}parameter(){return this.astParam.parameter()}typeDesc(){return{dataType:this.astParam.type||"error",expressionType:"scalar",evalSpace:"input"}}};Op.AbstractParameter=CY;var RY=class extends ZC{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{dataType:this.paramDef.type,expressionType:"scalar",evalSpace:"input"}}};Op.DefinedParameter=RY});var e5=v(_L=>{"use strict";Object.defineProperty(_L,"__esModule",{value:!0});_L.StructSpaceFieldBase=void 0;var gZe=ua(),OY=class extends gZe.SpaceField{constructor(e){super(),this.sourceDef=e}get structRelationship(){return this.sourceDef.structRelationship}fieldDef(){return this.sourceDef}typeDesc(){return{dataType:"struct",expressionType:"scalar",evalSpace:"input"}}};_L.StructSpaceFieldBase=OY});var NY=v(bL=>{"use strict";Object.defineProperty(bL,"__esModule",{value:!0});bL.ColumnSpaceField=void 0;var yZe=ua(),DY=class extends yZe.SpaceField{constructor(e){super(),this.haveFieldDef=e}fieldDef(){return this.haveFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.haveFieldDef)}};bL.ColumnSpaceField=DY});var l3e=v(TL=>{"use strict";Object.defineProperty(TL,"__esModule",{value:!0});TL.IRViewField=void 0;var EZe=hL(),FY=class extends EZe.ViewField{constructor(e,r){super(e),this.turtleDef=r,this.haveFieldDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}};TL.IRViewField=FY});var tl=v(_A=>{"use strict";Object.defineProperty(_A,"__esModule",{value:!0});_A.StructSpaceField=_A.StaticSpace=void 0;var SZe=AF(),AZe=Ke(),vZe=vL(),_Ze=ua(),CL=e5(),bZe=NY(),TZe=l3e(),RL=class{constructor(e){this.type="fieldSpace",this.fromStruct=e}dialectObj(){try{return(0,SZe.getDialect)(this.fromStruct.dialect)}catch{return}}defToSpaceField(e){return e.type==="struct"?new OL(e):(0,AZe.isTurtleDef)(e)?new TZe.IRViewField(this,e):new bZe.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(let e of this.fromStruct.fields){let r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if(this.fromStruct.parameters)for(let[e,r]of Object.entries(this.fromStruct.parameters)){if(this.memoMap[e])throw new Error(`In struct '${this.fromStruct.as||this.fromStruct.name}': : Field and parameter name conflict '${e}`);this.memoMap[e]=new vZe.DefinedParameter(r)}}return this.memoMap}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,r){this.map[e]=r}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){return{...this.fromStruct,fields:[]}}lookup(e){let r=e[0],n=e.slice(1),i=this.entry(r.refString);if(!i)return{error:`'${r}' is not defined`,found:i};if(i instanceof _Ze.SpaceField){let o=i.fieldDef();o&&r.addReference({type:i instanceof CL.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:r.location,text:r.refString})}let s=i instanceof CL.StructSpaceFieldBase?[{name:r.refString,structRelationship:i.structRelationship}]:[];if(n.length){if(i instanceof CL.StructSpaceFieldBase){let o=i.fieldSpace.lookup(n);return o.found?{...o,relationship:[...s,...o.relationship]}:o}return{error:`'${r}' cannot contain a '${n[0]}'`,found:void 0}}return{found:i,error:void 0,relationship:s,isOutputField:!1}}isQueryFieldSpace(){return!1}};_A.StaticSpace=RL;var OL=class extends CL.StructSpaceFieldBase{constructor(e){super(e)}get fieldSpace(){return new RL(this.sourceDef)}};_A.StructSpaceField=OL});var LY=v(DL=>{"use strict";Object.defineProperty(DL,"__esModule",{value:!0});DL.JoinSpaceField=void 0;var CZe=tl(),wY=class extends CZe.StructSpaceField{constructor(e){super(e.structDef()),this.join=e}};DL.JoinSpaceField=wY});var MY=v(NL=>{"use strict";Object.defineProperty(NL,"__esModule",{value:!0});NL.SpaceSeed=void 0;var RZe=tl();function c3e(t){return t.type==="fieldSpace"}var IY=class{constructor(e){this.sourceSpec=e,this.spaceSpec=e}get structDef(){return c3e(this.spaceSpec)?(this.asStruct||(this.asStruct=this.spaceSpec.structDef()),this.asStruct):this.spaceSpec}get fieldSpace(){return c3e(this.spaceSpec)?this.spaceSpec:(this.asFS||(this.asFS=new RZe.StaticSpace(this.spaceSpec)),this.asFS)}};NL.SpaceSeed=IY});var x3e=v(FL=>{"use strict";Object.defineProperty(FL,"__esModule",{value:!0});FL.DynamicSpace=void 0;var OZe=AL(),DZe=la(),NZe=ua(),FZe=LY(),wZe=hL(),f3e=vL(),LZe=MY(),IZe=tl(),MZe=e5(),PY=class extends IZe.StaticSpace{constructor(e){let r=new LZe.SpaceSeed(e);super(structuredClone(r.structDef)),this.completions=[],this.complete=!1,this.final=void 0,this.source=r}isComplete(){this.complete=!0}setEntry(e,r){if(this.final)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(let r of e)this.setEntry(r.name,new f3e.AbstractParameter(r));return this}newEntry(e,r,n){if(this.entry(e)){r.log(`Cannot redefine '${e}'`);return}this.setEntry(e,n)}renameEntry(e,r,n){this.dropEntry(e),this.setEntry(r,n)}addFieldDef(e){this.setEntry((0,OZe.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){let e=this.fromStruct.parameters||{};if(this.final===void 0){this.final={...this.fromStruct,fields:[]};let r=[],n=[],i=[],s=[];for(let[a,u]of this.entries())u instanceof MZe.StructSpaceFieldBase?n.push([a,u]):u instanceof wZe.ViewField?i.push([a,u]):u instanceof NZe.SpaceField?r.push([a,u]):u instanceof f3e.SpaceParam&&(e[a]=u.parameter());let o=[...r,...n,...i];for(let[,a]of o)if(a instanceof FZe.JoinSpaceField){let u=a.join.structDef();DZe.ErrorFactory.isErrorStructDef(u)||(this.final.fields.push(u),s.push([a.join,u]))}else{let u=a.fieldDef();u&&this.final.fields.push(u)}Object.entries(e).length>0&&(this.final.parameters=e);for(let[a,u]of s)a.fixupJoinOn(this,u)}return this.newTimezone&&(this.final.queryTimezone=this.newTimezone),this.isComplete(),this.final}};FL.DynamicSpace=PY});var LL=v(wL=>{"use strict";Object.defineProperty(wL,"__esModule",{value:!0});wL.RefinedSpace=void 0;var PZe=x3e(),kZe=fL(),kY=class t extends PZe.DynamicSpace{static filteredFrom(e,r){let n=new t(e);if(r){let i=r.refs.list,s=n.entries();n.dropEntries();for(let[o,a]of s){let u=!!i.find(c=>c.refString===o),l=r.edit==="accept";u===l&&n.setEntry(o,a)}}return n}pushFields(...e){for(let r of e)(0,kZe.canMakeEntry)(r)?r.makeEntry(this):r.log(`Internal error, ${r.elementType} not expected in this context`)}};wL.RefinedSpace=kY});var n0=v(IL=>{"use strict";Object.defineProperty(IL,"__esModule",{value:!0});IL.DefinitionList=void 0;var BZe=mt(),d3e=Vc(),BY=class extends BZe.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,d3e.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(let e of this.elements)(0,d3e.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}};IL.DefinitionList=BY});var bA=v(ML=>{"use strict";Object.defineProperty(ML,"__esModule",{value:!0});ML.DeclareFields=void 0;var qZe=n0(),UZe=Ii(),qY=class extends qZe.DefinitionList{constructor(e){super(e),this.elementType="declareFields",this.queryRefinementStage=UZe.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(let r of this.list)e.inputFS.extendSource(r)}};ML.DeclareFields=qY});var hs=v(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});Dp.nullsafeNot=Dp.compressExpr=Dp.compose=void 0;var $Ze=Ke();function h3e(t){return t.length>1?["(",...t,")"]:t.length===0?["__MISSING_VALUE__"]:t}function jZe(t,e,r){let n=e.match(/^[A-Za-z]/),i=t.length===1&&n?" ":"",s=r.length===1&&n?" ":"",o=i+e+s;return[...h3e(t),o,...h3e(r)]}Dp.compose=jZe;function HZe(t){let e=[],r;for(let n of t.flat())typeof n=="string"?r=r?r+n:n:(r&&(e.push(r),r=void 0),e.push(n));return r&&e.push(r),e}Dp.compressExpr=HZe;function zZe(t,e){return e===void 0||e==="!="||e==="!~"?(0,$Ze.mkExpr)`COALESCE(NOT(${t}),FALSE)`:t}Dp.nullsafeNot=zZe});var Ym=v(TA=>{"use strict";Object.defineProperty(TA,"__esModule",{value:!0});TA.Filter=TA.FilterElement=void 0;var p3e=Ke(),GZe=hs(),m3e=mt(),UY=Ii(),$Y=class extends m3e.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterExpression(e){let r=this.expr.getExpression(e);return r.dataType!=="boolean"?(this.expr.log("Filter expression must have boolean value"),{code:this.exprSrc,expression:["_FILTER_MUST_RETURN_BOOLEAN_"],expressionType:"scalar"}):{code:this.exprSrc,expression:(0,GZe.compressExpr)(r.value),expressionType:r.expressionType}}};TA.FilterElement=$Y;var jY=class extends m3e.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=UY.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?UY.LegalRefinementStage.Tail:UY.LegalRefinementStage.Head}getFilterList(e){let r=[];for(let n of this.list){let i=n.filterExpression(e);if(this.havingClause!==void 0){let s=(0,p3e.expressionIsAggregate)(i.expressionType),o=(0,p3e.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){n.log("Analytic expressions are not allowed in `having:`");continue}}else if(o){n.log("Analytic expressions are not allowed in `where:`");continue}else s&&n.log("Aggregate expressions are not allowed in `where:`; use `having:`")}r.push(i)}return r}};TA.Filter=jY});var CA=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.Joins=Wc.ExpressionJoin=Wc.KeyJoin=Wc.Join=void 0;var QZe=Ke(),VZe=hs(),WZe=LY(),YZe=n0(),KZe=mt(),XZe=Vc(),JZe=Ii(),g3e=la(),t5=class extends KZe.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=XZe.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new WZe.JoinSpaceField(this))}getStructDefFromExpr(){let e=this.sourceExpr.getSource();return e?e.structDef():(this.sourceExpr.sqLog("Cannot great a source to join from"),g3e.ErrorFactory.structDef)}};Wc.Join=t5;var HY=class extends t5{constructor(e,r,n){super({name:e,sourceExpr:r,keyExpr:n}),this.name=e,this.sourceExpr=r,this.keyExpr=n,this.elementType="joinOnKey"}structDef(){var e;let r=this.getStructDefFromExpr(),n={...r,structRelationship:{type:"one",matrixOperation:"left",onExpression:["('join fixup'='not done yet')"]},location:this.location};return r.structSource.type==="query"?n.name=this.name.refString:n.as=this.name.refString,this.note&&(n.annotation=this.note),(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(n),n}fixupJoinOn(e,r){let n=this.keyExpr.getExpression(e);if(r.primaryKey){let i=r.fields.find(s=>(s.as||s.name)===r.primaryKey);if(i)if(i.type===n.dataType){r.structRelationship={type:"one",matrixOperation:"left",onExpression:[{type:"field",path:[this.name.refString,r.primaryKey]},"=",...n.value]};return}else this.log(`join_one: with type mismatch with primary key: ${n.dataType}/${i.type}`);else this.log(`join_one: Primary key '${i}' not found in source`)}else this.log("join_one: Cannot use with unless source has a primary key")}};Wc.KeyJoin=HY;var zY=class extends t5{constructor(e,r){super({name:e,sourceExpr:r}),this.name=e,this.sourceExpr=r,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,r){if(this.expr===void 0)return;let n=this.expr.getExpression(e);if(n.dataType!=="boolean"){this.log("join conditions must be boolean expressions");return}let i=r.structRelationship;(0,QZe.isJoinOn)(i)&&(i.onExpression=(0,VZe.compressExpr)(n.value))}structDef(){var e;let r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("Cannot create a source to join from"),g3e.ErrorFactory.structDef;let n=r.structDef(),i="left";this.inExperiment("join_types",!0)&&(i=this.matrixOperation);let s={...n,structRelationship:{type:this.joinType,matrixOperation:i},location:this.location};return n.structSource.type==="query"?(s.name=this.name.refString,delete s.as):s.as=this.name.refString,this.note&&(s.annotation=this.note),(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(s),s}};Wc.ExpressionJoin=zY;var GY=class extends YZe.DefinitionList{constructor(e){super(e),this.elementType="joinList",this.forceQueryClass=void 0,this.queryRefinementStage=JZe.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)e.inputFS.extendSource(r)}};Wc.Joins=GY});var kL=v(PL=>{"use strict";Object.defineProperty(PL,"__esModule",{value:!0});PL.FieldListEdit=void 0;var ZZe=mt(),QY=class extends ZZe.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}};PL.FieldListEdit=QY});var qL=v(BL=>{"use strict";Object.defineProperty(BL,"__esModule",{value:!0});BL.PrimaryKey=void 0;var eet=mt(),VY=class extends eet.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}};BL.PrimaryKey=VY});var $L=v(UL=>{"use strict";Object.defineProperty(UL,"__esModule",{value:!0});UL.Views=void 0;var tet=n0(),WY=class extends tet.DefinitionList{constructor(){super(...arguments),this.elementType="turtleDefList"}};UL.Views=WY});var HL=v(jL=>{"use strict";Object.defineProperty(jL,"__esModule",{value:!0});jL.TimezoneStatement=void 0;var ret=mt(),YY=class extends ret.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)}};jL.TimezoneStatement=YY});var GL=v(RA=>{"use strict";Object.defineProperty(RA,"__esModule",{value:!0});RA.ModelAnnotation=RA.ObjectAnnotation=void 0;var net=Wm(),iet=mt(),zL=class extends iet.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}};RA.ObjectAnnotation=zL;var KY=class extends zL{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){let n=net.Tag.annotationToTag({notes:this.notes},{prefix:/^##! /,extending:e});return n.log.forEach(i=>r.log(i)),n.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}};RA.ModelAnnotation=KY});var y3e=v(QL=>{"use strict";Object.defineProperty(QL,"__esModule",{value:!0});QL.RenameSpaceField=void 0;var set=ua(),XY=class extends set.SpaceField{constructor(e,r,n){super(),this.otherField=e,this.newName=r,this.location=n}fieldDef(){let e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}};QL.RenameSpaceField=XY});var VL=v(OA=>{"use strict";Object.defineProperty(OA,"__esModule",{value:!0});OA.Renames=OA.RenameField=void 0;var oet=y3e(),E3e=mt(),aet=ua(),JY=class extends E3e.MalloyElement{constructor(e,r){super(),this.newName=e,this.oldName=r,this.elementType="renameField",this.has({oldName:r})}makeEntry(e){if(this.oldName.refString===this.newName){this.log("Can't rename field to itself");return}let r=this.oldName.getField(e);r.found?r.found instanceof aet.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new oet.RenameSpaceField(r.found,this.newName,this.location)):this.log(`'${this.oldName}' cannot be renamed`):this.log(`Can't rename '${this.oldName}', no such field`)}};OA.RenameField=JY;var ZY=class extends E3e.ListOf{constructor(){super(...arguments),this.elementType="renameFields"}};OA.Renames=ZY});var tK=v(WL=>{"use strict";Object.defineProperty(WL,"__esModule",{value:!0});WL.RefinedSource=void 0;var uet=Ke(),cet=LL(),fet=bA(),xet=Ym(),det=CA(),het=kL(),pet=qL(),met=$L(),get=Px(),yet=HL(),Eet=GL(),Aet=VL(),eK=class extends get.Source{constructor(e,r){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.elementType="refinedSource"}structDef(){return this.withParameters([])}withParameters(e){var r;let n,i,s=[],o=[],a;for(let d of this.refinement.list){if(d instanceof Eet.ObjectAnnotation)continue;let h=d;d instanceof pet.PrimaryKey?(n&&(n.log("Primary key already defined"),d.log("Primary key redefined")),n=d):d instanceof het.FieldListEdit?(i&&(i.log("Too many accept/except statements"),d.log("Too many accept/except statements")),i=d):d instanceof fet.DeclareFields||d instanceof det.Joins||d instanceof met.Views||d instanceof Aet.Renames?s.push(...d.list):d instanceof xet.Filter?o.push(d):d instanceof yet.TimezoneStatement?a=d.tz:h.log(`Unexpected source property: '${h.elementType}'`)}let u=structuredClone(this.source.structDef());n&&(u.primaryKey=n.field.name);let l=cet.RefinedSpace.filteredFrom(u,i);if(a&&l.setTimezone(a),l.pushFields(...s),e&&l.addParameters(e),n){let d=n.field.getField(l);d.error&&n.log(d.error)}let c=l.structDef(),f=c.filterList||[],x=!1;for(let d of o)for(let h of d.list){let p=h.filterExpression(l);(0,uet.expressionIsCalculation)(p.expressionType)?h.log("Can't use aggregate computations in top level filters"):(f.push(p),x=!0)}return x?{...c,filterList:f}:((r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(c),c)}};WL.RefinedSource=eK});var Np=v(YL=>{"use strict";Object.defineProperty(YL,"__esModule",{value:!0});YL.SourceQueryElement=void 0;var vet=mt(),rK=class t extends vet.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e){this.isErrorFree()&&this.log(e),this.errored=!0}isErrorFree(){if(this.errored)return!1;let e=!0;for(let r of this.walk())if(r instanceof t&&r.errored){e=!1;break}return e}};YL.SourceQueryElement=rK});var r5=v(KL=>{"use strict";Object.defineProperty(KL,"__esModule",{value:!0});KL.QuerySource=void 0;var _et=Px(),nK=class extends _et.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}structDef(){var e;let r=this.query.queryComp(!1),n={...r.outputStruct,structSource:{type:"query",query:r.query}};return(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(n),n}};KL.QuerySource=nK});var sK=v(XL=>{"use strict";Object.defineProperty(XL,"__esModule",{value:!0});XL.QueryBase=void 0;var bet=Z9(),Tet=mt(),iK=class extends Tet.MalloyElement{query(){let e=this.queryComp(!0).query;return{...e,pipeline:(0,bet.detectAndRemovePartialStages)(e.pipeline,this)}}};XL.QueryBase=iK});var ZL=v(JL=>{"use strict";Object.defineProperty(JL,"__esModule",{value:!0});JL.QueryArrow=void 0;var Cet=Ke(),Ret=Px(),S3e=tl(),Oet=sK(),oK=class extends Oet.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){let r,n,i;if(this.source instanceof Ret.Source){let l=e?this.source.structRef():this.source.structDef();n={type:"query",structRef:l,pipeline:[],location:this.location},r=(0,Cet.refIsStructDef)(l)?l:this.source.structDef(),i=new S3e.StaticSpace(r)}else{let l=this.source.queryComp(e);n=l.query,r=l.outputStruct,i=new S3e.StaticSpace(l.outputStruct)}let{pipeline:s,annotation:o,outputStruct:a,name:u}=this.view.pipelineComp(i);return{query:{...n,name:u,annotation:o,pipeline:[...n.pipeline,...s]},outputStruct:a,inputStruct:r}}};JL.QueryArrow=oK});var A3e=v(eI=>{"use strict";Object.defineProperty(eI,"__esModule",{value:!0});eI.SQArrow=void 0;var Det=Np(),Net=r5(),Fet=ZL(),aK=class extends Det.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){let e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("Could not get LHS of arrow operation");return}let r=new Fet.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){let e=this.getQuery();if(!e){this.sqLog("Couldn't comprehend query well enough to make a source");return}let r=new Net.QuerySource(e);return this.has({asSource:r}),r}};eI.SQArrow=aK});var Km=v(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});Fp.getStructFieldDef=Fp.getFinalStruct=Fp.opOutputStruct=void 0;var wet=Vd(),Let=$G(),Iet=Ke(),v3e=la();function _3e(t,e,r){let n=v3e.ErrorFactory.isErrorStructDef(e);if((0,Iet.isPartialSegment)(r)&&(r={...r,type:"reduce"}),!n)try{return Let.Segment.nextStructDef(e,r)}catch(i){t.log(`INTERNAL ERROR model/Segment.nextStructDef: ${i.message}
676
676
  QUERY: ${(0,wet.inspect)(r,{breakLength:72,depth:1/0})}`)}return{...v3e.ErrorFactory.structDef,dialect:e.dialect}}Fp.opOutputStruct=_3e;function Met(t,e,r){for(let n of r)e=_3e(t,e,n);return e}Fp.getFinalStruct=Met;function Pet(t,e){return t.fields.find(r=>(r.as||r.name)===e)}Fp.getStructFieldDef=Pet});var rI=v(tI=>{"use strict";Object.defineProperty(tI,"__esModule",{value:!0});tI.QueryRefine=void 0;var ket=tl(),Bet=Km(),qet=sK(),uK=class extends qet.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){let r=this.base.queryComp(e),n=new ket.StaticSpace(r.inputStruct),i=this.refinement.refine(n,r.query.pipeline,void 0);return{query:{...r.query,pipeline:i},outputStruct:(0,Bet.getFinalStruct)(this.refinement,r.inputStruct,i),inputStruct:r.inputStruct}}};tI.QueryRefine=uK});var DA=v(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.dateOffset=Mi.timestampOffset=Mi.timeResult=Mi.resolution=Mi.castDateToTimestamp=Mi.castTimestampToDate=Mi.castTo=Mi.timeOffset=void 0;var Uet=Ke(),b3e=hs();function $et(t,e,r,n,i){return[{type:"dialect",function:"delta",base:{valueType:t,value:e},op:r,delta:n,units:i}]}Mi.timeOffset=$et;function jet(t,e,r,n=!1){let i={type:"dialect",function:"cast",dstType:t,expr:e,safe:n};return(0,Uet.isAtomicFieldType)(r)&&(i.srcType=r),[i]}Mi.castTo=jet;function Het(t,e=!1){return[{type:"dialect",function:"cast",dstType:"date",srcType:"timestamp",expr:t,safe:e}]}Mi.castTimestampToDate=Het;function zet(t,e=!1){return[{type:"dialect",function:"cast",dstType:"timestamp",srcType:"date",expr:t,safe:e}]}Mi.castDateToTimestamp=zet;function Get(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Mi.resolution=Get;function Qet(t,e){return e?{...t,timeframe:e}:t}Mi.timeResult=Qet;function Vet(t,e,r,n,i=!1){let s=["week","month","quarter","year"].includes(n),o=e==="+"?"_ADD":"_SUB",a=n.toUpperCase();if(s)return[`TIMESTAMP(DATETIME${o}(DATETIME(`,...t,"),INTERVAL ",...r,` ${a}))`];let u=i?["TIMESTAMP(",...t,")"]:t;return(0,b3e.compressExpr)([`TIMESTAMP${o}(`,...u,",INTERVAL ",...r,` ${a})`])}Mi.timestampOffset=Vet;function Wet(t,e,r,n){let i=e==="+"?"_ADD":"_SUB",s=n.toUpperCase();return(0,b3e.compressExpr)([`DATE${i}(`,...t,",INTERVAL ",...r,` ${s})`])}Mi.dateOffset=Wet});var n5=v(NA=>{"use strict";Object.defineProperty(NA,"__esModule",{value:!0});NA.NamedSource=NA.IsValueBlock=void 0;var nI=Ke(),Yet=Px(),Ket=la(),Xet=DA(),iI=mt(),sI=class extends iI.MalloyElement{constructor(e){super(),this.isMap=e,this.elementType="isValueBlock",this.has(e)}};NA.IsValueBlock=sI;var lK=class extends Yet.Source{constructor(e,r={}){super(),this.ref=e,this.elementType="namedSource",r&&Object.keys(r).length>0&&(this.isBlock=new sI(r),this.has({parameterValues:this.isBlock})),e instanceof iI.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof iI.ModelEntryReference?this.ref.name:this.ref}structRef(){if(this.isBlock)return this.structDef();let e=this.modelEntry(this.ref);return e&&!e.exported?this.structDef():this.refName}modelStruct(){let e=this.modelEntry(this.ref),r=e?.entry;if(!r){let n=`Undefined source '${this.refName}'`;(this.ref instanceof iI.ModelEntryReference?this.ref:this).log(n);return}if(r.type==="query"){this.log(`Cannot construct a source from a query '${this.refName}'`);return}else if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot construct a source from a connection '${this.refName}'`);return}else if((0,nI.isSQLBlockStruct)(r)&&r.declaredSQLBlock){this.log(`Must use 'from_sql()' for sql source '${this.refName}'`);return}return{...r}}structDef(){var e,r;let n=this.modelStruct();if(!n){let o=Ket.ErrorFactory.structDef,a=`${this.refName}-undefined`;return o.name=o.name+a,o.dialect=o.dialect+a,o}let i={...n.parameters},s=((e=this.isBlock)===null||e===void 0?void 0:e.isMap)||{};for(let[o,a]of Object.entries(s)){let u=i[o];if(!u)this.log(`Value given for undeclared parameter '${o}`);else if((0,nI.isValueParameter)(u))if(u.constant)a.log(`Cannot override constant parameter ${o}`);else{let l=a.constantValue(),c=l.value;l.dataType!==u.type&&(0,nI.isCastType)(u.type)&&(c=(0,Xet.castTo)(u.type,l.value,l.dataType,!0)),u.value=c}else u.condition=a.constantCondition(u.type).value}for(let o in n.parameters)(0,nI.paramHasValue)(i[o])||this.log(`Value not provided for required parameter ${o}`);return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(n),n}};NA.NamedSource=lK});var T3e=v(oI=>{"use strict";Object.defineProperty(oI,"__esModule",{value:!0});oI.QueryHeadStruct=void 0;var Jet=Ke(),Zet=Px(),ett=n5(),cK=class extends Zet.Source{constructor(e){super(),this.fromRef=e,this.elementType="internalOnlyQueryHead"}structRef(){return this.fromRef}structDef(){if((0,Jet.refIsStructDef)(this.fromRef))return this.fromRef;let e=new ett.NamedSource(this.fromRef);return this.has({exploreReference:e}),e.structDef()}};oI.QueryHeadStruct=cK});var dK=v(aI=>{"use strict";Object.defineProperty(aI,"__esModule",{value:!0});aI.QueryReference=void 0;var fK=la(),ttt=mt(),rtt=T3e(),ntt=Ke(),itt=Km(),xK=class extends ttt.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){let r=this.modelEntry(this.name),n=r?.entry,i=function(){return{inputStruct:fK.ErrorFactory.structDef,outputStruct:fK.ErrorFactory.structDef,query:fK.ErrorFactory.query}};if(!n)return this.log(`Reference to undefined query '${this.name.refString}'`),i();if(n.type==="query"){let s=new rtt.QueryHeadStruct(n.structRef);this.has({queryHead:s});let o=s.structDef(),a=(0,itt.getFinalStruct)(this,o,n.pipeline);return{query:e||(0,ntt.refIsStructDef)(n.structRef)?n:{...n,structRef:o},outputStruct:a,inputStruct:o}}return this.log(`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}};aI.QueryReference=xK});var pK=v(uI=>{"use strict";Object.defineProperty(uI,"__esModule",{value:!0});uI.SQReference=void 0;var stt=Np(),ott=r5(),att=n5(),C3e=dK(),hK=class extends stt.SourceQueryElement{constructor(e){super({ref:e}),this.ref=e,this.elementType="sq-reference"}getQuery(){let e=this.ref.getNamed();if(e)if(e.type==="query"){let r=new C3e.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog(`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){var e;return((e=this.ref.getNamed())===null||e===void 0?void 0:e.type)==="struct"}getSource(){if(this.asSource)return this.asSource;let e=this.ref.getNamed();if(!e){this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){let r=new C3e.QueryReference(this.ref);this.asSource=new ott.QuerySource(r)}else if(e.type==="struct")this.asSource=new att.NamedSource(this.ref);else{this.sqLog(`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}};uI.SQReference=hK});var R3e=v(lI=>{"use strict";Object.defineProperty(lI,"__esModule",{value:!0});lI.SQRefine=void 0;var utt=Np(),ltt=r5(),ctt=rI(),ftt=pK(),mK=class extends utt.SourceQueryElement{constructor(e,r){super({toRefine:e,refine:r}),this.toRefine=e,this.refine=r,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof ftt.SQReference?this.sqLog(`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("Cannot add view refinements to a source");return}let e=this.toRefine.getQuery();if(e){let r=new ctt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){let e=this.getQuery();if(e){let r=new ltt.QuerySource(e);return this.has({queryAsSource:r}),r}}};lI.SQRefine=mK});var yK=v(cI=>{"use strict";Object.defineProperty(cI,"__esModule",{value:!0});cI.QueryRaw=void 0;var xtt=Ke(),dtt=mt(),gK=class extends dtt.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){let r=e?this.source.structRef():this.source.structDef(),n=(0,xtt.refIsStructDef)(r)?r:this.source.structDef();return{query:{type:"query",structRef:r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:n,inputStruct:n}}query(){return this.queryComp(!0).query}};cI.QueryRaw=gK});var EK=v(fI=>{"use strict";Object.defineProperty(fI,"__esModule",{value:!0});fI.makeSQLBlock=void 0;var htt=Ke(),ptt=jd();function mtt(t,e){let r={name:`md5:/${e||"$default"}//${gtt(t)}`,select:t};return e&&(r.connection=e),r}fI.makeSQLBlock=mtt;function gtt(t){let e=t.map(r=>(0,htt.isSQLFragment)(r)?r.sql:JSON.stringify(r));return(0,ptt.generateHash)(e.join(";"))}});var AK=v(dI=>{"use strict";Object.defineProperty(dI,"__esModule",{value:!0});dI.SQLSource=void 0;var ytt=EK(),Ett=Px(),xI=la(),SK=class extends Ett.Source{constructor(e,r){super(),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1,this.has({connectionName:e,select:r})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,ytt.makeSQLBlock)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return this.structDef()}validateConnectionName(){var e;let r=this.modelEntry(this.connectionName),n=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(n,{entry:{type:"connection",name:n},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.log(`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;let n=super.needs(e);if(n)return n;let i=this.sqlBlock(),s=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!s){this.log("Cant't look up schema for sql block");return}if(s.reference(i.name,this.location),s.getEntry(i.name).status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0}}structDef(){var e;if(!this.validateConnectionName())return xI.ErrorFactory.structDef;let r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.log("Cant't look up schema for sql block"),xI.ErrorFactory.structDef;let n=this.sqlBlock();r.reference(n.name,this.location);let i=r.getEntry(n.name);if(i.status==="error"){let s=i.message.split(/\r?\n/);return this.select.log("Invalid SQL, "+s.join(`
677
- `)),xI.ErrorFactory.structDef}else if(i.status==="present"){let s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},a=this.document(),u=a?.currentModelAnnotation();return u&&(o.modelAnnotation=u),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),xI.ErrorFactory.structDef}};dI.SQLSource=SK});var O3e=v(hI=>{"use strict";Object.defineProperty(hI,"__esModule",{value:!0});hI.SQSource=void 0;var Stt=Np(),Att=yK(),vtt=AK(),vK=class extends Stt.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 vtt.SQLSource){let e=new Att.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}};hI.SQSource=vK});var D3e=v(pI=>{"use strict";Object.defineProperty(pI,"__esModule",{value:!0});pI.SQExtend=void 0;var _tt=tK(),btt=Np(),_K=class extends btt.SourceQueryElement{constructor(e,r){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;let e=this.sqSrc.getSource();if(e)return this.asSource=new _tt.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}};pI.SQExtend=_K});var mI=v(FA=>{"use strict";Object.defineProperty(FA,"__esModule",{value:!0});FA.isComparison=FA.Comparison=void 0;var bK;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(bK||(FA.Comparison=bK={}));function Ttt(t){return Object.values(bK).includes(t)}FA.isComparison=Ttt});var pn=v(gI=>{"use strict";Object.defineProperty(gI,"__esModule",{value:!0});gI.FT=void 0;var Ctt=lc();function Xm(t,e="scalar",r="constant"){return{dataType:t,expressionType:e,evalSpace:r}}var $s=class t{static in(e,r){return e?r.find(i=>t.eq(i,e))!==void 0:!1}static eq(e,r){return r!==void 0&&e.dataType===r.dataType&&e.expressionType===r.expressionType}static typeEq(e,r,n=!1,i=!0){let s=e.dataType===r.dataType,o=n&&(e.dataType==="null"||r.dataType==="null"),a=i&&(e.dataType==="error"||r.dataType==="error");return s||o||a}static inspect(...e){return e.map(n=>{if(n){let i=n.dataType;return(0,Ctt.expressionIsScalar)(n.expressionType)||(i=`${n.expressionType} ${i}`),i}return"undefined"}).join(",")}};gI.FT=$s;$s.nullT=Xm("null");$s.numberT=Xm("number");$s.stringT=Xm("string");$s.dateT=Xm("date");$s.timestampT=Xm("timestamp");$s.boolT=Xm("boolean");$s.anyAtomicT=[$s.numberT,$s.stringT,$s.dateT,$s.timestampT,$s.boolT];$s.aggregateBoolT=Xm("boolean","aggregate")});var EI=v(yI=>{"use strict";Object.defineProperty(yI,"__esModule",{value:!0});yI.isGranularResult=void 0;function Rtt(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}yI.isGranularResult=Rtt});var js=v(SI=>{"use strict";Object.defineProperty(SI,"__esModule",{value:!0});SI.errorFor=void 0;function Ott(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}SI.errorFor=Ott});var N3e=v(wA=>{"use strict";Object.defineProperty(wA,"__esModule",{value:!0});wA.isEquality=wA.Equality=void 0;var TK;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(TK||(wA.Equality=TK={}));function Dtt(t){return Object.values(TK).includes(t)}wA.isEquality=Dtt});var ir=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.applyBinary=Yc.getMorphicValue=Yc.ExprDuration=Yc.ExpressionDef=void 0;var mn=Ke(),LA=js(),kx=hs(),Jm=pn(),AI=DA(),Ntt=mI(),Ftt=N3e(),L3e=EI(),wtt=mt(),RK=class extends Error{},vI=class extends wtt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Jm.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.dataType!=="error"&&!Jm.FT.in(r,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${Jm.FT.inspect(r)}`),!1):!0}apply(e,r,n){return P3e(e,n,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,mn.expressionIsAggregate)(e.expressionType)}};Yc.ExpressionDef=vI;var i5=class extends vI{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Jm.FT.timestampT,Jm.FT.dateT]}apply(e,r,n){let i=n.getExpression(e);if(this.typeCheck(this,i),(0,mn.isTimeFieldType)(i.dataType)&&(r==="+"||r==="-")){let s=this.n.getExpression(e);if(!Jm.FT.typeEq(s,Jm.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,LA.errorFor)("illegal unit expression");let o;if((0,L3e.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){let a=(0,AI.timeOffset)("timestamp",i.value,r,s.value,this.timeframe);return(0,AI.timeResult)({dataType:"timestamp",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a},o)}return(0,mn.isDateUnit)(this.timeframe)?(0,AI.timeResult)({dataType:"date",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,AI.timeOffset)("date",i.value,r,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,LA.errorFor)("ofsset date error"))}return super.apply(e,r,n)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}};Yc.ExprDuration=i5;function F3e(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function Ltt(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}Yc.getMorphicValue=Ltt;function I3e(t,e,r,n){let i=(0,mn.isTimeFieldType)(e.dataType),s=(0,mn.isTimeFieldType)(n.dataType);if(i&&s)if(e.dataType!==n.dataType){let o=F3e(e,"timestamp"),a=F3e(n,"timestamp");if(o&&a)return(0,kx.compose)(o,r,a)}else return(0,kx.compose)(e.value,r,n.value);if((i||s)&&e.dataType!=="null"&&n.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${n.dataType}`),["false"]}function w3e(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:t.value,regexp:e.value}]}else if(e.dataType==="string"&&t.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:e.value,regexp:t.value}]}function Itt(t,e,r){let n=e==="!="||e==="!~";if(t.dataType==="null"||r.dataType==="null"){let i=n?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:r.dataType!=="null"?[...r.value,`IS${i} NULL`]:[n?"false":"true"]}}function Mtt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;if(i.dataType==="unsupported"||s.dataType==="unsupported"){let l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){let f=o5(e,i,n,s);if(f)return{...f,dataType:"boolean"}}}let u=I3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(r){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")u=(0,kx.compose)(i.value,"LIKE",s.value);else{let l=w3e(i,s);if(l===void 0)throw new RK("Incompatible types for match('~') operator");u=l}u=(0,kx.nullsafeNot)(u,r);break}case"=":case"!=":{let l=Itt(i,r,s);l?u=l:u=(0,kx.nullsafeNot)(w3e(i,s)||(0,kx.compose)(i.value,"=",s.value),r);break}}return{dataType:"boolean",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u}}function Ptt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;let a=(0,mn.maxExpressionType)(i.expressionType,s.expressionType),u=o5(e,i,n,s);if(u)return{...u,dataType:"boolean"};let l=I3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);return{dataType:"boolean",expressionType:a,evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function CK(t,...e){return e.includes(t)}function ktt(t,...e){for(let r of e)if(r.dataType!==t)return!1;return!0}function M3e(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("number",i,s);if(o)return o;let a=o5(e,i,n,s);if(a)return a;let u=(0,mn.maxExpressionType)(i.expressionType,s.expressionType);return ktt("number",i,s)?{dataType:"number",expressionType:u,value:(0,kx.compose)(i.value,r,s.value),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)}:(e.log(`Non numeric('${i.dataType},${s.dataType}') value with '${r}'`),(0,LA.errorFor)("numbers required"))}function Btt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return o;let a=(0,mn.isTimeFieldType)(i.dataType),u=s5(a?"error":"number",i,s);if(u)return u;if(a){let l=n;if(s.dataType!=="duration")if((0,L3e.isGranularResult)(i))l=new i5(n,i.timeframe);else if(i.dataType==="date")l=new i5(n,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,LA.errorFor)(`time plus ${s.dataType}`);return l.apply(t,r,e)}return M3e(t,e,r,n)}function P3e(t,e,r,n){if((0,Ftt.isEquality)(r))return Mtt(t,e,r,n);if((0,Ntt.isComparison)(r))return Ptt(t,e,r,n);if(CK(r,"+","-"))return Btt(t,e,r,n);if(CK(r,"*","%"))return M3e(t,e,r,n);if(CK(r,"/")){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return e.log("Cannot operate with unsupported type"),o;let a=s5("number",i,s);if(a)return a;if(i.dataType!=="number")e.log("Numerator for division must be a number");else if(s.dataType!=="number")n.log("Denominator for division must be a number");else{let u={type:"dialect",function:"div",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[u]}}return(0,LA.errorFor)("divide type mismatch")}return e.log(`Cannot use ${r} operator here`),(0,LA.errorFor)("applybinary bad operator")}Yc.applyBinary=P3e;function s5(t,...e){if(e.some(r=>r.dataType==="error"))return{dataType:t,expressionType:(0,mn.maxOfExpressionTypes)(e.map(r=>r.expressionType)),value:["'cascading error'"],evalSpace:(0,mn.mergeEvalSpaces)(...e.map(r=>r.evalSpace))}}function o5(t,e,r,n){let i={dataType:e.dataType,expressionType:(0,mn.maxExpressionType)(e.expressionType,n.expressionType),value:["'unsupported operation'"],evalSpace:(0,mn.mergeEvalSpaces)(e.evalSpace,n.evalSpace)};if(e.dataType==="unsupported")return t.log("Unsupported type not allowed in expression"),{...i,dataType:n.dataType};if(n.dataType==="unsupported")return r.log("Unsupported type not allowed in expression"),i}});var bI=v(_I=>{"use strict";Object.defineProperty(_I,"__esModule",{value:!0});_I.BinaryBoolean=void 0;var k3e=Ke(),qtt=js(),Utt=pn(),$tt=ir(),jtt=hs(),OK=class extends $tt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="abstract boolean binary",this.legalChildTypes=[Utt.FT.boolT]}getExpression(e){let r=this.left.getExpression(e),n=this.right.getExpression(e);if(this.typeCheck(this.left,r)&&this.typeCheck(this.right,n)){let i=(0,k3e.mergeEvalSpaces)(r.evalSpace,n.evalSpace);return{dataType:"boolean",expressionType:(0,k3e.maxExpressionType)(r.expressionType,n.expressionType),evalSpace:i,value:(0,jtt.compose)(r.value,this.op,n.value)}}return(0,qtt.errorFor)("logial required boolean")}};_I.BinaryBoolean=OK});var CI=v(TI=>{"use strict";Object.defineProperty(TI,"__esModule",{value:!0});TI.ExprTime=void 0;var Htt=Ke(),ztt=hs(),Gtt=ir(),DK=class t extends Gtt.ExpressionDef{constructor(e,r,n="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:n,value:typeof r=="string"?[r]:r,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,r){let n=r.value;if(e!==r.dataType){let i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:r.value};(0,Htt.isTimeFieldType)(r.dataType)&&(i.srcType=r.dataType),n=(0,ztt.compressExpr)([i])}return new t(e,n,r.expressionType)}};TI.ExprTime=DK});var IA=v(RI=>{"use strict";Object.defineProperty(RI,"__esModule",{value:!0});RI.Range=void 0;var B3e=Ke(),Qtt=js(),Vtt=ir(),Wtt=hs(),NK=class extends Vtt.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,n){switch(r){case"=":case"!=":{let i=r==="="?">=":"<",s=r==="="?"and":"or",o=r==="="?"<":">=",a=this.first.apply(e,i,n),u=this.last.apply(e,o,n);return{dataType:"boolean",expressionType:(0,B3e.maxExpressionType)(a.expressionType,u.expressionType),evalSpace:(0,B3e.mergeEvalSpaces)(a.evalSpace,u.evalSpace),value:(0,Wtt.compose)(a.value,s,u.value)}}case">":return this.last.apply(e,">=",n);case">=":return this.first.apply(e,">=",n);case"<":return this.first.apply(e,"<",n);case"<=":return this.last.apply(e,"<",n)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,Qtt.errorFor)("a range is not a value")}};RI.Range=NK});var LK=v(DI=>{"use strict";Object.defineProperty(DI,"__esModule",{value:!0});DI.ExprGranularTime=void 0;var FK=Ke(),Ytt=js(),q3e=pn(),U3e=DA(),Ktt=ir(),OI=CI(),$3e=IA(),wK=class extends Ktt.ExpressionDef{constructor(e,r,n){super({expr:e}),this.expr=e,this.units=r,this.truncate=n,this.elementType="granularTime",this.legalChildTypes=[q3e.FT.timestampT,q3e.FT.dateT]}granular(){return!0}getExpression(e){let r=this.units,n=this.expr.getExpression(e);if((0,FK.isTimeFieldType)(n.dataType)){let s={...n,dataType:n.dataType,timeframe:r};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:n.value,valueType:n.dataType},units:r}]),s}n.dataType!=="error"&&this.log(`Cannot do time truncation on type '${n.dataType}'`);let i=n.dataType==="error"?(0,FK.isDateUnit)(r)?"date":"timestamp":n.dataType;return{...n,dataType:i,value:(0,Ytt.errorFor)("granularity typecheck").value,evalSpace:"constant"}}apply(e,r,n){return this.getRange(e).apply(e,r,n)}getRange(e){let r=this.getExpression(e);if(r.dataType==="timestamp"){let o=OI.ExprTime.fromValue("timestamp",r),a=new OI.ExprTime("timestamp",(0,U3e.timeOffset)("timestamp",r.value,"+",(0,FK.mkExpr)`1`,this.units),r.expressionType);return new $3e.Range(o,a)}let n=new OI.ExprTime("date",r.value,r.expressionType),i=(0,U3e.timeOffset)("date",r.value,"+",["1"],this.units),s=new OI.ExprTime("date",i,r.expressionType);return new $3e.Range(n,s)}};DI.ExprGranularTime=wK});var MK=v(NI=>{"use strict";Object.defineProperty(NI,"__esModule",{value:!0});NI.ExprCompare=void 0;var Cr=pn(),Xtt=EI(),Jtt=bI(),Ztt=LK(),ert={"~":[Cr.FT.stringT],"!~":[Cr.FT.stringT],"<":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"<=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"!=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT]},IK=class extends Jtt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="a<=>b",this.legalChildTypes=ert[r]}getExpression(e){if(!this.right.granular()){let r=this.right.requestExpression(e);if(r&&(0,Xtt.isGranularResult)(r))return new Ztt.ExprGranularTime(this.right,r.timeframe,!1).apply(e,this.op,this.left)}return this.right.apply(e,this.op,this.left)}};NI.ExprCompare=IK});var j3e=v(FI=>{"use strict";Object.defineProperty(FI,"__esModule",{value:!0});FI.Apply=void 0;var trt=mI(),rrt=MK(),PK=class extends rrt.ExprCompare{constructor(e,r){super(e,trt.Comparison.EqualTo,r),this.left=e,this.right=r,this.elementType="apply"}};FI.Apply=PK});var LI=v(wI=>{"use strict";Object.defineProperty(wI,"__esModule",{value:!0});wI.BinaryNumeric=void 0;var nrt=pn(),irt=ir(),kK=class extends irt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="numeric binary abstract",this.legalChildTypes=[nrt.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}};wI.BinaryNumeric=kK});var H3e=v(II=>{"use strict";Object.defineProperty(II,"__esModule",{value:!0});II.Boolean=void 0;var srt=ir(),ort=pn(),BK=class extends srt.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...ort.FT.boolT,value:[this.value]}}};II.Boolean=BK});var PI=v(MI=>{"use strict";Object.defineProperty(MI,"__esModule",{value:!0});MI.ExprIdReference=void 0;var qK=Ke(),art=js(),urt=vL(),lrt=ir(),UK=class extends lrt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){let r=this.fieldReference.getField(e);if(r.found){let n=r.found.typeDesc();if(r.isOutputField)return{...n,evalSpace:n.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};let i=[{type:r.found.refType,path:this.fieldReference.path}],s=(0,qK.expressionIsAggregate)(n.expressionType)?"output":n.evalSpace;return{...n,value:i,evalSpace:s}}return this.log(r.error),(0,art.errorFor)(r.error)}apply(e,r,n){let i=this.fieldReference.getField(e).found;if(i instanceof urt.SpaceParam){let s=i.parameter();if((0,qK.isConditionParameter)(s)){let o=n.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,qK.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,r,n)}};MI.ExprIdReference=UK});var kI=v(MA=>{"use strict";Object.defineProperty(MA,"__esModule",{value:!0});MA.FunctionOrdering=MA.FunctionOrderBy=void 0;var $K=Ke(),z3e=mt(),crt=PI(),jK=class extends z3e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",this.has({field:e})}getAnalyticOrderBy(e){let r=this.field.getExpression(e);return(0,$K.expressionIsAggregate)(r.expressionType)||((0,$K.expressionIsScalar)(r.expressionType)?(!(this.field instanceof crt.ExprIdReference)||r.evalSpace==="input")&&this.field.log("analytic `order_by` must be an aggregate or an output field reference"):this.field.log("analytic `order_by` must be scalar or aggregate")),{e:r.value,dir:this.dir}}getAggregateOrderBy(e){let r=this.field.getExpression(e);return(0,$K.expressionIsScalar)(r.expressionType)||this.field.log("aggregate `order_by` must be scalar"),{e:r.value,dir:this.dir}}};MA.FunctionOrderBy=jK;var HK=class extends z3e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e){return this.list.map(r=>r.getAggregateOrderBy(e))}};MA.FunctionOrdering=HK});var G3e=v(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.ExprAddSub=void 0;var frt=LI(),zK=class extends frt.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}};BI.ExprAddSub=zK});var QK=v(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.ReferenceField=void 0;var Q3e=ua(),GK=class extends Q3e.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){let r=this.fieldRef.getField(e);r.error&&this.fieldRef.log(r.error),this.queryFieldDef={type:"fieldref",path:this.fieldRef.list.map(i=>i.name)};let n=this.referenceTo;if(n instanceof Q3e.SpaceField&&n.haveFieldDef){let i=n.haveFieldDef,s=this.fieldRef.note;if(i.annotation||s){let o=s||{};i.annotation&&(o.inherits=i.annotation),this.queryFieldDef.annotation=o}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;let e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}};qI.ReferenceField=GK});var VK=v(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.typecheckGroupBy=Pi.typecheckAggregate=Pi.typecheckCalculate=Pi.typecheckDeclare=Pi.typecheckMeasure=Pi.typecheckDimension=Pi.typecheckIndex=Pi.typecheckProject=void 0;var gn=lc();function xrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a select operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckProject=xrt;function drt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r;if(t.dataType==="turtle")r="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in an index operation`)}}Pi.typecheckIndex=drt;function hrt(t,e){if(!(0,gn.expressionIsScalar)(t.expressionType))if((0,gn.expressionIsAggregate)(t.expressionType))e.log("Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckDimension=hrt;function prt(t,e){if(!(0,gn.expressionIsAggregate)(t.expressionType))if((0,gn.expressionIsScalar)(t.expressionType))e.log("Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckMeasure=prt;function mrt(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,gn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Pi.typecheckDeclare=mrt;function grt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAnalytic)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a calculate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckCalculate=grt;function yrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAggregate)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${n} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckAggregate=yrt;function Ert(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a group_by operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckGroupBy=Ert});var PA=v(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.FieldReferences=Gt.WildcardFieldReference=Gt.ViewOrScalarFieldReference=Gt.DimensionFieldReference=Gt.MeasureFieldReference=Gt.DeclareFieldReference=Gt.ProjectFieldReference=Gt.GroupByFieldReference=Gt.AggregateFieldReference=Gt.IndexFieldReference=Gt.CalculateFieldReference=Gt.PartitionByFieldReference=Gt.ExpressionFieldReference=Gt.AcceptExceptFieldReference=Gt.FieldReference=void 0;var Srt=QK(),Art=n0(),V3e=mt(),W3e=Vc(),wp=VK(),Co=class extends V3e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=W3e.extendNoteMethod}makeEntry(e){let r=this.outputName;if(e.entry(r))this.log(`Output already has a field named '${r}'`);else{let n=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Srt.ReferenceField(this,n))}}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){let r=e.lookup(this.list);if(r.found){let n=r.found.typeDesc();this.typecheck(n)}return r}};Gt.FieldReference=Co;var WK=class extends Co{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}};Gt.AcceptExceptFieldReference=WK;var YK=class extends Co{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}};Gt.ExpressionFieldReference=YK;var KK=class extends Co{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}};Gt.PartitionByFieldReference=KK;var XK=class extends Co{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,wp.typecheckCalculate)(e,this)}};Gt.CalculateFieldReference=XK;var JK=class t extends Co{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,wp.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return t.indexOutputName(this.path)}};Gt.IndexFieldReference=JK;var ZK=class extends Co{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,wp.typecheckAggregate)(e,this)}};Gt.AggregateFieldReference=ZK;var eX=class extends Co{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,wp.typecheckGroupBy)(e,this)}};Gt.GroupByFieldReference=eX;var tX=class extends Co{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,wp.typecheckProject)(e,this)}};Gt.ProjectFieldReference=tX;var rX=class extends Co{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,wp.typecheckDeclare)(e,this)}};Gt.DeclareFieldReference=rX;var nX=class extends Co{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,wp.typecheckMeasure)(e,this)}};Gt.MeasureFieldReference=nX;var iX=class extends Co{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,wp.typecheckDimension)(e,this)}};Gt.DimensionFieldReference=iX;var sX=class extends Co{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}};Gt.ViewOrScalarFieldReference=sX;var oX=class extends V3e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=W3e.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}.*`:"*"}};Gt.WildcardFieldReference=oX;var aX=class extends Art.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}};Gt.FieldReferences=aX});var Zm=v(UI=>{"use strict";Object.defineProperty(UI,"__esModule",{value:!0});UI.ExprAggregateFunction=void 0;var Y3e=Ke(),vrt=jd(),a5=js(),_rt=tl(),brt=e5(),Trt=pn(),Crt=PA(),Rrt=ir(),Ort=ua(),Drt=PI(),uX=class extends Rrt.ExpressionDef{constructor(e,r,n){super(),this.func=e,this.legalChildTypes=[Trt.FT.numberT],this.elementType=e,this.explicitSource=n,r&&(this.expr=r,this.has({expr:r}))}returns(e){return"number"}getExpression(e){var r,n;let i=e.isQueryFieldSpace()?e.inputSpace():e,s=this.expr,o=(r=this.expr)===null||r===void 0?void 0:r.getExpression(i),a=(n=this.source)===null||n===void 0?void 0:n.path,u=[];if(this.source){let c=this.source.getField(i);if(c.found){u=c.relationship;let f=c.found,x=f.typeDesc();if((0,Y3e.isAtomicFieldType)(x.dataType)){s=this.source,o={dataType:x.dataType,expressionType:x.expressionType,value:[x.evalSpace==="output"?{type:"outputField",name:this.source.refString}:{type:"field",path:this.source.path}],evalSpace:x.evalSpace},a=this.source.path;let d=this.getJoinUsage(i);(d.length===1||d.slice(1).every(p=>Nrt(p,d[0])))&&(a=d[0].map(p=>p.name),u=d[0])}else if(!(f instanceof brt.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,a5.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,a5.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,a5.errorFor)("agggregate without expression");if((0,Y3e.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,a5.errorFor)("reagggregate");if(!(o.dataType==="error")){let c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(d=>d.length===0))&&!this.isSymmetricFunction()){let d=cX(u,c),h=fX(this.elementType,d),p=f?h:"Join path is required for this calculation";if(p){let m=Frt(p,c,s,this.elementType);this.log(m,h?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){let c={type:"aggregate",function:this.func,e:o.value};return a&&a.length>0&&(c.structPath=a),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,a5.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){let r=[];if(this.source&&this.source.getField(e).found){let i=[{type:"field",path:this.source.path}];r.push(...lX(e,i))}if(this.expr){let n=this.expr.getExpression(e).value;r.push(...lX(e,n))}return r}};UI.ExprAggregateFunction=uX;function Nrt(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function lX(t,e){let r=[],n=(i,s)=>{let o=s[0],a=s.slice(1),u=i.entry(o);if(u===void 0)throw new Error(`Invalid field lookup ${o}`);if(u instanceof _rt.StructSpaceField&&a.length>0){let l=n(u.fieldSpace,a);return{...l,relationship:[{name:o,structRelationship:u.structRelationship},...l.relationship]}}else if(u instanceof Ort.SpaceField){if(a.length!==0)throw new Error(`${o} cannot contain a ${a.join(".")}`);let l=u.fieldDef();if(l)return{fs:i,def:l,relationship:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};return(0,vrt.exprWalk)(e,i=>{if(typeof i!="string"&&i.type==="field"){let s=n(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){let o=lX(s.fs,s.def.e);r.push(...o.map(a=>[...s.relationship,...a]))}else r.push(s.relationship)}}),r}function cX(t,e){let r=[];for(let n of e){let i=0;for(let u=0;u<t.length&&u<n.length&&t[u].name===n[u].name;u++)i=u+1;let s=t.slice(i),o=n.slice(i),a=[...s.map(u=>({...u,reverse:!0})),...o.map(u=>({...u,reverse:!1}))];r.push(a)}return r}function fX(t,e){for(let r of e)for(let n of r){if(n.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${n.name}\``;if(n.structRelationship.type==="many"&&!n.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${n.name}\``;if(n.structRelationship.type==="nested"&&!n.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${n.name}\``}}function Frt(t,e,r,n){if(e.length===0)return t;let i=e[0];for(let h of e.slice(1))for(let p=0;p<i.length;p++){let m=i[p],g=h[p];if(m.name!==g.name){i=i.slice(0,p);break}}let s=cX(i,e),o=fX(n,s),a=i.slice().reverse().findIndex(h=>h.structRelationship.type==="many"||h.structRelationship.type==="cross"),u=a===-1?0:i.length-a,l=i.slice(0,u),c=cX(l,e),f=fX(n,c),x=i.length>0?i.map(h=>h.name).join("."):"source",d=l.length>0?l.map(h=>h.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()`";{let h=r instanceof Crt.FieldReference?`${r.refString}.${n}()`:r instanceof Drt.ExprIdReference?`${r.fieldReference.refString}.${n}()`:`${x}.${n}(${r.code})`,p=`${d}.${n}(${r.code})`,m=`${t}; use \`${h}\``;return f===void 0&&d!==x&&(m+=` or \`${p}\` to get a result weighted with respect to \`${d}\``),m}}});var X3e=v($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.ExprAlternationTree=void 0;var K3e=Ke(),wrt=js(),Lrt=bI(),Irt=hs(),xX=class extends Lrt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="alternation",this.elementType=`${r}alternation${r}`}apply(e,r,n){let i=this.left.apply(e,r,n),s=this.right.apply(e,r,n);return{dataType:"boolean",expressionType:(0,K3e.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,K3e.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,Irt.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,wrt.errorFor)("no value from alternation tree")}};$I.ExprAlternationTree=xX});var HI=v(jI=>{"use strict";Object.defineProperty(jI,"__esModule",{value:!0});jI.ExprAsymmetric=void 0;var Mrt=Zm(),dX=class extends Mrt.ExprAggregateFunction{constructor(e,r,n,i){super(e,r,i),this.func=e,this.expr=r,this.source=n,this.has({source:n})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){let e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}};jI.ExprAsymmetric=dX});var J3e=v(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.ExprAvg=void 0;var Prt=HI(),hX=class extends Prt.ExprAsymmetric{constructor(e,r,n){super("avg",e,r,n),this.has({source:r})}};zI.ExprAvg=hX});var Z3e=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.ExprCast=void 0;var krt=DA(),Brt=ir(),qrt=hs(),pX=class extends Brt.ExpressionDef{constructor(e,r,n=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=n,this.elementType="cast"}getExpression(e){var r,n,i;let s=this.expr.getExpression(e),o="unsupported";if(typeof this.castType=="string")o=this.castType;else{let a=e.dialectObj();a&&(a.validateTypeName(this.castType.raw)?o=(i=(n=(r=e.dialectObj())===null||r===void 0?void 0:r.sqlTypeToMalloyType(this.castType.raw))===null||n===void 0?void 0:n.type)!==null&&i!==void 0?i:"unsupported":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${a.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,qrt.compressExpr)((0,krt.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}};GI.ExprCast=pX});var tye=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.ExprCoalesce=void 0;var mX=lc(),eye=pn(),Urt=ir(),gX=class extends Urt.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=eye.FT.anyAtomicT}getExpression(e){let r=this.expr.getExpression(e),n=this.altExpr.getExpression(e);return r.dataType==="null"?n:(eye.FT.typeEq(r,n)||this.log(`Mismatched types for coalesce (${r.dataType}, ${n.dataType})`),{...n,dataType:r.dataType==="error"?n.dataType:r.dataType,expressionType:(0,mX.maxExpressionType)(r.expressionType,n.expressionType),value:(0,mX.mkExpr)`COALESCE(${r.value},${n.value})`,evalSpace:(0,mX.mergeEvalSpaces)(r.evalSpace,n.evalSpace)})}};QI.ExprCoalesce=gX});var rye=v(VI=>{"use strict";Object.defineProperty(VI,"__esModule",{value:!0});VI.ExprCount=void 0;var $rt=Zm(),yX=class extends $rt.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){let r={type:"aggregate",function:"count",e:[]};return this.source&&(r.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[r],evalSpace:"output"}}};VI.ExprCount=yX});var nye=v(YI=>{"use strict";Object.defineProperty(YI,"__esModule",{value:!0});YI.ExprCountDistinct=void 0;var WI=pn(),jrt=Zm(),EX=class extends jrt.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[WI.FT.numberT,WI.FT.stringT,WI.FT.dateT,WI.FT.timestampT]}};YI.ExprCountDistinct=EX});var kA=v(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.Limit=void 0;var Hrt=mt(),zrt=Ii(),SX=class extends Hrt.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=zrt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}};KI.Limit=SX});var JI=v(XI=>{"use strict";Object.defineProperty(XI,"__esModule",{value:!0});XI.PartitionBy=void 0;var Grt=mt(),AX=class extends Grt.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}};XI.PartitionBy=AX});var _X=v(ZI=>{"use strict";Object.defineProperty(ZI,"__esModule",{value:!0});ZI.ExprFunc=void 0;var i0=Ke(),Bx=js(),Qrt=e5(),Vrt=ir(),iye=hs(),vX=class extends Vrt.ExpressionDef{constructor(e,r,n,i,s){super({args:r}),this.name=e,this.args=r,this.isRaw=n,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}getPropsExpression(e,r){var n,i,s,o,a;let u=this.args.map(O=>O.getExpression(e));if(this.isRaw){let O="scalar",N,P=[`${this.name}(`];for(let H of u)O=(0,i0.maxExpressionType)(O,H.expressionType),N?P.push(","):N=H.dataType,P.push(...H.value);return P.push(")"),{dataType:(i=(n=this.rawType)!==null&&n!==void 0?n:N)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,iye.compressExpr)(P),evalSpace:(0,i0.mergeEvalSpaces)(...u.map(H=>H.evalSpace))}}let l=(s=this.modelEntry(this.name.toLowerCase()))===null||s===void 0?void 0:s.entry;if(l===void 0)return this.log(`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),(0,Bx.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,Bx.errorFor)("called non function");l.name!==this.name&&this.log(`Case insensitivity for function names is deprecated, use '${l.name}' instead`,"warn");let c,f=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){let O=this.source.getField(e).found;if(O){let N=O.typeDesc();if((0,i0.isAtomicFieldType)(N.dataType))c={dataType:N.dataType,expressionType:N.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:N.evalSpace},f=this.source.path.slice(0,-1);else if(!(O instanceof Qrt.StructSpaceFieldBase)){let P=`Aggregate source cannot be a ${N.dataType}`;return this.log(P),(0,Bx.errorFor)(P)}}else{let N=`Reference to undefined value ${this.source.refString}`;return this.log(N),(0,Bx.errorFor)(N)}}let x=[...c?[c]:[],...u],d=Wrt(l,x);if(d===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,Bx.errorFor)("no matching overload");let{overload:h,expressionTypeErrors:p,evalSpaceErrors:m,nullabilityErrors:g}=d;for(let O of p){let N=O.argIndex-(c?1:0),P=(0,i0.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${P}, but received ${O.actualExpressionType}`)}for(let O of m){let N=O.argIndex-(c?1:0),P=O.maxEvalSpace==="literal"?"literal":O.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${P}, but received ${O.actualEvalSpace}`)}for(let O of g){let N=O.argIndex-(c?1:0);this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must not be a literal null`)}let y=h.returnType,S=(0,i0.maxOfExpressionTypes)([y.expressionType,...x.map(O=>O.expressionType)]);if(!(0,i0.expressionIsAggregate)(h.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(O=>O.dataType).join(", ")}) with source`),(0,Bx.errorFor)("cannot call with source");let A={type:"function_call",overload:h,args:x.map(O=>O.value),expressionType:S,structPath:f},T=[A],b=(a=e.dialectObj())===null||a===void 0?void 0:a.name,_=b?h.dialect[b]:void 0;if(_===void 0)this.log(`Function ${this.name} is not defined in dialect ${b}`);else{if(r?.orderBys&&r.orderBys.length>0){let O=(0,i0.expressionIsAnalytic)(h.returnType.expressionType);if(_.supportsOrderBy||O){let N=r.orderBys.flatMap(P=>O?P.getAnalyticOrderBy(e):P.getAggregateOrderBy(e));A.orderBy=N}else r.orderBys[0].log(`Function ${this.name} does not support order_by`)}r?.limit!==void 0&&(_.supportsLimit?A.limit=r.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(r?.partitionBys&&r.partitionBys.length>0){let O=[];for(let N of r.partitionBys)for(let P of N.partitionFields){let k=P.getField(e);k.found===void 0?P.log(`${P.refString} is not defined`):(0,i0.expressionIsScalar)(k.found.typeDesc().expressionType)?O.push(P.nameString):P.log("Partition expression must be scalar")}A.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,Bx.errorFor)(`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);let O=x[0].value;if(O.length!==1||typeof O[0]=="string"||O[0].type!=="dialect"||O[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{let N=O[0].literal,P=Yrt(N),k=P.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(k.length>0){let H=k.length===1?`'.' paths are not yet supported in sql interpolations, found ${k.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${k.join(", ")}]`;return this.log(H),(0,Bx.errorFor)(`${H}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}T=[{type:"sql-string",e:P.map(H=>H.type==="string"?H.value:H.name==="TABLE"?{type:"source-reference"}:{type:"field",path:[H.name]})}]}}if(y.dataType==="any")return this.log(`Invalid return type ${y.dataType} for function '${this.name}'`),(0,Bx.errorFor)("invalid return type");let R=(0,i0.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),D=R==="constant"?"constant":(0,i0.expressionIsScalar)(S)?R:"output";return{dataType:y.dataType,expressionType:S,value:(0,iye.compressExpr)(T),evalSpace:D}}};ZI.ExprFunc=vX;function Wrt(t,e){for(let r of t.overloads){let n=0,i=!0,s=!1,o=[],a=[],u=[];for(let l=0;l<e.length;l++){let c=e[l],f=r.params[n];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(d=>{let h=d.dataType===c.dataType||d.dataType==="any"||c.dataType==="null"||c.dataType==="error";return d.expressionType&&((0,i0.isExpressionTypeLEQ)(c.expressionType,d.expressionType)||o.push({argIndex:l,maxExpressionType:d.expressionType,actualExpressionType:c.expressionType,param:f})),(d.evalSpace==="literal"&&c.evalSpace!=="literal"||d.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||d.evalSpace==="output"&&c.evalSpace==="input")&&a.push({argIndex:l,param:f,maxEvalSpace:d.evalSpace,actualEvalSpace:c.evalSpace}),d.evalSpace==="literal"&&c.dataType==="null"&&u.push({argIndex:l,param:f}),h})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):n++}if(!(!s&&(n!==e.length||n!==r.params.length))&&i)return{overload:r,expressionTypeErrors:o,evalSpaceErrors:a,nullabilityErrors:u}}}function Yrt(t){let e=[],r=t;for(;r.length;){let n=r.indexOf("${");if(n===-1){e.push({type:"string",value:r});break}else{let i=r.slice(n).indexOf("}");if(i===-1){e.push({type:"string",value:r});break}n>0&&e.push({type:"string",value:r.slice(0,n)}),e.push({type:"interpolation",name:r.slice(n+2,i+n)}),r=r.slice(i+n+1)}}return e}});var sye=v(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.ExprProps=void 0;var Krt=Ke(),Xrt=js(),Jrt=pn(),Zrt=kI(),ent=kA(),tnt=JI(),rnt=ir(),nnt=_X(),bX=class extends rnt.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=Jrt.FT.anyAtomicT}getFilteredExpression(e,r,n){if(n.length>0){if(!this.expr.supportsWhere(r))return this.expr.log("Filtered expression requires an aggregate computation"),r;let i=[];for(let s of n){let o=s.getFilterList(e);if(o.find(a=>(0,Krt.expressionIsCalculation)(a.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),r;i.push(...o)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,value:[{type:"filterExpression",e:r.value,filterList:i}]}:(this.expr.log(`Cannot filter '${r.dataType}' data`),(0,Xrt.errorFor)("cannot filter type"))}return r}getExpression(e){let r=[],n,i=[],s=[];for(let a of this.statements)a instanceof tnt.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.log("`partition_by` is not supported for this kind of expression"):a instanceof ent.Limit?n?a.log("limit already specified"):this.expr.canSupportLimit()?n=a:a.log("`limit` is not supported for this kind of expression"):a instanceof Zrt.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(a):a.log("`order_by` is not supported for this kind of expression"):s.push(a);let o=this.expr instanceof nnt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:n,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}};eM.ExprProps=bX});var aye=v(tM=>{"use strict";Object.defineProperty(tM,"__esModule",{value:!0});tM.ExprLogicalOp=void 0;var int=bI(),oye=pn(),TX=class extends int.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[oye.FT.boolT,oye.FT.aggregateBoolT]}};tM.ExprLogicalOp=TX});var uye=v(nM=>{"use strict";Object.defineProperty(nM,"__esModule",{value:!0});nM.ExprMax=void 0;var rM=pn(),snt=Zm(),CX=class extends snt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[rM.FT.numberT,rM.FT.stringT,rM.FT.dateT,rM.FT.timestampT]}returns(e){return e.dataType}};nM.ExprMax=CX});var lye=v(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.ExprMin=void 0;var iM=pn(),ont=Zm(),RX=class extends ont.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[iM.FT.numberT,iM.FT.stringT,iM.FT.dateT,iM.FT.timestampT]}returns(e){return e.dataType}};sM.ExprMin=RX});var cye=v(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.ExprMinus=void 0;var ant=js(),unt=pn(),lnt=ir(),OX=class extends lnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[unt.FT.numberT]}getExpression(e){let r=this.expr.getExpression(e);return this.typeCheck(this.expr,r)?r.value.length>1?{...r,dataType:"number",value:["-(",...r.value,")"]}:{...r,dataType:"number",value:["-",...r.value]}:(0,ant.errorFor)("negate requires number")}};oM.ExprMinus=OX});var fye=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.ExprMulDiv=void 0;var cnt=LI(),DX=class extends cnt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}};aM.ExprMulDiv=DX});var FX=v(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.Unary=void 0;var fnt=ir(),NX=class extends fnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}};uM.Unary=NX});var dye=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.ExprNot=void 0;var xye=pn(),xnt=FX(),dnt=hs(),wX=class extends xnt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[xye.FT.boolT,xye.FT.nullT]}getExpression(e){let r=this.expr.getExpression(e),n=this.typeCheck(this.expr,r);return{...r,dataType:"boolean",value:n?(0,dnt.nullsafeNot)(r.value):["false"]}}};lM.ExprNot=wX});var hye=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0});cM.ExprNow=void 0;var hnt=ir(),LX=class extends hnt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}};cM.ExprNow=LX});var pye=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0});fM.ExprNULL=void 0;var pnt=ir(),IX=class extends pnt.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}};fM.ExprNULL=IX});var mye=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.ExprNumber=void 0;var mnt=pn(),gnt=ir(),MX=class extends gnt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...mnt.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}};xM.ExprNumber=MX});var gye=v(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.ExprParens=void 0;var ynt=ir(),PX=class extends ynt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){let r=this.expr.getExpression(e);return{...r,value:["(",...r.value,")"]}}};dM.ExprParens=PX});var yye=v(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.ExprRegEx=void 0;var Ent=ir(),kX=class extends Ent.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:[{type:"dialect",function:"regexpLiteral",literal:this.regex}],evalSpace:"literal"}}};hM.ExprRegEx=kX});var Eye=v(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.ExprString=void 0;var Snt=ir(),Ant=pn(),BX=class extends Snt.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...Ant.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}};pM.ExprString=BX});var Sye=v(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.ExprSum=void 0;var vnt=HI(),qX=class extends vnt.ExprAsymmetric{constructor(e,r,n){super("sum",e,r,n),this.has({source:r})}};mM.ExprSum=qX});var Aye=v(yM=>{"use strict";Object.defineProperty(yM,"__esModule",{value:!0});yM.ExprTimeExtract=void 0;var eg=Ke(),Lp=js(),UX=ir(),_nt=IA(),gM=class t extends UX.ExpressionDef{static extractor(e){let r=t.pluralMap[e];if(r)return r;if((0,eg.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){let r=t.extractor(this.extractText);if(r){if(this.args.length!==1)return this.log(`Extraction function ${r} requires one argument`),(0,Lp.errorFor)("{this.name} arg count");let n=this.args[0];if(n instanceof _nt.Range){let i=n.first.getExpression(e),s=n.last.getExpression(e),o=(0,eg.maxExpressionType)(i.expressionType,s.expressionType),a=(0,eg.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:a,value:(0,Lp.errorFor)("extract from error").value};if(!(0,eg.isTimeFieldType)(i.dataType))return n.first.log(`Can't extract ${r} from '${i.dataType}'`),(0,Lp.errorFor)(`${r} bad type ${i.dataType}`);if(!(0,eg.isTimeFieldType)(s.dataType))return n.last.log(`Cannot extract ${r} from '${s.dataType}'`),(0,Lp.errorFor)(`${r} bad type ${s.dataType}`);let u=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(u="timestamp",i.dataType==="date"){let c=(0,UX.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{let c=(0,UX.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return n.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,Lp.errorFor)(`${r} range mismatch`)}return["week","month","quarter","year"].includes(r)?(this.log(`Cannot measure interval using '${r}'`),(0,Lp.errorFor)(`${r} civil extraction`)):(0,eg.isTimestampUnit)(r)?{dataType:"number",expressionType:o,evalSpace:a,value:[{type:"dialect",function:"timeDiff",units:r,left:{valueType:u,value:i.value},right:{valueType:u,value:s.value}}]}:(this.log(`Cannot extract ${r} from a range`),(0,Lp.errorFor)(`${r} bad extraction`))}else{let i=n.getExpression(e);return(0,eg.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:r}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,Lp.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}};yM.ExprTimeExtract=gM;gM.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"}});var u5=v(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.FieldName=void 0;var bnt=mt(),$X=class extends bnt.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])}};EM.FieldName=$X});var vye=v(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.QueryInputSpace=void 0;var Tnt=CA(),Cnt=MY(),Rnt=LL(),jX=class extends Rnt.RefinedSpace{constructor(e,r){let n=new Cnt.SpaceSeed(e);super(n.structDef),this.queryOutput=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof Tnt.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}};SM.QueryInputSpace=jX});var l5=v(ca=>{"use strict";var Ont=ca&&ca.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dnt=ca&&ca.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nnt=ca&&ca.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ont(e,t,r);return Dnt(e,t),e};Object.defineProperty(ca,"__esModule",{value:!0});ca.ReduceFieldSpace=ca.QuerySpace=ca.QueryOperationSpace=void 0;var AM=Nnt(Ke()),HX=AL(),Fnt=u5(),wnt=ua(),Lnt=PA(),Int=LL(),Mnt=NY(),Pnt=tl(),knt=vye(),vM=class extends Int.RefinedSpace{constructor(e,r,n,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=n,this.astEl=i,this.expandedWild={},this.exprSpace=new knt.QueryInputSpace(e,this),r&&this.addRefineFromFields(r)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof Pnt.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries())if(!e.except.has(a))if(this.entry(a)){let l=(r=this.expandedWild[a])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{let l=u.typeDesc();AM.isAtomicFieldType(l.dataType)&&AM.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:a,entry:u}),this.expandedWild[a]=i.concat(a))}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};ca.QueryOperationSpace=vM;var _M=class extends vM{addRefineFromFields(e){var r;if(AM.isQuerySegment(e))for(let n of e.queryFields)if(n.type==="fieldref"){let i=this.exprSpace.lookup(n.path.map(s=>new Fnt.FieldName(s)));i.found&&this.setEntry(n.path[n.path.length-1],i.found)}else n.type!=="turtle"&&this.setEntry((r=n.as)!==null&&r!==void 0?r:n.name,new Mnt.ColumnSpaceField(n))}pushFields(...e){for(let r of e)r instanceof Lnt.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){let e=[];for(let[r,n]of this.entries())if(n instanceof wnt.SpaceField){let i=this.expandedWild[r];if(i){e.push({type:"fieldref",path:i});continue}let s=n.getQueryFieldDef(this.exprSpace);if(s){let o=n.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!Bnt(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){let r=this.getPipeSegment(e);if(AM.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.log("internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};if(e?.extendSource)for(let n of e.extendSource)this.exprSpace.addFieldDef(n);let r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,HX.mergeFields)(e?.queryFields,r.queryFields),e?.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){let n=[],i=this.exprSpace.structDef();for(let s of this.exprSpace.extendList){let o=i.fields.find(a=>(0,HX.nameFromDef)(a)===s);o&&n.push(o)}r.extendSource=(0,HX.mergeFields)(r.extendSource,n)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),this.isComplete(),r}lookup(e){let r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}};ca.QuerySpace=_M;var zX=class extends _M{constructor(){super(...arguments),this.segmentType="reduce"}};ca.ReduceFieldSpace=zX;function Bnt(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}});var bye=v(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.ExprUngroup=void 0;var _ye=Ke(),GX=js(),qnt=l5(),Unt=pn(),$nt=ir(),QX=class extends $nt.ExpressionDef{constructor(e,r,n){super({expr:r,fields:n}),this.control=e,this.expr=r,this.fields=n,this.legalChildTypes=Unt.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){let r=this.expr.getExpression(e);if(!(0,_ye.expressionIsAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,GX.errorFor)("ungrouped scalar");if((0,_ye.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,GX.errorFor)("doubly-ungrouped aggregate");let n={type:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){let i=[],s=this.control==="exclude";for(let o of this.fields){let a=e.outputSpace(),u=!0;for(;a;){let l=a.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),u=!1;else if(a instanceof qnt.QuerySpace){a=a.nestParent;continue}break}if(u){let l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}n.fields=i}return{dataType:this.returns(r),expressionType:"ungrouped_aggregate",value:[n],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,GX.errorFor)("ungrouped type check")}};bM.ExprUngroup=QX});var Oye=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0});RM.ForRange=void 0;var Tye=lc(),VX=js(),Cye=pn(),TM=DA(),jnt=ir(),CM=CI(),Rye=IA(),WX=class extends jnt.ExpressionDef{constructor(e,r,n){super({from:e,duration:r,timeframe:n}),this.from=e,this.duration=r,this.timeframe=n,this.elementType="forRange",this.legalChildTypes=[Cye.FT.timestampT,Cye.FT.dateT]}apply(e,r,n){let i=this.from.getExpression(e),s=n.getExpression(e);if(!this.typeCheck(n,s))return(0,VX.errorFor)("no time for range");let o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.log(`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,Tye.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,Tye.maxExpressionType)(i.expressionType,s.expressionType),value:(0,VX.errorFor)("for not number").value};let a=this.timeframe.text,u=(0,TM.resolution)(a);if(i.dataType==="timestamp"&&(u="timestamp"),s.dataType==="date"&&u==="date"){let h=this.from,p=(0,TM.timeOffset)("date",i.value,"+",o.value,a),m=new CM.ExprTime("date",p);return new Rye.Range(h,m).apply(e,r,n)}let l=CM.ExprTime.fromValue("timestamp",s),c=this.from,f=i.value;if(i.dataType==="date"){let h=i.morphic&&i.morphic.timestamp;h?f=h:f=(0,TM.castDateToTimestamp)(f),c=new CM.ExprTime("timestamp",f,i.expressionType)}let x=(0,TM.timeOffset)("timestamp",f,"+",o.value,a),d=new CM.ExprTime("timestamp",x,i.expressionType);return new Rye.Range(c,d).apply(e,r,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,VX.errorFor)("range has no value")}};RM.ForRange=WX});var _J=v(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var Ux=class extends Error{},nJ=class extends Ux{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},iJ=class extends Ux{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},sJ=class extends Ux{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ig=class extends Ux{},IM=class extends Ux{constructor(e){super(`Invalid unit ${e}`)}},fa=class extends Ux{},Kc=class extends Ux{constructor(){super("Zone is an abstract class")}},Re="numeric",u0="short",uu="long",oJ={year:Re,month:Re,day:Re},Zye={year:Re,month:u0,day:Re},Hnt={year:Re,month:u0,day:Re,weekday:u0},eEe={year:Re,month:uu,day:Re},tEe={year:Re,month:uu,day:Re,weekday:uu},rEe={hour:Re,minute:Re},nEe={hour:Re,minute:Re,second:Re},iEe={hour:Re,minute:Re,second:Re,timeZoneName:u0},sEe={hour:Re,minute:Re,second:Re,timeZoneName:uu},oEe={hour:Re,minute:Re,hourCycle:"h23"},aEe={hour:Re,minute:Re,second:Re,hourCycle:"h23"},uEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:u0},lEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:uu},cEe={year:Re,month:Re,day:Re,hour:Re,minute:Re},fEe={year:Re,month:Re,day:Re,hour:Re,minute:Re,second:Re},xEe={year:Re,month:u0,day:Re,hour:Re,minute:Re},dEe={year:Re,month:u0,day:Re,hour:Re,minute:Re,second:Re},znt={year:Re,month:u0,day:Re,weekday:u0,hour:Re,minute:Re},hEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,timeZoneName:u0},pEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,second:Re,timeZoneName:u0},mEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,timeZoneName:uu},gEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,second:Re,timeZoneName:uu};function kt(t){return typeof t>"u"}function og(t){return typeof t=="number"}function UM(t){return typeof t=="number"&&t%1===0}function Gnt(t){return typeof t=="string"}function Qnt(t){return Object.prototype.toString.call(t)==="[object Date]"}function yEe(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Vnt(t){return Array.isArray(t)?t:[t]}function Dye(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let s=[e(i),i];return n&&r(n[0],s[0])===n[0]?n:s},null)[1]}function Wnt(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function UA(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qx(t,e,r){return UM(t)&&t>=e&&t<=r}function Ynt(t,e){return t-e*Math.floor(t/e)}function jn(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function Ip(t){if(!(kt(t)||t===null||t===""))return parseInt(t,10)}function tg(t){if(!(kt(t)||t===null||t===""))return parseFloat(t)}function mJ(t){if(!(kt(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function gJ(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function g5(t){return t%4===0&&(t%100!==0||t%400===0)}function p5(t){return g5(t)?366:365}function MM(t,e){let r=Ynt(e-1,12)+1,n=t+(e-r)/12;return r===2?g5(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function yJ(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 PM(t){let e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,r=t-1,n=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7;return e===4||n===3?53:52}function aJ(t){return t>99?t:t>60?1900+t:2e3+t}function EEe(t,e,r,n=null){let i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(s.timeZone=n);let o={timeZoneName:e,...s},a=new Intl.DateTimeFormat(r,o).formatToParts(i).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function $M(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function SEe(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new fa(`Invalid unit value ${t}`);return e}function kM(t,e){let r={};for(let n in t)if(UA(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=SEe(i)}return r}function m5(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${jn(r,2)}:${jn(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${jn(r,2)}${jn(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function jM(t){return Wnt(t,["hour","minute","second","millisecond"])}var AEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,Knt=["January","February","March","April","May","June","July","August","September","October","November","December"],vEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Xnt=["J","F","M","A","M","J","J","A","S","O","N","D"];function _Ee(t){switch(t){case"narrow":return[...Xnt];case"short":return[...vEe];case"long":return[...Knt];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}}var bEe=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],TEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Jnt=["M","T","W","T","F","S","S"];function CEe(t){switch(t){case"narrow":return[...Jnt];case"short":return[...TEe];case"long":return[...bEe];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var REe=["AM","PM"],Znt=["Before Christ","Anno Domini"],eit=["BC","AD"],tit=["B","A"];function OEe(t){switch(t){case"narrow":return[...tit];case"short":return[...eit];case"long":return[...Znt];default:return null}}function rit(t){return REe[t.hour<12?0:1]}function nit(t,e){return CEe(e)[t.weekday-1]}function iit(t,e){return _Ee(e)[t.month-1]}function sit(t,e){return OEe(e)[t.year<0?0:1]}function oit(t,e,r="always",n=!1){let 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(r==="auto"&&s){let 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]}`}}let o=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=i[t],c=n?u?l[1]:l[2]||l[1]:u?i[t][0]:t;return o?`${a} ${c} ago`:`in ${a} ${c}`}function Nye(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var ait={D:oJ,DD:Zye,DDD:eEe,DDDD:tEe,t:rEe,tt:nEe,ttt:iEe,tttt:sEe,T:oEe,TT:aEe,TTT:uEe,TTTT:lEe,f:cEe,ff:xEe,fff:hEe,ffff:mEe,F:fEe,FF:dEe,FFF:pEe,FFFF:gEe},a0=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,s=[];for(let o=0;o<e.length;o++){let a=e.charAt(o);a==="'"?(n.length>0&&s.push({literal:i,val:n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&s.push({literal:!1,val:n}),n=a,r=a)}return n.length>0&&s.push({literal:i,val:n}),s}static macroTokenToFormatOpts(e){return ait[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTime(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTimeParts(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).formatToParts()}resolvedOptions(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return jn(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(d,h)=>this.loc.extract(e,d,h),o=d=>e.isOffsetFixed&&e.offset===0&&d.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,d.format):"",a=()=>n?rit(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(d,h)=>n?iit(e,d):s(h?{month:d}:{month:d,day:"numeric"},"month"),l=(d,h)=>n?nit(e,d):s(h?{weekday:d}:{weekday:d,month:"long",day:"numeric"},"weekday"),c=d=>{let h=t.macroTokenToFormatOpts(d);return h?this.formatWithSystemDefault(e,h):d},f=d=>n?sit(e,d):s({era:d},"era"),x=d=>{switch(d){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 a();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 u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("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 u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("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(d)}};return Nye(t.parseFormat(r),x)}formatDurationFromString(e,r){let n=u=>{switch(u[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=u=>l=>{let c=n(l);return c?this.num(u.get(c),l.length):l},s=t.parseFormat(r),o=s.reduce((u,{literal:l,val:c})=>l?u:u.concat(c),[]),a=e.shiftTo(...o.map(n).filter(u=>u));return Nye(s,i(a))}},au=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},Pp=class{get type(){throw new Kc}get name(){throw new Kc}get ianaName(){return this.name}get isUniversal(){throw new Kc}offsetName(e,r){throw new Kc}formatOffset(e,r){throw new Kc}offset(e){throw new Kc}equals(e){throw new Kc}get isValid(){throw new Kc}},YX=null,BM=class t extends Pp{static get instance(){return YX===null&&(YX=new t),YX}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EEe(e,r,n)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},wM={};function uit(t){return wM[t]||(wM[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"})),wM[t]}var lit={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function cit(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,s,o,a,u,l,c]=n;return[o,i,s,a,u,l,c]}function fit(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=lit[s];s==="era"?n[a]=o:kt(a)||(n[a]=parseInt(o,10))}return n}var OM={},$x=class t extends Pp{static create(e){return OM[e]||(OM[e]=new t(e)),OM[e]}static resetCache(){OM={},wM={}}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=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EEe(e,r,n,this.name)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=uit(this.name),[i,s,o,a,u,l,c]=n.formatToParts?fit(n,r):cit(n,r);a==="BC"&&(i=-Math.abs(i)+1);let x=yJ({year:i,month:s,day:o,hour:u===24?0:u,minute:l,second:c,millisecond:0}),d=+r,h=d%1e3;return d-=h>=0?h:1e3+h,(x-d)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},KX=null,lu=class t extends Pp{static get utcInstance(){return KX===null&&(KX=new t(0)),KX}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t($M(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${m5(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${m5(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return m5(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},qM=class extends Pp{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 Mp(t,e){if(kt(t)||t===null)return e;if(t instanceof Pp)return t;if(Gnt(t)){let r=t.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?lu.utcInstance:lu.parseSpecifier(r)||$x.create(t)}else return og(t)?lu.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new qM(t)}var Fye=()=>Date.now(),wye="system",Lye=null,Iye=null,Mye=null,Pye,yn=class{static get now(){return Fye}static set now(e){Fye=e}static set defaultZone(e){wye=e}static get defaultZone(){return Mp(wye,BM.instance)}static get defaultLocale(){return Lye}static set defaultLocale(e){Lye=e}static get defaultNumberingSystem(){return Iye}static set defaultNumberingSystem(e){Iye=e}static get defaultOutputCalendar(){return Mye}static set defaultOutputCalendar(e){Mye=e}static get throwOnInvalid(){return Pye}static set throwOnInvalid(e){Pye=e}static resetCaches(){Hn.resetCache(),$x.resetCache()}},kye={};function xit(t,e={}){let r=JSON.stringify([t,e]),n=kye[r];return n||(n=new Intl.ListFormat(t,e),kye[r]=n),n}var uJ={};function lJ(t,e={}){let r=JSON.stringify([t,e]),n=uJ[r];return n||(n=new Intl.DateTimeFormat(t,e),uJ[r]=n),n}var cJ={};function dit(t,e={}){let r=JSON.stringify([t,e]),n=cJ[r];return n||(n=new Intl.NumberFormat(t,e),cJ[r]=n),n}var fJ={};function hit(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=fJ[i];return s||(s=new Intl.RelativeTimeFormat(t,e),fJ[i]=s),s}var h5=null;function pit(){return h5||(h5=new Intl.DateTimeFormat().resolvedOptions().locale,h5)}function mit(t){let e=t.indexOf("-u-");if(e===-1)return[t];{let r,n=t.substring(0,e);try{r=lJ(t).resolvedOptions()}catch{r=lJ(n).resolvedOptions()}let{numberingSystem:i,calendar:s}=r;return[n,i,s]}}function git(t,e,r){return(r||e)&&(t+="-u",r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function yit(t){let e=[];for(let r=1;r<=12;r++){let n=En.utc(2016,r,1);e.push(t(n))}return e}function Eit(t){let e=[];for(let r=1;r<=7;r++){let n=En.utc(2016,11,13+r);e.push(t(n))}return e}function DM(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function Sit(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"}var xJ=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:s,...o}=n;if(!r||Object.keys(o).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=dit(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):gJ(e,3);return jn(r,this.padTo)}}},dJ=class{constructor(e,r,n){this.opts=n;let i;if(e.zone.isUniversal){let o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&$x.create(a).valid?(i=a,this.dt=e):(i="UTC",n.timeZoneName?this.dt=e:this.dt=e.offset===0?e:En.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);let s={...this.opts};i&&(s.timeZone=i),this.dtf=lJ(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},hJ=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&yEe()&&(this.rtf=hit(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):oit(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},Hn=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,r,n,i=!1){let s=e||yn.defaultLocale,o=s||(i?"en-US":pit()),a=r||yn.defaultNumberingSystem,u=n||yn.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){h5=null,uJ={},cJ={},fJ={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=mit(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=git(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=Sit(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.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,r=!1,n=!0){return DM(this,e,n,_Ee,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=yit(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return DM(this,e,n,CEe,()=>{let i=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=r?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=Eit(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return DM(this,void 0,e,()=>REe,()=>{if(!this.meridiemCache){let r={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[En.utc(2016,11,13,9),En.utc(2016,11,13,19)].map(n=>this.extract(n,r,"dayperiod"))}return this.meridiemCache})}eras(e,r=!0){return DM(this,e,r,OEe,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[En.utc(-40,1,1),En.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),s=i.formatToParts(),o=s.find(a=>a.type.toLowerCase()===n);return o?o.value:null}numberFormatter(e={}){return new xJ(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new dJ(e,this.intl,r)}relFormatter(e={}){return new hJ(this.intl,this.isEnglish(),e)}listFormatter(e={}){return xit(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 $A(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function jA(...t){return e=>t.reduce(([r,n,i],s)=>{let[o,a,u]=s(e,i);return[{...r,...o},a||n,u]},[{},null,1]).slice(0,2)}function HA(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function DEe(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=Ip(e[r+i]);return[n,null,r+i]}}var NEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Ait=`(?:${NEe.source}?(?:\\[(${AEe.source})\\])?)?`,EJ=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,FEe=RegExp(`${EJ.source}${Ait}`),SJ=RegExp(`(?:T${FEe.source})?`),vit=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,_it=/(\d{4})-?W(\d\d)(?:-?(\d))?/,bit=/(\d{4})-?(\d{3})/,Tit=DEe("weekYear","weekNumber","weekDay"),Cit=DEe("year","ordinal"),Rit=/(\d{4})-(\d\d)-(\d\d)/,wEe=RegExp(`${EJ.source} ?(?:${NEe.source}|(${AEe.source}))?`),Oit=RegExp(`(?: ${wEe.source})?`);function qA(t,e,r){let n=t[e];return kt(n)?r:Ip(n)}function Dit(t,e){return[{year:qA(t,e),month:qA(t,e+1,1),day:qA(t,e+2,1)},null,e+3]}function zA(t,e){return[{hours:qA(t,e,0),minutes:qA(t,e+1,0),seconds:qA(t,e+2,0),milliseconds:mJ(t[e+3])},null,e+4]}function y5(t,e){let r=!t[e]&&!t[e+1],n=$M(t[e+1],t[e+2]),i=r?null:lu.instance(n);return[{},i,e+3]}function E5(t,e){let r=t[e]?$x.create(t[e]):null;return[{},r,e+1]}var Nit=RegExp(`^T?${EJ.source}$`),Fit=/^-?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 wit(t){let[e,r,n,i,s,o,a,u,l]=t,c=e[0]==="-",f=u&&u[0]==="-",x=(d,h=!1)=>d!==void 0&&(h||d&&c)?-d:d;return[{years:x(tg(r)),months:x(tg(n)),weeks:x(tg(i)),days:x(tg(s)),hours:x(tg(o)),minutes:x(tg(a)),seconds:x(tg(u),u==="-0"),milliseconds:x(mJ(l),f)}]}var Lit={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 AJ(t,e,r,n,i,s,o){let a={year:e.length===2?aJ(Ip(e)):Ip(e),month:vEe.indexOf(r)+1,day:Ip(n),hour:Ip(i),minute:Ip(s)};return o&&(a.second=Ip(o)),t&&(a.weekday=t.length>3?bEe.indexOf(t)+1:TEe.indexOf(t)+1),a}var Iit=/^(?:(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 Mit(t){let[,e,r,n,i,s,o,a,u,l,c,f]=t,x=AJ(e,i,n,r,s,o,a),d;return u?d=Lit[u]:l?d=0:d=$M(c,f),[x,new lu(d)]}function Pit(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var kit=/^(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$/,Bit=/^(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$/,qit=/^(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 Bye(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,i,n,r,s,o,a),lu.utcInstance]}function Uit(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,a,r,n,i,s,o),lu.utcInstance]}var $it=$A(vit,SJ),jit=$A(_it,SJ),Hit=$A(bit,SJ),zit=$A(FEe),LEe=jA(Dit,zA,y5,E5),Git=jA(Tit,zA,y5,E5),Qit=jA(Cit,zA,y5,E5),Vit=jA(zA,y5,E5);function Wit(t){return HA(t,[$it,LEe],[jit,Git],[Hit,Qit],[zit,Vit])}function Yit(t){return HA(Pit(t),[Iit,Mit])}function Kit(t){return HA(t,[kit,Bye],[Bit,Bye],[qit,Uit])}function Xit(t){return HA(t,[Fit,wit])}var Jit=jA(zA);function Zit(t){return HA(t,[Nit,Jit])}var est=$A(Rit,Oit),tst=$A(wEe),rst=jA(zA,y5,E5);function nst(t){return HA(t,[est,LEe],[tst,rst])}var ist="Invalid Duration",IEe={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}},sst={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},...IEe},rl=146097/400,BA=146097/4800,ost={years:{quarters:4,months:12,weeks:rl/7,days:rl,hours:rl*24,minutes:rl*24*60,seconds:rl*24*60*60,milliseconds:rl*24*60*60*1e3},quarters:{months:3,weeks:rl/28,days:rl/4,hours:rl*24/4,minutes:rl*24*60/4,seconds:rl*24*60*60/4,milliseconds:rl*24*60*60*1e3/4},months:{weeks:BA/7,days:BA,hours:BA*24,minutes:BA*24*60,seconds:BA*24*60*60,milliseconds:BA*24*60*60*1e3},...IEe},ng=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ast=ng.slice(0).reverse();function rg(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new ci(n)}function ust(t){return t<0?Math.floor(t):Math.ceil(t)}function MEe(t,e,r,n,i){let s=t[i][r],o=e[r]/s,a=Math.sign(o)===Math.sign(n[i]),u=!a&&n[i]!==0&&Math.abs(o)<=1?ust(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function lst(t,e){ast.reduce((r,n)=>kt(e[n])?r:(r&&MEe(t,e,r,e,n),n),null)}var ci=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||Hn.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r?ost:sst,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new fa(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:kM(e,t.normalizeUnit),loc:Hn.fromObject(r),conversionAccuracy:r.conversionAccuracy})}static fromDurationLike(e){if(og(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new fa(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Xit(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=Zit(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new fa("need to specify a reason the Duration is invalid");let n=e instanceof au?e:new au(e,r);if(yn.throwOnInvalid)throw new sJ(n);return new t({invalid:n})}static normalizeUnit(e){let r={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(!r)throw new IM(e);return r}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,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?a0.create(this.loc,n).formatDurationFromString(this,e):ist}toHuman(e={}){let r=ng.map(n=>{let i=this.values[n];return kt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}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+=gJ(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();if(r<0||r>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};let n=this.shiftTo("hours","minutes","seconds","milliseconds"),i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||n.seconds!==0||n.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||n.milliseconds!==0)&&(i+=".SSS"));let s=n.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;let r=t.fromDurationLike(e),n={};for(let i of ng)(UA(r.values,i)||UA(this.values,i))&&(n[i]=r.get(i)+this.get(i));return rg(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=SEe(e(this.values[n],n));return rg(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...kM(e,t.normalizeUnit)};return rg(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r}),s={loc:i};return n&&(s.conversionAccuracy=n),rg(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return lst(this.matrix,e),rg(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>t.normalizeUnit(o));let r={},n={},i=this.toObject(),s;for(let o of ng)if(e.indexOf(o)>=0){s=o;let a=0;for(let l in n)a+=this.matrix[l][o]*n[l],n[l]=0;og(i[o])&&(a+=i[o]);let u=Math.trunc(a);r[o]=u,n[o]=(a*1e3-u*1e3)/1e3;for(let l in i)ng.indexOf(l)>ng.indexOf(o)&&MEe(this.matrix,i,l,r,o)}else og(i[o])&&(n[o]=i[o]);for(let o in n)n[o]!==0&&(r[s]+=o===s?n[o]:n[o]/this.matrix[s][o]);return rg(this,{values:r},!0).normalize()}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return rg(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 r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of ng)if(!r(this.values[n],e.values[n]))return!1;return!0}},c5="Invalid Interval";function cst(t,e){return!t||!t.isValid?ag.invalid("missing or invalid start"):!e||!e.isValid?ag.invalid("missing or invalid end"):e<t?ag.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}var ag=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new fa("need to specify a reason the Interval is invalid");let n=e instanceof au?e:new au(e,r);if(yn.throwOnInvalid)throw new iJ(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=d5(e),i=d5(r),s=cst(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let s,o;try{s=En.fromISO(n,r),o=s.isValid}catch{o=!1}let a,u;try{a=En.fromISO(i,r),u=a.isValid}catch{u=!1}if(o&&u)return t.fromDateTimes(s,a);if(o){let l=ci.fromISO(i,r);if(l.isValid)return t.after(s,l)}else if(u){let l=ci.fromISO(n,r);if(l.isValid)return t.before(a,l)}}return t.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;let r=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(r,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:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(d5).filter(o=>this.contains(o)).sort(),n=[],{s:i}=this,s=0;for(;i<this.e;){let o=r[s]||this.e,a=+o>+this.e?this.e:o;n.push(t.fromDateTimes(i,a)),i=a,s+=1}return n}splitBy(e){let r=ci.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,s,o=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(u=>u*i));s=+a>+this.e?this.e:a,o.push(t.fromDateTimes(n,s)),n=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;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=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 n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],s=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),o=Array.prototype.concat(...s),a=o.sort((u,l)=>u.time-l.time);for(let u of a)n+=u.type==="s"?1:-1,n===1?r=u.time:(r&&+r!=+u.time&&i.push(t.fromDateTimes(r,u.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:c5}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:c5}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:c5}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:c5}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:c5}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):ci.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},sg=class{static hasDST(e=yn.defaultZone){let r=En.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return $x.isValidZone(e)}static normalizeZone(e){return Mp(e,yn.defaultZone)}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Hn.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return Hn.create(r,null,"gregory").eras(e)}static features(){return{relative:yEe()}}};function qye(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(ci.fromMillis(n).as("days"))}function fst(t,e,r){let n=[["years",(a,u)=>u.year-a.year],["quarters",(a,u)=>u.quarter-a.quarter],["months",(a,u)=>u.month-a.month+(u.year-a.year)*12],["weeks",(a,u)=>{let l=qye(a,u);return(l-l%7)/7}],["days",qye]],i={},s,o;for(let[a,u]of n)if(r.indexOf(a)>=0){s=a;let l=u(t,e);o=t.plus({[a]:l}),o>e?(t=t.plus({[a]:l-1}),l-=1):t=o,i[a]=l}return[t,i,o,s]}function xst(t,e,r,n){let[i,s,o,a]=fst(t,e,r),u=e-i,l=r.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[a]:1})),o!==i&&(s[a]=(s[a]||0)+u/(o-i)));let c=ci.fromObject(s,n);return l.length>0?ci.fromMillis(u,n).shiftTo(...l).plus(c):c}var vJ={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Uye={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]},dst=vJ.hanidec.replace(/[\[|\]]/g,"").split("");function hst(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(vJ.hanidec)!==-1)e+=dst.indexOf(t[r]);else for(let i in Uye){let[s,o]=Uye[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function s0({numberingSystem:t},e=""){return new RegExp(`${vJ[t||"latn"]}${e}`)}var pst="missing Intl.DateTimeFormat.formatToParts support";function Yt(t,e=r=>r){return{regex:t,deser:([r])=>e(hst(r))}}var mst="\xA0",PEe=`[ ${mst}]`,kEe=new RegExp(PEe,"g");function gst(t){return t.replace(/\./g,"\\.?").replace(kEe,PEe)}function $ye(t){return t.replace(/\./g,"").replace(kEe," ").toLowerCase()}function o0(t,e){return t===null?null:{regex:RegExp(t.map(gst).join("|")),deser:([r])=>t.findIndex(n=>$ye(r)===$ye(n))+e}}function jye(t,e){return{regex:t,deser:([,r,n])=>$M(r,n),groups:e}}function XX(t){return{regex:t,deser:([e])=>e}}function yst(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Est(t,e){let r=s0(e),n=s0(e,"{2}"),i=s0(e,"{3}"),s=s0(e,"{4}"),o=s0(e,"{6}"),a=s0(e,"{1,2}"),u=s0(e,"{1,3}"),l=s0(e,"{1,6}"),c=s0(e,"{1,9}"),f=s0(e,"{2,4}"),x=s0(e,"{4,6}"),d=m=>({regex:RegExp(yst(m.val)),deser:([g])=>g,literal:!0}),p=(m=>{if(t.literal)return d(m);switch(m.val){case"G":return o0(e.eras("short",!1),0);case"GG":return o0(e.eras("long",!1),0);case"y":return Yt(l);case"yy":return Yt(f,aJ);case"yyyy":return Yt(s);case"yyyyy":return Yt(x);case"yyyyyy":return Yt(o);case"M":return Yt(a);case"MM":return Yt(n);case"MMM":return o0(e.months("short",!0,!1),1);case"MMMM":return o0(e.months("long",!0,!1),1);case"L":return Yt(a);case"LL":return Yt(n);case"LLL":return o0(e.months("short",!1,!1),1);case"LLLL":return o0(e.months("long",!1,!1),1);case"d":return Yt(a);case"dd":return Yt(n);case"o":return Yt(u);case"ooo":return Yt(i);case"HH":return Yt(n);case"H":return Yt(a);case"hh":return Yt(n);case"h":return Yt(a);case"mm":return Yt(n);case"m":return Yt(a);case"q":return Yt(a);case"qq":return Yt(n);case"s":return Yt(a);case"ss":return Yt(n);case"S":return Yt(u);case"SSS":return Yt(i);case"u":return XX(c);case"uu":return XX(a);case"uuu":return Yt(r);case"a":return o0(e.meridiems(),0);case"kkkk":return Yt(s);case"kk":return Yt(f,aJ);case"W":return Yt(a);case"WW":return Yt(n);case"E":case"c":return Yt(r);case"EEE":return o0(e.weekdays("short",!1,!1),1);case"EEEE":return o0(e.weekdays("long",!1,!1),1);case"ccc":return o0(e.weekdays("short",!0,!1),1);case"cccc":return o0(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return jye(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return jye(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return XX(/[a-z_+-/]{1,256}?/i);default:return d(m)}})(t)||{invalidReason:pst};return p.token=t,p}var Sst={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 Ast(t,e,r){let{type:n,value:i}=t;if(n==="literal")return{literal:!0,val:i};let s=r[n],o=Sst[n];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function vst(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function _st(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(UA(r,o)){let a=r[o],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(s,s+u))),s+=u}return[n,i]}else return[n,{}]}function bst(t){let 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}},r=null,n;return kt(t.z)||(r=$x.create(t.z)),kt(t.Z)||(r||(r=new lu(t.Z)),n=t.Z),kt(t.q)||(t.M=(t.q-1)*3+1),kt(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),kt(t.u)||(t.S=mJ(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var JX=null;function Tst(){return JX||(JX=En.fromMillis(1555555555555)),JX}function Cst(t,e){if(t.literal)return t;let r=a0.macroTokenToFormatOpts(t.val);if(!r)return t;let s=a0.create(e,r).formatDateTimeParts(Tst()).map(o=>Ast(o,e,r));return s.includes(void 0)?t:s}function Rst(t,e){return Array.prototype.concat(...t.map(r=>Cst(r,e)))}function BEe(t,e,r){let n=Rst(a0.parseFormat(r),t),i=n.map(o=>Est(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=vst(i),u=RegExp(o,"i"),[l,c]=_st(e,u,a),[f,x,d]=c?bst(c):[null,null,void 0];if(UA(c,"a")&&UA(c,"H"))throw new ig("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:u,rawMatches:l,matches:c,result:f,zone:x,specificOffset:d}}}function Ost(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=BEe(t,e,r);return[n,i,s,o]}var qEe=[0,31,59,90,120,151,181,212,243,273,304,334],UEe=[0,31,60,91,121,152,182,213,244,274,305,335];function nl(t,e){return new au("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function $Ee(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function jEe(t,e,r){return r+(g5(t)?UEe:qEe)[e-1]}function HEe(t,e){let r=g5(t)?UEe:qEe,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function pJ(t){let{year:e,month:r,day:n}=t,i=jEe(e,r,n),s=$Ee(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=PM(a)):o>PM(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...jM(t)}}function Hye(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=$Ee(e,1,4),s=p5(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=p5(a)):o>s?(a=e+1,o-=p5(e)):a=e;let{month:u,day:l}=HEe(a,o);return{year:a,month:u,day:l,...jM(t)}}function ZX(t){let{year:e,month:r,day:n}=t,i=jEe(e,r,n);return{year:e,ordinal:i,...jM(t)}}function zye(t){let{year:e,ordinal:r}=t,{month:n,day:i}=HEe(e,r);return{year:e,month:n,day:i,...jM(t)}}function Dst(t){let e=UM(t.weekYear),r=qx(t.weekNumber,1,PM(t.weekYear)),n=qx(t.weekday,1,7);return e?r?n?!1:nl("weekday",t.weekday):nl("week",t.week):nl("weekYear",t.weekYear)}function Nst(t){let e=UM(t.year),r=qx(t.ordinal,1,p5(t.year));return e?r?!1:nl("ordinal",t.ordinal):nl("year",t.year)}function zEe(t){let e=UM(t.year),r=qx(t.month,1,12),n=qx(t.day,1,MM(t.year,t.month));return e?r?n?!1:nl("day",t.day):nl("month",t.month):nl("year",t.year)}function GEe(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=qx(e,0,23)||e===24&&r===0&&n===0&&i===0,o=qx(r,0,59),a=qx(n,0,59),u=qx(i,0,999);return s?o?a?u?!1:nl("millisecond",i):nl("second",n):nl("minute",r):nl("hour",e)}var eJ="Invalid DateTime",Gye=864e13;function NM(t){return new au("unsupported zone",`the zone "${t.name}" is not supported`)}function tJ(t){return t.weekData===null&&(t.weekData=pJ(t.c)),t.weekData}function f5(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new En({...r,...e,old:r})}function QEe(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let s=r.offset(n);return i===s?[n,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function Qye(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function LM(t,e,r){return QEe(yJ(t),e,r)}function Vye(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:n,month:i,day:Math.min(t.c.day,MM(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ci.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"),a=yJ(s),[u,l]=QEe(a,r,t.zone);return o!==0&&(u+=o,l=t.zone.offset(u)),{ts:u,o:l}}function x5(t,e,r,n,i,s){let{setZone:o,zone:a}=r;if(t&&Object.keys(t).length!==0){let u=e||a,l=En.fromObject(t,{...r,zone:u,specificOffset:s});return o?l:l.setZone(a)}else return En.invalid(new au("unparsable",`the input "${i}" can't be parsed as ${n}`))}function FM(t,e,r=!0){return t.isValid?a0.create(Hn.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function rJ(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=jn(t.c.year,r?6:4),e?(n+="-",n+=jn(t.c.month),n+="-",n+=jn(t.c.day)):(n+=jn(t.c.month),n+=jn(t.c.day)),n}function Wye(t,e,r,n,i,s){let o=jn(t.c.hour);return e?(o+=":",o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=":")):o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=jn(t.c.second),(t.c.millisecond!==0||!n)&&(o+=".",o+=jn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=jn(Math.trunc(-t.o/60)),o+=":",o+=jn(Math.trunc(-t.o%60))):(o+="+",o+=jn(Math.trunc(t.o/60)),o+=":",o+=jn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}var VEe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Fst={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},wst={ordinal:1,hour:0,minute:0,second:0,millisecond:0},WEe=["year","month","day","hour","minute","second","millisecond"],Lst=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Ist=["year","ordinal","hour","minute","second","millisecond"];function Yye(t){let 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 IM(t);return e}function Kye(t,e){let r=Mp(e.zone,yn.defaultZone),n=Hn.fromObject(e),i=yn.now(),s,o;if(kt(t.year))s=i;else{for(let l of WEe)kt(t[l])&&(t[l]=VEe[l]);let a=zEe(t)||GEe(t);if(a)return En.invalid(a);let u=r.offset(i);[s,o]=LM(t,u,r)}return new En({ts:s,zone:r,loc:n,o})}function Xye(t,e,r){let n=kt(r.round)?!0:r.round,i=(o,a)=>(o=gJ(o,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(o,a)),s=o=>r.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(r.unit)return i(s(r.unit),r.unit);for(let o of r.units){let a=s(o);if(Math.abs(a)>=1)return i(a,o)}return i(t>e?-0:0,r.units[r.units.length-1])}function Jye(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var En=class t{constructor(e){let r=e.zone||yn.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new au("invalid input"):null)||(r.isValid?null:NM(r));this.ts=kt(e.ts)?yn.now():e.ts;let i=null,s=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,s]=[e.old.c,e.old.o];else{let a=r.offset(this.ts);i=Qye(this.ts,a),n=Number.isNaN(i.year)?new au("invalid input"):null,i=n?null:i,s=n?null:a}this._zone=r,this.loc=e.loc||Hn.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=Jye(arguments),[n,i,s,o,a,u,l]=r;return Kye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,r]=Jye(arguments),[n,i,s,o,a,u,l]=r;return e.zone=lu.utcInstance,Kye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,r={}){let n=Qnt(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Mp(r.zone,yn.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:Hn.fromObject(r)}):t.invalid(NM(i))}static fromMillis(e,r={}){if(og(e))return e<-Gye||e>Gye?t.invalid("Timestamp out of range"):new t({ts:e,zone:Mp(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new fa(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(og(e))return new t({ts:e*1e3,zone:Mp(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new fa("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Mp(r.zone,yn.defaultZone);if(!n.isValid)return t.invalid(NM(n));let i=yn.now(),s=kt(r.specificOffset)?n.offset(i):r.specificOffset,o=kM(e,Yye),a=!kt(o.ordinal),u=!kt(o.year),l=!kt(o.month)||!kt(o.day),c=u||l,f=o.weekYear||o.weekNumber,x=Hn.fromObject(r);if((c||a)&&f)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new ig("Can't mix ordinal dates with month/day");let d=f||o.weekday&&!c,h,p,m=Qye(i,s);d?(h=Lst,p=Fst,m=pJ(m)):a?(h=Ist,p=wst,m=ZX(m)):(h=WEe,p=VEe);let g=!1;for(let R of h){let D=o[R];kt(D)?g?o[R]=p[R]:o[R]=m[R]:g=!0}let y=d?Dst(o):a?Nst(o):zEe(o),S=y||GEe(o);if(S)return t.invalid(S);let A=d?Hye(o):a?zye(o):o,[T,b]=LM(A,s,n),_=new t({ts:T,zone:n,o:b,loc:x});return o.weekday&&c&&e.weekday!==_.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,r={}){let[n,i]=Wit(e);return x5(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Yit(e);return x5(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Kit(e);return x5(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(kt(e)||kt(r))throw new fa("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[a,u,l,c]=Ost(o,e,r);return c?t.invalid(c):x5(a,u,n,`format ${r}`,e,l)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=nst(e);return x5(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new fa("need to specify a reason the DateTime is invalid");let n=e instanceof au?e:new au(e,r);if(yn.throwOnInvalid)throw new nJ(n);return new t({invalid:n})}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?tJ(this).weekYear:NaN}get weekNumber(){return this.isValid?tJ(this).weekNumber:NaN}get weekday(){return this.isValid?tJ(this).weekday:NaN}get ordinal(){return this.isValid?ZX(this.c).ordinal:NaN}get monthShort(){return this.isValid?sg.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?sg.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?sg.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?sg.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 g5(this.year)}get daysInMonth(){return MM(this.year,this.month)}get daysInYear(){return this.isValid?p5(this.year):NaN}get weeksInWeekYear(){return this.isValid?PM(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=a0.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(lu.instance(e),r)}toLocal(){return this.setZone(yn.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Mp(e,yn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let s=e.offset(this.ts),o=this.toObject();[i]=LM(o,s,e)}return f5(this,{ts:i,zone:e})}else return t.invalid(NM(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return f5(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=kM(e,Yye),n=!kt(r.weekYear)||!kt(r.weekNumber)||!kt(r.weekday),i=!kt(r.ordinal),s=!kt(r.year),o=!kt(r.month)||!kt(r.day),a=s||o,u=r.weekYear||r.weekNumber;if((a||i)&&u)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new ig("Can't mix ordinal dates with month/day");let l;n?l=Hye({...pJ(this.c),...r}):kt(r.ordinal)?(l={...this.toObject(),...r},kt(r.day)&&(l.day=Math.min(MM(l.year,l.month),l.day))):l=zye({...ZX(this.c),...r});let[c,f]=LM(l,this.o,this.zone);return f5(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e);return f5(this,Vye(this,r))}minus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e).negate();return f5(this,Vye(this,r))}startOf(e){if(!this.isValid)return this;let r={},n=ci.normalizeUnit(e);switch(n){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break}if(n==="weeks"&&(r.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,r={}){return this.isValid?a0.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):eJ}toLocaleString(e=oJ,r={}){return this.isValid?a0.create(this.loc.clone(r),e).formatDateTime(this):eJ}toLocaleParts(e={}){return this.isValid?a0.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;let o=e==="extended",a=rJ(this,o);return a+="T",a+=Wye(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?rJ(this,e==="extended"):null}toISOWeekDate(){return FM(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+Wye(this,o==="extended",r,e,n,s):null}toRFC2822(){return FM(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return FM(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?rJ(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),FM(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():eJ}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{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return ci.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},s=Vnt(r).map(ci.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=xst(a,u,s,i);return o?l.negate():l}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?ag.fromDateTimes(this,e):this}hasSame(e,r){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(r)<=n&&n<=i.endOf(r)}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;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),Xye(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?Xye(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new fa("min requires all arguments be DateTimes");return Dye(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new fa("max requires all arguments be DateTimes");return Dye(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return BEe(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return oJ}static get DATE_MED(){return Zye}static get DATE_MED_WITH_WEEKDAY(){return Hnt}static get DATE_FULL(){return eEe}static get DATE_HUGE(){return tEe}static get TIME_SIMPLE(){return rEe}static get TIME_WITH_SECONDS(){return nEe}static get TIME_WITH_SHORT_OFFSET(){return iEe}static get TIME_WITH_LONG_OFFSET(){return sEe}static get TIME_24_SIMPLE(){return oEe}static get TIME_24_WITH_SECONDS(){return aEe}static get TIME_24_WITH_SHORT_OFFSET(){return uEe}static get TIME_24_WITH_LONG_OFFSET(){return lEe}static get DATETIME_SHORT(){return cEe}static get DATETIME_SHORT_WITH_SECONDS(){return fEe}static get DATETIME_MED(){return xEe}static get DATETIME_MED_WITH_SECONDS(){return dEe}static get DATETIME_MED_WITH_WEEKDAY(){return znt}static get DATETIME_FULL(){return hEe}static get DATETIME_FULL_WITH_SECONDS(){return pEe}static get DATETIME_HUGE(){return mEe}static get DATETIME_HUGE_WITH_SECONDS(){return gEe}};function d5(t){if(En.isDateTime(t))return t;if(t&&t.valueOf&&og(t.valueOf()))return En.fromJSDate(t);if(t&&typeof t=="object")return En.fromObject(t);throw new fa(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Mst="2.5.2";cu.DateTime=En;cu.Duration=ci;cu.FixedOffsetZone=lu;cu.IANAZone=$x;cu.Info=sg;cu.Interval=ag;cu.InvalidZone=qM;cu.Settings=yn;cu.SystemZone=BM;cu.VERSION=Mst;cu.Zone=Pp});var eSe=v(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.LiteralYear=ki.LiteralQuarter=ki.LiteralMonth=ki.LiteralWeek=ki.LiteralDay=ki.LiteralHour=ki.LiteralTimestamp=ki.TimeFormatError=void 0;var kp=_J(),Pst=Ke(),kst=IA(),YEe=CI(),bJ=ir(),TJ=class extends Error{};ki.TimeFormatError=TJ;function lg(t,e){let r=t.slice(1);if(e){let n=r.match(/\[[^\]]+]$/);if(n)return{tzSpec:n[0].slice(1,-1),text:r.slice(0,-n[0].length)}}return{text:r}}var KEe="yyyy",XEe=`${KEe}-LL`,il=`${XEe}-dd`,JEe=`${il} HH`,ZEe=`${JEe}:mm`,CJ=`${ZEe}:ss`,HM=class extends bJ.ExpressionDef{constructor(e,r,n){super(),this.units=r,this.timeType=n,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){let n={type:"dialect",function:"timeLiteral",literal:e,literalType:r};return this.timeZone&&(n.timezone=this.timeZone),n}makeValue(e,r){let n=this.makeLiteral(e,r),i="scalar",s=[n];return this.units?{dataType:r,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:r,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}},RJ=class t extends HM{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r,n=lg(e,!0);e=n.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),n.text=e);let i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=kp.DateTime.fromFormat(e,CJ);if(s.isValid)return new t(n,r);if(s=kp.DateTime.fromFormat(e,ZEe),s.isValid){n.text=n.text+":00",r="minute";let o=s.plus({minute:1}).toFormat(CJ);return new S5(n,r,"timestamp",o)}}};ki.LiteralTimestamp=RJ;var S5=class extends HM{constructor(e,r,n,i){super(e,r,n),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,r,n){let i=this.getExpression(e),s=this.getNext();if(s){let o=n.getExpression(e);if(o.dataType==="timestamp"){let a=(0,bJ.getMorphicValue)(i,"timestamp"),u=(0,bJ.getMorphicValue)(s,"timestamp");if(a&&u)i=a,s=u;else return super.apply(e,r,n)}if((0,Pst.isTimeFieldType)(o.dataType)){let a=o.dataType;return new kst.Range(new YEe.ExprTime(a,i.value),new YEe.ExprTime(a,s.value)).apply(e,r,n)}}return super.apply(e,r,n)}},OJ=class t extends S5{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,JEe);if(i.isValid)return r.text=r.text+":00:00",n=i.plus({hour:1}).toFormat(CJ),new t(r,n)}};ki.LiteralHour=OJ;var ug=class extends S5{constructor(e,r,n){super(e,r,"date",n)}getExpression(e){let r=this.makeValue(this.literalPart,"date"),n=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...r,morphic:{timestamp:n},evalSpace:"literal"}}getNext(){let e=this.makeValue(this.nextLit,"date"),r=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:r}}}},DJ=class t extends ug{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,il);if(i.isValid)return n=i.plus({day:1}).toFormat(il),new t(r,n)}};ki.LiteralDay=DJ;var NJ=class t extends ug{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.slice(0,10),s=kp.DateTime.fromFormat(i,il);if(s.isValid&&s.weekday===7){let a=s.plus({days:7});return r.text=s.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralWeek=NJ;var FJ=class t extends ug{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,XEe);if(i.isValid){let s=i.plus({months:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralMonth=FJ;var wJ=class t extends ug{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.match(/(^\d{4})-[qQ](\d)$/);if(i){let s=Number.parseInt(i[2])-1,o=kp.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));let a=o.plus({quarter:1});return r.text=o.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralQuarter=wJ;var LJ=class t extends ug{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,KEe);if(i.isValid){let s=i.plus({year:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralYear=LJ});var tSe=v(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.PartialCompare=void 0;var Bst=js(),qst=ir(),IJ=class extends qst.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,n){return this.right.apply(e,this.op,n)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,Bst.errorFor)("no value for partial compare")}};zM.PartialCompare=IJ});var nSe=v(GA=>{"use strict";Object.defineProperty(GA,"__esModule",{value:!0});GA.PickWhen=GA.Pick=void 0;var Xc=Ke(),Bp=js(),l0=pn(),Ust=ir(),$st=mt(),rSe=hs();function GM(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}var MJ=class extends Ust.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(let r of this.choices){if(r.pick===void 0)return;let n=r.when.requestExpression(e);if(n===void 0||n.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,r,n){let i=["CASE"],s,o="scalar",a="constant";for(let c of this.choices){let f=c.when.apply(e,"=",n),x=c.pick?c.pick.getExpression(e):n.getExpression(e);if(o=(0,Xc.maxExpressionType)(o,(0,Xc.maxExpressionType)(f.expressionType,x.expressionType)),a=(0,Xc.mergeEvalSpaces)(a,f.evalSpace,x.evalSpace),s&&!l0.FT.typeEq(s,x,!0)){let d=l0.FT.inspect(x);return this.log(`pick type '${d}', expected '${s.dataType}'`),(0,Bp.errorFor)("pick when type")}s=GM(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}let l=(this.elsePick||n).getExpression(e);if(s=GM(s,l),!l0.FT.typeEq(s,l,!0)){let c=this.elsePick?"else":"pick default";return this.log(`${c} type '${l0.FT.inspect(l)}', expected '${s.dataType}'`),(0,Bp.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Xc.maxExpressionType)(o,l.expressionType),evalSpace:(0,Xc.mergeEvalSpaces)(a,l.evalSpace),value:(0,rSe.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,Bp.errorFor)("no value for partial pick");let r=[];for(let u of this.choices){if(u.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,Bp.errorFor)("no value for partial pick");if(u.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,Bp.errorFor)("partial when");r.push({pick:u.pick.getExpression(e),when:u.when.getExpression(e)})}let n,i=["CASE"],s="scalar",o="constant";for(let u of r){if(!l0.FT.typeEq(u.when,l0.FT.boolT))return this.log(`when expression must be boolean, not '${l0.FT.inspect(u.when)}`),(0,Bp.errorFor)("pick when type");if(n&&!l0.FT.typeEq(n,u.pick,!0)){let l=l0.FT.inspect(u.pick);return this.log(`pick type '${l}', expected '${n.dataType}'`),(0,Bp.errorFor)("pick value type")}n=GM(n,u.pick),s=(0,Xc.maxExpressionType)(s,(0,Xc.maxExpressionType)(u.pick.expressionType,u.when.expressionType)),o=(0,Xc.mergeEvalSpaces)(o,u.pick.evalSpace,u.when.evalSpace),i.push(" WHEN ",...u.when.value," THEN ",...u.pick.value)}let a=this.elsePick.getExpression(e);return s=(0,Xc.maxExpressionType)(s,a.expressionType),o=(0,Xc.mergeEvalSpaces)(o,a.evalSpace),n=GM(n,a),l0.FT.typeEq(n,a,!0)?(i.push(" ELSE ",...a.value," END"),{dataType:n.dataType,expressionType:s,value:(0,rSe.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${l0.FT.inspect(a)}', expected '${n.dataType}'`),(0,Bp.errorFor)("pick value type mismatch"))}};GA.Pick=MJ;var PJ=class extends $st.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="pickWhen",this.has({pick:e})}};GA.PickWhen=PJ});var iSe=v(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.Timeframe=void 0;var jst=Ke(),Hst=mt(),kJ=class extends Hst.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,jst.isTimestampUnit)(r)?r:"second"}};QM.Timeframe=kJ});var oSe=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.TopBy=void 0;var zst=Ke(),sSe=ir(),Gst=mt(),Qst=hs(),BJ=class extends Gst.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof sSe.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof sSe.ExpressionDef){let r=this.by.getExpression(e);return(0,zst.expressionIsAggregate)(r.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,Qst.compressExpr)(r.value)}}return{by:"name",name:this.by}}};VM.TopBy=BJ});var aSe=v(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.ImportStatement=qp.ImportSelect=qp.ImportSourceName=void 0;var jJ=mt(),qJ=class extends jJ.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}};qp.ImportSourceName=qJ;var UJ=class extends jJ.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}};qp.ImportSelect=UJ;var $J=class extends jJ.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.log("Invalid URI in import statement")}}needs(){let e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){let n=e.childRequest(this.fullURL);if(n)return n}}execute(e){let r=this.translator();if(!r)this.log("Cannot import without translation context");else if(this.fullURL){let n=r.root.importZone.getEntry(this.fullURL);if(n.status==="present"){let i=r.getChildExports(this.fullURL);if(this.notEmpty())for(let s of this.list){let o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){let a={...i[o.text]};s.from&&(a.as=s.text),e.setEntry(s.text,{entry:a,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(let[s,o]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else n.status==="error"?this.log(`import failed: '${n.message}'`):this.log(`import failed with status: '${n.status}'`)}}};qp.ImportStatement=$J});var zJ=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.ExtendBlock=void 0;var Vst=mt(),Wst=Ii(),HJ=class extends Vst.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Wst.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)for(let n of r.list)e.inputFS.extendSource(n)}};WM.ExtendBlock=HJ});var uSe=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.AnonymousQuery=void 0;var Yst=mt(),Kst=Vc(),GJ=class extends Yst.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Kst.extendNoteMethod,this.has({queryExpr:e})}execute(e){let r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("Cannot run this object as a query");return}let n={...r.query()},i=this.note||{};n.annotation&&(i.inherits=n.annotation),(i.notes||i.blockNotes||i.inherits)&&(n.annotation=i),e.queryList.push(n)}};YM.AnonymousQuery=GJ});var QA=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.View=void 0;var Xst=mt(),QJ=class extends Xst.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}};KM.View=QJ});var lSe=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.ViewArrow=void 0;var Jst=tl(),Zst=QA(),VJ=class extends Zst.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){let r=this.base.pipelineComp(e),n=new Jst.StaticSpace(r.outputStruct),i=this.operation.pipelineComp(n);return{pipeline:[...r.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,r,n){return this.log("A multi-segment view cannot be used as a refinement"),[]}};XM.ViewArrow=VJ});var KJ=v(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.refine=void 0;var WJ=lc(),YJ=AL();function eot(t,e,r){var n,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;let s={...e[0]},o=r;if((0,WJ.isRawSegment)(s))t.log("Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.log(`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&((o.orderBy!==void 0||o.by!==void 0)&&(s.orderBy===void 0&&s.by===void 0?o.orderBy?s.orderBy=o.orderBy:o.by&&(s.by=o.by):t.log("refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.log("refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(n=s.filterList)!==null&&n!==void 0?n:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,WJ.isQuerySegment)(o)&&(0,WJ.isQuerySegment)(s)){let a=[],u=[],l=new Map(s.queryFields.map(c=>[(0,YJ.nameFromDef)(c),c]));for(let c of o.queryFields)l.has((0,YJ.nameFromDef)(c))?a.push(c):u.push(c);s.queryFields=[...s.queryFields,...u],a.length>0&&t.log(`overlapping fields in refinement: ${a.map(YJ.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}JM.refine=eot});var cSe=v(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.ViewRefine=void 0;var tot=la(),rot=Km(),not=KJ(),iot=QA(),XJ=class extends iot.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){let n=this.base.pipelineComp(e),i=this.refinement.refine(e,n.pipeline,r);return{pipeline:i,annotation:n.annotation,outputStruct:i.length>0?(0,rot.getFinalStruct)(this.refinement,e.structDef(),i):tot.ErrorFactory.structDef}}refine(e,r,n){let i=this.pipeline(e,n);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),r):(0,not.refine)(this,r,i[0])}};ZM.ViewRefine=XJ});var dSe=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0});eP.ReferenceView=void 0;var fSe=Ke(),xSe=la(),sot=Km(),oot=ua(),aot=KJ(),uot=QA(),JJ=class extends uot.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){let n=this.reference.getField(e),i=function(){return{inputStruct:xSe.ErrorFactory.structDef,outputStruct:xSe.ErrorFactory.structDef,pipeline:[],error:!0}};if(!n.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(n.found instanceof oot.SpaceField))throw new Error("Expected space field");let s=n.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,fSe.isAtomicFieldType)(s.type)){this.inExperiment("scalar_lenses",!0)||(r?this.reference.log(`Cannot use scalar field \`${this.reference.refString}\` as a refinement; use \`scalar_lenses\` experiment to enable this behavior`):this.reference.log(`Cannot use scalar field \`${this.reference.refString}\` as a view; use \`scalar_lenses\` experiment to enable this behavior`));let o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:a,queryTimezone:u,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:a,queryTimezone:u,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,fSe.isTurtleDef)(s)?this.reference.list.length>1?(r?this.log("Cannot use view from join as refinement"):this.log("Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,sot.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(r?this.reference.log(`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.log("This operation is not supported"),i())}getRefinementSegment(e){let{pipeline:r,error:n}=this._pipelineComp(e,{forRefinement:!0});if(!n){if(r.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,n){let i=this.getRefinementSegment(e);return i?(0,aot.refine)(this,r,i):r}};eP.ReferenceView=JJ});var eZ=v(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.Index=void 0;var lot=mt(),cot=Ii(),ZJ=class extends lot.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=cot.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};tP.Index=ZJ});var rZ=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0});rP.SampleProperty=void 0;var fot=mt(),hSe=Ii(),tZ=class extends fot.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=hSe.LegalRefinementStage.Tail,this.forceQueryClass=hSe.QueryClass.Index}sampling(){return this.sample}};rP.SampleProperty=tZ});var mSe=v(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.IndexFieldSpace=void 0;var pSe=Ke(),nZ=PA(),xot=ua(),dot=l5(),hot=QK(),pot=tl(),iZ=class extends dot.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(let r of e)r instanceof nZ.FieldReference?super.pushFields(r):r instanceof nZ.WildcardFieldReference?this.addWild(r):r.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};let r=[];for(let[n,i]of this.entries())if(i instanceof xot.SpaceField){let s=this.expandedWild[n];if(s){r.push({type:"fieldref",path:s});continue}if(i instanceof hot.ReferenceField){let o=i.fieldRef,a=o.getField(this.exprSpace);a.error?o.log(a.error):r.push(o.refToField)}}return{type:"index",indexFields:r}}addRefineFromFields(e){}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof pot.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries()){if(e.except.has(a))continue;let l=nZ.IndexFieldReference.indexOutputName([...i,a]);if(this.entry(l)){let c=(r=this.expandedWild[l])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{let c=u.typeDesc();(0,pSe.isAtomicFieldType)(c.dataType)&&(0,pSe.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:l,entry:u}),this.expandedWild[l]=i.concat(a))}}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};nP.IndexFieldSpace=iZ});var gSe=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0});iP.IndexBuilder=void 0;var sZ=Ke(),mot=la(),got=Ym(),yot=eZ(),Eot=kA(),Sot=rZ(),Aot=mSe(),oZ=class{constructor(e,r,n,i){this.filters=[],this.type="index",this.resultFS=new Aot.IndexFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof got.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof Eot.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof yot.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Sot.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,sZ.isIndexSegment)(e)&&!(0,sZ.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),mot.ErrorFactory.indexSegment;let r=this.resultFS.getPipeSegment(e),n=e?.filterList||[];return this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters]),e?.limit&&(r.limit=e.limit),this.limit&&(r.limit=this.limit.limit),this.indexOn&&(r.weightMeasure=this.indexOn.refString),e&&(0,sZ.isIndexSegment)(e)&&e?.sample&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),r}};iP.IndexBuilder=oZ});var uZ=v(sP=>{"use strict";Object.defineProperty(sP,"__esModule",{value:!0});sP.GroupBy=void 0;var vot=n0(),ySe=Ii(),aZ=class extends vot.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=ySe.LegalRefinementStage.Single,this.forceQueryClass=ySe.QueryClass.Grouping}};sP.GroupBy=aZ});var ESe=v(oP=>{"use strict";Object.defineProperty(oP,"__esModule",{value:!0});oP.ProjectFieldSpace=void 0;var lZ=Ke(),_ot=l5(),cZ=class extends _ot.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,lZ.expressionIsAggregate)(e.expressionType)?!1:(0,lZ.expressionInvolvesAggregate)(e.expressionType)&&(0,lZ.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}};oP.ProjectFieldSpace=cZ});var dZ=v(VA=>{"use strict";Object.defineProperty(VA,"__esModule",{value:!0});VA.Ordering=VA.OrderBy=void 0;var bot=Ke(),SSe=u5(),ASe=mt(),Tot=Ii(),fZ=class extends ASe.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof SSe.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof SSe.FieldName&&e.isQueryFieldSpace()){let i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.log(s.error),(!s.found||!s.isOutputField)&&this.log(`Unknown field ${this.field.refString} in output space`),(0,bot.expressionIsAnalytic)((r=s.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}let n={field:this.modelField};return this.dir&&(n.dir=this.dir),n}};VA.OrderBy=fZ;var xZ=class extends ASe.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Tot.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}};VA.Ordering=xZ});var pZ=v(aP=>{"use strict";Object.defineProperty(aP,"__esModule",{value:!0});aP.Top=void 0;var vSe=Ke(),Cot=hs(),Rot=u5(),Oot=mt(),Dot=Ii(),hZ=class extends Oot.MalloyElement{constructor(e,r){super(),this.limit=e,this.by=r,this.elementType="top",this.queryRefinementStage=Dot.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:r})}getBy(e){var r;if(this.by)if(this.by instanceof Rot.FieldName){if(e.isQueryFieldSpace()){let n=e.outputSpace(),i=this.by.getField(n);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,vSe.expressionIsAnalytic)((r=i.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{let n=this.by.getExpression(e);return(0,vSe.expressionIsAggregate)(n.expressionType)&&this.by.log("top by expression must be an aggregate"),n.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,Cot.compressExpr)(n.value)}}}};aP.Top=hZ});var lP=v(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.ReduceBuilder=WA.QuerySegmentBuilder=void 0;var _Se=Ke(),Not=la(),Fot=Ym(),wot=kA(),bSe=dZ(),TSe=pZ(),Lot=l5(),Iot=n0(),uP=class{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof Iot.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof Fot.Filter){let r=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(r))}else e instanceof TSe.Top?(this.limit?e.log("Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.log("Query operation is already sorted"):this.order=e)):e instanceof wot.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof bSe.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,r){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?r.orderBy=e.orderBy:e.by&&(r.by=e.by)),!this.limit&&e.limit&&(r.limit=e.limit)),this.limit&&(r.limit=this.limit),this.order instanceof TSe.Top){let i=this.order.getBy(this.inputFS);i&&(r.by=i)}this.order instanceof bSe.Ordering&&(r.orderBy=this.order.getOrderBy(this.inputFS));let n=e?.filterList||[];this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters])}};WA.QuerySegmentBuilder=uP;var mZ=class extends uP{constructor(e,r,n,i){super(),this.type="grouping",this.resultFS=new Lot.ReduceFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,_Se.isReduceSegment)(e)||(0,_Se.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),Not.ErrorFactory.reduceSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};WA.ReduceBuilder=mZ});var RSe=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0});cP.ProjectBuilder=void 0;var CSe=Ke(),Mot=la(),Pot=uZ(),kot=ESe(),Bot=lP(),gZ=class extends Bot.QuerySegmentBuilder{constructor(e,r,n,i){super(),this.type="project",this.resultFS=new kot.ProjectFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Pot.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,CSe.isProjectSegment)(e)||(0,CSe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),Mot.ErrorFactory.projectSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};cP.ProjectBuilder=gZ});var OSe=v(fP=>{"use strict";Object.defineProperty(fP,"__esModule",{value:!0});fP.PartialBuilder=void 0;var qot=lc(),Uot=lP(),yZ=class extends Uot.ReduceBuilder{finalize(e){let r=super.finalize(e);if((0,qot.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}};fP.PartialBuilder=yZ});var SZ=v(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.QOpDesc=void 0;var $ot=gSe(),jot=RSe(),Hot=lP(),zot=mt(),Got=Km(),Qot=tl(),cg=Ii(),Vot=OSe(),EZ=class extends zot.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,n=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=cg.QueryClass.Grouping:this.refineThis.type==="project"?r=cg.QueryClass.Project:this.refineThis.type==="index"&&(r=cg.QueryClass.Index));for(let i of this.list)i.forceQueryClass&&(r?r!==i.forceQueryClass&&i.log(`Not legal in ${r} query`):r=i.forceQueryClass),n||(n=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&n&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),r=cg.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,n){switch(this.computeType()){case cg.QueryClass.Grouping:return new Hot.ReduceBuilder(e,this.refineThis,r,n);case cg.QueryClass.Project:return new jot.ProjectBuilder(e,this.refineThis,r,n);case cg.QueryClass.Index:return new $ot.IndexBuilder(e,this.refineThis,r,n);case void 0:return new Vot.PartialBuilder(e,this.refineThis,r,n)}}getOp(e,r){let n=this.getBuilder(e,r,this);for(let s of this.list)n.execute(s);let i=n.finalize(this.refineThis);return{segment:i,outputSpace:()=>new Qot.StaticSpace((0,Got.opOutputStruct)(this,e.structDef(),i))}}};xP.QOpDesc=EZ});var NSe=v(dP=>{"use strict";Object.defineProperty(dP,"__esModule",{value:!0});dP.QOpDescView=void 0;var Wot=Ke(),Yot=tl(),DSe=SZ(),Kot=Km(),AZ=Ii(),Xot=QA(),vZ=class extends Xot.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){let n=this.operation.getOp(e,r);return{pipeline:[n.segment],outputStruct:n.outputSpace().structDef()}}getOp(e,r,n,i){return(0,Wot.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(n.refineFrom(i),n.getOp(e,r).segment)}refine(e,r,n){let i=[...r];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,n,this.operation,i[0])];let s=new DSe.QOpDesc([]),o=new DSe.QOpDesc([]);for(let a of this.operation.list)switch(a.queryRefinementStage){case AZ.LegalRefinementStage.Head:s.push(a);break;case AZ.LegalRefinementStage.Single:a.log("Illegal in refinement of a query with more than one stage");break;case AZ.LegalRefinementStage.Tail:o.push(a);break;default:a.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){let a=i.length-1;this.has({tailRefinements:o});let u=(0,Kot.getFinalStruct)(this,e.structDef(),i.slice(-1));i[a]=this.getOp(new Yot.StaticSpace(u),void 0,o,i[a])}return i}};dP.QOpDescView=vZ});var NZ=v(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.FieldDefinitionValue=Sn.DefSpace=Sn.DimensionFieldDeclaration=Sn.MeasureFieldDeclaration=Sn.DeclareFieldDeclaration=Sn.ProjectFieldDeclaration=Sn.GroupByFieldDeclaration=Sn.AggregateFieldDeclaration=Sn.CalculateFieldDeclaration=Sn.AtomicFieldDeclaration=void 0;var Jot=Ke(),Zot=hs(),eat=pn(),tat=EI(),rat=mt(),fg=VK(),nat=Vc(),iat=ua(),Jc=class extends rat.MalloyElement{constructor(e,r,n){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=n,this.isNoteableObj=!0,this.extendNote=nat.extendNoteMethod}fieldDef(e,r){return this.queryFieldDef(new A5(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let n;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{let u=this.executesInOutputSpace()?i():e;n=this.expr.getExpression(u)}catch(u){return this.log(`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}let s=(0,Zot.compressExpr)(n.value),o=n.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,Jot.isAtomicFieldType)(o)&&o!=="error"){let u={name:r,type:o,location:this.location};return s.length>0&&(u.e=s),n.expressionType&&(u.expressionType=n.expressionType),this.typecheckExprValue(n),this.exprSrc&&(u.code=this.exprSrc),(0,tat.isGranularResult)(n)&&u.type==="timestamp"&&(u.timeframe=n.timeframe),this.note&&(u.annotation=this.note),u}if(!(e instanceof A5&&e.foundCircle)&&n.dataType!=="error"){let u=eat.FT.inspect(n);this.log(`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new hP(e,this))}};Sn.AtomicFieldDeclaration=Jc;var _Z=class extends Jc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}};Sn.CalculateFieldDeclaration=_Z;var bZ=class extends Jc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckAggregate)(e,this)}};Sn.AggregateFieldDeclaration=bZ;var TZ=class extends Jc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckGroupBy)(e,this)}};Sn.GroupByFieldDeclaration=TZ;var CZ=class extends Jc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckProject)(e,this)}};Sn.ProjectFieldDeclaration=CZ;var RZ=class extends Jc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDeclare)(e,this)}};Sn.DeclareFieldDeclaration=RZ;var OZ=class extends Jc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckMeasure)(e,this)}};Sn.MeasureFieldDeclaration=OZ;var DZ=class extends Jc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDimension)(e,this)}};Sn.DimensionFieldDeclaration=DZ;var A5=class{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:`Circular reference to '${this.circular.defineName}' in definition`,found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}};Sn.DefSpace=A5;var hP=class extends iat.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){return this.haveFieldDef||(this.haveFieldDef=this.exprDef.fieldDef(this.space,this.name)),this.haveFieldDef}getQueryFieldDef(e){if(!this.qfd){let r=this.exprDef.queryFieldDef(e,this.name);this.qfd=r}return this.qfd}typeDesc(){let e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}};Sn.FieldDefinitionValue=hP});var wSe=v(pP=>{"use strict";Object.defineProperty(pP,"__esModule",{value:!0});pP.Aggregate=void 0;var sat=n0(),FSe=Ii(),FZ=class extends sat.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=FSe.LegalRefinementStage.Single,this.forceQueryClass=FSe.QueryClass.Grouping}};pP.Aggregate=FZ});var LSe=v(mP=>{"use strict";Object.defineProperty(mP,"__esModule",{value:!0});mP.Calculate=void 0;var oat=n0(),aat=Ii(),wZ=class extends oat.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=aat.LegalRefinementStage.Single}};mP.Calculate=wZ});var IZ=v(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.Dimensions=void 0;var uat=bA(),LZ=class extends uat.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}};gP.Dimensions=LZ});var PZ=v(yP=>{"use strict";Object.defineProperty(yP,"__esModule",{value:!0});yP.Measures=void 0;var lat=bA(),MZ=class extends lat.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}};yP.Measures=MZ});var MSe=v(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.Nests=void 0;var cat=n0(),ISe=Ii(),kZ=class extends cat.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=ISe.LegalRefinementStage.Single,this.forceQueryClass=ISe.QueryClass.Grouping}};EP.Nests=kZ});var kSe=v(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.ProjectStatement=void 0;var fat=n0(),PSe=Ii(),BZ=class extends fat.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=PSe.QueryClass.Project,this.queryRefinementStage=PSe.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}};SP.ProjectStatement=BZ});var qSe=v(AP=>{"use strict";Object.defineProperty(AP,"__esModule",{value:!0});AP.FromSQLSource=void 0;var BSe=Ke(),xat=n5(),qZ=class extends xat.NamedSource{constructor(){super(...arguments),this.elementType="fromSQLSource"}structRef(){return this.structDef()}modelStruct(){let e=this.modelEntry(this.ref),r=e?.entry;if(!r){this.log(`Undefined from_sql source '${this.refName}'`);return}if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="query"){this.log(`Cannot use 'from_sql()' with a query '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot use 'from_sql()' with a connection '${this.refName}'`);return}else if((0,BSe.isSQLBlockStruct)(r)&&r.declaredSQLBlock){let{declaredSQLBlock:n,...i}=r;return i}else if(!(0,BSe.isSQLBlockStruct)(r)){this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`);return}this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`)}};AP.FromSQLSource=qZ});var HZ=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.findReferences=Up.deprecatedParseTableURI=Up.constructTableKey=void 0;var dat=bp(),$Z=WC();function UZ(t){let e=(0,$Z.getStringIfShort)(t);if(e)return e;let r=[],n=t.string().sqlString();if(n){for(let i of(0,$Z.getStringParts)(n))typeof i=="string"&&r.push(i);return r.join("")}return""}var jZ=class{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,n){let i=USe(e,r);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:r,firstReference:n})}enterTableMethod(e){let r=(0,$Z.getId)(e.connectionId()),n=UZ(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(r,n,i)}enterTableFunction(e){let r=UZ(e.tableURI()),{connectionName:n,tablePath:i}=$Se(r),s=this.trans.rangeFromContext(e);this.registerTableReference(n,i,s)}enterImportURL(e){let r=UZ(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}};function USe(t,e){return t===void 0?e:`${t}:${e}`}Up.constructTableKey=USe;function $Se(t){let e=t.match(/^([^:]*):(.*)$/);if(e){let[,r,n]=e;return{connectionName:r,tablePath:n}}else return{tablePath:t}}Up.deprecatedParseTableURI=$Se;function hat(t,e,r){let n=new jZ(t,e),i=n;return dat.ParseTreeWalker.DEFAULT.walk(i,r),{tables:n.needTables,urls:n.needImports}}Up.findReferences=hat});var zSe=v($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});$p.TableFunctionSource=$p.TableMethodSource=$p.TableSource=void 0;var HSe=HZ(),pat=Px(),jSe=la(),v5=class extends pat.Source{structDef(){var e,r;let n=this.getTableInfo();if(n===void 0)return jSe.ErrorFactory.structDef;let{tablePath:i,connectionName:s}=n,o=(0,HSe.constructTableKey)(s,i),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(o),u=`Schema read failure for table '${i}' for connection '${s}'`;if(a){if(a.status==="present"){a.value.location=this.location,a.value.fields.forEach(c=>{c.location=this.location});let l={...a.value,fields:a.value.fields.map(c=>({...c,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(l),l}a.status==="error"&&(u=a.message)}return this.log(u),jSe.ErrorFactory.structDef}};$p.TableSource=v5;var zZ=class extends v5{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;let r=this.modelEntry(this.connectionName),n=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(n,{entry:{type:"connection",name:n},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}};$p.TableMethodSource=zZ;var GZ=class extends v5{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,HSe.deprecatedParseTableURI)(this.tableURI)}};$p.TableFunctionSource=GZ});var GSe=v(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.SQLStatement=void 0;var mat=EK(),gat=mt(),QZ=class extends gat.MalloyElement{constructor(e){super(),this.select=e,this.elementType="sqlStatement",this.has({select:e})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,mat.makeSQLBlock)(this.select.sqlPhrases(),this.connection)),this.requestBlock}lookupCompiledSQL(e){var r;let n=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(n)return n.reference(e.name,this.location),n.getEntry(e.name)}needs(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(n?.status==="reference")return{compileSQL:r,partialModel:this.select.containsQueries?e.modelDef():void 0}}execute(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(!n){this.log("Cant't look up schema for sql block");return}if(n.status==="error"){let i=n.message.split(/\r?\n/);this.select.log("Invalid SQL, "+i.join(`
677
+ `)),xI.ErrorFactory.structDef}else if(i.status==="present"){let s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},a=this.document(),u=a?.currentModelAnnotation();return u&&(o.modelAnnotation=u),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),xI.ErrorFactory.structDef}};dI.SQLSource=SK});var O3e=v(hI=>{"use strict";Object.defineProperty(hI,"__esModule",{value:!0});hI.SQSource=void 0;var Stt=Np(),Att=yK(),vtt=AK(),vK=class extends Stt.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 vtt.SQLSource){let e=new Att.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}};hI.SQSource=vK});var D3e=v(pI=>{"use strict";Object.defineProperty(pI,"__esModule",{value:!0});pI.SQExtend=void 0;var _tt=tK(),btt=Np(),_K=class extends btt.SourceQueryElement{constructor(e,r){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;let e=this.sqSrc.getSource();if(e)return this.asSource=new _tt.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}};pI.SQExtend=_K});var mI=v(FA=>{"use strict";Object.defineProperty(FA,"__esModule",{value:!0});FA.isComparison=FA.Comparison=void 0;var bK;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(bK||(FA.Comparison=bK={}));function Ttt(t){return Object.values(bK).includes(t)}FA.isComparison=Ttt});var pn=v(gI=>{"use strict";Object.defineProperty(gI,"__esModule",{value:!0});gI.FT=void 0;var Ctt=lc();function Xm(t,e="scalar",r="constant"){return{dataType:t,expressionType:e,evalSpace:r}}var $s=class t{static in(e,r){return e?r.find(i=>t.eq(i,e))!==void 0:!1}static eq(e,r){return r!==void 0&&e.dataType===r.dataType&&e.expressionType===r.expressionType}static typeEq(e,r,n=!1,i=!0){let s=e.dataType===r.dataType,o=n&&(e.dataType==="null"||r.dataType==="null"),a=i&&(e.dataType==="error"||r.dataType==="error");return s||o||a}static inspect(...e){return e.map(n=>{if(n){let i=n.dataType;return(0,Ctt.expressionIsScalar)(n.expressionType)||(i=`${n.expressionType} ${i}`),i}return"undefined"}).join(",")}};gI.FT=$s;$s.nullT=Xm("null");$s.numberT=Xm("number");$s.stringT=Xm("string");$s.dateT=Xm("date");$s.timestampT=Xm("timestamp");$s.boolT=Xm("boolean");$s.anyAtomicT=[$s.numberT,$s.stringT,$s.dateT,$s.timestampT,$s.boolT];$s.aggregateBoolT=Xm("boolean","aggregate")});var EI=v(yI=>{"use strict";Object.defineProperty(yI,"__esModule",{value:!0});yI.isGranularResult=void 0;function Rtt(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}yI.isGranularResult=Rtt});var js=v(SI=>{"use strict";Object.defineProperty(SI,"__esModule",{value:!0});SI.errorFor=void 0;function Ott(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}SI.errorFor=Ott});var N3e=v(wA=>{"use strict";Object.defineProperty(wA,"__esModule",{value:!0});wA.isEquality=wA.Equality=void 0;var TK;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(TK||(wA.Equality=TK={}));function Dtt(t){return Object.values(TK).includes(t)}wA.isEquality=Dtt});var ir=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.applyBinary=Yc.getMorphicValue=Yc.ExprDuration=Yc.ExpressionDef=void 0;var mn=Ke(),LA=js(),kx=hs(),Jm=pn(),AI=DA(),Ntt=mI(),Ftt=N3e(),L3e=EI(),wtt=mt(),RK=class extends Error{},vI=class extends wtt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Jm.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.dataType!=="error"&&!Jm.FT.in(r,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${Jm.FT.inspect(r)}`),!1):!0}apply(e,r,n){return P3e(e,n,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,mn.expressionIsAggregate)(e.expressionType)}};Yc.ExpressionDef=vI;var i5=class extends vI{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Jm.FT.timestampT,Jm.FT.dateT]}apply(e,r,n){let i=n.getExpression(e);if(this.typeCheck(this,i),(0,mn.isTimeFieldType)(i.dataType)&&(r==="+"||r==="-")){let s=this.n.getExpression(e);if(!Jm.FT.typeEq(s,Jm.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,LA.errorFor)("illegal unit expression");let o;if((0,L3e.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){let a=(0,AI.timeOffset)("timestamp",i.value,r,s.value,this.timeframe);return(0,AI.timeResult)({dataType:"timestamp",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a},o)}return(0,mn.isDateUnit)(this.timeframe)?(0,AI.timeResult)({dataType:"date",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,AI.timeOffset)("date",i.value,r,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,LA.errorFor)("ofsset date error"))}return super.apply(e,r,n)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}};Yc.ExprDuration=i5;function F3e(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function Ltt(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}Yc.getMorphicValue=Ltt;function I3e(t,e,r,n){let i=(0,mn.isTimeFieldType)(e.dataType),s=(0,mn.isTimeFieldType)(n.dataType);if(i&&s)if(e.dataType!==n.dataType){let o=F3e(e,"timestamp"),a=F3e(n,"timestamp");if(o&&a)return(0,kx.compose)(o,r,a)}else return(0,kx.compose)(e.value,r,n.value);if((i||s)&&e.dataType!=="null"&&n.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${n.dataType}`),["false"]}function w3e(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:t.value,regexp:e.value}]}else if(e.dataType==="string"&&t.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:e.value,regexp:t.value}]}function Itt(t,e,r){let n=e==="!="||e==="!~";if(t.dataType==="null"||r.dataType==="null"){let i=n?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:r.dataType!=="null"?[...r.value,`IS${i} NULL`]:[n?"false":"true"]}}function Mtt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;if(i.dataType==="unsupported"||s.dataType==="unsupported"){let l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){let f=o5(e,i,n,s);if(f)return{...f,dataType:"boolean"}}}let u=I3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(r){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")u=(0,kx.compose)(i.value,"LIKE",s.value);else{let l=w3e(i,s);if(l===void 0)throw new RK("Incompatible types for match('~') operator");u=l}u=(0,kx.nullsafeNot)(u,r);break}case"=":case"!=":{let l=Itt(i,r,s);l?u=l:u=(0,kx.nullsafeNot)(w3e(i,s)||(0,kx.compose)(i.value,"=",s.value),r);break}}return{dataType:"boolean",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u}}function Ptt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;let a=(0,mn.maxExpressionType)(i.expressionType,s.expressionType),u=o5(e,i,n,s);if(u)return{...u,dataType:"boolean"};let l=I3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);return{dataType:"boolean",expressionType:a,evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function CK(t,...e){return e.includes(t)}function ktt(t,...e){for(let r of e)if(r.dataType!==t)return!1;return!0}function M3e(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("number",i,s);if(o)return o;let a=o5(e,i,n,s);if(a)return a;let u=(0,mn.maxExpressionType)(i.expressionType,s.expressionType);return ktt("number",i,s)?{dataType:"number",expressionType:u,value:(0,kx.compose)(i.value,r,s.value),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)}:(e.log(`Non numeric('${i.dataType},${s.dataType}') value with '${r}'`),(0,LA.errorFor)("numbers required"))}function Btt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return o;let a=(0,mn.isTimeFieldType)(i.dataType),u=s5(a?"error":"number",i,s);if(u)return u;if(a){let l=n;if(s.dataType!=="duration")if((0,L3e.isGranularResult)(i))l=new i5(n,i.timeframe);else if(i.dataType==="date")l=new i5(n,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,LA.errorFor)(`time plus ${s.dataType}`);return l.apply(t,r,e)}return M3e(t,e,r,n)}function P3e(t,e,r,n){if((0,Ftt.isEquality)(r))return Mtt(t,e,r,n);if((0,Ntt.isComparison)(r))return Ptt(t,e,r,n);if(CK(r,"+","-"))return Btt(t,e,r,n);if(CK(r,"*","%"))return M3e(t,e,r,n);if(CK(r,"/")){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return e.log("Cannot operate with unsupported type"),o;let a=s5("number",i,s);if(a)return a;if(i.dataType!=="number")e.log("Numerator for division must be a number");else if(s.dataType!=="number")n.log("Denominator for division must be a number");else{let u={type:"dialect",function:"div",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[u]}}return(0,LA.errorFor)("divide type mismatch")}return e.log(`Cannot use ${r} operator here`),(0,LA.errorFor)("applybinary bad operator")}Yc.applyBinary=P3e;function s5(t,...e){if(e.some(r=>r.dataType==="error"))return{dataType:t,expressionType:(0,mn.maxOfExpressionTypes)(e.map(r=>r.expressionType)),value:["'cascading error'"],evalSpace:(0,mn.mergeEvalSpaces)(...e.map(r=>r.evalSpace))}}function o5(t,e,r,n){let i={dataType:e.dataType,expressionType:(0,mn.maxExpressionType)(e.expressionType,n.expressionType),value:["'unsupported operation'"],evalSpace:(0,mn.mergeEvalSpaces)(e.evalSpace,n.evalSpace)};if(e.dataType==="unsupported")return t.log("Unsupported type not allowed in expression"),{...i,dataType:n.dataType};if(n.dataType==="unsupported")return r.log("Unsupported type not allowed in expression"),i}});var bI=v(_I=>{"use strict";Object.defineProperty(_I,"__esModule",{value:!0});_I.BinaryBoolean=void 0;var k3e=Ke(),qtt=js(),Utt=pn(),$tt=ir(),jtt=hs(),OK=class extends $tt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="abstract boolean binary",this.legalChildTypes=[Utt.FT.boolT]}getExpression(e){let r=this.left.getExpression(e),n=this.right.getExpression(e);if(this.typeCheck(this.left,r)&&this.typeCheck(this.right,n)){let i=(0,k3e.mergeEvalSpaces)(r.evalSpace,n.evalSpace);return{dataType:"boolean",expressionType:(0,k3e.maxExpressionType)(r.expressionType,n.expressionType),evalSpace:i,value:(0,jtt.compose)(r.value,this.op,n.value)}}return(0,qtt.errorFor)("logial required boolean")}};_I.BinaryBoolean=OK});var CI=v(TI=>{"use strict";Object.defineProperty(TI,"__esModule",{value:!0});TI.ExprTime=void 0;var Htt=Ke(),ztt=hs(),Gtt=ir(),DK=class t extends Gtt.ExpressionDef{constructor(e,r,n="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:n,value:typeof r=="string"?[r]:r,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,r){let n=r.value;if(e!==r.dataType){let i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:r.value};(0,Htt.isTimeFieldType)(r.dataType)&&(i.srcType=r.dataType),n=(0,ztt.compressExpr)([i])}return new t(e,n,r.expressionType)}};TI.ExprTime=DK});var IA=v(RI=>{"use strict";Object.defineProperty(RI,"__esModule",{value:!0});RI.Range=void 0;var B3e=Ke(),Qtt=js(),Vtt=ir(),Wtt=hs(),NK=class extends Vtt.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,n){switch(r){case"=":case"!=":{let i=r==="="?">=":"<",s=r==="="?"and":"or",o=r==="="?"<":">=",a=this.first.apply(e,i,n),u=this.last.apply(e,o,n);return{dataType:"boolean",expressionType:(0,B3e.maxExpressionType)(a.expressionType,u.expressionType),evalSpace:(0,B3e.mergeEvalSpaces)(a.evalSpace,u.evalSpace),value:(0,Wtt.compose)(a.value,s,u.value)}}case">":return this.last.apply(e,">=",n);case">=":return this.first.apply(e,">=",n);case"<":return this.first.apply(e,"<",n);case"<=":return this.last.apply(e,"<",n)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,Qtt.errorFor)("a range is not a value")}};RI.Range=NK});var LK=v(DI=>{"use strict";Object.defineProperty(DI,"__esModule",{value:!0});DI.ExprGranularTime=void 0;var FK=Ke(),Ytt=js(),q3e=pn(),U3e=DA(),Ktt=ir(),OI=CI(),$3e=IA(),wK=class extends Ktt.ExpressionDef{constructor(e,r,n){super({expr:e}),this.expr=e,this.units=r,this.truncate=n,this.elementType="granularTime",this.legalChildTypes=[q3e.FT.timestampT,q3e.FT.dateT]}granular(){return!0}getExpression(e){let r=this.units,n=this.expr.getExpression(e);if((0,FK.isTimeFieldType)(n.dataType)){let s={...n,dataType:n.dataType,timeframe:r};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:n.value,valueType:n.dataType},units:r}]),s}n.dataType!=="error"&&this.log(`Cannot do time truncation on type '${n.dataType}'`);let i=n.dataType==="error"?(0,FK.isDateUnit)(r)?"date":"timestamp":n.dataType;return{...n,dataType:i,value:(0,Ytt.errorFor)("granularity typecheck").value,evalSpace:"constant"}}apply(e,r,n){return this.getRange(e).apply(e,r,n)}getRange(e){let r=this.getExpression(e);if(r.dataType==="timestamp"){let o=OI.ExprTime.fromValue("timestamp",r),a=new OI.ExprTime("timestamp",(0,U3e.timeOffset)("timestamp",r.value,"+",(0,FK.mkExpr)`1`,this.units),r.expressionType);return new $3e.Range(o,a)}let n=new OI.ExprTime("date",r.value,r.expressionType),i=(0,U3e.timeOffset)("date",r.value,"+",["1"],this.units),s=new OI.ExprTime("date",i,r.expressionType);return new $3e.Range(n,s)}};DI.ExprGranularTime=wK});var MK=v(NI=>{"use strict";Object.defineProperty(NI,"__esModule",{value:!0});NI.ExprCompare=void 0;var Cr=pn(),Xtt=EI(),Jtt=bI(),Ztt=LK(),ert={"~":[Cr.FT.stringT],"!~":[Cr.FT.stringT],"<":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"<=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"!=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT]},IK=class extends Jtt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="a<=>b",this.legalChildTypes=ert[r]}getExpression(e){if(!this.right.granular()){let r=this.right.requestExpression(e);if(r&&(0,Xtt.isGranularResult)(r))return new Ztt.ExprGranularTime(this.right,r.timeframe,!1).apply(e,this.op,this.left)}return this.right.apply(e,this.op,this.left)}};NI.ExprCompare=IK});var j3e=v(FI=>{"use strict";Object.defineProperty(FI,"__esModule",{value:!0});FI.Apply=void 0;var trt=mI(),rrt=MK(),PK=class extends rrt.ExprCompare{constructor(e,r){super(e,trt.Comparison.EqualTo,r),this.left=e,this.right=r,this.elementType="apply"}};FI.Apply=PK});var LI=v(wI=>{"use strict";Object.defineProperty(wI,"__esModule",{value:!0});wI.BinaryNumeric=void 0;var nrt=pn(),irt=ir(),kK=class extends irt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="numeric binary abstract",this.legalChildTypes=[nrt.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}};wI.BinaryNumeric=kK});var H3e=v(II=>{"use strict";Object.defineProperty(II,"__esModule",{value:!0});II.Boolean=void 0;var srt=ir(),ort=pn(),BK=class extends srt.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...ort.FT.boolT,value:[this.value]}}};II.Boolean=BK});var PI=v(MI=>{"use strict";Object.defineProperty(MI,"__esModule",{value:!0});MI.ExprIdReference=void 0;var qK=Ke(),art=js(),urt=vL(),lrt=ir(),UK=class extends lrt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){let r=this.fieldReference.getField(e);if(r.found){let n=r.found.typeDesc();if(r.isOutputField)return{...n,evalSpace:n.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};let i=[{type:r.found.refType,path:this.fieldReference.path}],s=(0,qK.expressionIsAggregate)(n.expressionType)?"output":n.evalSpace;return{...n,value:i,evalSpace:s}}return this.log(r.error),(0,art.errorFor)(r.error)}apply(e,r,n){let i=this.fieldReference.getField(e).found;if(i instanceof urt.SpaceParam){let s=i.parameter();if((0,qK.isConditionParameter)(s)){let o=n.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,qK.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,r,n)}};MI.ExprIdReference=UK});var kI=v(MA=>{"use strict";Object.defineProperty(MA,"__esModule",{value:!0});MA.FunctionOrdering=MA.FunctionOrderBy=void 0;var $K=Ke(),z3e=mt(),crt=PI(),jK=class extends z3e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",this.has({field:e})}getAnalyticOrderBy(e){let r=this.field.getExpression(e);return(0,$K.expressionIsAggregate)(r.expressionType)||((0,$K.expressionIsScalar)(r.expressionType)?(!(this.field instanceof crt.ExprIdReference)||r.evalSpace==="input")&&this.field.log("analytic `order_by` must be an aggregate or an output field reference"):this.field.log("analytic `order_by` must be scalar or aggregate")),{e:r.value,dir:this.dir}}getAggregateOrderBy(e){let r=this.field.getExpression(e);return(0,$K.expressionIsScalar)(r.expressionType)||this.field.log("aggregate `order_by` must be scalar"),{e:r.value,dir:this.dir}}};MA.FunctionOrderBy=jK;var HK=class extends z3e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e){return this.list.map(r=>r.getAggregateOrderBy(e))}};MA.FunctionOrdering=HK});var G3e=v(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.ExprAddSub=void 0;var frt=LI(),zK=class extends frt.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}};BI.ExprAddSub=zK});var QK=v(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.ReferenceField=void 0;var Q3e=ua(),GK=class extends Q3e.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){let r=this.fieldRef.getField(e);r.error&&this.fieldRef.log(r.error),this.queryFieldDef={type:"fieldref",path:this.fieldRef.list.map(i=>i.name)};let n=this.referenceTo;if(n instanceof Q3e.SpaceField&&n.haveFieldDef){let i=n.haveFieldDef,s=this.fieldRef.note;if(i.annotation||s){let o=s||{};i.annotation&&(o.inherits=i.annotation),this.queryFieldDef.annotation=o}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;let e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}};qI.ReferenceField=GK});var VK=v(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.typecheckGroupBy=Pi.typecheckAggregate=Pi.typecheckCalculate=Pi.typecheckDeclare=Pi.typecheckMeasure=Pi.typecheckDimension=Pi.typecheckIndex=Pi.typecheckProject=void 0;var gn=lc();function xrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a select operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckProject=xrt;function drt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r;if(t.dataType==="turtle")r="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in an index operation`)}}Pi.typecheckIndex=drt;function hrt(t,e){if(!(0,gn.expressionIsScalar)(t.expressionType))if((0,gn.expressionIsAggregate)(t.expressionType))e.log("Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckDimension=hrt;function prt(t,e){if(!(0,gn.expressionIsAggregate)(t.expressionType))if((0,gn.expressionIsScalar)(t.expressionType))e.log("Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckMeasure=prt;function mrt(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,gn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Pi.typecheckDeclare=mrt;function grt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAnalytic)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a calculate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckCalculate=grt;function yrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAggregate)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${n} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckAggregate=yrt;function Ert(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a group_by operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckGroupBy=Ert});var PA=v(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.FieldReferences=Gt.WildcardFieldReference=Gt.ViewOrScalarFieldReference=Gt.DimensionFieldReference=Gt.MeasureFieldReference=Gt.DeclareFieldReference=Gt.ProjectFieldReference=Gt.GroupByFieldReference=Gt.AggregateFieldReference=Gt.IndexFieldReference=Gt.CalculateFieldReference=Gt.PartitionByFieldReference=Gt.ExpressionFieldReference=Gt.AcceptExceptFieldReference=Gt.FieldReference=void 0;var Srt=QK(),Art=n0(),V3e=mt(),W3e=Vc(),wp=VK(),Co=class extends V3e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=W3e.extendNoteMethod}makeEntry(e){let r=this.outputName;if(e.entry(r))this.log(`Output already has a field named '${r}'`);else{let n=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Srt.ReferenceField(this,n))}}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){let r=e.lookup(this.list);if(r.found){let n=r.found.typeDesc();this.typecheck(n)}return r}};Gt.FieldReference=Co;var WK=class extends Co{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}};Gt.AcceptExceptFieldReference=WK;var YK=class extends Co{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}};Gt.ExpressionFieldReference=YK;var KK=class extends Co{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}};Gt.PartitionByFieldReference=KK;var XK=class extends Co{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,wp.typecheckCalculate)(e,this)}};Gt.CalculateFieldReference=XK;var JK=class t extends Co{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,wp.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return t.indexOutputName(this.path)}};Gt.IndexFieldReference=JK;var ZK=class extends Co{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,wp.typecheckAggregate)(e,this)}};Gt.AggregateFieldReference=ZK;var eX=class extends Co{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,wp.typecheckGroupBy)(e,this)}};Gt.GroupByFieldReference=eX;var tX=class extends Co{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,wp.typecheckProject)(e,this)}};Gt.ProjectFieldReference=tX;var rX=class extends Co{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,wp.typecheckDeclare)(e,this)}};Gt.DeclareFieldReference=rX;var nX=class extends Co{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,wp.typecheckMeasure)(e,this)}};Gt.MeasureFieldReference=nX;var iX=class extends Co{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,wp.typecheckDimension)(e,this)}};Gt.DimensionFieldReference=iX;var sX=class extends Co{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}};Gt.ViewOrScalarFieldReference=sX;var oX=class extends V3e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=W3e.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}.*`:"*"}};Gt.WildcardFieldReference=oX;var aX=class extends Art.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}};Gt.FieldReferences=aX});var Zm=v(UI=>{"use strict";Object.defineProperty(UI,"__esModule",{value:!0});UI.ExprAggregateFunction=void 0;var Y3e=Ke(),vrt=jd(),a5=js(),_rt=tl(),brt=e5(),Trt=pn(),Crt=PA(),Rrt=ir(),Ort=ua(),Drt=PI(),uX=class extends Rrt.ExpressionDef{constructor(e,r,n){super(),this.func=e,this.legalChildTypes=[Trt.FT.numberT],this.elementType=e,this.explicitSource=n,r&&(this.expr=r,this.has({expr:r}))}returns(e){return"number"}getExpression(e){var r,n;let i=e.isQueryFieldSpace()?e.inputSpace():e,s=this.expr,o=(r=this.expr)===null||r===void 0?void 0:r.getExpression(i),a=(n=this.source)===null||n===void 0?void 0:n.path,u=[];if(this.source){let c=this.source.getField(i);if(c.found){u=c.relationship;let f=c.found,x=f.typeDesc();if((0,Y3e.isAtomicFieldType)(x.dataType)){s=this.source,o={dataType:x.dataType,expressionType:x.expressionType,value:[x.evalSpace==="output"?{type:"outputField",name:this.source.refString}:{type:"field",path:this.source.path}],evalSpace:x.evalSpace},a=this.source.path;let d=this.getJoinUsage(i);(d.length===1||d.slice(1).every(p=>Nrt(p,d[0])))&&(a=d[0].map(p=>p.name),u=d[0])}else if(!(f instanceof brt.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,a5.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,a5.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,a5.errorFor)("agggregate without expression");if((0,Y3e.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,a5.errorFor)("reagggregate");if(!(o.dataType==="error")){let c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(d=>d.length===0))&&!this.isSymmetricFunction()){let d=cX(u,c),h=fX(this.elementType,d),p=f?h:"Join path is required for this calculation";if(p){let m=Frt(p,c,s,this.elementType);this.log(m,h?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){let c={type:"aggregate",function:this.func,e:o.value};return a&&a.length>0&&(c.structPath=a),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,a5.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){let r=[];if(this.source&&this.source.getField(e).found){let i=[{type:"field",path:this.source.path}];r.push(...lX(e,i))}if(this.expr){let n=this.expr.getExpression(e).value;r.push(...lX(e,n))}return r}};UI.ExprAggregateFunction=uX;function Nrt(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function lX(t,e){let r=[],n=(i,s)=>{let o=s[0],a=s.slice(1),u=i.entry(o);if(u===void 0)throw new Error(`Invalid field lookup ${o}`);if(u instanceof _rt.StructSpaceField&&a.length>0){let l=n(u.fieldSpace,a);return{...l,relationship:[{name:o,structRelationship:u.structRelationship},...l.relationship]}}else if(u instanceof Ort.SpaceField){if(a.length!==0)throw new Error(`${o} cannot contain a ${a.join(".")}`);let l=u.fieldDef();if(l)return{fs:i,def:l,relationship:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};return(0,vrt.exprWalk)(e,i=>{if(typeof i!="string"&&i.type==="field"){let s=n(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){let o=lX(s.fs,s.def.e);r.push(...o.map(a=>[...s.relationship,...a]))}else r.push(s.relationship)}}),r}function cX(t,e){let r=[];for(let n of e){let i=0;for(let u=0;u<t.length&&u<n.length&&t[u].name===n[u].name;u++)i=u+1;let s=t.slice(i),o=n.slice(i),a=[...s.map(u=>({...u,reverse:!0})),...o.map(u=>({...u,reverse:!1}))];r.push(a)}return r}function fX(t,e){for(let r of e)for(let n of r){if(n.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${n.name}\``;if(n.structRelationship.type==="many"&&!n.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${n.name}\``;if(n.structRelationship.type==="nested"&&!n.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${n.name}\``}}function Frt(t,e,r,n){if(e.length===0)return t;let i=e[0];for(let h of e.slice(1))for(let p=0;p<i.length;p++){let m=i[p],g=h[p];if(m.name!==g.name){i=i.slice(0,p);break}}let s=cX(i,e),o=fX(n,s),a=i.slice().reverse().findIndex(h=>h.structRelationship.type==="many"||h.structRelationship.type==="cross"),u=a===-1?0:i.length-a,l=i.slice(0,u),c=cX(l,e),f=fX(n,c),x=i.length>0?i.map(h=>h.name).join("."):"source",d=l.length>0?l.map(h=>h.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()`";{let h=r instanceof Crt.FieldReference?`${r.refString}.${n}()`:r instanceof Drt.ExprIdReference?`${r.fieldReference.refString}.${n}()`:`${x}.${n}(${r.code})`,p=`${d}.${n}(${r.code})`,m=`${t}; use \`${h}\``;return f===void 0&&d!==x&&(m+=` or \`${p}\` to get a result weighted with respect to \`${d}\``),m}}});var X3e=v($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.ExprAlternationTree=void 0;var K3e=Ke(),wrt=js(),Lrt=bI(),Irt=hs(),xX=class extends Lrt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="alternation",this.elementType=`${r}alternation${r}`}apply(e,r,n){let i=this.left.apply(e,r,n),s=this.right.apply(e,r,n);return{dataType:"boolean",expressionType:(0,K3e.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,K3e.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,Irt.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,wrt.errorFor)("no value from alternation tree")}};$I.ExprAlternationTree=xX});var HI=v(jI=>{"use strict";Object.defineProperty(jI,"__esModule",{value:!0});jI.ExprAsymmetric=void 0;var Mrt=Zm(),dX=class extends Mrt.ExprAggregateFunction{constructor(e,r,n,i){super(e,r,i),this.func=e,this.expr=r,this.source=n,this.has({source:n})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){let e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}};jI.ExprAsymmetric=dX});var J3e=v(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.ExprAvg=void 0;var Prt=HI(),hX=class extends Prt.ExprAsymmetric{constructor(e,r,n){super("avg",e,r,n),this.has({source:r})}};zI.ExprAvg=hX});var Z3e=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.ExprCast=void 0;var krt=DA(),Brt=ir(),qrt=hs(),pX=class extends Brt.ExpressionDef{constructor(e,r,n=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=n,this.elementType="cast"}getExpression(e){var r,n,i;let s=this.expr.getExpression(e),o="unsupported";if(typeof this.castType=="string")o=this.castType;else{let a=e.dialectObj();a&&(a.validateTypeName(this.castType.raw)?o=(i=(n=(r=e.dialectObj())===null||r===void 0?void 0:r.sqlTypeToMalloyType(this.castType.raw))===null||n===void 0?void 0:n.type)!==null&&i!==void 0?i:"unsupported":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${a.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,qrt.compressExpr)((0,krt.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}};GI.ExprCast=pX});var tye=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.ExprCoalesce=void 0;var mX=lc(),eye=pn(),Urt=ir(),gX=class extends Urt.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=eye.FT.anyAtomicT}getExpression(e){let r=this.expr.getExpression(e),n=this.altExpr.getExpression(e);return r.dataType==="null"?n:(eye.FT.typeEq(r,n)||this.log(`Mismatched types for coalesce (${r.dataType}, ${n.dataType})`),{...n,dataType:r.dataType==="error"?n.dataType:r.dataType,expressionType:(0,mX.maxExpressionType)(r.expressionType,n.expressionType),value:(0,mX.mkExpr)`COALESCE(${r.value},${n.value})`,evalSpace:(0,mX.mergeEvalSpaces)(r.evalSpace,n.evalSpace)})}};QI.ExprCoalesce=gX});var rye=v(VI=>{"use strict";Object.defineProperty(VI,"__esModule",{value:!0});VI.ExprCount=void 0;var $rt=Zm(),yX=class extends $rt.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){let r={type:"aggregate",function:"count",e:[]};return this.source&&(r.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[r],evalSpace:"output"}}};VI.ExprCount=yX});var nye=v(YI=>{"use strict";Object.defineProperty(YI,"__esModule",{value:!0});YI.ExprCountDistinct=void 0;var WI=pn(),jrt=Zm(),EX=class extends jrt.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[WI.FT.numberT,WI.FT.stringT,WI.FT.dateT,WI.FT.timestampT]}};YI.ExprCountDistinct=EX});var kA=v(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.Limit=void 0;var Hrt=mt(),zrt=Ii(),SX=class extends Hrt.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=zrt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}};KI.Limit=SX});var JI=v(XI=>{"use strict";Object.defineProperty(XI,"__esModule",{value:!0});XI.PartitionBy=void 0;var Grt=mt(),AX=class extends Grt.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}};XI.PartitionBy=AX});var _X=v(ZI=>{"use strict";Object.defineProperty(ZI,"__esModule",{value:!0});ZI.ExprFunc=void 0;var i0=Ke(),Bx=js(),Qrt=e5(),Vrt=ir(),iye=hs(),vX=class extends Vrt.ExpressionDef{constructor(e,r,n,i,s){super({args:r}),this.name=e,this.args=r,this.isRaw=n,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}getPropsExpression(e,r){var n,i,s,o,a;let u=this.args.map(O=>O.getExpression(e));if(this.isRaw){let O="scalar",N,P=[`${this.name}(`];for(let H of u)O=(0,i0.maxExpressionType)(O,H.expressionType),N?P.push(","):N=H.dataType,P.push(...H.value);return P.push(")"),{dataType:(i=(n=this.rawType)!==null&&n!==void 0?n:N)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,iye.compressExpr)(P),evalSpace:(0,i0.mergeEvalSpaces)(...u.map(H=>H.evalSpace))}}let l=(s=this.modelEntry(this.name.toLowerCase()))===null||s===void 0?void 0:s.entry;if(l===void 0)return this.log(`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),(0,Bx.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,Bx.errorFor)("called non function");l.name!==this.name&&this.log(`Case insensitivity for function names is deprecated, use '${l.name}' instead`,"warn");let c,f=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){let O=this.source.getField(e).found;if(O){let N=O.typeDesc();if((0,i0.isAtomicFieldType)(N.dataType))c={dataType:N.dataType,expressionType:N.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:N.evalSpace},f=this.source.path.slice(0,-1);else if(!(O instanceof Qrt.StructSpaceFieldBase)){let P=`Aggregate source cannot be a ${N.dataType}`;return this.log(P),(0,Bx.errorFor)(P)}}else{let N=`Reference to undefined value ${this.source.refString}`;return this.log(N),(0,Bx.errorFor)(N)}}let x=[...c?[c]:[],...u],d=Wrt(l,x);if(d===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,Bx.errorFor)("no matching overload");let{overload:h,expressionTypeErrors:p,evalSpaceErrors:m,nullabilityErrors:g}=d;for(let O of p){let N=O.argIndex-(c?1:0),P=(0,i0.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${P}, but received ${O.actualExpressionType}`)}for(let O of m){let N=O.argIndex-(c?1:0),P=O.maxEvalSpace==="literal"?"literal":O.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${P}, but received ${O.actualEvalSpace}`)}for(let O of g){let N=O.argIndex-(c?1:0);this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must not be a literal null`)}let y=h.returnType,S=(0,i0.maxOfExpressionTypes)([y.expressionType,...x.map(O=>O.expressionType)]);if(!(0,i0.expressionIsAggregate)(h.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(O=>O.dataType).join(", ")}) with source`),(0,Bx.errorFor)("cannot call with source");let A={type:"function_call",overload:h,args:x.map(O=>O.value),expressionType:S,structPath:f},T=[A],b=(a=e.dialectObj())===null||a===void 0?void 0:a.name,_=b?h.dialect[b]:void 0;if(_===void 0)this.log(`Function ${this.name} is not defined in dialect ${b}`);else{if(r?.orderBys&&r.orderBys.length>0){let O=(0,i0.expressionIsAnalytic)(h.returnType.expressionType);if(_.supportsOrderBy||O){let N=r.orderBys.flatMap(P=>O?P.getAnalyticOrderBy(e):P.getAggregateOrderBy(e));A.orderBy=N}else r.orderBys[0].log(`Function ${this.name} does not support order_by`)}r?.limit!==void 0&&(_.supportsLimit?A.limit=r.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(r?.partitionBys&&r.partitionBys.length>0){let O=[];for(let N of r.partitionBys)for(let P of N.partitionFields){let k=P.getField(e);k.found===void 0?P.log(`${P.refString} is not defined`):(0,i0.expressionIsScalar)(k.found.typeDesc().expressionType)?O.push(P.nameString):P.log("Partition expression must be scalar")}A.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,Bx.errorFor)(`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);let O=x[0].value;if(O.length!==1||typeof O[0]=="string"||O[0].type!=="dialect"||O[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{let N=O[0].literal,P=Yrt(N),k=P.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(k.length>0){let H=k.length===1?`'.' paths are not yet supported in sql interpolations, found ${k.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${k.join(", ")}]`;return this.log(H),(0,Bx.errorFor)(`${H}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}T=[{type:"sql-string",e:P.map(H=>H.type==="string"?H.value:H.name==="TABLE"?{type:"source-reference"}:{type:"field",path:[H.name]})}]}}if(y.dataType==="any")return this.log(`Invalid return type ${y.dataType} for function '${this.name}'`),(0,Bx.errorFor)("invalid return type");let R=(0,i0.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),D=R==="constant"?"constant":(0,i0.expressionIsScalar)(S)?R:"output";return{dataType:y.dataType,expressionType:S,value:(0,iye.compressExpr)(T),evalSpace:D}}};ZI.ExprFunc=vX;function Wrt(t,e){for(let r of t.overloads){let n=0,i=!0,s=!1,o=[],a=[],u=[];for(let l=0;l<e.length;l++){let c=e[l],f=r.params[n];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(d=>{let h=d.dataType===c.dataType||d.dataType==="any"||c.dataType==="null"||c.dataType==="error";return d.expressionType&&((0,i0.isExpressionTypeLEQ)(c.expressionType,d.expressionType)||o.push({argIndex:l,maxExpressionType:d.expressionType,actualExpressionType:c.expressionType,param:f})),(d.evalSpace==="literal"&&c.evalSpace!=="literal"||d.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||d.evalSpace==="output"&&c.evalSpace==="input")&&a.push({argIndex:l,param:f,maxEvalSpace:d.evalSpace,actualEvalSpace:c.evalSpace}),d.evalSpace==="literal"&&c.dataType==="null"&&u.push({argIndex:l,param:f}),h})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):n++}if(!(!s&&(n!==e.length||n!==r.params.length))&&i)return{overload:r,expressionTypeErrors:o,evalSpaceErrors:a,nullabilityErrors:u}}}function Yrt(t){let e=[],r=t;for(;r.length;){let n=r.indexOf("${");if(n===-1){e.push({type:"string",value:r});break}else{let i=r.slice(n).indexOf("}");if(i===-1){e.push({type:"string",value:r});break}n>0&&e.push({type:"string",value:r.slice(0,n)}),e.push({type:"interpolation",name:r.slice(n+2,i+n)}),r=r.slice(i+n+1)}}return e}});var sye=v(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.ExprProps=void 0;var Krt=Ke(),Xrt=js(),Jrt=pn(),Zrt=kI(),ent=kA(),tnt=JI(),rnt=ir(),nnt=_X(),bX=class extends rnt.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=Jrt.FT.anyAtomicT}getFilteredExpression(e,r,n){if(n.length>0){if(!this.expr.supportsWhere(r))return this.expr.log("Filtered expression requires an aggregate computation"),r;let i=[];for(let s of n){let o=s.getFilterList(e);if(o.find(a=>(0,Krt.expressionIsCalculation)(a.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),r;i.push(...o)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,value:[{type:"filterExpression",e:r.value,filterList:i}]}:(this.expr.log(`Cannot filter '${r.dataType}' data`),(0,Xrt.errorFor)("cannot filter type"))}return r}getExpression(e){let r=[],n,i=[],s=[];for(let a of this.statements)a instanceof tnt.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.log("`partition_by` is not supported for this kind of expression"):a instanceof ent.Limit?n?a.log("limit already specified"):this.expr.canSupportLimit()?n=a:a.log("`limit` is not supported for this kind of expression"):a instanceof Zrt.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(a):a.log("`order_by` is not supported for this kind of expression"):s.push(a);let o=this.expr instanceof nnt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:n,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}};eM.ExprProps=bX});var aye=v(tM=>{"use strict";Object.defineProperty(tM,"__esModule",{value:!0});tM.ExprLogicalOp=void 0;var int=bI(),oye=pn(),TX=class extends int.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[oye.FT.boolT,oye.FT.aggregateBoolT]}};tM.ExprLogicalOp=TX});var uye=v(nM=>{"use strict";Object.defineProperty(nM,"__esModule",{value:!0});nM.ExprMax=void 0;var rM=pn(),snt=Zm(),CX=class extends snt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[rM.FT.numberT,rM.FT.stringT,rM.FT.dateT,rM.FT.timestampT]}returns(e){return e.dataType}};nM.ExprMax=CX});var lye=v(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.ExprMin=void 0;var iM=pn(),ont=Zm(),RX=class extends ont.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[iM.FT.numberT,iM.FT.stringT,iM.FT.dateT,iM.FT.timestampT]}returns(e){return e.dataType}};sM.ExprMin=RX});var cye=v(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.ExprMinus=void 0;var ant=js(),unt=pn(),lnt=ir(),OX=class extends lnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[unt.FT.numberT]}getExpression(e){let r=this.expr.getExpression(e);return this.typeCheck(this.expr,r)?r.value.length>1?{...r,dataType:"number",value:["-(",...r.value,")"]}:{...r,dataType:"number",value:["-",...r.value]}:(0,ant.errorFor)("negate requires number")}};oM.ExprMinus=OX});var fye=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.ExprMulDiv=void 0;var cnt=LI(),DX=class extends cnt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}};aM.ExprMulDiv=DX});var FX=v(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.Unary=void 0;var fnt=ir(),NX=class extends fnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}};uM.Unary=NX});var dye=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.ExprNot=void 0;var xye=pn(),xnt=FX(),dnt=hs(),wX=class extends xnt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[xye.FT.boolT,xye.FT.nullT]}getExpression(e){let r=this.expr.getExpression(e),n=this.typeCheck(this.expr,r);return{...r,dataType:"boolean",value:n?(0,dnt.nullsafeNot)(r.value):["false"]}}};lM.ExprNot=wX});var hye=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0});cM.ExprNow=void 0;var hnt=ir(),LX=class extends hnt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}};cM.ExprNow=LX});var pye=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0});fM.ExprNULL=void 0;var pnt=ir(),IX=class extends pnt.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}};fM.ExprNULL=IX});var mye=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.ExprNumber=void 0;var mnt=pn(),gnt=ir(),MX=class extends gnt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...mnt.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}};xM.ExprNumber=MX});var gye=v(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.ExprParens=void 0;var ynt=ir(),PX=class extends ynt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){let r=this.expr.getExpression(e);return{...r,value:["(",...r.value,")"]}}};dM.ExprParens=PX});var yye=v(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.ExprRegEx=void 0;var Ent=ir(),kX=class extends Ent.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:[{type:"dialect",function:"regexpLiteral",literal:this.regex}],evalSpace:"literal"}}};hM.ExprRegEx=kX});var Eye=v(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.ExprString=void 0;var Snt=ir(),Ant=pn(),BX=class extends Snt.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...Ant.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}};pM.ExprString=BX});var Sye=v(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.ExprSum=void 0;var vnt=HI(),qX=class extends vnt.ExprAsymmetric{constructor(e,r,n){super("sum",e,r,n),this.has({source:r})}};mM.ExprSum=qX});var Aye=v(yM=>{"use strict";Object.defineProperty(yM,"__esModule",{value:!0});yM.ExprTimeExtract=void 0;var eg=Ke(),Lp=js(),UX=ir(),_nt=IA(),gM=class t extends UX.ExpressionDef{static extractor(e){let r=t.pluralMap[e];if(r)return r;if((0,eg.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){let r=t.extractor(this.extractText);if(r){if(this.args.length!==1)return this.log(`Extraction function ${r} requires one argument`),(0,Lp.errorFor)("{this.name} arg count");let n=this.args[0];if(n instanceof _nt.Range){let i=n.first.getExpression(e),s=n.last.getExpression(e),o=(0,eg.maxExpressionType)(i.expressionType,s.expressionType),a=(0,eg.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:a,value:(0,Lp.errorFor)("extract from error").value};if(!(0,eg.isTimeFieldType)(i.dataType))return n.first.log(`Can't extract ${r} from '${i.dataType}'`),(0,Lp.errorFor)(`${r} bad type ${i.dataType}`);if(!(0,eg.isTimeFieldType)(s.dataType))return n.last.log(`Cannot extract ${r} from '${s.dataType}'`),(0,Lp.errorFor)(`${r} bad type ${s.dataType}`);let u=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(u="timestamp",i.dataType==="date"){let c=(0,UX.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{let c=(0,UX.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return n.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,Lp.errorFor)(`${r} range mismatch`)}return["week","month","quarter","year"].includes(r)?(this.log(`Cannot measure interval using '${r}'`),(0,Lp.errorFor)(`${r} civil extraction`)):(0,eg.isTimestampUnit)(r)?{dataType:"number",expressionType:o,evalSpace:a,value:[{type:"dialect",function:"timeDiff",units:r,left:{valueType:u,value:i.value},right:{valueType:u,value:s.value}}]}:(this.log(`Cannot extract ${r} from a range`),(0,Lp.errorFor)(`${r} bad extraction`))}else{let i=n.getExpression(e);return(0,eg.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:r}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,Lp.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}};yM.ExprTimeExtract=gM;gM.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"}});var u5=v(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.FieldName=void 0;var bnt=mt(),$X=class extends bnt.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])}};EM.FieldName=$X});var vye=v(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.QueryInputSpace=void 0;var Tnt=CA(),Cnt=MY(),Rnt=LL(),jX=class extends Rnt.RefinedSpace{constructor(e,r){let n=new Cnt.SpaceSeed(e);super(n.structDef),this.queryOutput=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof Tnt.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}};SM.QueryInputSpace=jX});var l5=v(ca=>{"use strict";var Ont=ca&&ca.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dnt=ca&&ca.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nnt=ca&&ca.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ont(e,t,r);return Dnt(e,t),e};Object.defineProperty(ca,"__esModule",{value:!0});ca.ReduceFieldSpace=ca.QuerySpace=ca.QueryOperationSpace=void 0;var AM=Nnt(Ke()),HX=AL(),Fnt=u5(),wnt=ua(),Lnt=PA(),Int=LL(),Mnt=NY(),Pnt=tl(),knt=vye(),vM=class extends Int.RefinedSpace{constructor(e,r,n,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=n,this.astEl=i,this.expandedWild={},this.exprSpace=new knt.QueryInputSpace(e,this),r&&this.addRefineFromFields(r)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof Pnt.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries())if(!e.except.has(a))if(this.entry(a)){let l=(r=this.expandedWild[a])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{let l=u.typeDesc();AM.isAtomicFieldType(l.dataType)&&AM.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:a,entry:u}),this.expandedWild[a]=i.concat(a))}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};ca.QueryOperationSpace=vM;var _M=class extends vM{addRefineFromFields(e){var r;if(AM.isQuerySegment(e))for(let n of e.queryFields)if(n.type==="fieldref"){let i=this.exprSpace.lookup(n.path.map(s=>new Fnt.FieldName(s)));i.found&&this.setEntry(n.path[n.path.length-1],i.found)}else n.type!=="turtle"&&this.setEntry((r=n.as)!==null&&r!==void 0?r:n.name,new Mnt.ColumnSpaceField(n))}pushFields(...e){for(let r of e)r instanceof Lnt.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){let e=[];for(let[r,n]of this.entries())if(n instanceof wnt.SpaceField){let i=this.expandedWild[r];if(i){e.push({type:"fieldref",path:i});continue}let s=n.getQueryFieldDef(this.exprSpace);if(s){let o=n.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!Bnt(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){let r=this.getPipeSegment(e);if(AM.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.log("internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};if(e?.extendSource)for(let n of e.extendSource)this.exprSpace.addFieldDef(n);let r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,HX.mergeFields)(e?.queryFields,r.queryFields),e?.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){let n=[],i=this.exprSpace.structDef();for(let s of this.exprSpace.extendList){let o=i.fields.find(a=>(0,HX.nameFromDef)(a)===s);o&&n.push(o)}r.extendSource=(0,HX.mergeFields)(r.extendSource,n)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),this.isComplete(),r}lookup(e){let r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}};ca.QuerySpace=_M;var zX=class extends _M{constructor(){super(...arguments),this.segmentType="reduce"}};ca.ReduceFieldSpace=zX;function Bnt(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}});var bye=v(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.ExprUngroup=void 0;var _ye=Ke(),GX=js(),qnt=l5(),Unt=pn(),$nt=ir(),QX=class extends $nt.ExpressionDef{constructor(e,r,n){super({expr:r,fields:n}),this.control=e,this.expr=r,this.fields=n,this.legalChildTypes=Unt.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){let r=this.expr.getExpression(e);if(!(0,_ye.expressionIsAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,GX.errorFor)("ungrouped scalar");if((0,_ye.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,GX.errorFor)("doubly-ungrouped aggregate");let n={type:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){let i=[],s=this.control==="exclude";for(let o of this.fields){let a=e.outputSpace(),u=!0;for(;a;){let l=a.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),u=!1;else if(a instanceof qnt.QuerySpace){a=a.nestParent;continue}break}if(u){let l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}n.fields=i}return{dataType:this.returns(r),expressionType:"ungrouped_aggregate",value:[n],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,GX.errorFor)("ungrouped type check")}};bM.ExprUngroup=QX});var Oye=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0});RM.ForRange=void 0;var Tye=lc(),VX=js(),Cye=pn(),TM=DA(),jnt=ir(),CM=CI(),Rye=IA(),WX=class extends jnt.ExpressionDef{constructor(e,r,n){super({from:e,duration:r,timeframe:n}),this.from=e,this.duration=r,this.timeframe=n,this.elementType="forRange",this.legalChildTypes=[Cye.FT.timestampT,Cye.FT.dateT]}apply(e,r,n){let i=this.from.getExpression(e),s=n.getExpression(e);if(!this.typeCheck(n,s))return(0,VX.errorFor)("no time for range");let o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.log(`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,Tye.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,Tye.maxExpressionType)(i.expressionType,s.expressionType),value:(0,VX.errorFor)("for not number").value};let a=this.timeframe.text,u=(0,TM.resolution)(a);if(i.dataType==="timestamp"&&(u="timestamp"),s.dataType==="date"&&u==="date"){let h=this.from,p=(0,TM.timeOffset)("date",i.value,"+",o.value,a),m=new CM.ExprTime("date",p);return new Rye.Range(h,m).apply(e,r,n)}let l=CM.ExprTime.fromValue("timestamp",s),c=this.from,f=i.value;if(i.dataType==="date"){let h=i.morphic&&i.morphic.timestamp;h?f=h:f=(0,TM.castDateToTimestamp)(f),c=new CM.ExprTime("timestamp",f,i.expressionType)}let x=(0,TM.timeOffset)("timestamp",f,"+",o.value,a),d=new CM.ExprTime("timestamp",x,i.expressionType);return new Rye.Range(c,d).apply(e,r,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,VX.errorFor)("range has no value")}};RM.ForRange=WX});var _J=v(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var Ux=class extends Error{},nJ=class extends Ux{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},iJ=class extends Ux{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},sJ=class extends Ux{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ig=class extends Ux{},IM=class extends Ux{constructor(e){super(`Invalid unit ${e}`)}},fa=class extends Ux{},Kc=class extends Ux{constructor(){super("Zone is an abstract class")}},Re="numeric",u0="short",uu="long",oJ={year:Re,month:Re,day:Re},Zye={year:Re,month:u0,day:Re},Hnt={year:Re,month:u0,day:Re,weekday:u0},eEe={year:Re,month:uu,day:Re},tEe={year:Re,month:uu,day:Re,weekday:uu},rEe={hour:Re,minute:Re},nEe={hour:Re,minute:Re,second:Re},iEe={hour:Re,minute:Re,second:Re,timeZoneName:u0},sEe={hour:Re,minute:Re,second:Re,timeZoneName:uu},oEe={hour:Re,minute:Re,hourCycle:"h23"},aEe={hour:Re,minute:Re,second:Re,hourCycle:"h23"},uEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:u0},lEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:uu},cEe={year:Re,month:Re,day:Re,hour:Re,minute:Re},fEe={year:Re,month:Re,day:Re,hour:Re,minute:Re,second:Re},xEe={year:Re,month:u0,day:Re,hour:Re,minute:Re},dEe={year:Re,month:u0,day:Re,hour:Re,minute:Re,second:Re},znt={year:Re,month:u0,day:Re,weekday:u0,hour:Re,minute:Re},hEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,timeZoneName:u0},pEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,second:Re,timeZoneName:u0},mEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,timeZoneName:uu},gEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,second:Re,timeZoneName:uu};function kt(t){return typeof t>"u"}function og(t){return typeof t=="number"}function UM(t){return typeof t=="number"&&t%1===0}function Gnt(t){return typeof t=="string"}function Qnt(t){return Object.prototype.toString.call(t)==="[object Date]"}function yEe(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Vnt(t){return Array.isArray(t)?t:[t]}function Dye(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let s=[e(i),i];return n&&r(n[0],s[0])===n[0]?n:s},null)[1]}function Wnt(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function UA(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qx(t,e,r){return UM(t)&&t>=e&&t<=r}function Ynt(t,e){return t-e*Math.floor(t/e)}function jn(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function Ip(t){if(!(kt(t)||t===null||t===""))return parseInt(t,10)}function tg(t){if(!(kt(t)||t===null||t===""))return parseFloat(t)}function mJ(t){if(!(kt(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function gJ(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function g5(t){return t%4===0&&(t%100!==0||t%400===0)}function p5(t){return g5(t)?366:365}function MM(t,e){let r=Ynt(e-1,12)+1,n=t+(e-r)/12;return r===2?g5(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function yJ(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 PM(t){let e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,r=t-1,n=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7;return e===4||n===3?53:52}function aJ(t){return t>99?t:t>60?1900+t:2e3+t}function EEe(t,e,r,n=null){let i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(s.timeZone=n);let o={timeZoneName:e,...s},a=new Intl.DateTimeFormat(r,o).formatToParts(i).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function $M(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function SEe(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new fa(`Invalid unit value ${t}`);return e}function kM(t,e){let r={};for(let n in t)if(UA(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=SEe(i)}return r}function m5(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${jn(r,2)}:${jn(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${jn(r,2)}${jn(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function jM(t){return Wnt(t,["hour","minute","second","millisecond"])}var AEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,Knt=["January","February","March","April","May","June","July","August","September","October","November","December"],vEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Xnt=["J","F","M","A","M","J","J","A","S","O","N","D"];function _Ee(t){switch(t){case"narrow":return[...Xnt];case"short":return[...vEe];case"long":return[...Knt];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}}var bEe=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],TEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Jnt=["M","T","W","T","F","S","S"];function CEe(t){switch(t){case"narrow":return[...Jnt];case"short":return[...TEe];case"long":return[...bEe];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var REe=["AM","PM"],Znt=["Before Christ","Anno Domini"],eit=["BC","AD"],tit=["B","A"];function OEe(t){switch(t){case"narrow":return[...tit];case"short":return[...eit];case"long":return[...Znt];default:return null}}function rit(t){return REe[t.hour<12?0:1]}function nit(t,e){return CEe(e)[t.weekday-1]}function iit(t,e){return _Ee(e)[t.month-1]}function sit(t,e){return OEe(e)[t.year<0?0:1]}function oit(t,e,r="always",n=!1){let 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(r==="auto"&&s){let 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]}`}}let o=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=i[t],c=n?u?l[1]:l[2]||l[1]:u?i[t][0]:t;return o?`${a} ${c} ago`:`in ${a} ${c}`}function Nye(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var ait={D:oJ,DD:Zye,DDD:eEe,DDDD:tEe,t:rEe,tt:nEe,ttt:iEe,tttt:sEe,T:oEe,TT:aEe,TTT:uEe,TTTT:lEe,f:cEe,ff:xEe,fff:hEe,ffff:mEe,F:fEe,FF:dEe,FFF:pEe,FFFF:gEe},a0=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,s=[];for(let o=0;o<e.length;o++){let a=e.charAt(o);a==="'"?(n.length>0&&s.push({literal:i,val:n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&s.push({literal:!1,val:n}),n=a,r=a)}return n.length>0&&s.push({literal:i,val:n}),s}static macroTokenToFormatOpts(e){return ait[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTime(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTimeParts(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).formatToParts()}resolvedOptions(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return jn(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(d,h)=>this.loc.extract(e,d,h),o=d=>e.isOffsetFixed&&e.offset===0&&d.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,d.format):"",a=()=>n?rit(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(d,h)=>n?iit(e,d):s(h?{month:d}:{month:d,day:"numeric"},"month"),l=(d,h)=>n?nit(e,d):s(h?{weekday:d}:{weekday:d,month:"long",day:"numeric"},"weekday"),c=d=>{let h=t.macroTokenToFormatOpts(d);return h?this.formatWithSystemDefault(e,h):d},f=d=>n?sit(e,d):s({era:d},"era"),x=d=>{switch(d){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 a();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 u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("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 u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("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(d)}};return Nye(t.parseFormat(r),x)}formatDurationFromString(e,r){let n=u=>{switch(u[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=u=>l=>{let c=n(l);return c?this.num(u.get(c),l.length):l},s=t.parseFormat(r),o=s.reduce((u,{literal:l,val:c})=>l?u:u.concat(c),[]),a=e.shiftTo(...o.map(n).filter(u=>u));return Nye(s,i(a))}},au=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},Pp=class{get type(){throw new Kc}get name(){throw new Kc}get ianaName(){return this.name}get isUniversal(){throw new Kc}offsetName(e,r){throw new Kc}formatOffset(e,r){throw new Kc}offset(e){throw new Kc}equals(e){throw new Kc}get isValid(){throw new Kc}},YX=null,BM=class t extends Pp{static get instance(){return YX===null&&(YX=new t),YX}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EEe(e,r,n)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},wM={};function uit(t){return wM[t]||(wM[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"})),wM[t]}var lit={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function cit(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,s,o,a,u,l,c]=n;return[o,i,s,a,u,l,c]}function fit(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=lit[s];s==="era"?n[a]=o:kt(a)||(n[a]=parseInt(o,10))}return n}var OM={},$x=class t extends Pp{static create(e){return OM[e]||(OM[e]=new t(e)),OM[e]}static resetCache(){OM={},wM={}}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=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return EEe(e,r,n,this.name)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=uit(this.name),[i,s,o,a,u,l,c]=n.formatToParts?fit(n,r):cit(n,r);a==="BC"&&(i=-Math.abs(i)+1);let x=yJ({year:i,month:s,day:o,hour:u===24?0:u,minute:l,second:c,millisecond:0}),d=+r,h=d%1e3;return d-=h>=0?h:1e3+h,(x-d)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},KX=null,lu=class t extends Pp{static get utcInstance(){return KX===null&&(KX=new t(0)),KX}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t($M(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${m5(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${m5(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return m5(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},qM=class extends Pp{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 Mp(t,e){if(kt(t)||t===null)return e;if(t instanceof Pp)return t;if(Gnt(t)){let r=t.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?lu.utcInstance:lu.parseSpecifier(r)||$x.create(t)}else return og(t)?lu.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new qM(t)}var Fye=()=>Date.now(),wye="system",Lye=null,Iye=null,Mye=null,Pye,yn=class{static get now(){return Fye}static set now(e){Fye=e}static set defaultZone(e){wye=e}static get defaultZone(){return Mp(wye,BM.instance)}static get defaultLocale(){return Lye}static set defaultLocale(e){Lye=e}static get defaultNumberingSystem(){return Iye}static set defaultNumberingSystem(e){Iye=e}static get defaultOutputCalendar(){return Mye}static set defaultOutputCalendar(e){Mye=e}static get throwOnInvalid(){return Pye}static set throwOnInvalid(e){Pye=e}static resetCaches(){Hn.resetCache(),$x.resetCache()}},kye={};function xit(t,e={}){let r=JSON.stringify([t,e]),n=kye[r];return n||(n=new Intl.ListFormat(t,e),kye[r]=n),n}var uJ={};function lJ(t,e={}){let r=JSON.stringify([t,e]),n=uJ[r];return n||(n=new Intl.DateTimeFormat(t,e),uJ[r]=n),n}var cJ={};function dit(t,e={}){let r=JSON.stringify([t,e]),n=cJ[r];return n||(n=new Intl.NumberFormat(t,e),cJ[r]=n),n}var fJ={};function hit(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=fJ[i];return s||(s=new Intl.RelativeTimeFormat(t,e),fJ[i]=s),s}var h5=null;function pit(){return h5||(h5=new Intl.DateTimeFormat().resolvedOptions().locale,h5)}function mit(t){let e=t.indexOf("-u-");if(e===-1)return[t];{let r,n=t.substring(0,e);try{r=lJ(t).resolvedOptions()}catch{r=lJ(n).resolvedOptions()}let{numberingSystem:i,calendar:s}=r;return[n,i,s]}}function git(t,e,r){return(r||e)&&(t+="-u",r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function yit(t){let e=[];for(let r=1;r<=12;r++){let n=En.utc(2016,r,1);e.push(t(n))}return e}function Eit(t){let e=[];for(let r=1;r<=7;r++){let n=En.utc(2016,11,13+r);e.push(t(n))}return e}function DM(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function Sit(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"}var xJ=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:s,...o}=n;if(!r||Object.keys(o).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=dit(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):gJ(e,3);return jn(r,this.padTo)}}},dJ=class{constructor(e,r,n){this.opts=n;let i;if(e.zone.isUniversal){let o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&$x.create(a).valid?(i=a,this.dt=e):(i="UTC",n.timeZoneName?this.dt=e:this.dt=e.offset===0?e:En.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);let s={...this.opts};i&&(s.timeZone=i),this.dtf=lJ(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},hJ=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&yEe()&&(this.rtf=hit(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):oit(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},Hn=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,r,n,i=!1){let s=e||yn.defaultLocale,o=s||(i?"en-US":pit()),a=r||yn.defaultNumberingSystem,u=n||yn.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){h5=null,uJ={},cJ={},fJ={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=mit(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=git(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=Sit(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.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,r=!1,n=!0){return DM(this,e,n,_Ee,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=yit(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return DM(this,e,n,CEe,()=>{let i=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=r?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=Eit(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return DM(this,void 0,e,()=>REe,()=>{if(!this.meridiemCache){let r={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[En.utc(2016,11,13,9),En.utc(2016,11,13,19)].map(n=>this.extract(n,r,"dayperiod"))}return this.meridiemCache})}eras(e,r=!0){return DM(this,e,r,OEe,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[En.utc(-40,1,1),En.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),s=i.formatToParts(),o=s.find(a=>a.type.toLowerCase()===n);return o?o.value:null}numberFormatter(e={}){return new xJ(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new dJ(e,this.intl,r)}relFormatter(e={}){return new hJ(this.intl,this.isEnglish(),e)}listFormatter(e={}){return xit(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 $A(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function jA(...t){return e=>t.reduce(([r,n,i],s)=>{let[o,a,u]=s(e,i);return[{...r,...o},a||n,u]},[{},null,1]).slice(0,2)}function HA(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function DEe(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=Ip(e[r+i]);return[n,null,r+i]}}var NEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Ait=`(?:${NEe.source}?(?:\\[(${AEe.source})\\])?)?`,EJ=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,FEe=RegExp(`${EJ.source}${Ait}`),SJ=RegExp(`(?:T${FEe.source})?`),vit=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,_it=/(\d{4})-?W(\d\d)(?:-?(\d))?/,bit=/(\d{4})-?(\d{3})/,Tit=DEe("weekYear","weekNumber","weekDay"),Cit=DEe("year","ordinal"),Rit=/(\d{4})-(\d\d)-(\d\d)/,wEe=RegExp(`${EJ.source} ?(?:${NEe.source}|(${AEe.source}))?`),Oit=RegExp(`(?: ${wEe.source})?`);function qA(t,e,r){let n=t[e];return kt(n)?r:Ip(n)}function Dit(t,e){return[{year:qA(t,e),month:qA(t,e+1,1),day:qA(t,e+2,1)},null,e+3]}function zA(t,e){return[{hours:qA(t,e,0),minutes:qA(t,e+1,0),seconds:qA(t,e+2,0),milliseconds:mJ(t[e+3])},null,e+4]}function y5(t,e){let r=!t[e]&&!t[e+1],n=$M(t[e+1],t[e+2]),i=r?null:lu.instance(n);return[{},i,e+3]}function E5(t,e){let r=t[e]?$x.create(t[e]):null;return[{},r,e+1]}var Nit=RegExp(`^T?${EJ.source}$`),Fit=/^-?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 wit(t){let[e,r,n,i,s,o,a,u,l]=t,c=e[0]==="-",f=u&&u[0]==="-",x=(d,h=!1)=>d!==void 0&&(h||d&&c)?-d:d;return[{years:x(tg(r)),months:x(tg(n)),weeks:x(tg(i)),days:x(tg(s)),hours:x(tg(o)),minutes:x(tg(a)),seconds:x(tg(u),u==="-0"),milliseconds:x(mJ(l),f)}]}var Lit={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 AJ(t,e,r,n,i,s,o){let a={year:e.length===2?aJ(Ip(e)):Ip(e),month:vEe.indexOf(r)+1,day:Ip(n),hour:Ip(i),minute:Ip(s)};return o&&(a.second=Ip(o)),t&&(a.weekday=t.length>3?bEe.indexOf(t)+1:TEe.indexOf(t)+1),a}var Iit=/^(?:(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 Mit(t){let[,e,r,n,i,s,o,a,u,l,c,f]=t,x=AJ(e,i,n,r,s,o,a),d;return u?d=Lit[u]:l?d=0:d=$M(c,f),[x,new lu(d)]}function Pit(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var kit=/^(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$/,Bit=/^(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$/,qit=/^(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 Bye(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,i,n,r,s,o,a),lu.utcInstance]}function Uit(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,a,r,n,i,s,o),lu.utcInstance]}var $it=$A(vit,SJ),jit=$A(_it,SJ),Hit=$A(bit,SJ),zit=$A(FEe),LEe=jA(Dit,zA,y5,E5),Git=jA(Tit,zA,y5,E5),Qit=jA(Cit,zA,y5,E5),Vit=jA(zA,y5,E5);function Wit(t){return HA(t,[$it,LEe],[jit,Git],[Hit,Qit],[zit,Vit])}function Yit(t){return HA(Pit(t),[Iit,Mit])}function Kit(t){return HA(t,[kit,Bye],[Bit,Bye],[qit,Uit])}function Xit(t){return HA(t,[Fit,wit])}var Jit=jA(zA);function Zit(t){return HA(t,[Nit,Jit])}var est=$A(Rit,Oit),tst=$A(wEe),rst=jA(zA,y5,E5);function nst(t){return HA(t,[est,LEe],[tst,rst])}var ist="Invalid Duration",IEe={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}},sst={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},...IEe},rl=146097/400,BA=146097/4800,ost={years:{quarters:4,months:12,weeks:rl/7,days:rl,hours:rl*24,minutes:rl*24*60,seconds:rl*24*60*60,milliseconds:rl*24*60*60*1e3},quarters:{months:3,weeks:rl/28,days:rl/4,hours:rl*24/4,minutes:rl*24*60/4,seconds:rl*24*60*60/4,milliseconds:rl*24*60*60*1e3/4},months:{weeks:BA/7,days:BA,hours:BA*24,minutes:BA*24*60,seconds:BA*24*60*60,milliseconds:BA*24*60*60*1e3},...IEe},ng=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ast=ng.slice(0).reverse();function rg(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new ci(n)}function ust(t){return t<0?Math.floor(t):Math.ceil(t)}function MEe(t,e,r,n,i){let s=t[i][r],o=e[r]/s,a=Math.sign(o)===Math.sign(n[i]),u=!a&&n[i]!==0&&Math.abs(o)<=1?ust(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function lst(t,e){ast.reduce((r,n)=>kt(e[n])?r:(r&&MEe(t,e,r,e,n),n),null)}var ci=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||Hn.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r?ost:sst,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new fa(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:kM(e,t.normalizeUnit),loc:Hn.fromObject(r),conversionAccuracy:r.conversionAccuracy})}static fromDurationLike(e){if(og(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new fa(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Xit(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=Zit(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new fa("need to specify a reason the Duration is invalid");let n=e instanceof au?e:new au(e,r);if(yn.throwOnInvalid)throw new sJ(n);return new t({invalid:n})}static normalizeUnit(e){let r={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(!r)throw new IM(e);return r}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,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?a0.create(this.loc,n).formatDurationFromString(this,e):ist}toHuman(e={}){let r=ng.map(n=>{let i=this.values[n];return kt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}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+=gJ(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();if(r<0||r>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};let n=this.shiftTo("hours","minutes","seconds","milliseconds"),i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||n.seconds!==0||n.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||n.milliseconds!==0)&&(i+=".SSS"));let s=n.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;let r=t.fromDurationLike(e),n={};for(let i of ng)(UA(r.values,i)||UA(this.values,i))&&(n[i]=r.get(i)+this.get(i));return rg(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=SEe(e(this.values[n],n));return rg(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...kM(e,t.normalizeUnit)};return rg(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r}),s={loc:i};return n&&(s.conversionAccuracy=n),rg(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return lst(this.matrix,e),rg(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>t.normalizeUnit(o));let r={},n={},i=this.toObject(),s;for(let o of ng)if(e.indexOf(o)>=0){s=o;let a=0;for(let l in n)a+=this.matrix[l][o]*n[l],n[l]=0;og(i[o])&&(a+=i[o]);let u=Math.trunc(a);r[o]=u,n[o]=(a*1e3-u*1e3)/1e3;for(let l in i)ng.indexOf(l)>ng.indexOf(o)&&MEe(this.matrix,i,l,r,o)}else og(i[o])&&(n[o]=i[o]);for(let o in n)n[o]!==0&&(r[s]+=o===s?n[o]:n[o]/this.matrix[s][o]);return rg(this,{values:r},!0).normalize()}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return rg(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 r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of ng)if(!r(this.values[n],e.values[n]))return!1;return!0}},c5="Invalid Interval";function cst(t,e){return!t||!t.isValid?ag.invalid("missing or invalid start"):!e||!e.isValid?ag.invalid("missing or invalid end"):e<t?ag.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}var ag=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new fa("need to specify a reason the Interval is invalid");let n=e instanceof au?e:new au(e,r);if(yn.throwOnInvalid)throw new iJ(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=d5(e),i=d5(r),s=cst(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let s,o;try{s=En.fromISO(n,r),o=s.isValid}catch{o=!1}let a,u;try{a=En.fromISO(i,r),u=a.isValid}catch{u=!1}if(o&&u)return t.fromDateTimes(s,a);if(o){let l=ci.fromISO(i,r);if(l.isValid)return t.after(s,l)}else if(u){let l=ci.fromISO(n,r);if(l.isValid)return t.before(a,l)}}return t.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;let r=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(r,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:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(d5).filter(o=>this.contains(o)).sort(),n=[],{s:i}=this,s=0;for(;i<this.e;){let o=r[s]||this.e,a=+o>+this.e?this.e:o;n.push(t.fromDateTimes(i,a)),i=a,s+=1}return n}splitBy(e){let r=ci.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,s,o=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(u=>u*i));s=+a>+this.e?this.e:a,o.push(t.fromDateTimes(n,s)),n=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;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=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 n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],s=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),o=Array.prototype.concat(...s),a=o.sort((u,l)=>u.time-l.time);for(let u of a)n+=u.type==="s"?1:-1,n===1?r=u.time:(r&&+r!=+u.time&&i.push(t.fromDateTimes(r,u.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:c5}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:c5}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:c5}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:c5}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:c5}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):ci.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},sg=class{static hasDST(e=yn.defaultZone){let r=En.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return $x.isValidZone(e)}static normalizeZone(e){return Mp(e,yn.defaultZone)}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Hn.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return Hn.create(r,null,"gregory").eras(e)}static features(){return{relative:yEe()}}};function qye(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(ci.fromMillis(n).as("days"))}function fst(t,e,r){let n=[["years",(a,u)=>u.year-a.year],["quarters",(a,u)=>u.quarter-a.quarter],["months",(a,u)=>u.month-a.month+(u.year-a.year)*12],["weeks",(a,u)=>{let l=qye(a,u);return(l-l%7)/7}],["days",qye]],i={},s,o;for(let[a,u]of n)if(r.indexOf(a)>=0){s=a;let l=u(t,e);o=t.plus({[a]:l}),o>e?(t=t.plus({[a]:l-1}),l-=1):t=o,i[a]=l}return[t,i,o,s]}function xst(t,e,r,n){let[i,s,o,a]=fst(t,e,r),u=e-i,l=r.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[a]:1})),o!==i&&(s[a]=(s[a]||0)+u/(o-i)));let c=ci.fromObject(s,n);return l.length>0?ci.fromMillis(u,n).shiftTo(...l).plus(c):c}var vJ={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Uye={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]},dst=vJ.hanidec.replace(/[\[|\]]/g,"").split("");function hst(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(vJ.hanidec)!==-1)e+=dst.indexOf(t[r]);else for(let i in Uye){let[s,o]=Uye[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function s0({numberingSystem:t},e=""){return new RegExp(`${vJ[t||"latn"]}${e}`)}var pst="missing Intl.DateTimeFormat.formatToParts support";function Yt(t,e=r=>r){return{regex:t,deser:([r])=>e(hst(r))}}var mst="\xA0",PEe=`[ ${mst}]`,kEe=new RegExp(PEe,"g");function gst(t){return t.replace(/\./g,"\\.?").replace(kEe,PEe)}function $ye(t){return t.replace(/\./g,"").replace(kEe," ").toLowerCase()}function o0(t,e){return t===null?null:{regex:RegExp(t.map(gst).join("|")),deser:([r])=>t.findIndex(n=>$ye(r)===$ye(n))+e}}function jye(t,e){return{regex:t,deser:([,r,n])=>$M(r,n),groups:e}}function XX(t){return{regex:t,deser:([e])=>e}}function yst(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Est(t,e){let r=s0(e),n=s0(e,"{2}"),i=s0(e,"{3}"),s=s0(e,"{4}"),o=s0(e,"{6}"),a=s0(e,"{1,2}"),u=s0(e,"{1,3}"),l=s0(e,"{1,6}"),c=s0(e,"{1,9}"),f=s0(e,"{2,4}"),x=s0(e,"{4,6}"),d=m=>({regex:RegExp(yst(m.val)),deser:([g])=>g,literal:!0}),p=(m=>{if(t.literal)return d(m);switch(m.val){case"G":return o0(e.eras("short",!1),0);case"GG":return o0(e.eras("long",!1),0);case"y":return Yt(l);case"yy":return Yt(f,aJ);case"yyyy":return Yt(s);case"yyyyy":return Yt(x);case"yyyyyy":return Yt(o);case"M":return Yt(a);case"MM":return Yt(n);case"MMM":return o0(e.months("short",!0,!1),1);case"MMMM":return o0(e.months("long",!0,!1),1);case"L":return Yt(a);case"LL":return Yt(n);case"LLL":return o0(e.months("short",!1,!1),1);case"LLLL":return o0(e.months("long",!1,!1),1);case"d":return Yt(a);case"dd":return Yt(n);case"o":return Yt(u);case"ooo":return Yt(i);case"HH":return Yt(n);case"H":return Yt(a);case"hh":return Yt(n);case"h":return Yt(a);case"mm":return Yt(n);case"m":return Yt(a);case"q":return Yt(a);case"qq":return Yt(n);case"s":return Yt(a);case"ss":return Yt(n);case"S":return Yt(u);case"SSS":return Yt(i);case"u":return XX(c);case"uu":return XX(a);case"uuu":return Yt(r);case"a":return o0(e.meridiems(),0);case"kkkk":return Yt(s);case"kk":return Yt(f,aJ);case"W":return Yt(a);case"WW":return Yt(n);case"E":case"c":return Yt(r);case"EEE":return o0(e.weekdays("short",!1,!1),1);case"EEEE":return o0(e.weekdays("long",!1,!1),1);case"ccc":return o0(e.weekdays("short",!0,!1),1);case"cccc":return o0(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return jye(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return jye(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return XX(/[a-z_+-/]{1,256}?/i);default:return d(m)}})(t)||{invalidReason:pst};return p.token=t,p}var Sst={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 Ast(t,e,r){let{type:n,value:i}=t;if(n==="literal")return{literal:!0,val:i};let s=r[n],o=Sst[n];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function vst(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function _st(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(UA(r,o)){let a=r[o],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(s,s+u))),s+=u}return[n,i]}else return[n,{}]}function bst(t){let 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}},r=null,n;return kt(t.z)||(r=$x.create(t.z)),kt(t.Z)||(r||(r=new lu(t.Z)),n=t.Z),kt(t.q)||(t.M=(t.q-1)*3+1),kt(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),kt(t.u)||(t.S=mJ(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var JX=null;function Tst(){return JX||(JX=En.fromMillis(1555555555555)),JX}function Cst(t,e){if(t.literal)return t;let r=a0.macroTokenToFormatOpts(t.val);if(!r)return t;let s=a0.create(e,r).formatDateTimeParts(Tst()).map(o=>Ast(o,e,r));return s.includes(void 0)?t:s}function Rst(t,e){return Array.prototype.concat(...t.map(r=>Cst(r,e)))}function BEe(t,e,r){let n=Rst(a0.parseFormat(r),t),i=n.map(o=>Est(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=vst(i),u=RegExp(o,"i"),[l,c]=_st(e,u,a),[f,x,d]=c?bst(c):[null,null,void 0];if(UA(c,"a")&&UA(c,"H"))throw new ig("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:u,rawMatches:l,matches:c,result:f,zone:x,specificOffset:d}}}function Ost(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=BEe(t,e,r);return[n,i,s,o]}var qEe=[0,31,59,90,120,151,181,212,243,273,304,334],UEe=[0,31,60,91,121,152,182,213,244,274,305,335];function nl(t,e){return new au("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function $Ee(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function jEe(t,e,r){return r+(g5(t)?UEe:qEe)[e-1]}function HEe(t,e){let r=g5(t)?UEe:qEe,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function pJ(t){let{year:e,month:r,day:n}=t,i=jEe(e,r,n),s=$Ee(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=PM(a)):o>PM(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...jM(t)}}function Hye(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=$Ee(e,1,4),s=p5(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=p5(a)):o>s?(a=e+1,o-=p5(e)):a=e;let{month:u,day:l}=HEe(a,o);return{year:a,month:u,day:l,...jM(t)}}function ZX(t){let{year:e,month:r,day:n}=t,i=jEe(e,r,n);return{year:e,ordinal:i,...jM(t)}}function zye(t){let{year:e,ordinal:r}=t,{month:n,day:i}=HEe(e,r);return{year:e,month:n,day:i,...jM(t)}}function Dst(t){let e=UM(t.weekYear),r=qx(t.weekNumber,1,PM(t.weekYear)),n=qx(t.weekday,1,7);return e?r?n?!1:nl("weekday",t.weekday):nl("week",t.week):nl("weekYear",t.weekYear)}function Nst(t){let e=UM(t.year),r=qx(t.ordinal,1,p5(t.year));return e?r?!1:nl("ordinal",t.ordinal):nl("year",t.year)}function zEe(t){let e=UM(t.year),r=qx(t.month,1,12),n=qx(t.day,1,MM(t.year,t.month));return e?r?n?!1:nl("day",t.day):nl("month",t.month):nl("year",t.year)}function GEe(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=qx(e,0,23)||e===24&&r===0&&n===0&&i===0,o=qx(r,0,59),a=qx(n,0,59),u=qx(i,0,999);return s?o?a?u?!1:nl("millisecond",i):nl("second",n):nl("minute",r):nl("hour",e)}var eJ="Invalid DateTime",Gye=864e13;function NM(t){return new au("unsupported zone",`the zone "${t.name}" is not supported`)}function tJ(t){return t.weekData===null&&(t.weekData=pJ(t.c)),t.weekData}function f5(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new En({...r,...e,old:r})}function QEe(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let s=r.offset(n);return i===s?[n,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function Qye(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function LM(t,e,r){return QEe(yJ(t),e,r)}function Vye(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:n,month:i,day:Math.min(t.c.day,MM(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ci.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"),a=yJ(s),[u,l]=QEe(a,r,t.zone);return o!==0&&(u+=o,l=t.zone.offset(u)),{ts:u,o:l}}function x5(t,e,r,n,i,s){let{setZone:o,zone:a}=r;if(t&&Object.keys(t).length!==0){let u=e||a,l=En.fromObject(t,{...r,zone:u,specificOffset:s});return o?l:l.setZone(a)}else return En.invalid(new au("unparsable",`the input "${i}" can't be parsed as ${n}`))}function FM(t,e,r=!0){return t.isValid?a0.create(Hn.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function rJ(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=jn(t.c.year,r?6:4),e?(n+="-",n+=jn(t.c.month),n+="-",n+=jn(t.c.day)):(n+=jn(t.c.month),n+=jn(t.c.day)),n}function Wye(t,e,r,n,i,s){let o=jn(t.c.hour);return e?(o+=":",o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=":")):o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=jn(t.c.second),(t.c.millisecond!==0||!n)&&(o+=".",o+=jn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=jn(Math.trunc(-t.o/60)),o+=":",o+=jn(Math.trunc(-t.o%60))):(o+="+",o+=jn(Math.trunc(t.o/60)),o+=":",o+=jn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}var VEe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Fst={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},wst={ordinal:1,hour:0,minute:0,second:0,millisecond:0},WEe=["year","month","day","hour","minute","second","millisecond"],Lst=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Ist=["year","ordinal","hour","minute","second","millisecond"];function Yye(t){let 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 IM(t);return e}function Kye(t,e){let r=Mp(e.zone,yn.defaultZone),n=Hn.fromObject(e),i=yn.now(),s,o;if(kt(t.year))s=i;else{for(let l of WEe)kt(t[l])&&(t[l]=VEe[l]);let a=zEe(t)||GEe(t);if(a)return En.invalid(a);let u=r.offset(i);[s,o]=LM(t,u,r)}return new En({ts:s,zone:r,loc:n,o})}function Xye(t,e,r){let n=kt(r.round)?!0:r.round,i=(o,a)=>(o=gJ(o,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(o,a)),s=o=>r.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(r.unit)return i(s(r.unit),r.unit);for(let o of r.units){let a=s(o);if(Math.abs(a)>=1)return i(a,o)}return i(t>e?-0:0,r.units[r.units.length-1])}function Jye(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var En=class t{constructor(e){let r=e.zone||yn.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new au("invalid input"):null)||(r.isValid?null:NM(r));this.ts=kt(e.ts)?yn.now():e.ts;let i=null,s=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,s]=[e.old.c,e.old.o];else{let a=r.offset(this.ts);i=Qye(this.ts,a),n=Number.isNaN(i.year)?new au("invalid input"):null,i=n?null:i,s=n?null:a}this._zone=r,this.loc=e.loc||Hn.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=Jye(arguments),[n,i,s,o,a,u,l]=r;return Kye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,r]=Jye(arguments),[n,i,s,o,a,u,l]=r;return e.zone=lu.utcInstance,Kye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,r={}){let n=Qnt(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Mp(r.zone,yn.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:Hn.fromObject(r)}):t.invalid(NM(i))}static fromMillis(e,r={}){if(og(e))return e<-Gye||e>Gye?t.invalid("Timestamp out of range"):new t({ts:e,zone:Mp(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new fa(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(og(e))return new t({ts:e*1e3,zone:Mp(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new fa("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Mp(r.zone,yn.defaultZone);if(!n.isValid)return t.invalid(NM(n));let i=yn.now(),s=kt(r.specificOffset)?n.offset(i):r.specificOffset,o=kM(e,Yye),a=!kt(o.ordinal),u=!kt(o.year),l=!kt(o.month)||!kt(o.day),c=u||l,f=o.weekYear||o.weekNumber,x=Hn.fromObject(r);if((c||a)&&f)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new ig("Can't mix ordinal dates with month/day");let d=f||o.weekday&&!c,h,p,m=Qye(i,s);d?(h=Lst,p=Fst,m=pJ(m)):a?(h=Ist,p=wst,m=ZX(m)):(h=WEe,p=VEe);let g=!1;for(let R of h){let D=o[R];kt(D)?g?o[R]=p[R]:o[R]=m[R]:g=!0}let y=d?Dst(o):a?Nst(o):zEe(o),S=y||GEe(o);if(S)return t.invalid(S);let A=d?Hye(o):a?zye(o):o,[T,b]=LM(A,s,n),_=new t({ts:T,zone:n,o:b,loc:x});return o.weekday&&c&&e.weekday!==_.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,r={}){let[n,i]=Wit(e);return x5(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Yit(e);return x5(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Kit(e);return x5(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(kt(e)||kt(r))throw new fa("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[a,u,l,c]=Ost(o,e,r);return c?t.invalid(c):x5(a,u,n,`format ${r}`,e,l)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=nst(e);return x5(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new fa("need to specify a reason the DateTime is invalid");let n=e instanceof au?e:new au(e,r);if(yn.throwOnInvalid)throw new nJ(n);return new t({invalid:n})}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?tJ(this).weekYear:NaN}get weekNumber(){return this.isValid?tJ(this).weekNumber:NaN}get weekday(){return this.isValid?tJ(this).weekday:NaN}get ordinal(){return this.isValid?ZX(this.c).ordinal:NaN}get monthShort(){return this.isValid?sg.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?sg.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?sg.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?sg.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 g5(this.year)}get daysInMonth(){return MM(this.year,this.month)}get daysInYear(){return this.isValid?p5(this.year):NaN}get weeksInWeekYear(){return this.isValid?PM(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=a0.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(lu.instance(e),r)}toLocal(){return this.setZone(yn.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Mp(e,yn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let s=e.offset(this.ts),o=this.toObject();[i]=LM(o,s,e)}return f5(this,{ts:i,zone:e})}else return t.invalid(NM(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return f5(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=kM(e,Yye),n=!kt(r.weekYear)||!kt(r.weekNumber)||!kt(r.weekday),i=!kt(r.ordinal),s=!kt(r.year),o=!kt(r.month)||!kt(r.day),a=s||o,u=r.weekYear||r.weekNumber;if((a||i)&&u)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new ig("Can't mix ordinal dates with month/day");let l;n?l=Hye({...pJ(this.c),...r}):kt(r.ordinal)?(l={...this.toObject(),...r},kt(r.day)&&(l.day=Math.min(MM(l.year,l.month),l.day))):l=zye({...ZX(this.c),...r});let[c,f]=LM(l,this.o,this.zone);return f5(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e);return f5(this,Vye(this,r))}minus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e).negate();return f5(this,Vye(this,r))}startOf(e){if(!this.isValid)return this;let r={},n=ci.normalizeUnit(e);switch(n){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break}if(n==="weeks"&&(r.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,r={}){return this.isValid?a0.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):eJ}toLocaleString(e=oJ,r={}){return this.isValid?a0.create(this.loc.clone(r),e).formatDateTime(this):eJ}toLocaleParts(e={}){return this.isValid?a0.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;let o=e==="extended",a=rJ(this,o);return a+="T",a+=Wye(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?rJ(this,e==="extended"):null}toISOWeekDate(){return FM(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+Wye(this,o==="extended",r,e,n,s):null}toRFC2822(){return FM(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return FM(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?rJ(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),FM(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():eJ}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{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return ci.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},s=Vnt(r).map(ci.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=xst(a,u,s,i);return o?l.negate():l}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?ag.fromDateTimes(this,e):this}hasSame(e,r){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(r)<=n&&n<=i.endOf(r)}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;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),Xye(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?Xye(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new fa("min requires all arguments be DateTimes");return Dye(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new fa("max requires all arguments be DateTimes");return Dye(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return BEe(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return oJ}static get DATE_MED(){return Zye}static get DATE_MED_WITH_WEEKDAY(){return Hnt}static get DATE_FULL(){return eEe}static get DATE_HUGE(){return tEe}static get TIME_SIMPLE(){return rEe}static get TIME_WITH_SECONDS(){return nEe}static get TIME_WITH_SHORT_OFFSET(){return iEe}static get TIME_WITH_LONG_OFFSET(){return sEe}static get TIME_24_SIMPLE(){return oEe}static get TIME_24_WITH_SECONDS(){return aEe}static get TIME_24_WITH_SHORT_OFFSET(){return uEe}static get TIME_24_WITH_LONG_OFFSET(){return lEe}static get DATETIME_SHORT(){return cEe}static get DATETIME_SHORT_WITH_SECONDS(){return fEe}static get DATETIME_MED(){return xEe}static get DATETIME_MED_WITH_SECONDS(){return dEe}static get DATETIME_MED_WITH_WEEKDAY(){return znt}static get DATETIME_FULL(){return hEe}static get DATETIME_FULL_WITH_SECONDS(){return pEe}static get DATETIME_HUGE(){return mEe}static get DATETIME_HUGE_WITH_SECONDS(){return gEe}};function d5(t){if(En.isDateTime(t))return t;if(t&&t.valueOf&&og(t.valueOf()))return En.fromJSDate(t);if(t&&typeof t=="object")return En.fromObject(t);throw new fa(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Mst="2.5.2";cu.DateTime=En;cu.Duration=ci;cu.FixedOffsetZone=lu;cu.IANAZone=$x;cu.Info=sg;cu.Interval=ag;cu.InvalidZone=qM;cu.Settings=yn;cu.SystemZone=BM;cu.VERSION=Mst;cu.Zone=Pp});var eSe=v(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.LiteralYear=ki.LiteralQuarter=ki.LiteralMonth=ki.LiteralWeek=ki.LiteralDay=ki.LiteralHour=ki.LiteralTimestamp=ki.TimeFormatError=void 0;var kp=_J(),Pst=Ke(),kst=IA(),YEe=CI(),bJ=ir(),TJ=class extends Error{};ki.TimeFormatError=TJ;function lg(t,e){let r=t.slice(1);if(e){let n=r.match(/\[[^\]]+]$/);if(n)return{tzSpec:n[0].slice(1,-1),text:r.slice(0,-n[0].length)}}return{text:r}}var KEe="yyyy",XEe=`${KEe}-LL`,il=`${XEe}-dd`,JEe=`${il} HH`,ZEe=`${JEe}:mm`,CJ=`${ZEe}:ss`,HM=class extends bJ.ExpressionDef{constructor(e,r,n){super(),this.units=r,this.timeType=n,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){let n={type:"dialect",function:"timeLiteral",literal:e,literalType:r};return this.timeZone&&(n.timezone=this.timeZone),n}makeValue(e,r){let n=this.makeLiteral(e,r),i="scalar",s=[n];return this.units?{dataType:r,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:r,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}},RJ=class t extends HM{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r,n=lg(e,!0);e=n.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),n.text=e);let i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=kp.DateTime.fromFormat(e,CJ);if(s.isValid)return new t(n,r);if(s=kp.DateTime.fromFormat(e,ZEe),s.isValid){n.text=n.text+":00",r="minute";let o=s.plus({minute:1}).toFormat(CJ);return new S5(n,r,"timestamp",o)}}};ki.LiteralTimestamp=RJ;var S5=class extends HM{constructor(e,r,n,i){super(e,r,n),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,r,n){let i=this.getExpression(e),s=this.getNext();if(s){let o=n.getExpression(e);if(o.dataType==="timestamp"){let a=(0,bJ.getMorphicValue)(i,"timestamp"),u=(0,bJ.getMorphicValue)(s,"timestamp");if(a&&u)i=a,s=u;else return super.apply(e,r,n)}if((0,Pst.isTimeFieldType)(o.dataType)){let a=o.dataType;return new kst.Range(new YEe.ExprTime(a,i.value),new YEe.ExprTime(a,s.value)).apply(e,r,n)}}return super.apply(e,r,n)}},OJ=class t extends S5{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,JEe);if(i.isValid)return r.text=r.text+":00:00",n=i.plus({hour:1}).toFormat(CJ),new t(r,n)}};ki.LiteralHour=OJ;var ug=class extends S5{constructor(e,r,n){super(e,r,"date",n)}getExpression(e){let r=this.makeValue(this.literalPart,"date"),n=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...r,morphic:{timestamp:n},evalSpace:"literal"}}getNext(){let e=this.makeValue(this.nextLit,"date"),r=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:r}}}},DJ=class t extends ug{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,il);if(i.isValid)return n=i.plus({day:1}).toFormat(il),new t(r,n)}};ki.LiteralDay=DJ;var NJ=class t extends ug{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.slice(0,10),s=kp.DateTime.fromFormat(i,il);if(s.isValid&&s.weekday===7){let a=s.plus({days:7});return r.text=s.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralWeek=NJ;var FJ=class t extends ug{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,XEe);if(i.isValid){let s=i.plus({months:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralMonth=FJ;var wJ=class t extends ug{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.match(/(^\d{4})-[qQ](\d)$/);if(i){let s=Number.parseInt(i[2])-1,o=kp.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));let a=o.plus({quarter:1});return r.text=o.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralQuarter=wJ;var LJ=class t extends ug{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){let r=lg(e,!1),n=r.text,i=kp.DateTime.fromFormat(r.text,KEe);if(i.isValid){let s=i.plus({year:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralYear=LJ});var tSe=v(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.PartialCompare=void 0;var Bst=js(),qst=ir(),IJ=class extends qst.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,n){return this.right.apply(e,this.op,n)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,Bst.errorFor)("no value for partial compare")}};zM.PartialCompare=IJ});var nSe=v(GA=>{"use strict";Object.defineProperty(GA,"__esModule",{value:!0});GA.PickWhen=GA.Pick=void 0;var Xc=Ke(),Bp=js(),l0=pn(),Ust=ir(),$st=mt(),rSe=hs();function GM(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}var MJ=class extends Ust.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(let r of this.choices){if(r.pick===void 0)return;let n=r.when.requestExpression(e);if(n===void 0||n.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,r,n){let i=["CASE"],s,o="scalar",a="constant";for(let c of this.choices){let f=c.when.apply(e,"=",n),x=c.pick?c.pick.getExpression(e):n.getExpression(e);if(o=(0,Xc.maxExpressionType)(o,(0,Xc.maxExpressionType)(f.expressionType,x.expressionType)),a=(0,Xc.mergeEvalSpaces)(a,f.evalSpace,x.evalSpace),s&&!l0.FT.typeEq(s,x,!0)){let d=l0.FT.inspect(x);return this.log(`pick type '${d}', expected '${s.dataType}'`),(0,Bp.errorFor)("pick when type")}s=GM(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}let l=(this.elsePick||n).getExpression(e);if(s=GM(s,l),!l0.FT.typeEq(s,l,!0)){let c=this.elsePick?"else":"pick default";return this.log(`${c} type '${l0.FT.inspect(l)}', expected '${s.dataType}'`),(0,Bp.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Xc.maxExpressionType)(o,l.expressionType),evalSpace:(0,Xc.mergeEvalSpaces)(a,l.evalSpace),value:(0,rSe.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,Bp.errorFor)("no value for partial pick");let r=[];for(let u of this.choices){if(u.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,Bp.errorFor)("no value for partial pick");if(u.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,Bp.errorFor)("partial when");r.push({pick:u.pick.getExpression(e),when:u.when.getExpression(e)})}let n,i=["CASE"],s="scalar",o="constant";for(let u of r){if(!l0.FT.typeEq(u.when,l0.FT.boolT))return this.log(`when expression must be boolean, not '${l0.FT.inspect(u.when)}`),(0,Bp.errorFor)("pick when type");if(n&&!l0.FT.typeEq(n,u.pick,!0)){let l=l0.FT.inspect(u.pick);return this.log(`pick type '${l}', expected '${n.dataType}'`),(0,Bp.errorFor)("pick value type")}n=GM(n,u.pick),s=(0,Xc.maxExpressionType)(s,(0,Xc.maxExpressionType)(u.pick.expressionType,u.when.expressionType)),o=(0,Xc.mergeEvalSpaces)(o,u.pick.evalSpace,u.when.evalSpace),i.push(" WHEN ",...u.when.value," THEN ",...u.pick.value)}let a=this.elsePick.getExpression(e);return s=(0,Xc.maxExpressionType)(s,a.expressionType),o=(0,Xc.mergeEvalSpaces)(o,a.evalSpace),n=GM(n,a),l0.FT.typeEq(n,a,!0)?(i.push(" ELSE ",...a.value," END"),{dataType:n.dataType,expressionType:s,value:(0,rSe.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${l0.FT.inspect(a)}', expected '${n.dataType}'`),(0,Bp.errorFor)("pick value type mismatch"))}};GA.Pick=MJ;var PJ=class extends $st.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="pickWhen",this.has({pick:e})}};GA.PickWhen=PJ});var iSe=v(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.Timeframe=void 0;var jst=Ke(),Hst=mt(),kJ=class extends Hst.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,jst.isTimestampUnit)(r)?r:"second"}};QM.Timeframe=kJ});var oSe=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.TopBy=void 0;var zst=Ke(),sSe=ir(),Gst=mt(),Qst=hs(),BJ=class extends Gst.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof sSe.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof sSe.ExpressionDef){let r=this.by.getExpression(e);return(0,zst.expressionIsAggregate)(r.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,Qst.compressExpr)(r.value)}}return{by:"name",name:this.by}}};VM.TopBy=BJ});var aSe=v(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.ImportStatement=qp.ImportSelect=qp.ImportSourceName=void 0;var jJ=mt(),qJ=class extends jJ.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}};qp.ImportSourceName=qJ;var UJ=class extends jJ.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}};qp.ImportSelect=UJ;var $J=class extends jJ.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.log("Invalid URI in import statement")}}needs(){let e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){let n=e.childRequest(this.fullURL);if(n)return n}}execute(e){let r=this.translator();if(!r)this.log("Cannot import without translation context");else if(this.fullURL){let n=r.root.importZone.getEntry(this.fullURL);if(n.status==="present"){let i=r.getChildExports(this.fullURL);if(this.notEmpty())for(let s of this.list){let o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){let a={...i[o.text]};s.from&&(a.as=s.text),e.setEntry(s.text,{entry:a,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(let[s,o]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else n.status==="error"?this.log(`import failed: '${n.message}'`):this.log(`import failed with status: '${n.status}'`)}}};qp.ImportStatement=$J});var zJ=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.ExtendBlock=void 0;var Vst=mt(),Wst=Ii(),HJ=class extends Vst.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Wst.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)for(let n of r.list)e.inputFS.extendSource(n)}};WM.ExtendBlock=HJ});var uSe=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.AnonymousQuery=void 0;var Yst=mt(),Kst=Vc(),GJ=class extends Yst.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Kst.extendNoteMethod,this.has({queryExpr:e})}execute(e){let r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("Cannot run this object as a query");return}let n={...r.query()},i=this.note||{};n.annotation&&(i.inherits=n.annotation),(i.notes||i.blockNotes||i.inherits)&&(n.annotation=i),e.queryList.push(n)}};YM.AnonymousQuery=GJ});var QA=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.View=void 0;var Xst=mt(),QJ=class extends Xst.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}};KM.View=QJ});var lSe=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.ViewArrow=void 0;var Jst=tl(),Zst=QA(),VJ=class extends Zst.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){let r=this.base.pipelineComp(e),n=new Jst.StaticSpace(r.outputStruct),i=this.operation.pipelineComp(n);return{pipeline:[...r.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,r,n){return this.log("A multi-segment view cannot be used as a refinement"),[]}};XM.ViewArrow=VJ});var KJ=v(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.refine=void 0;var WJ=lc(),YJ=AL();function eot(t,e,r){var n,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;let s={...e[0]},o=r;if((0,WJ.isRawSegment)(s))t.log("Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.log(`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&((o.orderBy!==void 0||o.by!==void 0)&&(s.orderBy===void 0&&s.by===void 0?o.orderBy?s.orderBy=o.orderBy:o.by&&(s.by=o.by):t.log("refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.log("refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(n=s.filterList)!==null&&n!==void 0?n:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,WJ.isQuerySegment)(o)&&(0,WJ.isQuerySegment)(s)){let a=[],u=[],l=new Map(s.queryFields.map(c=>[(0,YJ.nameFromDef)(c),c]));for(let c of o.queryFields)l.has((0,YJ.nameFromDef)(c))?a.push(c):u.push(c);s.queryFields=[...s.queryFields,...u],a.length>0&&t.log(`overlapping fields in refinement: ${a.map(YJ.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}JM.refine=eot});var cSe=v(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.ViewRefine=void 0;var tot=la(),rot=Km(),not=KJ(),iot=QA(),XJ=class extends iot.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){let n=this.base.pipelineComp(e),i=this.refinement.refine(e,n.pipeline,r);return{pipeline:i,annotation:n.annotation,outputStruct:i.length>0?(0,rot.getFinalStruct)(this.refinement,e.structDef(),i):tot.ErrorFactory.structDef}}refine(e,r,n){let i=this.pipeline(e,n);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),r):(0,not.refine)(this,r,i[0])}};ZM.ViewRefine=XJ});var dSe=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0});eP.ReferenceView=void 0;var fSe=Ke(),xSe=la(),sot=Km(),oot=ua(),aot=KJ(),uot=QA(),JJ=class extends uot.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){let n=this.reference.getField(e),i=function(){return{inputStruct:xSe.ErrorFactory.structDef,outputStruct:xSe.ErrorFactory.structDef,pipeline:[],error:!0}};if(!n.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(n.found instanceof oot.SpaceField))throw new Error("Expected space field");let s=n.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,fSe.isAtomicFieldType)(s.type)){let o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:a,queryTimezone:u,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:a,queryTimezone:u,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,fSe.isTurtleDef)(s)?this.reference.list.length>1?(r?this.log("Cannot use view from join as refinement"):this.log("Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,sot.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(r?this.reference.log(`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.log("This operation is not supported"),i())}getRefinementSegment(e){let{pipeline:r,error:n}=this._pipelineComp(e,{forRefinement:!0});if(!n){if(r.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,n){let i=this.getRefinementSegment(e);return i?(0,aot.refine)(this,r,i):r}};eP.ReferenceView=JJ});var eZ=v(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.Index=void 0;var lot=mt(),cot=Ii(),ZJ=class extends lot.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=cot.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};tP.Index=ZJ});var rZ=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0});rP.SampleProperty=void 0;var fot=mt(),hSe=Ii(),tZ=class extends fot.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=hSe.LegalRefinementStage.Tail,this.forceQueryClass=hSe.QueryClass.Index}sampling(){return this.sample}};rP.SampleProperty=tZ});var mSe=v(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.IndexFieldSpace=void 0;var pSe=Ke(),nZ=PA(),xot=ua(),dot=l5(),hot=QK(),pot=tl(),iZ=class extends dot.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(let r of e)r instanceof nZ.FieldReference?super.pushFields(r):r instanceof nZ.WildcardFieldReference?this.addWild(r):r.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};let r=[];for(let[n,i]of this.entries())if(i instanceof xot.SpaceField){let s=this.expandedWild[n];if(s){r.push({type:"fieldref",path:s});continue}if(i instanceof hot.ReferenceField){let o=i.fieldRef,a=o.getField(this.exprSpace);a.error?o.log(a.error):r.push(o.refToField)}}return{type:"index",indexFields:r}}addRefineFromFields(e){}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof pot.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries()){if(e.except.has(a))continue;let l=nZ.IndexFieldReference.indexOutputName([...i,a]);if(this.entry(l)){let c=(r=this.expandedWild[l])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{let c=u.typeDesc();(0,pSe.isAtomicFieldType)(c.dataType)&&(0,pSe.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:l,entry:u}),this.expandedWild[l]=i.concat(a))}}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};nP.IndexFieldSpace=iZ});var gSe=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0});iP.IndexBuilder=void 0;var sZ=Ke(),mot=la(),got=Ym(),yot=eZ(),Eot=kA(),Sot=rZ(),Aot=mSe(),oZ=class{constructor(e,r,n,i){this.filters=[],this.type="index",this.resultFS=new Aot.IndexFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof got.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof Eot.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof yot.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Sot.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,sZ.isIndexSegment)(e)&&!(0,sZ.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),mot.ErrorFactory.indexSegment;let r=this.resultFS.getPipeSegment(e),n=e?.filterList||[];return this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters]),e?.limit&&(r.limit=e.limit),this.limit&&(r.limit=this.limit.limit),this.indexOn&&(r.weightMeasure=this.indexOn.refString),e&&(0,sZ.isIndexSegment)(e)&&e?.sample&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),r}};iP.IndexBuilder=oZ});var uZ=v(sP=>{"use strict";Object.defineProperty(sP,"__esModule",{value:!0});sP.GroupBy=void 0;var vot=n0(),ySe=Ii(),aZ=class extends vot.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=ySe.LegalRefinementStage.Single,this.forceQueryClass=ySe.QueryClass.Grouping}};sP.GroupBy=aZ});var ESe=v(oP=>{"use strict";Object.defineProperty(oP,"__esModule",{value:!0});oP.ProjectFieldSpace=void 0;var lZ=Ke(),_ot=l5(),cZ=class extends _ot.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,lZ.expressionIsAggregate)(e.expressionType)?!1:(0,lZ.expressionInvolvesAggregate)(e.expressionType)&&(0,lZ.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}};oP.ProjectFieldSpace=cZ});var dZ=v(VA=>{"use strict";Object.defineProperty(VA,"__esModule",{value:!0});VA.Ordering=VA.OrderBy=void 0;var bot=Ke(),SSe=u5(),ASe=mt(),Tot=Ii(),fZ=class extends ASe.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof SSe.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof SSe.FieldName&&e.isQueryFieldSpace()){let i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.log(s.error),(!s.found||!s.isOutputField)&&this.log(`Unknown field ${this.field.refString} in output space`),(0,bot.expressionIsAnalytic)((r=s.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}let n={field:this.modelField};return this.dir&&(n.dir=this.dir),n}};VA.OrderBy=fZ;var xZ=class extends ASe.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Tot.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}};VA.Ordering=xZ});var pZ=v(aP=>{"use strict";Object.defineProperty(aP,"__esModule",{value:!0});aP.Top=void 0;var vSe=Ke(),Cot=hs(),Rot=u5(),Oot=mt(),Dot=Ii(),hZ=class extends Oot.MalloyElement{constructor(e,r){super(),this.limit=e,this.by=r,this.elementType="top",this.queryRefinementStage=Dot.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:r})}getBy(e){var r;if(this.by)if(this.by instanceof Rot.FieldName){if(e.isQueryFieldSpace()){let n=e.outputSpace(),i=this.by.getField(n);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,vSe.expressionIsAnalytic)((r=i.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{let n=this.by.getExpression(e);return(0,vSe.expressionIsAggregate)(n.expressionType)&&this.by.log("top by expression must be an aggregate"),n.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,Cot.compressExpr)(n.value)}}}};aP.Top=hZ});var lP=v(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.ReduceBuilder=WA.QuerySegmentBuilder=void 0;var _Se=Ke(),Not=la(),Fot=Ym(),wot=kA(),bSe=dZ(),TSe=pZ(),Lot=l5(),Iot=n0(),uP=class{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof Iot.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof Fot.Filter){let r=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(r))}else e instanceof TSe.Top?(this.limit?e.log("Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.log("Query operation is already sorted"):this.order=e)):e instanceof wot.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof bSe.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,r){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?r.orderBy=e.orderBy:e.by&&(r.by=e.by)),!this.limit&&e.limit&&(r.limit=e.limit)),this.limit&&(r.limit=this.limit),this.order instanceof TSe.Top){let i=this.order.getBy(this.inputFS);i&&(r.by=i)}this.order instanceof bSe.Ordering&&(r.orderBy=this.order.getOrderBy(this.inputFS));let n=e?.filterList||[];this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters])}};WA.QuerySegmentBuilder=uP;var mZ=class extends uP{constructor(e,r,n,i){super(),this.type="grouping",this.resultFS=new Lot.ReduceFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,_Se.isReduceSegment)(e)||(0,_Se.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),Not.ErrorFactory.reduceSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};WA.ReduceBuilder=mZ});var RSe=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0});cP.ProjectBuilder=void 0;var CSe=Ke(),Mot=la(),Pot=uZ(),kot=ESe(),Bot=lP(),gZ=class extends Bot.QuerySegmentBuilder{constructor(e,r,n,i){super(),this.type="project",this.resultFS=new kot.ProjectFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Pot.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,CSe.isProjectSegment)(e)||(0,CSe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),Mot.ErrorFactory.projectSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};cP.ProjectBuilder=gZ});var OSe=v(fP=>{"use strict";Object.defineProperty(fP,"__esModule",{value:!0});fP.PartialBuilder=void 0;var qot=lc(),Uot=lP(),yZ=class extends Uot.ReduceBuilder{finalize(e){let r=super.finalize(e);if((0,qot.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}};fP.PartialBuilder=yZ});var SZ=v(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.QOpDesc=void 0;var $ot=gSe(),jot=RSe(),Hot=lP(),zot=mt(),Got=Km(),Qot=tl(),cg=Ii(),Vot=OSe(),EZ=class extends zot.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,n=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=cg.QueryClass.Grouping:this.refineThis.type==="project"?r=cg.QueryClass.Project:this.refineThis.type==="index"&&(r=cg.QueryClass.Index));for(let i of this.list)i.forceQueryClass&&(r?r!==i.forceQueryClass&&i.log(`Not legal in ${r} query`):r=i.forceQueryClass),n||(n=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&n&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),r=cg.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,n){switch(this.computeType()){case cg.QueryClass.Grouping:return new Hot.ReduceBuilder(e,this.refineThis,r,n);case cg.QueryClass.Project:return new jot.ProjectBuilder(e,this.refineThis,r,n);case cg.QueryClass.Index:return new $ot.IndexBuilder(e,this.refineThis,r,n);case void 0:return new Vot.PartialBuilder(e,this.refineThis,r,n)}}getOp(e,r){let n=this.getBuilder(e,r,this);for(let s of this.list)n.execute(s);let i=n.finalize(this.refineThis);return{segment:i,outputSpace:()=>new Qot.StaticSpace((0,Got.opOutputStruct)(this,e.structDef(),i))}}};xP.QOpDesc=EZ});var NSe=v(dP=>{"use strict";Object.defineProperty(dP,"__esModule",{value:!0});dP.QOpDescView=void 0;var Wot=Ke(),Yot=tl(),DSe=SZ(),Kot=Km(),AZ=Ii(),Xot=QA(),vZ=class extends Xot.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){let n=this.operation.getOp(e,r);return{pipeline:[n.segment],outputStruct:n.outputSpace().structDef()}}getOp(e,r,n,i){return(0,Wot.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(n.refineFrom(i),n.getOp(e,r).segment)}refine(e,r,n){let i=[...r];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,n,this.operation,i[0])];let s=new DSe.QOpDesc([]),o=new DSe.QOpDesc([]);for(let a of this.operation.list)switch(a.queryRefinementStage){case AZ.LegalRefinementStage.Head:s.push(a);break;case AZ.LegalRefinementStage.Single:a.log("Illegal in refinement of a query with more than one stage");break;case AZ.LegalRefinementStage.Tail:o.push(a);break;default:a.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){let a=i.length-1;this.has({tailRefinements:o});let u=(0,Kot.getFinalStruct)(this,e.structDef(),i.slice(-1));i[a]=this.getOp(new Yot.StaticSpace(u),void 0,o,i[a])}return i}};dP.QOpDescView=vZ});var NZ=v(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.FieldDefinitionValue=Sn.DefSpace=Sn.DimensionFieldDeclaration=Sn.MeasureFieldDeclaration=Sn.DeclareFieldDeclaration=Sn.ProjectFieldDeclaration=Sn.GroupByFieldDeclaration=Sn.AggregateFieldDeclaration=Sn.CalculateFieldDeclaration=Sn.AtomicFieldDeclaration=void 0;var Jot=Ke(),Zot=hs(),eat=pn(),tat=EI(),rat=mt(),fg=VK(),nat=Vc(),iat=ua(),Jc=class extends rat.MalloyElement{constructor(e,r,n){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=n,this.isNoteableObj=!0,this.extendNote=nat.extendNoteMethod}fieldDef(e,r){return this.queryFieldDef(new A5(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let n;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{let u=this.executesInOutputSpace()?i():e;n=this.expr.getExpression(u)}catch(u){return this.log(`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}let s=(0,Zot.compressExpr)(n.value),o=n.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,Jot.isAtomicFieldType)(o)&&o!=="error"){let u={name:r,type:o,location:this.location};return s.length>0&&(u.e=s),n.expressionType&&(u.expressionType=n.expressionType),this.typecheckExprValue(n),this.exprSrc&&(u.code=this.exprSrc),(0,tat.isGranularResult)(n)&&u.type==="timestamp"&&(u.timeframe=n.timeframe),this.note&&(u.annotation=this.note),u}if(!(e instanceof A5&&e.foundCircle)&&n.dataType!=="error"){let u=eat.FT.inspect(n);this.log(`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new hP(e,this))}};Sn.AtomicFieldDeclaration=Jc;var _Z=class extends Jc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}};Sn.CalculateFieldDeclaration=_Z;var bZ=class extends Jc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckAggregate)(e,this)}};Sn.AggregateFieldDeclaration=bZ;var TZ=class extends Jc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckGroupBy)(e,this)}};Sn.GroupByFieldDeclaration=TZ;var CZ=class extends Jc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckProject)(e,this)}};Sn.ProjectFieldDeclaration=CZ;var RZ=class extends Jc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDeclare)(e,this)}};Sn.DeclareFieldDeclaration=RZ;var OZ=class extends Jc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckMeasure)(e,this)}};Sn.MeasureFieldDeclaration=OZ;var DZ=class extends Jc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDimension)(e,this)}};Sn.DimensionFieldDeclaration=DZ;var A5=class{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:`Circular reference to '${this.circular.defineName}' in definition`,found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}};Sn.DefSpace=A5;var hP=class extends iat.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){return this.haveFieldDef||(this.haveFieldDef=this.exprDef.fieldDef(this.space,this.name)),this.haveFieldDef}getQueryFieldDef(e){if(!this.qfd){let r=this.exprDef.queryFieldDef(e,this.name);this.qfd=r}return this.qfd}typeDesc(){let e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}};Sn.FieldDefinitionValue=hP});var wSe=v(pP=>{"use strict";Object.defineProperty(pP,"__esModule",{value:!0});pP.Aggregate=void 0;var sat=n0(),FSe=Ii(),FZ=class extends sat.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=FSe.LegalRefinementStage.Single,this.forceQueryClass=FSe.QueryClass.Grouping}};pP.Aggregate=FZ});var LSe=v(mP=>{"use strict";Object.defineProperty(mP,"__esModule",{value:!0});mP.Calculate=void 0;var oat=n0(),aat=Ii(),wZ=class extends oat.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=aat.LegalRefinementStage.Single}};mP.Calculate=wZ});var IZ=v(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.Dimensions=void 0;var uat=bA(),LZ=class extends uat.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}};gP.Dimensions=LZ});var PZ=v(yP=>{"use strict";Object.defineProperty(yP,"__esModule",{value:!0});yP.Measures=void 0;var lat=bA(),MZ=class extends lat.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}};yP.Measures=MZ});var MSe=v(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.Nests=void 0;var cat=n0(),ISe=Ii(),kZ=class extends cat.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=ISe.LegalRefinementStage.Single,this.forceQueryClass=ISe.QueryClass.Grouping}};EP.Nests=kZ});var kSe=v(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.ProjectStatement=void 0;var fat=n0(),PSe=Ii(),BZ=class extends fat.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=PSe.QueryClass.Project,this.queryRefinementStage=PSe.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}};SP.ProjectStatement=BZ});var qSe=v(AP=>{"use strict";Object.defineProperty(AP,"__esModule",{value:!0});AP.FromSQLSource=void 0;var BSe=Ke(),xat=n5(),qZ=class extends xat.NamedSource{constructor(){super(...arguments),this.elementType="fromSQLSource"}structRef(){return this.structDef()}modelStruct(){let e=this.modelEntry(this.ref),r=e?.entry;if(!r){this.log(`Undefined from_sql source '${this.refName}'`);return}if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="query"){this.log(`Cannot use 'from_sql()' with a query '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot use 'from_sql()' with a connection '${this.refName}'`);return}else if((0,BSe.isSQLBlockStruct)(r)&&r.declaredSQLBlock){let{declaredSQLBlock:n,...i}=r;return i}else if(!(0,BSe.isSQLBlockStruct)(r)){this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`);return}this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`)}};AP.FromSQLSource=qZ});var HZ=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.findReferences=Up.deprecatedParseTableURI=Up.constructTableKey=void 0;var dat=bp(),$Z=WC();function UZ(t){let e=(0,$Z.getStringIfShort)(t);if(e)return e;let r=[],n=t.string().sqlString();if(n){for(let i of(0,$Z.getStringParts)(n))typeof i=="string"&&r.push(i);return r.join("")}return""}var jZ=class{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,n){let i=USe(e,r);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:r,firstReference:n})}enterTableMethod(e){let r=(0,$Z.getId)(e.connectionId()),n=UZ(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(r,n,i)}enterTableFunction(e){let r=UZ(e.tableURI()),{connectionName:n,tablePath:i}=$Se(r),s=this.trans.rangeFromContext(e);this.registerTableReference(n,i,s)}enterImportURL(e){let r=UZ(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}};function USe(t,e){return t===void 0?e:`${t}:${e}`}Up.constructTableKey=USe;function $Se(t){let e=t.match(/^([^:]*):(.*)$/);if(e){let[,r,n]=e;return{connectionName:r,tablePath:n}}else return{tablePath:t}}Up.deprecatedParseTableURI=$Se;function hat(t,e,r){let n=new jZ(t,e),i=n;return dat.ParseTreeWalker.DEFAULT.walk(i,r),{tables:n.needTables,urls:n.needImports}}Up.findReferences=hat});var zSe=v($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});$p.TableFunctionSource=$p.TableMethodSource=$p.TableSource=void 0;var HSe=HZ(),pat=Px(),jSe=la(),v5=class extends pat.Source{structDef(){var e,r;let n=this.getTableInfo();if(n===void 0)return jSe.ErrorFactory.structDef;let{tablePath:i,connectionName:s}=n,o=(0,HSe.constructTableKey)(s,i),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(o),u=`Schema read failure for table '${i}' for connection '${s}'`;if(a){if(a.status==="present"){a.value.location=this.location,a.value.fields.forEach(c=>{c.location=this.location});let l={...a.value,fields:a.value.fields.map(c=>({...c,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(l),l}a.status==="error"&&(u=a.message)}return this.log(u),jSe.ErrorFactory.structDef}};$p.TableSource=v5;var zZ=class extends v5{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;let r=this.modelEntry(this.connectionName),n=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(n,{entry:{type:"connection",name:n},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}};$p.TableMethodSource=zZ;var GZ=class extends v5{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,HSe.deprecatedParseTableURI)(this.tableURI)}};$p.TableFunctionSource=GZ});var GSe=v(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.SQLStatement=void 0;var mat=EK(),gat=mt(),QZ=class extends gat.MalloyElement{constructor(e){super(),this.select=e,this.elementType="sqlStatement",this.has({select:e})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,mat.makeSQLBlock)(this.select.sqlPhrases(),this.connection)),this.requestBlock}lookupCompiledSQL(e){var r;let n=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(n)return n.reference(e.name,this.location),n.getEntry(e.name)}needs(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(n?.status==="reference")return{compileSQL:r,partialModel:this.select.containsQueries?e.modelDef():void 0}}execute(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(!n){this.log("Cant't look up schema for sql block");return}if(n.status==="error"){let i=n.message.split(/\r?\n/);this.select.log("Invalid SQL, "+i.join(`
678
678
  `));return}if(n.status==="present"){let i=this.select.location,s={...n.value,fields:n.value.fields.map(o=>({...o,location:i})),location:this.location};this.is&&!e.defineSQL(s,this.is)&&this.log(`'${this.is}' already defined`);return}}};vP.SQLStatement=QZ});var VSe=v(_P=>{"use strict";Object.defineProperty(_P,"__esModule",{value:!0});_P.SQLString=void 0;var yat=mt(),QSe=Np(),VZ=class extends yat.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(Eat)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof QSe.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.log("This element is not legal inside an SQL string")}sqlPhrases(){let e=[];for(let r of this.elements)if(typeof r=="string")e.push({sql:r});else{let n=r.getQuery();n?e.push(n.query()):r.sqLog("Cannot expand into a query")}return e}};_P.SQLString=VZ;function Eat(t){return t instanceof QSe.SourceQueryElement}});var WSe=v(bP=>{"use strict";Object.defineProperty(bP,"__esModule",{value:!0});bP.SourceDesc=void 0;var Sat=mt(),WZ=class extends Sat.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}};bP.SourceDesc=WZ});var YSe=v(TP=>{"use strict";Object.defineProperty(TP,"__esModule",{value:!0});TP.isSourceProperty=void 0;var Aat=Ym(),vat=CA(),_at=bA(),bat=kL(),Tat=VL(),Cat=qL(),Rat=$L(),Oat=HL(),Dat=GL();function Nat(t){return t instanceof Aat.Filter||t instanceof vat.Joins||t instanceof _at.DeclareFields||t instanceof bat.FieldListEdit||t instanceof Tat.Renames||t instanceof Cat.PrimaryKey||t instanceof Dat.ObjectAnnotation||t instanceof Rat.Views||t instanceof Oat.TimezoneStatement}TP.isSourceProperty=Nat});var XSe=v(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.isFieldCollectionMember=void 0;var Fat=NZ(),KSe=PA();function wat(t){return t instanceof KSe.FieldReference||t instanceof KSe.WildcardFieldReference||t instanceof Fat.AtomicFieldDeclaration}CP.isFieldCollectionMember=wat});var JSe=v(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.isQueryElement=void 0;var Lat=ZL(),Iat=rI(),Mat=dK(),Pat=yK();function kat(t){return t instanceof Lat.QueryArrow||t instanceof Iat.QueryRefine||t instanceof Mat.QueryReference||t instanceof Pat.QueryRaw}RP.isQueryElement=kat});var eAe=v(ZSe=>{"use strict";Object.defineProperty(ZSe,"__esModule",{value:!0})});var tAe=v(OP=>{"use strict";Object.defineProperty(OP,"__esModule",{value:!0});OP.isQueryProperty=void 0;function Bat(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}OP.isQueryProperty=Bat});var rAe=v(DP=>{"use strict";Object.defineProperty(DP,"__esModule",{value:!0});DP.isQueryExtendProperty=void 0;var qat=IZ(),Uat=CA(),$at=PZ();function jat(t){return t instanceof qat.Dimensions||t instanceof $at.Measures||t instanceof Uat.Joins}DP.isQueryExtendProperty=jat});var nAe=v(NP=>{"use strict";Object.defineProperty(NP,"__esModule",{value:!0});NP.isFieldPropStatement=void 0;var Hat=kI(),zat=Ym(),Gat=kA(),Qat=JI();function Vat(t){return t instanceof zat.Filter||t instanceof Gat.Limit||t instanceof Qat.PartitionBy||t instanceof Hat.FunctionOrdering}NP.isFieldPropStatement=Vat});var FP=v(ne=>{"use strict";var Wat=ne&&ne.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ie=ne&&ne.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Wat(e,t,r)};Object.defineProperty(ne,"__esModule",{value:!0});ie(mY(),ne);ie(o3e(),ne);ie(u3e(),ne);ie(Px(),ne);ie(tK(),ne);ie(Np(),ne);ie(A3e(),ne);ie(R3e(),ne);ie(O3e(),ne);ie(pK(),ne);ie(D3e(),ne);ie(kL(),ne);ie(qL(),ne);ie(VL(),ne);ie($L(),ne);ie(HL(),ne);ie(j3e(),ne);ie(LI(),ne);ie(H3e(),ne);ie(kI(),ne);ie(G3e(),ne);ie(Zm(),ne);ie(X3e(),ne);ie(HI(),ne);ie(J3e(),ne);ie(Z3e(),ne);ie(tye(),ne);ie(MK(),ne);ie(rye(),ne);ie(nye(),ne);ie(sye(),ne);ie(_X(),ne);ie(LK(),ne);ie(PI(),ne);ie(aye(),ne);ie(uye(),ne);ie(lye(),ne);ie(cye(),ne);ie(fye(),ne);ie(dye(),ne);ie(hye(),ne);ie(pye(),ne);ie(mye(),ne);ie(gye(),ne);ie(yye(),ne);ie(Eye(),ne);ie(Sye(),ne);ie(Aye(),ne);ie(bye(),ne);ie(Oye(),ne);ie(eSe(),ne);ie(tSe(),ne);ie(JI(),ne);ie(nSe(),ne);ie(IA(),ne);ie(iSe(),ne);ie(oSe(),ne);ie(FX(),ne);ie(hs(),ne);ie(aSe(),ne);ie(zJ(),ne);ie(EY(),ne);ie(uSe(),ne);ie(rI(),ne);ie(ZL(),ne);ie(QA(),ne);ie(lSe(),ne);ie(cSe(),ne);ie(dSe(),ne);ie(NSe(),ne);ie(NZ(),ne);ie(PA(),ne);ie(wSe(),ne);ie(LSe(),ne);ie(bA(),ne);ie(IZ(),ne);ie(zJ(),ne);ie(Ym(),ne);ie(uZ(),ne);ie(eZ(),ne);ie(CA(),ne);ie(hY(),ne);ie(kA(),ne);ie(PZ(),ne);ie(mY(),ne);ie(MSe(),ne);ie(dZ(),ne);ie(kSe(),ne);ie(SZ(),ne);ie(rZ(),ne);ie(pZ(),ne);ie(n5(),ne);ie(r5(),ne);ie(qSe(),ne);ie(AK(),ne);ie(zSe(),ne);ie(GSe(),ne);ie(VSe(),ne);ie(GL(),ne);ie(mI(),ne);ie(WSe(),ne);ie(YSe(),ne);ie(ir(),ne);ie(XSe(),ne);ie(u5(),ne);ie(mt(),ne);ie(JSe(),ne);ie(eAe(),ne);ie(tAe(),ne);ie(rAe(),ne);ie(nAe(),ne)});var sAe=v(Zc=>{"use strict";var Yat=Zc&&Zc.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Kat=Zc&&Zc.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xat=Zc&&Zc.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yat(e,t,r);return Kat(e,t),e};Object.defineProperty(Zc,"__esModule",{value:!0});Zc.MalloyToAST=void 0;var iAe=y8(),Jat=ZW(),L=Xat(FP()),Zat=Is(),eut=FP(),zn=WC(),YZ=Ke(),tut=Wm(),wP=class extends L.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}},_5=class extends L.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}},rut=["##! m4warnings=error"],KZ=class extends Jat.AbstractParseTreeVisitor{constructor(e,r,n){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=n;for(let i of rut){let s=tut.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,r){let n=`Internal Translator Error: ${r}`;return this.contextError(e,n),new Error(n)}astError(e,r,n="error"){this.msgLog.log({message:r,at:e.location,severity:n})}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}contextError(e,r,n="error"){this.msgLog.log({message:r,at:this.getLocation(e),severity:n})}inExperiment(e,r){let n=this.compilerFlags.tag("experimental");return n&&(n.bare()||n.has(e))?!0:(this.contextError(r,`Experimental flag '${e}' required to enable this feature`),!1)}m4Severity(){let e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r){let n=this.m4Severity();n&&this.contextError(e,r,n)}only(e,r,n){let i=[];for(let s of e){let o=r(s);o?i.push(o):s instanceof _5||this.astError(s,`Parser enountered unexpected statement type '${s.elementType}' when it needed '${n}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new L.FieldName((0,zn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new L.ModelEntryReference((0,zn.getId)(e)),e.id())}defaultResult(){return new L.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(r)},e}getSourceCode(e){let r=e.start.startIndex,n=e.stop||e.start,i=new Zat.Interval(r,n.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){let r=this.getFieldExpr(e),n=new L.FilterElement(r,this.getSourceCode(e));return this.astAt(n,e)}getFieldDefs(e,r){return e.map(n=>this.getFieldDef(n,r))}getFieldExpr(e){let r=this.visit(e);if(r instanceof L.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getFilterShortcut(e){let r=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new L.Filter([r])}getPlainString(e){let r=(0,zn.getStringIfShort)(e);if(r)return r;let n=[],i=e.string().sqlString();if(i){for(let s of(0,zn.getStringParts)(i))s instanceof iAe.ParserRuleContext?this.contextError(s,"%{ query } illegal in this string"):n.push(s);return(0,zn.unIndent)(n),n.join("")}return""}makeSqlString(e,r){for(let n of e.sqlInterpolation())n.CLOSE_CODE()&&this.m4advisory(n,"Use %{ ... } instead of %{ ... }%");for(let n of(0,zn.getStringParts)(e))n instanceof iAe.ParserRuleContext?r.push(this.visit(n)):r.push(n);r.complete(),this.astAt(r,e)}parseTime(e,r){let n=r(e.text);return n||(this.contextError(e,"Time data parse error"),n=new L.LiteralTimestamp({text:e.text})),this.astAt(n,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){let r=this.only(e.malloyStatement().map(n=>this.visit(n)),n=>L.isDocStatementOrDocStatementList(n)&&n,"statement");return new L.Document(r)}visitDefineSourceStatement(e){let n=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new L.DefineSourceList(n);return s.extendNote({blockNotes:i}),s}visitSourceDefinition(e){let r=this.visit(e.sqExplore()),n=new L.DefineSource((0,zn.getId)(e.sourceNameDef()),r instanceof L.SourceQueryElement?r:void 0,!0,[]),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return n.extendNote({notes:i}),this.astAt(n,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){let r=e.filterShortcut(),n=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>L.isSourceProperty(s)&&s,"source property"),i=new L.SourceDesc(n);return r&&i.push(this.getFilterShortcut(r)),i}visitTableFunction(e){let r=this.getPlainString(e.tableURI()),n=this.astAt(new L.TableFunctionSource(r),e);return this.m4advisory(e,"`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),n}visitTableMethod(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=this.getPlainString(e.tablePath());return this.astAt(new L.TableMethodSource(n,i),e)}getLegacySQLSouce(e){let r=this.getModelEntryName(e);return this.astAt(new L.FromSQLSource(r),e)}visitSqlSource(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=new L.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);let o=e.shortString();o&&i.push((0,zn.getShortString)(o));let a=new L.SQLSource(n,i);return this.astAt(a,e)}visitDefJoinMany(e){let r=[];for(let i of e.joinList().joinDef()){let s=this.visit(i);s instanceof L.Join&&(r.push(s),s instanceof L.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof L.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}let n=new L.Joins(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitDefJoinOne(e){let r=this.getJoinList(e.joinList()),n=[];for(let s of r)s instanceof L.Join&&(n.push(s),s instanceof L.ExpressionJoin&&(s.joinType="one"));let i=new L.Joins(n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinCross(e){let r=this.getJoinList(e.joinList()),n=[];for(let s of r)s instanceof L.Join&&(n.push(s),s instanceof L.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));let i=new L.Joins(n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return e.joinDef().map(r=>this.visit(r))}getJoinSource(e,r){if(r){let n=this.getSqExpr(r.sqExpr()),i=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:n,notes:i}}return{joinFrom:new L.SQReference(e),notes:[]}}visitQueryJoinStatement(e){let r=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"Joins in queries are deprecated, move into an `extend:` block."),r}visitJoinOn(e){var r;let n=this.getModelEntryName(e.joinNameDef()),{joinFrom:i,notes:s}=this.getJoinSource(n,e.isExplore()),o=new L.ExpressionJoin(n,i),a=e.joinExpression(),u=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,YZ.isMatrixOperation)(u)?o.matrixOperation=u:this.contextError(e,"Internal Error: Unknown matrixOperation"),a&&(o.joinOn=this.getFieldExpr(a)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){let r=this.getModelEntryName(e.joinNameDef()),{joinFrom:n,notes:i}=this.getJoinSource(r,e.isExplore()),s=this.getFieldExpr(e.fieldExpr()),o=new L.KeyJoin(r,n,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,r){let n=e.fieldExpr(),i=(0,zn.getId)(e.fieldNameDef()),s=this.getFieldExpr(n),o=new r(s,i,this.getSourceCode(n)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:a}),this.astAt(o,e)}visitDefDimensions(e){let r=this.getFieldDefs(e.defList().fieldDef(),L.DimensionFieldDeclaration),n=new L.Dimensions(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitDefMeasures(e){let r=this.getFieldDefs(e.defList().fieldDef(),L.MeasureFieldDeclaration),n=new L.Measures(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitQueryExtend(e){let r=[],n=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(let s of n)if(L.isQueryExtendProperty(s))r.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);let i=new L.ExtendBlock(r);return this.astAt(i,e)}visitDeclareStatement(e){let r=this.getFieldDefs(e.defList().fieldDef(),L.DeclareFieldDeclaration),n=new L.DeclareFields(r),i=this.astAt(n,e);return this.m4advisory(e,"`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),i}visitExploreRenameDef(e){let r=e.fieldName(0),n=e.fieldName(1),i=new L.RenameField((0,zn.getId)(r),this.getFieldName(n));return this.astAt(i,e)}visitDefExploreRename(e){let n=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new L.Renames(n);return this.astAt(i,e)}visitFilterClauseList(e){return new L.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){let r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){let r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitSubQueryDefList(e){let r=e.exploreQueryDef().map(n=>this.visitExploreQueryDef(n));return new L.Views(r)}visitDefExploreQuery(e){let r=this.visitSubQueryDefList(e.subQueryDefList()),n=this.getNotes(e.tags());return r.extendNote({blockNotes:n}),e.QUERY()&&this.m4advisory(e,"Use view: inside of a source instead of query:"),r}visitDefExplorePrimaryKey(e){let r=new L.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}visitFieldNameList(e){let r=e.fieldName().map(n=>new L.AcceptExceptFieldReference([this.getFieldName(n)]));return new L.FieldReferences(r)}visitDefExploreEditField(e){let r=e.ACCEPT()?"accept":"except";return new L.FieldListEdit(r,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){let r=this.getPlainString(e),n=this.astAt(new L.TimezoneStatement(r),e.string());return n.isValid||this.astError(n,`Invalid timezone: ${n.tz}`),this.astAt(n,e)}visitQueryProperties(e){let r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>L.isQueryProperty(i)&&i,"query statement"),n=e.filterShortcut();return n&&r.push(this.getFilterShortcut(n)),new L.QOpDesc(r)}getFieldPath(e,r){let n=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new r(n),e)}getQueryFieldDef(e,r){let n=this.getFieldDef(e,r);return this.astAt(n,e)}getQueryFieldEntry(e,r,n){let i=e.taggedRef();if(i)return this.getTaggedRef(i,r,n);let s=e.fieldDef();if(s)return this.getQueryFieldDef(s,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,n){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,r,n)),i=>i instanceof L.FieldReference||i instanceof L.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){let r=new L.Aggregate(this.getQueryItems(e.queryFieldList(),L.AggregateFieldDeclaration,L.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){let r=new L.GroupBy(this.getQueryItems(e.queryFieldList(),L.GroupByFieldDeclaration,L.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){let r=new L.Calculate(this.getQueryItems(e.queryFieldList(),L.CalculateFieldDeclaration,L.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,n){let i=e.refExpr();if(i){let o=this.getFieldPath(e.fieldPath(),L.ExpressionFieldReference),a,u=i.timeframe();u&&(a=new L.ExprGranularTime(new L.ExprIdReference(o),this.visitTimeframe(u).text,!0));let l=i.aggregate();if(l)if(l.text.toLowerCase()==="sum")a=new L.ExprSum(void 0,o);else return this.contextError(l,"'${aggFunc}' is not legal in a reference-only aggregation"),o;let c=new r(a,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}let s=this.getFieldPath(e.fieldPath(),n);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,r,n){let i=e.fieldDef();if(i)return this.getFieldDef(i,r);let s=e.taggedRef();if(s)return this.getTaggedRef(s,r,n);let o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){let r=e.collectionMember().map(n=>this.getFieldCollectionMember(n,L.ProjectFieldDeclaration,L.ProjectFieldReference));return this.astAt(new L.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project: keyword is deprecated, use select:");let r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;let n=e.fieldPath(),i=n?this.getFieldPath(n,L.ProjectFieldReference):void 0,s=this.astAt(new L.WildcardFieldReference(i),e),o=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(let a of o)for(let u of a.fieldName())s.except.add((0,zn.getId)(u));return s}visitIndexFields(e){let r=e.indexElement().map(n=>{let i=n.fieldPath();if(!i)return this.astAt(new L.WildcardFieldReference(void 0),e);let s=this.getFieldPath(i,L.IndexFieldReference);return n.STAR()?this.astAt(new L.WildcardFieldReference(s),e):this.astAt(s,e)});return new L.FieldReferences(r)}visitIndexStatement(e){let r=this.visitIndexFields(e.indexFields()),n=new L.Index(r),i=e.fieldName();return i&&n.useWeight(this.getFieldName(i)),this.astAt(n,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new L.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=this.getFieldExpr(e.fieldExpr());return this.astAt(new L.FunctionOrderBy(n,r),e)}visitAggregateOrderByStatement(e){return this.inExperiment("function_order_by",e),this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){let r=e.aggregateOrderBySpec().map(n=>this.visitAggregateOrderBySpec(n));return this.astAt(new L.FunctionOrdering(r),e)}visitOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.INTEGER_LITERAL();if(n)return new L.OrderBy(this.getNumber(n),r);let i=e.fieldName();if(i)return new L.OrderBy(this.getFieldName(i),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){let r=e.orderBySpec().map(n=>this.visitOrderBySpec(n));return this.astAt(new L.Ordering(r),e)}visitTopStatement(e){let r=e.bySpec(),n=this.getNumber(e.INTEGER_LITERAL()),i;if(r){this.m4advisory(r,"by clause of top statement unupported. Use order_by instead");let s=r.fieldName();if(s){let a=this.getFieldName(s);i=new L.Top(n,a)}let o=r.fieldExpr();o&&(i=new L.Top(n,this.getFieldExpr(o)))}return i||(i=new L.Top(n,void 0)),this.astAt(i,e)}visitSourceID(e){return this.astAt(new L.NamedSource((0,zn.getId)(e)),e)}visitTopLevelQueryDefs(e){let r=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),n=this.getNotes(e.tags()),i=new L.DefineQueryList(r);return i.extendNote({blockNotes:n}),i}visitTopLevelQueryDef(e){let r=(0,zn.getId)(e.queryName()),n=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(n instanceof L.SourceQueryElement){let s=new L.DefineQuery(r,n);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${n.elementType}'`)}visitAnonymousQuery(e){let r=e.topLevelAnonQueryDef(),n=this.getSqExpr(r.sqExpr()),i=this.astAt(new L.AnonymousQuery(n),r),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(r,"Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){let r=e.topLevelAnonQueryDef(),n=this.getSqExpr(r.sqExpr()),i=this.astAt(new L.AnonymousQuery(n),r),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){let r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new L.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof L.NestFieldDeclaration&&r,"query"))}visitNestExisting(e){let r=e.fieldPath(),n=this.getFieldPath(r,L.ViewOrScalarFieldReference),i=this.astAt(new L.ReferenceView(n),r),s=e.vExpr(),o=this.getNotes(e.tags());if(s){let u=new L.NestFieldDeclaration(n.nameString,new L.ViewRefine(i,this.getVExpr(s)));return u.extendNote({notes:o}),this.astAt(u,e)}let a=new L.NestFieldDeclaration(n.nameString,i);return a.extendNote({notes:o}),this.astAt(a,e)}visitNestDef(e){let r=(0,zn.getId)(e.queryName()),n=this.getVExpr(e.vExpr()),i=new L.NestFieldDeclaration(r,n);return i.extendNote({notes:this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()))}),this.astAt(i,e)}visitExploreQueryDef(e){let r=(0,zn.getId)(e.exploreQueryNameDef()),n=new L.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return n.extendNote({notes:i}),this.astAt(n,e)}visitExprNot(e){return new L.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new L.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new L.ExprLogicalOp(r,"or",n)}visitExprLogicalAnd(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new L.ExprLogicalOp(r,"and",n)}visitExprOrTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new L.ExprAlternationTree(r,"|",n),e)}visitExprAndTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new L.ExprAlternationTree(r,"&",n),e)}visitExprCoalesce(e){let r=this.getFieldExpr(e.fieldExpr()[0]),n=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new L.ExprCoalesce(r,n),e)}visitPartialAllowedFieldExpr(e){var r;let n=this.getFieldExpr(e.fieldExpr()),i=(r=e.compareOp())===null||r===void 0?void 0:r.text;if(i){if(L.isComparison(i))return this.astAt(new L.PartialCompare(i,n),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return n}visitExprString(e){let r=this.getPlainString(e);return new L.ExprString(r)}visitExprRegex(e){let r=e.HACKY_REGEX().text;return new L.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new L.ExprNow}visitExprNumber(e){return new L.ExprNumber(e.text)}visitExprFieldPath(e){let r=new L.ExprIdReference(this.getFieldPath(e.fieldPath(),L.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new L.ExprNULL}visitExprExpr(e){return new L.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new L.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new L.ExprAddSub(r,i,n)}visitExprMulDiv(e){let r=e.STAR()?"*":e.SLASH()?"/":"%";return new L.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){let r=e.compareOp().text;if(L.isComparison(r))return new L.ExprCompare(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)));throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprCountDisinct(e){return this.m4advisory(e,"`count(distinct expression)` deprecated, use `count(expression)` instead"),this.astAt(new L.ExprCountDistinct(this.getFieldExpr(e.fieldExpr())),e)}visitExprUngroup(e){let r=e.fieldName().map(i=>this.getFieldName(i)),n=e.ungroup().text.toLowerCase();return this.astAt(new L.ExprUngroup(n==="all"?n:"exclude",this.getFieldExpr(e.fieldExpr()),r),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){let r=e.fieldPath(),n=this.getFieldPath(r,L.ExpressionFieldReference),i=r&&n?this.astAt(n,r):void 0,s=e.aggregate().text.toLowerCase(),o=e.fieldExpr();if(e.aggregate().COUNT())return o&&this.contextError(o,"Expression illegal inside path.count()"),new L.ExprCount(i);let a=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(a)this.contextError(e,this.symmetricAggregateUsageError(s));else{let u=this.astAt(new L.ExprIdReference(n),r);return s==="min"?new L.ExprMin(u):new L.ExprMax(u)}else{if(s==="avg")return new L.ExprAvg(a,i);if(s==="sum")return new L.ExprSum(a,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new L.ExprNULL}visitExprPathlessAggregate(e){let r=e.fieldExpr(),n=r?this.getFieldExpr(r):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,`* illegal inside ${s}()`),s==="count")return this.astAt(n?new L.ExprCountDistinct(n):new L.ExprCount,e);if(s==="min"){if(n)return new L.ExprMin(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(n)return new L.ExprMax(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(n===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new L.ExprNULL;let o=e.SOURCE_KW()!==void 0;if(s==="avg")return new L.ExprAvg(n,i,o);if(s==="sum")return new L.ExprSum(n,i,o)}return new L.ExprNULL}visitExprApply(e){return new L.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new L.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new L.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyOrSQLType(e){let r=e.malloyType();if(r){let i=r.text;if((0,YZ.isCastType)(i))return i;throw this.internalError(e,`unknown type '${i}'`)}let n=e.string();if(n)return{raw:this.getPlainString({string:()=>n})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new L.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new L.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new L.Timeframe(e.text)}visitExprForRange(e){let r=this.getFieldExpr(e._startAt),n=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new L.ForRange(r,n,i)}visitExprAggFunc(e){let r=e.argumentList(),n=r?this.allFieldExpressions(r.fieldExpr()):[],i=(0,zn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,L.ExpressionFieldReference):void 0,a=s&&o?this.astAt(o,s):void 0;return L.ExprTimeExtract.extractor(i)?this.astAt(new L.ExprTimeExtract(i,n),e):this.astAt(new L.ExprFunc(i,n,!1,void 0,a),e)}visitExprFunc(e){var r,n;let i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text,u;a&&((0,YZ.isCastType)(a)?u=a:(this.contextError(e,`'#' assertion for unknown type '${a}'`),u=void 0));let l=(0,zn.getOptionalId)(e)||((n=e.timeframe())===null||n===void 0?void 0:n.text);return l===void 0&&(this.contextError(e,"Function name error"),l="FUNCTION_NAME_ERROR"),L.ExprTimeExtract.extractor(l)?this.astAt(new L.ExprTimeExtract(l,s),e):this.astAt(new L.ExprFunc(l,s,o,u),e)}visitExprDuration(e){return new L.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitPickStatement(e){let r=e.pick().map(n=>{let i;return n._pickValue&&(i=this.getFieldExpr(n._pickValue)),new L.PickWhen(i,this.getFieldExpr(n._pickWhen))});return e.ELSE()?new L.Pick(r,this.getFieldExpr(e._pickElse)):new L.Pick(r)}visitExprFieldProps(e){let r=this.only(e.fieldProperties().fieldPropertyStatement().map(n=>this.visit(n)),n=>L.isFieldPropStatement(n)&&n,"field property statement");return new L.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.inExperiment("partition_by",e),this.astAt(new L.PartitionBy(e.id().map(r=>this.astAt(new L.PartitionByFieldReference([this.astAt(new L.FieldName((0,zn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,L.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,L.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,L.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,L.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,L.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,L.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,L.LiteralYear.parse)}visitImportStatement(e){let r=this.getPlainString(e.importURL()),n=this.astAt(new L.ImportStatement(r,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(let s of i.importItem()){let o=s.id(),a=o[1]?this.astAt(new L.ImportSourceName((0,zn.idToStr)(o[1])),o[1]):void 0;n.push(this.astAt(new L.ImportSelect((0,zn.idToStr)(o[0]),a),o[0]))}return n}visitJustExpr(e){return this.getFieldExpr(e.fieldExpr())}visitDefineSQLStatement(e){var r;let n=(r=e.nameSQLBlock())===null||r===void 0?void 0:r.text,i=e.sqlBlock().blockSQLDef(),s=new L.SQLString,o;for(let l of i){let c=l.connectionName();c&&(o?this.contextError(c,"Cannot redefine connection"):o=this.getPlainString(c));let f=l.sqlString();f&&this.makeSqlString(f,s)}let a=new L.SQLStatement(s);o!==void 0&&(a.connection=o),a.is=n;let u=this.astAt(a,e);return this.m4advisory(e,"`sql:` statement is deprecated, use `connection_name.sql(...)` instead"),u}visitSampleStatement(e){let r=e.sampleSpec().INTEGER_LITERAL();if(r)return new L.SampleProperty({rows:this.getNumber(r)});let n=e.sampleSpec().PERCENT_LITERAL();if(n)return new L.SampleProperty({percent:this.getNumber(n)});let i=e.sampleSpec().TRUE()!==void 0;return new L.SampleProperty({enable:i})}visitDocAnnotations(e){let r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),n=new L.ModelAnnotation(r);return this.compilerFlags=n.getCompilerFlags(this.compilerFlags,this.msgLog),n}visitIgnoredObjectAnnotations(e){return this.contextError(e,"Object annotation not connected to any object"),new _5(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new _5(e.text)}visitDefExploreAnnotation(e){let r=this.getNotes(e);return new L.ObjectAnnotation(r)}visitSQID(e){let r=this.getModelEntryName(e);return this.astAt(new L.SQReference(r),e.id())}getSqExpr(e){let r=this.visit(e);return r instanceof L.SourceQueryElement?r:(this.contextError(e,`Expected a source/query expression, not '${r.elementType}'`),new wP)}visitSQExtendedSource(e){let r=this.getSqExpr(e.sqExpr()),n=new L.SQExtend(r,this.getSourceExtensions(e.exploreProperties()));return this.astAt(n,e)}visitSQParens(e){let r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQArrow(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new L.SQArrow(r,this.getVExpr(n));return this.astAt(i,e)}getVExpr(e){let r=this.visit(e);if(r instanceof L.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new L.ReferenceView(this.getFieldPath(e.fieldPath(),L.ViewOrScalarFieldReference))}visitSegOps(e){return new L.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new L.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new L.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new L.SQRefine(r,this.getVExpr(n));return this.astAt(i,e)}visitSQTable(e){let r=this.visit(e.exploreTable());if(r instanceof eut.TableSource){let n=new L.SQSource(r);return this.astAt(n,e)}return new wP}visitSQSQL(e){let r=new L.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new L.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}};Zc.MalloyToAST=KZ});var oAe=v(LP=>{"use strict";Object.defineProperty(LP,"__esModule",{value:!0});LP.MessageLog=void 0;var XZ=class{constructor(){this.rawLog=[]}getLog(){return this.rawLog}log(e){this.rawLog.push(e)}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(r=>r.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}};LP.MessageLog=XZ});var aAe=v(IP=>{"use strict";Object.defineProperty(IP,"__esModule",{value:!0});IP.Zone=void 0;var JZ=class{constructor(){this.location={},this.zone=new Map}get(e){let r=this.zone.get(e);if(r?.status==="present")return r.value}getEntry(e){let r=this.zone.get(e);return r?r.firstReference||!this.location[e]?r:{...r,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,r){this.zone.set(e,{status:"present",value:r})}reference(e,r){let n=this.zone.get(e);n?.status===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){let e=[];for(let[r,n]of this.zone)n.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(let[n,i]of Object.entries(e))i!==void 0&&this.define(n,i);if(r)for(let[n,i]of Object.entries(r))this.zone.set(n,{status:"error",message:i})}};IP.Zone=JZ});var uAe=v(ef=>{"use strict";var nut=ef&&ef.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),iut=ef&&ef.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sut=ef&&ef.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&nut(e,t,r);return iut(e,t),e};Object.defineProperty(ef,"__esModule",{value:!0});ef.walkForDocumentSymbols=void 0;var out=bp(),aut=sut(X9()),uut=WC(),ZZ=class{constructor(e,r,n,i){this.translator=e,this.tokens=r,this.scopes=n,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){let r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}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){let r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){let r=this.translator.rangeFromContext(e);this.scopes.push({range:r,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){let r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){let r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){let r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},n=this.peekScope();n&&n.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}handleNestEntry(e){let r={range:this.translator.rangeFromContext(e),name:e instanceof aut.NestExistingContext?e.fieldPath().text:e.queryName().id().text,type:"query",children:[]},n=this.peekScope();return n&&n.children.push(r),r}enterNestExisting(e){this.handleNestEntry(e)}enterNestDef(e){let r=this.handleNestEntry(e);this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){let r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},n=this.peekScope();n&&n.children.push(r)}enterQueryFieldEntry(e){var r;let n=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(n===void 0)return;let i={range:this.translator.rangeFromContext(e),name:n.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){let r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},n=this.peekScope();n&&n.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){let r={range:this.translator.rangeFromContext(e),name:e.joinNameDef().id().text,type:"join",children:[]},n=this.peekScope();n&&n.children.push(r)}enterDefineSQLStatement(e){let r=e.nameSQLBlock().text,n={range:this.translator.rangeFromContext(e),name:r,type:"sql",children:[]};this.symbols.push(n)}enterImportStatement(e){let r=(0,uut.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){let e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){let r=this.peekScope();if(r)for(let n of e.importItem()){let i={range:this.translator.rangeFromContext(e),name:n.text,type:"import_item",children:[]};r.children.push(i)}}};function lut(t,e,r){let n=new ZZ(t,e,[],[]),i=n;return out.ParseTreeWalker.DEFAULT.walk(i,r),n.symbols}ef.walkForDocumentSymbols=lut});var tee=v(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.sortHighlights=Ue.walkForDocumentHighlights=Ue.passForHighlights=Ue.HighlightType=void 0;var cut=bp(),Te=X9();Ue.HighlightType={Identifier:"identifier",Type:"type",Literal:{Date:"literal.date",Number:"literal.number",String:"literal.string",RegularExpression:"literal.regular_expression",Boolean:"literal.boolean",Null:"literal.null"},Call:{Aggregate:"call.aggregate",TimeFrame:"call.time_frame",Cast:"call.cast",Table:"call.table",From:"call.from",Function:"call.function",FromSQL:"call.from_sql"},Keyword:{AggregateModifier:{Distinct:"keyword.aggregate_modifier.distinct"},CastModifier:{As:"keyword.cast_modifier.as"},Is:"keyword.is",On:"keyword.on",Desc:"keyword.desc",Asc:"keyword.asc",Pick:"keyword.pick",When:"keyword.when",Else:"keyword.else",With:"keyword.with",JSON:"keyword.json",Turtle:"keyword.turtle",Import:"keyword.import"},Operator:{Comparison:"operator.comparison",Boolean:"operator.boolean",Date:"operator.date"},Comment:{Line:"comment.line",Block:"comment.block"},Property:{Accept:"property.accept",Aggregate:"property.aggregate",Dimension:"property.dimension",Except:"property.except",Source:"property.source",GroupBy:"property.group_by",Having:"property.having",Index:"property.index",JoinOne:"keyword.join_one",JoinMany:"keyword.join_many",JoinCross:"keyword.join_cross",Limit:"property.limit",Measure:"property.measure",Nest:"property.nest",OrderBy:"property.order_by",PrimaryKey:"property.primary_key",Project:"property.project",Query:"property.query",Rename:"property.rename",Top:"property.top",Where:"property.where",SQL:"property.sql"}};function fut(t){let e=[],r=(n,i,s=!1)=>{var o;let a=n.startIndex-n.charPositionInLine,u=((o=n.text)===null||o===void 0?void 0:o.split(`
679
679
  `))||[],l=u.length,c=u.slice(0,-1).reduce((x,d)=>x+d.length,0),f=s?1:0;e.push({type:i,range:{start:{line:n.line-1,character:n.startIndex-a},end:{line:n.line-1+l-1,character:n.stopIndex+2-(l>1?n.startIndex:a)-c-l-f}}})};for(let n=0;n<t.size;n++){let i=t.get(n);switch(i.type){case Te.MalloyParser.ACCEPT:r(i,Ue.HighlightType.Property.Accept,!0);break;case Te.MalloyParser.AGGREGATE:r(i,Ue.HighlightType.Property.Aggregate,!0);break;case Te.MalloyParser.DIMENSION:r(i,Ue.HighlightType.Property.Dimension,!0);break;case Te.MalloyParser.EXCEPT:r(i,Ue.HighlightType.Property.Except,!0);break;case Te.MalloyParser.GROUP_BY:r(i,Ue.HighlightType.Property.GroupBy,!0);break;case Te.MalloyParser.HAVING:r(i,Ue.HighlightType.Property.Having,!0);break;case Te.MalloyParser.INDEX:r(i,Ue.HighlightType.Property.Index,!0);break;case Te.MalloyParser.JOIN_CROSS:r(i,Ue.HighlightType.Property.JoinOne,!0);break;case Te.MalloyParser.JOIN_ONE:r(i,Ue.HighlightType.Property.JoinMany,!0);break;case Te.MalloyParser.JOIN_MANY:r(i,Ue.HighlightType.Property.JoinCross,!0);break;case Te.MalloyParser.LIMIT:r(i,Ue.HighlightType.Property.Limit,!0);break;case Te.MalloyParser.MEASURE:r(i,Ue.HighlightType.Property.Measure,!0);break;case Te.MalloyParser.NEST:r(i,Ue.HighlightType.Property.Nest,!0);break;case Te.MalloyParser.ORDER_BY:r(i,Ue.HighlightType.Property.OrderBy,!0);break;case Te.MalloyParser.PRIMARY_KEY:r(i,Ue.HighlightType.Property.PrimaryKey,!0);break;case Te.MalloyParser.PROJECT:r(i,Ue.HighlightType.Property.Project,!0);break;case Te.MalloyParser.QUERY:r(i,Ue.HighlightType.Property.Query,!0);break;case Te.MalloyParser.RENAME:r(i,Ue.HighlightType.Property.Rename,!0);break;case Te.MalloyParser.SOURCE:r(i,Ue.HighlightType.Property.Source,!0);break;case Te.MalloyParser.TOP:r(i,Ue.HighlightType.Property.Top,!0);break;case Te.MalloyParser.WHERE:r(i,Ue.HighlightType.Property.Where,!0);break;case Te.MalloyParser.SQL:r(i,Ue.HighlightType.Property.SQL,!0);break;case Te.MalloyParser.TABLE:r(i,Ue.HighlightType.Call.Table);break;case Te.MalloyParser.FROM:r(i,Ue.HighlightType.Call.From);break;case Te.MalloyParser.FROM_SQL:r(i,Ue.HighlightType.Call.FromSQL);break;case Te.MalloyParser.SQ_STRING:case Te.MalloyParser.DQ_STRING:r(i,Ue.HighlightType.Literal.String);break;case Te.MalloyParser.NUMERIC_LITERAL:case Te.MalloyParser.INTEGER_LITERAL:r(i,Ue.HighlightType.Literal.Number);break;case Te.MalloyParser.HACKY_REGEX:r(i,Ue.HighlightType.Literal.RegularExpression);break;case Te.MalloyParser.IS:r(i,Ue.HighlightType.Keyword.Is);break;case Te.MalloyParser.DISTINCT:r(i,Ue.HighlightType.Keyword.AggregateModifier.Distinct);break;case Te.MalloyParser.ON:r(i,Ue.HighlightType.Keyword.On);break;case Te.MalloyParser.DESC:r(i,Ue.HighlightType.Keyword.Desc);break;case Te.MalloyParser.ASC:r(i,Ue.HighlightType.Keyword.Asc);break;case Te.MalloyParser.CAST:r(i,Ue.HighlightType.Call.Cast);break;case Te.MalloyParser.AS:r(i,Ue.HighlightType.Keyword.CastModifier.As);break;case Te.MalloyParser.PICK:r(i,Ue.HighlightType.Keyword.Pick);break;case Te.MalloyParser.WHEN:r(i,Ue.HighlightType.Keyword.When);break;case Te.MalloyParser.WITH:r(i,Ue.HighlightType.Keyword.With);break;case Te.MalloyParser.ELSE:r(i,Ue.HighlightType.Keyword.Else);break;case Te.MalloyParser.JSON:r(i,Ue.HighlightType.Keyword.JSON);break;case Te.MalloyParser.TURTLE:r(i,Ue.HighlightType.Keyword.Turtle);break;case Te.MalloyParser.TRUE:case Te.MalloyParser.FALSE:r(i,Ue.HighlightType.Literal.Boolean);break;case Te.MalloyParser.NOW:case Te.MalloyParser.LITERAL_TIMESTAMP:case Te.MalloyParser.LITERAL_QUARTER:case Te.MalloyParser.LITERAL_MONTH:case Te.MalloyParser.LITERAL_DAY:case Te.MalloyParser.LITERAL_WEEK:case Te.MalloyParser.LITERAL_YEAR:r(i,Ue.HighlightType.Literal.Date);break;case Te.MalloyParser.NULL:r(i,Ue.HighlightType.Literal.Null);break;case Te.MalloyParser.AND:case Te.MalloyParser.OR:case Te.MalloyParser.NOT:r(i,Ue.HighlightType.Operator.Boolean);break;case Te.MalloyParser.FOR:r(i,Ue.HighlightType.Operator.Date);break;case Te.MalloyParser.COMMENT_TO_EOL:r(i,Ue.HighlightType.Comment.Line);break;case Te.MalloyParser.BLOCK_COMMENT:r(i,Ue.HighlightType.Comment.Block);break;case Te.MalloyParser.SUM:case Te.MalloyParser.COUNT:case Te.MalloyParser.AVG:case Te.MalloyParser.MIN:case Te.MalloyParser.MAX:r(i,Ue.HighlightType.Call.Aggregate);break;case Te.MalloyParser.IDENTIFIER:case Te.MalloyParser.BQ_STRING:r(i,Ue.HighlightType.Identifier);break;case Te.MalloyParser.STRING:case Te.MalloyParser.NUMBER:case Te.MalloyParser.BOOLEAN:case Te.MalloyParser.DATE:case Te.MalloyParser.TIMESTAMP:r(i,Ue.HighlightType.Type);break;case Te.MalloyParser.SECOND:case Te.MalloyParser.MINUTE:case Te.MalloyParser.HOUR:case Te.MalloyParser.DAY:case Te.MalloyParser.WEEK:case Te.MalloyParser.MONTH:case Te.MalloyParser.QUARTER:case Te.MalloyParser.YEAR:r(i,Ue.HighlightType.Call.TimeFrame);break;case Te.MalloyParser.IMPORT:r(i,Ue.HighlightType.Keyword.Import);break}}return e}Ue.passForHighlights=fut;var eee=class{constructor(e,r){this.tokens=e,this.highlights=r}rangeOf(e){let r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}enterExprFunc(e){let r=e.id()||e.timeframe();r&&this.highlights.push({range:this.rangeOf(r),type:Ue.HighlightType.Call.Function})}};function xut(t,e){let r=new eee(t,[]),n=r;return cut.ParseTreeWalker.DEFAULT.walk(n,e),r.highlights}Ue.walkForDocumentHighlights=xut;function dut(t){return t.sort((e,r)=>e.range.start.line<r.range.start.line?-1:e.range.start.line>r.range.start.line?1:e.range.start.character<r.range.start.character?-1:e.range.start.character>r.range.start.character?1:0)}Ue.sortHighlights=dut});var lAe=v(MP=>{"use strict";Object.defineProperty(MP,"__esModule",{value:!0});MP.walkForDocumentCompletions=void 0;var hut=bp(),put=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],mut=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],gut=["source","explore","query","sql"],ree=class{constructor(e,r,n){this.tokens=e,this.completions=r,this.position=n}rangeOf(e){let r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){let{start:r,end:n}=e,i=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,s=this.position.line<n.line||this.position.line===n.line&&this.position.character<=n.character;return i&&s}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(let n of e.exploreStatement())this.inRange(this.rangeOf(n))&&(r=!0);if(!r)for(let n of put)this.completions.push({type:"explore_property",text:`${n}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(let n of e.queryStatement())this.inRange(this.rangeOf(n))&&(r=!0);if(!r)for(let n of mut)this.completions.push({type:"query_property",text:`${n}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(let n of e.malloyStatement())this.inRange(this.rangeOf(n))&&(r=!0);if(!r)for(let n of gut)this.completions.push({type:"model_property",text:`${n}: `})}}};function yut(t,e,r){let n=new ree(t,[],r),i=n;return hut.ParseTreeWalker.DEFAULT.walk(i,e),n.completions}MP.walkForDocumentCompletions=yut});var cAe=v(PP=>{"use strict";Object.defineProperty(PP,"__esModule",{value:!0});PP.walkForDocumentHelpContext=void 0;var Eut=tY(),nee=class extends Eut.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){let r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.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 r=this.defaultResult();if(this.inRange(this.rangeOf(e))){r={type:this.type,token:e.start.text};let n=e.childCount;for(let i=0;i<n;i++){let o=e.getChild(i).accept(this);o&&(r=this.aggregateResult(r,o))}}return r}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,r){return r}};function Sut(t,e){return new nee(e).visit(t)}PP.walkForDocumentHelpContext=Sut});var iee=v(kP=>{"use strict";Object.defineProperty(kP,"__esModule",{value:!0});kP.locationContainsPosition=void 0;function Aut(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)}kP.locationContainsPosition=Aut});var fAe=v(BP=>{"use strict";Object.defineProperty(BP,"__esModule",{value:!0});BP.ReferenceList=void 0;var vut=iee(),see=class{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let r=0,n=this.references.length;for(;r<n;){let i=Math.floor((r+n)/2),s=this.references[i].location.range.end;s.line<e.line||s.line===e.line&&s.character<e.character?r=i+1:n=i}return r}add(e){if(e.location.url!==this.sourceURL)return;let r=this.findIndexBefore(e.location.range.end);r<this.references.length&&this.isPositionEqual(e,this.references[r])||this.references.splice(r,0,e)}isPositionEqual(e,r){let n=e.location.range,i=r.location.range;return n.start.line===i.start.line&&n.start.character===i.start.character&&n.end.line===i.end.line&&n.end.character===i.end.character}find(e){let r=this.findIndexBefore(e);if(r===this.references.length)return;let n=this.references[r];if((0,vut.locationContainsPosition)(n.location,e))return n}};BP.ReferenceList=see});var xAe=v(qP=>{"use strict";Object.defineProperty(qP,"__esModule",{value:!0});qP.isNeedResponse=void 0;function _ut(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}qP.isNeedResponse=_ut});var dAe=v(UP=>{"use strict";Object.defineProperty(UP,"__esModule",{value:!0});UP.walkForModelAnnotation=void 0;var but=bp(),oee=class{constructor(e,r,n){this.translator=e,this.tokens=r,this.parseInfo=n,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}enterDocAnnotations(e){let r=e.DOC_ANNOTATION().map(n=>({text:n.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}};function Tut(t,e,r){let n=new oee(t,e,r),i=n;return but.ParseTreeWalker.DEFAULT.walk(i,r.root),n.annotation}UP.walkForModelAnnotation=Tut});var mAe=v(Hs=>{"use strict";var Cut=Hs&&Hs.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Rut=Hs&&Hs.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Out=Hs&&Hs.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cut(e,t,r);return Rut(e,t),e};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.MalloyParserErrorHandler=Hs.MalloyTranslator=Hs.MalloyChildTranslator=Hs.MalloyTranslation=void 0;var hAe=y8(),Dut=Tge(),Nut=X9(),$P=Out(FP()),Fut=sAe(),wut=oAe(),Lut=HZ(),aee=aAe(),Iut=uAe(),uee=tee(),Mut=lAe(),Put=cAe(),kut=fAe(),jP=xAe(),But=iee(),pAe=Wm(),qut=dAe(),lee=class extends Dut.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}},cee=class{step(e){if(this.response)return this.response;if(e.urlIsFullPath===void 0)try{let s=new URL(e.sourceURL);e.urlIsFullPath=!0}catch(s){let o=s instanceof Error?s.message:"";e.urlIsFullPath=!1,e.root.logger.log({message:`Could not compute full path URL: ${o}`,severity:"error"})}if(!e.urlIsFullPath)return e.fatalResponse();let r=e.root.importZone.getEntry(e.sourceURL);if(r.status!=="present"){if(r.status==="error"){let s=r.message.includes(e.sourceURL)?`import error: ${r.message}`:`import '${e.sourceURL}' error: ${r.message}`,o=r.firstReference||e.defaultLocation();return e.root.logger.log({message:s,at:o,severity:"error"}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}let n=r.value===""?`
680
680
  `:r.value;this.sourceInfo=this.getSourceInfo(n);let i;try{i=this.runParser(n,e)}catch(s){e.root.logger.log({message:`Malloy internal parser exception [${s.message}]`,severity:"error"}),i=void 0}return e.root.logger.hasErrors()?this.response={parse:i,...e.fatalResponse()}:this.response={parse:i},this.response}getSourceInfo(e){let r=/\r?\n/,n={at:[],lines:[],length:e.length},i=e,s=0;for(;i!=="";){let o=i.match(r);if(o&&o.index!==void 0){n.lines.push(i.slice(0,o.index));let a=o.index+o[0].length;n.at.push({begin:s,end:s+a}),s+=a,i=i.slice(a)}else{n.lines.push(i),n.at.push({begin:s,end:s+i.length});break}}return n}runParser(e,r){let n=hAe.CharStreams.fromString(e),i=new lee(n),s=new hAe.CommonTokenStream(i),o=new Nut.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new zP(r,r.root.logger));let a=o[r.grammarRule];if(!a)throw new Error(`No such parse rule as ${r.grammarRule}`);return{root:a.call(o),tokenStream:s,sourceStream:n,sourceURL:r.sourceURL,importBaseURL:r.importBaseURL||r.sourceURL,rangeFromContext:u=>r.rangeFromContext(u),malloyVersion:"4.0.0"}}},fee=class{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){let r=this.parseStep.step(e);if(r.parse===void 0)return r;if(!this.parseReferences){this.parseReferences=(0,Lut.findReferences)(e,r.parse.tokenStream,r.parse.root);for(let o in this.parseReferences.tables)e.root.schemaZone.reference(o,{url:e.sourceURL,range:this.parseReferences.tables[o].firstReference});for(let o in this.parseReferences.urls){let a=this.parseReferences.urls[o];try{let u=decodeURI(new URL(o,e.importBaseURL||e.sourceURL).toString());e.addChild(u),e.imports.push({importURL:u,location:{url:e.sourceURL,range:a}}),e.root.importZone.reference(u,{url:e.sourceURL,range:a})}catch{e.root.logger.log({message:`Malformed URL '${o}'"`,at:{url:e.sourceURL,range:a},severity:"error"})}}}if(e.root.logger.hasErrors())return null;let n={},i=e.root.schemaZone.getUndefined();if(i){let o={};for(let a of i){let u=this.parseReferences.tables[a];o[a]={connectionName:u.connectionName,tablePath:u.tablePath}}n={tables:o}}let s=e.root.importZone.getUndefined();if(s&&(n={...n,urls:s}),(0,jP.isNeedResponse)(n))return n;for(let o of e.childTranslators.values()){let a=o.importsAndTablesStep.step(o);if((0,jP.isNeedResponse)(a))return a}return null}},xee=class{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;let r=this.importStep.step(e);if(r)return r;let n=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;let i=n?.parse;if(!i)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");let s=new Fut.MalloyToAST(i,e.root.logger,e.compilerFlags),o=s.visit(i.root);if(e.compilerFlags=s.compilerFlags,e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;if(o.elementType==="unimplemented")throw new Error("TRANSLATOR INTERNAL ERROR: Unimplemented AST node");let a={};if(!this.walked){for(let u of o.walk())u instanceof $P.FromSQLSource?(a[u.refName]||(a[u.refName]={}),a[u.refName].ref=u):u instanceof $P.SQLStatement&&u.is?(a[u.is]||(a[u.is]={}),a[u.is].def=u):u instanceof $P.Unimplemented&&u.log("INTERNAL COMPILER ERROR: Untranslated parse node");this.walked=!0}if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;for(let u of e.childTranslators.values()){let l=u.astStep.step(u);if((0,jP.isNeedResponse)(l))return l}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}},dee=class{constructor(e){this.parseStep=e}step(e){if(!this.response){let r=this.parseStep.step(e);if(r.parse){let n;try{n=(0,Iut.walkForDocumentSymbols)(e,r.parse.tokenStream,r.parse.root)}catch{}let i;try{i=(0,uee.walkForDocumentHighlights)(r.parse.tokenStream,r.parse.root)}catch{i=[]}this.response={symbols:n,highlights:(0,uee.sortHighlights)([...(0,uee.passForHighlights)(r.parse.tokenStream),...i]),final:!0}}else return r}return this.response}},hee=class{constructor(e){this.parseStep=e}step(e,r){let n=this.parseStep.step(e);if(n.parse){let i=[];if(r!==void 0)try{i=(0,Mut.walkForDocumentCompletions)(n.parse.tokenStream,n.parse.root,r)}catch{}return{...n,completions:i}}else return n}},pee=class{constructor(e){this.parseStep=e}step(e,r){let n=this.parseStep.step(e);if(n.parse){let i;if(r!==void 0)try{i=(0,Put.walkForDocumentHelpContext)(n.parse.root,r)}catch{}return{...n,helpContext:i}}else return n}},mee=class{constructor(e){this.parseStep=e}step(e,r){if(!this.response){let n=this.parseStep.step(e);if(!n.parse||n.final)return n;{let i=(0,qut.walkForModelAnnotation)(e,n.parse.tokenStream,n.parse);this.response={modelAnnotation:{...i,inherits:r?.annotation}}}}return this.response}},gee=class{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,r){if(this.response)return this.response;if(r&&!this.importedAnnotations){let i=pAe.Tag.annotationToTag(r.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}let n=this.astStep.step(e);if((0,jP.isNeedResponse)(n))return n;if(!n.ast)return this.response=n,this.response;if(e.grammarRule==="malloyDocument")if(n.ast instanceof $P.Document){let i=n.ast;for(i.initModelDef(r);;){let s=i.compile();if(s.needs)return s.needs;e.modelDef=s.modelDef,e.queryList=s.queryList,e.sqlBlocks=s.sqlBlocks;break}}else e.root.logger.log({message:`'${e.sourceURL}' did not parse to malloy document`,at:e.defaultLocation(),severity:"error"});return e.root.logger.hasErrors()?this.response={fromSources:e.getDependencies(),...e.fatalResponse()}:this.response={translated:{modelDef:e.modelDef,queryList:e.queryList,sqlBlocks:e.sqlBlocks},fromSources:e.getDependencies(),...e.problemResponse(),final:!0},this.response}},b5=class{constructor(e,r=null,n="malloyDocument"){this.sourceURL=e,this.importBaseURL=r,this.grammarRule=n,this.queryList=[],this.sqlBlocks=[],this.imports=[],this.compilerFlags=new pAe.Tag,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new cee,this.modelAnnotationStep=new mee(this.parseStep),this.metadataStep=new dee(this.parseStep),this.completionsStep=new hee(this.parseStep),this.helpContextStep=new pee(this.parseStep),this.importsAndTablesStep=new fee(this.parseStep),this.astStep=new xee(this.importsAndTablesStep),this.translateStep=new gee(this.astStep),this.references=new kut.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new HP(e,this.root))}getDependencies(){let e=[this.sourceURL];for(let[r,n]of this.childTranslators)e.push(...n.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 r,n;if(e===this.sourceURL)return(r=this.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines;let i=this.childTranslators.get(e);if(i)return(n=i.parseStep.sourceInfo)===null||n===void 0?void 0:n.lines}codeAtLocation(e){let r=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return r[e.range.start.line].slice(e.range.start.character,e.range.end.character);let n="";n+=r[e.range.start.line].slice(e.range.start.character);for(let i=e.range.start.line+1;i<e.range.end.line;i++)n+=r[i];return n+=r[e.range.end.line].slice(0,e.range.end.character),n}prettyErrors(){let e="",r="";for(let n of this.root.logger.getLog()){let i=n.message,s=this.sourceURL;if(n.at){s=n.at.url;let o=n.at.range.start.line,a=n.at.range.start.character,u=this.getLineMap(n.at.url);if(u){let l=u[o];i=`line ${o+1}: ${n.message}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.121-dev240202151424",
3
+ "version": "0.0.121",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@lit/context": "^1.1.0",
28
- "@malloydata/malloy": "^0.0.121-dev240202151424",
28
+ "@malloydata/malloy": "^0.0.121",
29
29
  "@types/luxon": "^2.4.0",
30
30
  "lit": "^3.0.2",
31
31
  "lodash": "^4.17.20",