@malloydata/render 0.0.123-dev240205203117 → 0.0.123-dev240205203120

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.
@@ -25,7 +25,7 @@
25
25
  `)}vi.indent=Tke;function Cke(t){return`'${t.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}vi.generateSQLStringLiteral=Cke;var Zz=class t{constructor(e){this.clauses=[],e&&this.clauses.push(e)}clone(){let e=new t;return e.addChain(this),e}add(e){return this.clauses.push(e),this}addChain(e){return this.clauses.push(...e.clauses),this}empty(){return this.clauses.length===0}present(){return this.clauses.length>0}sqlOr(){return this.empty()?"":this.clauses.map(e=>`(${e})`).join("OR ")+`
26
26
  `}sql(e){if(this.empty())return"";let r="",n="";return e&&(r=e.toUpperCase()+" ",n=`
27
27
  `),this.clauses.length===1?r+this.clauses[0]+n:r+this.clauses.map(i=>`(${i})`).join(`
28
- AND `)+n}};vi.AndChain=Zz;function Rke(t){return(0,bke.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}vi.generateHash=Rke;function po(t,e){return t.flatMap(r=>e(r).map(i=>{if(typeof i=="string")return i;switch(i.type){case"aggregate":case"all":case"spread":case"sql_expression":case"exclude":return{...i,e:po(i.e,e)};case"apply":return{...i,to:po(i.to,e),value:po(i.value,e)};case"applyVal":case"field":case"function_parameter":case"parameter":case"outputField":case"source-reference":case"aggregate_limit":case"aggregate_order_by":return i;case"sql-string":return{...i,e:po(i.e,e)};case"function_call":return{...i,args:i.args.map(s=>po(s,e))};case"filterExpression":return{...i,e:po(i.e,e),filterList:i.filterList.map(s=>({...s,expression:po(s.expression,e)}))};case"dialect":switch(i.function){case"cast":case"regexpMatch":return{...i,expr:po(i.expr,e)};case"delta":return{...i,delta:po(i.delta,e)};case"div":return{...i,denominator:po(i.denominator,e),numerator:po(i.numerator,e)};case"now":case"numberLiteral":case"stringLiteral":case"timeLiteral":case"regexpLiteral":return i;case"extract":case"trunc":return{...i,expr:{...i.expr,value:po(i.expr.value,e)}};case"timeDiff":return{...i,left:{...i.left,value:po(i.left.value,e)},right:{...i.left,value:po(i.left.value,e)}};default:throw new Error("unexpected dialect function")}default:throw new Error("unexpected")}}))}vi.exprMap=po;function mo(t,e){t.forEach(r=>{if(e(r),typeof r=="string")return r;switch(r.type){case"aggregate":case"all":case"spread":case"sql_expression":case"exclude":return{...r,e:mo(r.e,e)};case"apply":return{...r,to:mo(r.to,e),value:mo(r.value,e)};case"applyVal":case"field":case"function_parameter":case"parameter":case"outputField":case"source-reference":case"aggregate_limit":case"aggregate_order_by":return r;case"function_call":return{...r,args:r.args.map(n=>mo(n,e))};case"sql-string":return{...r,e:mo(r.e,e)};case"filterExpression":return{...r,e:mo(r.e,e),filterList:r.filterList.map(n=>({...n,expression:mo(n.expression,e)}))};case"dialect":switch(r.function){case"cast":case"regexpMatch":return{...r,expr:mo(r.expr,e)};case"delta":return{...r,delta:mo(r.delta,e)};case"div":return{...r,denominator:mo(r.denominator,e),numerator:mo(r.numerator,e)};case"now":case"numberLiteral":case"stringLiteral":case"timeLiteral":case"regexpLiteral":return r;case"extract":case"trunc":return{...r,expr:{...r.expr,value:mo(r.expr.value,e)}};case"timeDiff":return{...r,left:{...r.left,value:mo(r.left.value,e)},right:{...r.left,value:mo(r.left.value,e)}};default:throw new Error("unexpected dialect function")}default:throw new Error(`unexpected fragment type ${r.type}`)}})}vi.exprWalk=mo;function Oke(t,e){let r=[];for(let n=0;n<t.length;n++)r.push(...t[n]),n<t.length-1&&r.push(e);return r}vi.joinWith=Oke;function Dke(t,e){return Array.from({length:e-t},(r,n)=>n+t)}vi.range=Dke});var tfe=v(cN=>{"use strict";Object.defineProperty(cN,"__esModule",{value:!0});cN.fnConcat=void 0;var Ua=Pe();function Nke(){return[(0,Ua.overload)((0,Ua.minScalar)("string"),[],[{type:"dialect",function:"stringLiteral",literal:""}]),(0,Ua.overload)((0,Ua.minScalar)("string"),[(0,Ua.params)("values",(0,Ua.anyExprType)("string"),(0,Ua.anyExprType)("number"),(0,Ua.anyExprType)("date"),(0,Ua.anyExprType)("timestamp"),(0,Ua.anyExprType)("boolean"))],(0,Ua.sql)`CONCAT(${(0,Ua.spread)((0,Ua.arg)("values"))})`)]}cN.fnConcat=Nke});var rfe=v(fN=>{"use strict";Object.defineProperty(fN,"__esModule",{value:!0});fN.fnTrunc=void 0;var tc=Pe();function Fke(){let t=(0,tc.makeParam)("value",(0,tc.anyExprType)("number")),e=(0,tc.makeParam)("precision",(0,tc.anyExprType)("number"));return[(0,tc.overload)((0,tc.minScalar)("number"),[t.param],(0,tc.sql)`TRUNC(${t.arg})`),(0,tc.overload)((0,tc.minScalar)("number"),[t.param,e.param],(0,tc.sql)`TRUNC(${t.arg}, ${e.arg})`)]}fN.fnTrunc=Fke});var nfe=v(xN=>{"use strict";Object.defineProperty(xN,"__esModule",{value:!0});xN.fnStddev=void 0;var lb=Pe();function wke(){let t=(0,lb.makeParam)("value",(0,lb.maxScalar)("number"));return[(0,lb.overload)((0,lb.minAggregate)("number"),[t.param],(0,lb.sql)`STDDEV(${t.arg})`)]}xN.fnStddev=wke});var ife=v(dN=>{"use strict";Object.defineProperty(dN,"__esModule",{value:!0});dN.fnRound=void 0;var rc=Pe();function Lke(){let t=(0,rc.makeParam)("value",(0,rc.anyExprType)("number")),e=(0,rc.makeParam)("precision",(0,rc.anyExprType)("number"));return[(0,rc.overload)((0,rc.minScalar)("number"),[t.param],(0,rc.sql)`ROUND(${t.arg})`),(0,rc.overload)((0,rc.minScalar)("number"),[t.param,e.param],(0,rc.sql)`ROUND(${t.arg}, ${e.arg})`)]}dN.fnRound=Lke});var sfe=v(hN=>{"use strict";Object.defineProperty(hN,"__esModule",{value:!0});hN.fnLower=void 0;var cb=Pe();function Ike(){let t=(0,cb.makeParam)("base",(0,cb.anyExprType)("string"));return[(0,cb.overload)((0,cb.minScalar)("string"),[t.param],(0,cb.sql)`LOWER(${t.arg})`)]}hN.fnLower=Ike});var ofe=v(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});jd.fnUnicode=jd.fnAscii=jd.fnChr=void 0;var ii=Pe();function Mke(){return[(0,ii.overload)((0,ii.minScalar)("string"),[(0,ii.param)("value",(0,ii.anyExprType)("number"))],(0,ii.sql)`CASE WHEN ${(0,ii.arg)("value")} = 0 THEN '' ELSE CHR(${(0,ii.arg)("value")}) END`)]}jd.fnChr=Mke;function Pke(){return[(0,ii.overload)((0,ii.minScalar)("number"),[(0,ii.param)("value",(0,ii.anyExprType)("string"))],(0,ii.sql)`ASCII(${(0,ii.arg)("value")})`)]}jd.fnAscii=Pke;function kke(){return[(0,ii.overload)((0,ii.minScalar)("number"),[(0,ii.param)("value",(0,ii.anyExprType)("string"))],(0,ii.sql)`UNICODE(${(0,ii.arg)("value")})`)]}jd.fnUnicode=kke});var afe=v(pN=>{"use strict";Object.defineProperty(pN,"__esModule",{value:!0});pN.fnUpper=void 0;var fb=Pe();function Bke(){let t=(0,fb.makeParam)("value",(0,fb.anyExprType)("string"));return[(0,fb.overload)((0,fb.minScalar)("string"),[t.param],(0,fb.sql)`UPPER(${t.arg})`)]}pN.fnUpper=Bke});var ufe=v(mN=>{"use strict";Object.defineProperty(mN,"__esModule",{value:!0});mN.fnSubstr=void 0;var wu=Pe();function qke(){let t=(0,wu.makeParam)("value",(0,wu.anyExprType)("string")),e=(0,wu.makeParam)("position",(0,wu.anyExprType)("number")),r=(0,wu.makeParam)("length",(0,wu.anyExprType)("number"));return[(0,wu.overload)((0,wu.minScalar)("string"),[t.param,e.param],(0,wu.sql)`SUBSTR(${t.arg}, ${e.arg})`),(0,wu.overload)((0,wu.minScalar)("string"),[t.param,e.param,r.param],(0,wu.sql)`SUBSTR(${t.arg}, ${e.arg}, ${r.arg})`)]}mN.fnSubstr=qke});var lfe=v(gN=>{"use strict";Object.defineProperty(gN,"__esModule",{value:!0});gN.fnRegexpExtract=void 0;var _1=Pe();function Uke(){let t=(0,_1.makeParam)("value",(0,_1.anyExprType)("string")),e=(0,_1.makeParam)("pattern",(0,_1.anyExprType)("regular expression"));return[(0,_1.overload)((0,_1.minScalar)("string"),[t.param,e.param],(0,_1.sql)`REGEXP_EXTRACT(${t.arg}, ${e.arg})`)]}gN.fnRegexpExtract=Uke});var cfe=v(yN=>{"use strict";Object.defineProperty(yN,"__esModule",{value:!0});yN.fnReplace=void 0;var Xo=Pe();function $ke(){let t=(0,Xo.makeParam)("value",(0,Xo.anyExprType)("string")),e=(0,Xo.makeParam)("pattern",(0,Xo.anyExprType)("string")),r=(0,Xo.makeParam)("pattern",(0,Xo.anyExprType)("regular expression")),n=(0,Xo.makeParam)("replacement",(0,Xo.anyExprType)("string"));return[(0,Xo.overload)((0,Xo.minScalar)("string"),[t.param,e.param,n.param],(0,Xo.sql)`REPLACE(${t.arg}, ${e.arg}, ${n.arg})`),(0,Xo.overload)((0,Xo.minScalar)("string"),[t.param,r.param,n.param],(0,Xo.sql)`REGEXP_REPLACE(${t.arg}, ${r.arg}, ${n.arg})`)]}yN.fnReplace=$ke});var ffe=v(X3=>{"use strict";Object.defineProperty(X3,"__esModule",{value:!0});X3.fnByteLength=X3.fnLength=void 0;var Lu=Pe();function jke(){return[(0,Lu.overload)((0,Lu.minScalar)("number"),[(0,Lu.param)("value",(0,Lu.anyExprType)("string"))],(0,Lu.sql)`LENGTH(${(0,Lu.arg)("value")})`)]}X3.fnLength=jke;function Hke(){return[(0,Lu.overload)((0,Lu.minScalar)("number"),[(0,Lu.param)("value",(0,Lu.anyExprType)("string"))],(0,Lu.sql)`BYTE_LENGTH(${(0,Lu.arg)("value")})`)]}X3.fnByteLength=Hke});var xfe=v(EN=>{"use strict";Object.defineProperty(EN,"__esModule",{value:!0});EN.fnIfnull=void 0;var Kf=Pe(),zke=["string","number","timestamp","date","json"];function Gke(){return zke.map(t=>(0,Kf.overload)((0,Kf.minScalar)(t),[(0,Kf.param)("value",(0,Kf.anyExprType)(t)),(0,Kf.param)("default",(0,Kf.anyExprType)(t))],(0,Kf.sql)`IFNULL(${(0,Kf.arg)("value")}, ${(0,Kf.arg)("default")})`))}EN.fnIfnull=Gke});var dfe=v(AN=>{"use strict";Object.defineProperty(AN,"__esModule",{value:!0});AN.fnNullif=void 0;var b1=Pe(),Qke=["string","number","timestamp","date","json"];function Vke(){return Qke.map(t=>{let e=(0,b1.makeParam)("value1",(0,b1.anyExprType)(t)),r=(0,b1.makeParam)("value2",(0,b1.anyExprType)(t));return(0,b1.overload)((0,b1.minScalar)(t),[e.param,r.param],(0,b1.sql)`NULLIF(${e.arg}, ${r.arg})`)})}AN.fnNullif=Vke});var hfe=v(SN=>{"use strict";Object.defineProperty(SN,"__esModule",{value:!0});SN.fnRowNumber=void 0;var eG=Pe();function Wke(){return[(0,eG.overload)((0,eG.minAnalytic)("number"),[],(0,eG.sql)`ROW_NUMBER()`,{needsWindowOrderBy:!0})]}SN.fnRowNumber=Wke});var pfe=v(vN=>{"use strict";Object.defineProperty(vN,"__esModule",{value:!0});vN.fnLag=void 0;var _i=Pe(),Yke=["string","number","timestamp","date","json","boolean"];function Kke(){return Yke.flatMap(t=>{let e=(0,_i.makeParam)("value",(0,_i.output)((0,_i.maxAggregate)(t))),r=(0,_i.makeParam)("offset",(0,_i.literal)((0,_i.maxScalar)("number"))),n=(0,_i.makeParam)("default",(0,_i.constant)((0,_i.maxAggregate)(t)));return[(0,_i.overload)((0,_i.minAnalytic)(t),[e.param],(0,_i.sql)`LAG(${e.arg})`,{needsWindowOrderBy:!0}),(0,_i.overload)((0,_i.minAnalytic)(t),[e.param,r.param],(0,_i.sql)`LAG(${e.arg}, ${r.arg})`,{needsWindowOrderBy:!0}),(0,_i.overload)((0,_i.minAnalytic)(t),[e.param,r.param,n.param],(0,_i.sql)`LAG(${e.arg}, ${r.arg}, ${n.arg})`,{needsWindowOrderBy:!0})]})}vN.fnLag=Kke});var mfe=v(_N=>{"use strict";Object.defineProperty(_N,"__esModule",{value:!0});_N.fnLead=void 0;var bi=Pe(),Xke=["string","number","timestamp","date","json","boolean"];function Jke(){return Xke.flatMap(t=>{let e=(0,bi.makeParam)("value",(0,bi.output)((0,bi.maxAggregate)(t))),r=(0,bi.makeParam)("offset",(0,bi.literal)((0,bi.maxScalar)("number"))),n=(0,bi.makeParam)("default",(0,bi.constant)((0,bi.maxAggregate)(t)));return[(0,bi.overload)((0,bi.minAnalytic)(t),[e.param],(0,bi.sql)`LEAD(${e.arg})`,{needsWindowOrderBy:!0}),(0,bi.overload)((0,bi.minAnalytic)(t),[e.param,r.param],(0,bi.sql)`LEAD(${e.arg}, ${r.arg})`,{needsWindowOrderBy:!0}),(0,bi.overload)((0,bi.minAnalytic)(t),[e.param,r.param,n.param],(0,bi.sql)`LEAD(${e.arg}, ${r.arg}, ${n.arg})`,{needsWindowOrderBy:!0})]})}_N.fnLead=Jke});var gfe=v(bN=>{"use strict";Object.defineProperty(bN,"__esModule",{value:!0});bN.fnRank=void 0;var tG=Pe();function Zke(){return[(0,tG.overload)((0,tG.minAnalytic)("number"),[],(0,tG.sql)`RANK()`,{needsWindowOrderBy:!0})]}bN.fnRank=Zke});var Efe=v(J3=>{"use strict";Object.defineProperty(J3,"__esModule",{value:!0});J3.fnLastValueWindow=J3.fnFirstValueWindow=void 0;var Jo=Pe(),yfe=["string","number","timestamp","date","json"];function eBe(){return yfe.flatMap(t=>[(0,Jo.overload)((0,Jo.minAnalytic)(t),[(0,Jo.param)("value",(0,Jo.output)((0,Jo.maxAggregate)(t)))],(0,Jo.sql)`FIRST_VALUE(${(0,Jo.arg)("value")})`,{needsWindowOrderBy:!0})])}J3.fnFirstValueWindow=eBe;function tBe(){return yfe.flatMap(t=>[(0,Jo.overload)((0,Jo.minAnalytic)(t),[(0,Jo.param)("value",(0,Jo.output)((0,Jo.maxAggregate)(t)))],(0,Jo.sql)`LAST_VALUE(${(0,Jo.arg)("value")})`,{needsWindowOrderBy:!0,between:{preceding:-1,following:-1}})])}J3.fnLastValueWindow=tBe});var Afe=v(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.fnSumWindow=Zo.fnMaxWindow=Zo.fnMinWindow=Zo.fnSumCumulative=Zo.fnMaxCumulative=Zo.fnMinCumulative=void 0;var Ft=Pe(),Z3=["string","number","timestamp","date"];function rBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MIN(${e.arg})`,{needsWindowOrderBy:!0})]})}Zo.fnMinCumulative=rBe;function nBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MAX(${e.arg})`,{needsWindowOrderBy:!0})]})}Zo.fnMaxCumulative=nBe;function iBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`SUM(${e.arg})`,{needsWindowOrderBy:!0})]})}Zo.fnSumCumulative=iBe;function sBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MIN(${e.arg})`,{needsWindowOrderBy:!1})]})}Zo.fnMinWindow=sBe;function oBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MAX(${e.arg})`,{needsWindowOrderBy:!1})]})}Zo.fnMaxWindow=oBe;function aBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`SUM(${e.arg})`,{needsWindowOrderBy:!1})]})}Zo.fnSumWindow=aBe});var Sfe=v(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});ey.fnEndsWith=ey.fnStartsWith=void 0;var ea=Pe();function uBe(){let t=(0,ea.makeParam)("value",(0,ea.anyExprType)("string")),e=(0,ea.makeParam)("prefix",(0,ea.anyExprType)("string"));return[(0,ea.overload)((0,ea.minScalar)("boolean"),[t.param,e.param],(0,ea.sql)`COALESCE(STARTS_WITH(${t.arg}, ${e.arg}), false)`)]}ey.fnStartsWith=uBe;function lBe(){let t=(0,ea.makeParam)("value",(0,ea.anyExprType)("string")),e=(0,ea.makeParam)("suffix",(0,ea.anyExprType)("string"));return[(0,ea.overload)((0,ea.minScalar)("boolean"),[t.param,e.param],(0,ea.sql)`COALESCE(ENDS_WITH(${t.arg}, ${e.arg}), false)`)]}ey.fnEndsWith=lBe});var vfe=v(TN=>{"use strict";Object.defineProperty(TN,"__esModule",{value:!0});TN.fnIsInf=void 0;var ty=Pe();function cBe(){return[(0,ty.overload)((0,ty.minScalar)("boolean"),[(0,ty.param)("value",(0,ty.anyExprType)("number"))],(0,ty.sql)`COALESCE(IS_INF(${(0,ty.arg)("value")}), false)`)]}TN.fnIsInf=cBe});var _fe=v(CN=>{"use strict";Object.defineProperty(CN,"__esModule",{value:!0});CN.fnIsNan=void 0;var ry=Pe();function fBe(){return[(0,ry.overload)((0,ry.minScalar)("boolean"),[(0,ry.param)("value",(0,ry.anyExprType)("number"))],(0,ry.sql)`COALESCE(IS_NAN(${(0,ry.arg)("value")}), false)`)]}CN.fnIsNan=fBe});var bfe=v(RN=>{"use strict";Object.defineProperty(RN,"__esModule",{value:!0});RN.fnAtan2=void 0;var Xf=Pe();function xBe(){return[(0,Xf.overload)((0,Xf.minScalar)("number"),[(0,Xf.param)("y",(0,Xf.anyExprType)("number")),(0,Xf.param)("x",(0,Xf.anyExprType)("number"))],(0,Xf.sql)`ATAN2(${(0,Xf.arg)("y")}, ${(0,Xf.arg)("x")})`)]}RN.fnAtan2=xBe});var Tfe=v(ON=>{"use strict";Object.defineProperty(ON,"__esModule",{value:!0});ON.fnPow=void 0;var T1=Pe();function dBe(){let t=(0,T1.makeParam)("base",(0,T1.anyExprType)("number")),e=(0,T1.makeParam)("exponent",(0,T1.anyExprType)("number"));return[(0,T1.overload)((0,T1.minScalar)("number"),[t.param,e.param],(0,T1.sql)`POW(${t.arg}, ${e.arg})`)]}ON.fnPow=dBe});var Cfe=v(DN=>{"use strict";Object.defineProperty(DN,"__esModule",{value:!0});DN.fnLog=void 0;var C1=Pe();function hBe(){let t=(0,C1.makeParam)("value",(0,C1.anyExprType)("number")),e=(0,C1.makeParam)("base",(0,C1.anyExprType)("number"));return[(0,C1.overload)((0,C1.minScalar)("number"),[t.param,e.param],(0,C1.sql)`LOG(${t.arg}, ${e.arg})`)]}DN.fnLog=hBe});var Rfe=v(NN=>{"use strict";Object.defineProperty(NN,"__esModule",{value:!0});NN.fnStrpos=void 0;var R1=Pe();function pBe(){let t=(0,R1.makeParam)("test_string",(0,R1.anyExprType)("string")),e=(0,R1.makeParam)("search_string",(0,R1.anyExprType)("string"));return[(0,R1.overload)((0,R1.minScalar)("number"),[t.param,e.param],(0,R1.sql)`STRPOS(${t.arg}, ${e.arg})`)]}NN.fnStrpos=pBe});var Ofe=v(FN=>{"use strict";Object.defineProperty(FN,"__esModule",{value:!0});FN.fnDiv=void 0;var Jf=Pe();function mBe(){return[(0,Jf.overload)((0,Jf.minScalar)("number"),[(0,Jf.param)("dividend",(0,Jf.anyExprType)("number")),(0,Jf.param)("divisor",(0,Jf.anyExprType)("number"))],(0,Jf.sql)`DIV(${(0,Jf.arg)("dividend")}, ${(0,Jf.arg)("divisor")})`)]}FN.fnDiv=mBe});var Nfe=v(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});ny.fnLeast=ny.fnGreatest=void 0;var O1=Pe(),gBe=["string","number","timestamp","date","json"];function Dfe(t){return gBe.map(e=>(0,O1.overload)((0,O1.minScalar)(e),[(0,O1.params)("values",(0,O1.anyExprType)(e))],[(0,O1.sqlFragment)(`${t}(`,(0,O1.spread)((0,O1.arg)("values")),")")]))}var yBe=()=>Dfe("GREATEST");ny.fnGreatest=yBe;var EBe=()=>Dfe("LEAST");ny.fnLeast=EBe});var Ffe=v(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});Hd.fnRtrim=Hd.fnLtrim=Hd.fnTrim=void 0;var go=Pe();function rG(t){return[(0,go.overload)((0,go.minScalar)("string"),[(0,go.param)("value",(0,go.anyExprType)("string"))],[(0,go.sqlFragment)(`${t}(`,(0,go.arg)("value"),")")]),(0,go.overload)((0,go.minScalar)("string"),[(0,go.param)("value",(0,go.anyExprType)("string")),(0,go.param)("trim_characters",(0,go.anyExprType)("string"))],[(0,go.sqlFragment)(`${t}(`,(0,go.arg)("value"),",",(0,go.arg)("trim_characters"),")")])]}var ABe=()=>rG("TRIM");Hd.fnTrim=ABe;var SBe=()=>rG("LTRIM");Hd.fnLtrim=SBe;var vBe=()=>rG("RTRIM");Hd.fnRtrim=vBe});var wfe=v(wN=>{"use strict";Object.defineProperty(wN,"__esModule",{value:!0});wN.fnRand=void 0;var nG=Pe();function _Be(){return[(0,nG.overload)((0,nG.minScalar)("number"),[],(0,nG.sql)`RAND()`)]}wN.fnRand=_Be});var Lfe=v(LN=>{"use strict";Object.defineProperty(LN,"__esModule",{value:!0});LN.fnPi=void 0;var iG=Pe();function bBe(){return[(0,iG.overload)((0,iG.minScalar)("number"),[],(0,iG.sql)`PI()`)]}LN.fnPi=bBe});var Ife=v(IN=>{"use strict";Object.defineProperty(IN,"__esModule",{value:!0});IN.fnRepeat=void 0;var D1=Pe();function TBe(){let t=(0,D1.makeParam)("value",(0,D1.anyExprType)("string")),e=(0,D1.makeParam)("count",(0,D1.anyExprType)("number"));return[(0,D1.overload)((0,D1.minScalar)("string"),[t.param,e.param],(0,D1.sql)`REPEAT(${t.arg}, ${e.arg})`)]}IN.fnRepeat=TBe});var Mfe=v(MN=>{"use strict";Object.defineProperty(MN,"__esModule",{value:!0});MN.fnReverse=void 0;var xb=Pe();function CBe(){let t=(0,xb.makeParam)("value",(0,xb.anyExprType)("string"));return[(0,xb.overload)((0,xb.minScalar)("string"),[t.param],(0,xb.sql)`REVERSE(${t.arg})`)]}MN.fnReverse=CBe});var Pfe=v(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.fnExp=Xt.fnLn=Xt.fnSqrt=Xt.fnAbs=Xt.fnFloor=Xt.fnCeil=Xt.fnSign=Xt.fnAtan=Xt.fnTan=Xt.fnAsin=Xt.fnSin=Xt.fnAcos=Xt.fnCos=Xt.simple=void 0;var iy=Pe();function ta(t){return[(0,iy.overload)((0,iy.minScalar)("number"),[(0,iy.param)("value",(0,iy.anyExprType)("number"))],[(0,iy.sqlFragment)(`${t}(`,(0,iy.arg)("value"),")")])]}Xt.simple=ta;var RBe=()=>ta("COS");Xt.fnCos=RBe;var OBe=()=>ta("ACOS");Xt.fnAcos=OBe;var DBe=()=>ta("SIN");Xt.fnSin=DBe;var NBe=()=>ta("ASIN");Xt.fnAsin=NBe;var FBe=()=>ta("TAN");Xt.fnTan=FBe;var wBe=()=>ta("ATAN");Xt.fnAtan=wBe;var LBe=()=>ta("SIGN");Xt.fnSign=LBe;var IBe=()=>ta("CEIL");Xt.fnCeil=IBe;var MBe=()=>ta("FLOOR");Xt.fnFloor=MBe;var PBe=()=>ta("ABS");Xt.fnAbs=PBe;var kBe=()=>ta("SQRT");Xt.fnSqrt=kBe;var BBe=()=>ta("LN");Xt.fnLn=BBe;var qBe=()=>ta("EXP");Xt.fnExp=qBe});var kfe=v(PN=>{"use strict";Object.defineProperty(PN,"__esModule",{value:!0});PN.fnAvgRolling=void 0;var yo=Pe(),UBe=["string","number","timestamp","date"];function $Be(){return UBe.flatMap(t=>{let e=(0,yo.makeParam)("value",(0,yo.output)((0,yo.maxAggregate)(t))),r=(0,yo.makeParam)("preceding",(0,yo.literal)((0,yo.maxScalar)("number"))),n=(0,yo.makeParam)("following",(0,yo.literal)((0,yo.maxScalar)("number")));return[(0,yo.overload)((0,yo.minAnalytic)(t),[e.param,r.param],(0,yo.sql)`AVG(${e.arg})`,{needsWindowOrderBy:!0,between:{preceding:"preceding",following:0}}),(0,yo.overload)((0,yo.minAnalytic)(t),[e.param,r.param,n.param],(0,yo.sql)`AVG(${e.arg})`,{needsWindowOrderBy:!0,between:{preceding:"preceding",following:"following"}})]})}PN.fnAvgRolling=$Be});var Bfe=v(kN=>{"use strict";Object.defineProperty(kN,"__esModule",{value:!0});kN.FunctionMap=void 0;var sG=class t{constructor(e){this.functions=new Map,this.sealed=!1,this.getters=e??new Map}clone(){return new t(new Map(this.getters))}add(e,r){this.ensureNotSealed(),this.getters.set(e,r)}get(e){this.ensureSealed();let r=this.functions.get(e);if(r)return r;let n=this.getters.get(e);if(n===void 0)return;let i=n();return this.functions.set(e,i),i}delete(e){this.ensureNotSealed(),this.functions.delete(e),this.getters.delete(e)}seal(){this.sealed=!0}ensureNotSealed(){if(this.sealed)throw new Error("Cannot update sealed FunctionMap")}ensureSealed(){if(!this.sealed)throw new Error("Cannot get from unsealed FunctionMap")}};kN.FunctionMap=sG});var qfe=v(BN=>{"use strict";Object.defineProperty(BN,"__esModule",{value:!0});BN.fnCoalesce=void 0;var N1=Pe(),jBe=["string","number","timestamp","date","json"];function HBe(){return jBe.map(t=>(0,N1.overload)((0,N1.minScalar)(t),[(0,N1.params)("values",(0,N1.anyExprType)(t))],(0,N1.sql)`COALESCE(${(0,N1.spread)((0,N1.arg)("values"))})`))}BN.fnCoalesce=HBe});var Ufe=v(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});sy.fnStringAggDistinct=sy.fnStringAgg=void 0;var fn=Pe();function zBe(){let t=(0,fn.makeParam)("value",(0,fn.maxScalar)("string")),e=(0,fn.makeParam)("separator",(0,fn.literal)((0,fn.maxScalar)("string"))),r={type:"aggregate_order_by"};return[(0,fn.overload)((0,fn.minAggregate)("string"),[t.param],(0,fn.sql)`STRING_AGG(${t.arg}${r})`,{supportsOrderBy:!0,defaultOrderByArgIndex:0}),(0,fn.overload)((0,fn.minAggregate)("string"),[t.param,e.param],(0,fn.sql)`STRING_AGG(${t.arg}, ${e.arg}${r})`,{supportsOrderBy:!0,defaultOrderByArgIndex:0})]}sy.fnStringAgg=zBe;function GBe(){let t=(0,fn.makeParam)("value",(0,fn.maxScalar)("string")),e=(0,fn.makeParam)("separator",(0,fn.literal)((0,fn.maxScalar)("string"))),r={type:"aggregate_order_by"};return[(0,fn.overload)((0,fn.minAggregate)("string"),[t.param],(0,fn.sql)`STRING_AGG(DISTINCT ${t.arg}${r})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,fn.overload)((0,fn.minAggregate)("string"),[t.param,e.param],(0,fn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${r})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}sy.fnStringAggDistinct=GBe});var $fe=v(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.fnSqlBoolean=Iu.fnSqlTimestamp=Iu.fnSqlDate=Iu.fnSqlString=Iu.fnSqlNumber=void 0;var Or=Pe();function QBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("number"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlNumber=QBe;function VBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("string"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlString=VBe;function WBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("date"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlDate=WBe;function YBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("timestamp"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlTimestamp=YBe;function KBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("boolean"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlBoolean=KBe});var Vfe=v(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.FUNCTIONS=void 0;var XBe=tfe(),JBe=rfe(),ZBe=nfe(),eqe=ife(),tqe=sfe(),oG=ofe(),rqe=afe(),nqe=ufe(),iqe=lfe(),sqe=cfe(),jfe=ffe(),oqe=xfe(),aqe=dfe(),uqe=hfe(),lqe=pfe(),cqe=mfe(),fqe=gfe(),Hfe=Efe(),oy=Afe(),zfe=Sfe(),xqe=vfe(),dqe=_fe(),hqe=bfe(),pqe=Tfe(),mqe=Cfe(),gqe=Rfe(),yqe=Ofe(),Gfe=Nfe(),aG=Ffe(),Eqe=wfe(),Aqe=Lfe(),Sqe=Ife(),vqe=Mfe(),$a=Pfe(),_qe=kfe(),bqe=Bfe(),Tqe=qfe(),Qfe=Ufe(),db=$fe();Ne.FUNCTIONS=new bqe.FunctionMap;Ne.FUNCTIONS.add("concat",XBe.fnConcat);Ne.FUNCTIONS.add("round",eqe.fnRound);Ne.FUNCTIONS.add("trunc",JBe.fnTrunc);Ne.FUNCTIONS.add("floor",$a.fnFloor);Ne.FUNCTIONS.add("ceil",$a.fnCeil);Ne.FUNCTIONS.add("cos",$a.fnCos);Ne.FUNCTIONS.add("acos",$a.fnAcos);Ne.FUNCTIONS.add("sin",$a.fnSin);Ne.FUNCTIONS.add("asin",$a.fnAsin);Ne.FUNCTIONS.add("tan",$a.fnTan);Ne.FUNCTIONS.add("atan",$a.fnAtan);Ne.FUNCTIONS.add("atan2",hqe.fnAtan2);Ne.FUNCTIONS.add("lower",tqe.fnLower);Ne.FUNCTIONS.add("upper",rqe.fnUpper);Ne.FUNCTIONS.add("sqrt",$a.fnSqrt);Ne.FUNCTIONS.add("pow",pqe.fnPow);Ne.FUNCTIONS.add("abs",$a.fnAbs);Ne.FUNCTIONS.add("sign",$a.fnSign);Ne.FUNCTIONS.add("is_inf",xqe.fnIsInf);Ne.FUNCTIONS.add("is_nan",dqe.fnIsNan);Ne.FUNCTIONS.add("greatest",Gfe.fnGreatest);Ne.FUNCTIONS.add("least",Gfe.fnLeast);Ne.FUNCTIONS.add("div",yqe.fnDiv);Ne.FUNCTIONS.add("strpos",gqe.fnStrpos);Ne.FUNCTIONS.add("starts_with",zfe.fnStartsWith);Ne.FUNCTIONS.add("ends_with",zfe.fnEndsWith);Ne.FUNCTIONS.add("trim",aG.fnTrim);Ne.FUNCTIONS.add("ltrim",aG.fnLtrim);Ne.FUNCTIONS.add("rtrim",aG.fnRtrim);Ne.FUNCTIONS.add("rand",Eqe.fnRand);Ne.FUNCTIONS.add("pi",Aqe.fnPi);Ne.FUNCTIONS.add("substr",nqe.fnSubstr);Ne.FUNCTIONS.add("regexp_extract",iqe.fnRegexpExtract);Ne.FUNCTIONS.add("replace",sqe.fnReplace);Ne.FUNCTIONS.add("length",jfe.fnLength);Ne.FUNCTIONS.add("byte_length",jfe.fnByteLength);Ne.FUNCTIONS.add("ifnull",oqe.fnIfnull);Ne.FUNCTIONS.add("coalesce",Tqe.fnCoalesce);Ne.FUNCTIONS.add("nullif",aqe.fnNullif);Ne.FUNCTIONS.add("chr",oG.fnChr);Ne.FUNCTIONS.add("ascii",oG.fnAscii);Ne.FUNCTIONS.add("unicode",oG.fnUnicode);Ne.FUNCTIONS.add("repeat",Sqe.fnRepeat);Ne.FUNCTIONS.add("reverse",vqe.fnReverse);Ne.FUNCTIONS.add("log",mqe.fnLog);Ne.FUNCTIONS.add("ln",$a.fnLn);Ne.FUNCTIONS.add("exp",$a.fnExp);Ne.FUNCTIONS.add("stddev",ZBe.fnStddev);Ne.FUNCTIONS.add("string_agg",Qfe.fnStringAgg);Ne.FUNCTIONS.add("string_agg_distinct",Qfe.fnStringAggDistinct);Ne.FUNCTIONS.add("row_number",uqe.fnRowNumber);Ne.FUNCTIONS.add("lag",lqe.fnLag);Ne.FUNCTIONS.add("lead",cqe.fnLead);Ne.FUNCTIONS.add("rank",fqe.fnRank);Ne.FUNCTIONS.add("first_value",Hfe.fnFirstValueWindow);Ne.FUNCTIONS.add("last_value",Hfe.fnLastValueWindow);Ne.FUNCTIONS.add("min_cumulative",oy.fnMinCumulative);Ne.FUNCTIONS.add("max_cumulative",oy.fnMaxCumulative);Ne.FUNCTIONS.add("sum_cumulative",oy.fnSumCumulative);Ne.FUNCTIONS.add("min_window",oy.fnMinWindow);Ne.FUNCTIONS.add("max_window",oy.fnMaxWindow);Ne.FUNCTIONS.add("sum_window",oy.fnSumWindow);Ne.FUNCTIONS.add("avg_moving",_qe.fnAvgRolling);Ne.FUNCTIONS.add("sql_number",db.fnSqlNumber);Ne.FUNCTIONS.add("sql_string",db.fnSqlString);Ne.FUNCTIONS.add("sql_date",db.fnSqlDate);Ne.FUNCTIONS.add("sql_timestamp",db.fnSqlTimestamp);Ne.FUNCTIONS.add("sql_boolean",db.fnSqlBoolean);Ne.FUNCTIONS.seal()});var hb=v(qN=>{"use strict";Object.defineProperty(qN,"__esModule",{value:!0});qN.FUNCTIONS=void 0;var Cqe=Vfe();Object.defineProperty(qN,"FUNCTIONS",{enumerable:!0,get:function(){return Cqe.FUNCTIONS}})});var Wfe=v(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});ay.fnStringAggDistinct=ay.fnStringAgg=void 0;var xn=Pe();function Rqe(){let t=(0,xn.makeParam)("value",(0,xn.maxScalar)("string")),e=(0,xn.makeParam)("separator",(0,xn.literal)((0,xn.maxScalar)("string"))),r={type:"aggregate_order_by"},n={type:"aggregate_limit"};return[(0,xn.overload)((0,xn.minAggregate)("string"),[t.param],(0,xn.sql)`STRING_AGG(${t.arg}${r}${n})`,{supportsOrderBy:!0,supportsLimit:!0,defaultOrderByArgIndex:0}),(0,xn.overload)((0,xn.minAggregate)("string"),[t.param,e.param],(0,xn.sql)`STRING_AGG(${t.arg}, ${e.arg}${r}${n})`,{supportsOrderBy:!0,supportsLimit:!0,defaultOrderByArgIndex:0})]}ay.fnStringAgg=Rqe;function Oqe(){let t=(0,xn.makeParam)("value",(0,xn.maxScalar)("string")),e=(0,xn.makeParam)("separator",(0,xn.literal)((0,xn.maxScalar)("string"))),r={type:"aggregate_order_by"},n={type:"aggregate_limit"};return[(0,xn.overload)((0,xn.minAggregate)("string"),[t.param],(0,xn.sql)`STRING_AGG(DISTINCT ${t.arg}${r}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",supportsLimit:!0,defaultOrderByArgIndex:0}),(0,xn.overload)((0,xn.minAggregate)("string"),[t.param,e.param],(0,xn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${r}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",supportsLimit:!0,defaultOrderByArgIndex:0})]}ay.fnStringAggDistinct=Oqe});var Yfe=v(UN=>{"use strict";Object.defineProperty(UN,"__esModule",{value:!0});UN.fnChr=void 0;var pb=Pe();function Dqe(){let t=(0,pb.makeParam)("value",(0,pb.anyExprType)("number"));return[(0,pb.overload)((0,pb.minScalar)("string"),[t.param],(0,pb.sql)`CASE WHEN IFNULL(${t.arg}, 1) = 0 THEN '' ELSE CHR(${t.arg}) END`)]}UN.fnChr=Dqe});var Kfe=v($N=>{"use strict";Object.defineProperty($N,"__esModule",{value:!0});$N.fnPi=void 0;var uG=Pe();function Nqe(){return[(0,uG.overload)((0,uG.minScalar)("number"),[],(0,uG.sql)`ACOS(-1)`)]}$N.fnPi=Nqe});var Jfe=v(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.STANDARDSQL_FUNCTIONS=void 0;var Fqe=hb(),Xfe=Wfe(),wqe=Yfe(),Lqe=Kfe();Zf.STANDARDSQL_FUNCTIONS=Fqe.FUNCTIONS.clone();Zf.STANDARDSQL_FUNCTIONS.add("pi",Lqe.fnPi);Zf.STANDARDSQL_FUNCTIONS.add("chr",wqe.fnChr);Zf.STANDARDSQL_FUNCTIONS.add("string_agg",Xfe.fnStringAgg);Zf.STANDARDSQL_FUNCTIONS.add("string_agg_distinct",Xfe.fnStringAggDistinct);Zf.STANDARDSQL_FUNCTIONS.seal()});var Zfe=v(jN=>{"use strict";Object.defineProperty(jN,"__esModule",{value:!0});jN.STANDARDSQL_FUNCTIONS=void 0;var Iqe=Jfe();Object.defineProperty(jN,"STANDARDSQL_FUNCTIONS",{enumerable:!0,get:function(){return Iqe.STANDARDSQL_FUNCTIONS}})});var cG=v(zN=>{"use strict";Object.defineProperty(zN,"__esModule",{value:!0});zN.StandardSQLDialect=void 0;var exe=$d(),qn=Ke(),Mqe=Zfe(),Pqe=sb();function txe(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function kqe(t){return["day","week","month","quarter","year"].includes(t)}var Bqe={day_of_week:"dayofweek",day_of_year:"dayofyear"};function HN(t){let e=t.queryTimezone;if(e&&e!=="UTC")return e}var qqe={DATE:{type:"date"},STRING:{type:"string"},INTEGER:{type:"number",numberType:"integer"},INT64:{type:"number",numberType:"integer"},FLOAT:{type:"number",numberType:"float"},FLOAT64:{type:"number",numberType:"float"},NUMERIC:{type:"number",numberType:"float"},BIGNUMERIC:{type:"number",numberType:"float"},TIMESTAMP:{type:"timestamp"},BOOLEAN:{type:"boolean"},BOOL:{type:"boolean"},JSON:{type:"json"}},lG=class extends Pqe.Dialect{constructor(){super(...arguments),this.name="standardsql",this.defaultNumberType="FLOAT64",this.defaultDecimalType="NUMERIC",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!0,this.keywords=`
28
+ AND `)+n}};vi.AndChain=Zz;function Rke(t){return(0,bke.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}vi.generateHash=Rke;function po(t,e){return t.flatMap(r=>e(r).map(i=>{if(typeof i=="string")return i;switch(i.type){case"aggregate":case"all":case"spread":case"sql_expression":case"exclude":return{...i,e:po(i.e,e)};case"apply":return{...i,to:po(i.to,e),value:po(i.value,e)};case"applyVal":case"field":case"function_parameter":case"parameter":case"outputField":return i;case"sql-string":return{...i,e:po(i.e,e)};case"function_call":return{...i,args:i.args.map(s=>po(s,e))};case"filterExpression":return{...i,e:po(i.e,e),filterList:i.filterList.map(s=>({...s,expression:po(s.expression,e)}))};case"dialect":switch(i.function){case"cast":case"regexpMatch":return{...i,expr:po(i.expr,e)};case"delta":return{...i,delta:po(i.delta,e)};case"div":return{...i,denominator:po(i.denominator,e),numerator:po(i.numerator,e)};case"now":case"numberLiteral":case"stringLiteral":case"timeLiteral":case"regexpLiteral":return i;case"extract":case"trunc":return{...i,expr:{...i.expr,value:po(i.expr.value,e)}};case"timeDiff":return{...i,left:{...i.left,value:po(i.left.value,e)},right:{...i.left,value:po(i.left.value,e)}};default:throw new Error("unexpected dialect function")}default:throw new Error("unexpected")}}))}vi.exprMap=po;function mo(t,e){t.forEach(r=>{if(e(r),typeof r=="string")return r;switch(r.type){case"aggregate":case"all":case"spread":case"sql_expression":case"exclude":return{...r,e:mo(r.e,e)};case"apply":return{...r,to:mo(r.to,e),value:mo(r.value,e)};case"applyVal":case"field":case"function_parameter":case"parameter":case"outputField":return r;case"function_call":return{...r,args:r.args.map(n=>mo(n,e))};case"sql-string":return{...r,e:mo(r.e,e)};case"filterExpression":return{...r,e:mo(r.e,e),filterList:r.filterList.map(n=>({...n,expression:mo(n.expression,e)}))};case"dialect":switch(r.function){case"cast":case"regexpMatch":return{...r,expr:mo(r.expr,e)};case"delta":return{...r,delta:mo(r.delta,e)};case"div":return{...r,denominator:mo(r.denominator,e),numerator:mo(r.numerator,e)};case"now":case"numberLiteral":case"stringLiteral":case"timeLiteral":case"regexpLiteral":return r;case"extract":case"trunc":return{...r,expr:{...r.expr,value:mo(r.expr.value,e)}};case"timeDiff":return{...r,left:{...r.left,value:mo(r.left.value,e)},right:{...r.left,value:mo(r.left.value,e)}};default:throw new Error("unexpected dialect function")}default:throw new Error("unexpected")}})}vi.exprWalk=mo;function Oke(t,e){let r=[];for(let n=0;n<t.length;n++)r.push(...t[n]),n<t.length-1&&r.push(e);return r}vi.joinWith=Oke;function Dke(t,e){return Array.from({length:e-t},(r,n)=>n+t)}vi.range=Dke});var tfe=v(cN=>{"use strict";Object.defineProperty(cN,"__esModule",{value:!0});cN.fnConcat=void 0;var Ua=Pe();function Nke(){return[(0,Ua.overload)((0,Ua.minScalar)("string"),[],[{type:"dialect",function:"stringLiteral",literal:""}]),(0,Ua.overload)((0,Ua.minScalar)("string"),[(0,Ua.params)("values",(0,Ua.anyExprType)("string"),(0,Ua.anyExprType)("number"),(0,Ua.anyExprType)("date"),(0,Ua.anyExprType)("timestamp"),(0,Ua.anyExprType)("boolean"))],(0,Ua.sql)`CONCAT(${(0,Ua.spread)((0,Ua.arg)("values"))})`)]}cN.fnConcat=Nke});var rfe=v(fN=>{"use strict";Object.defineProperty(fN,"__esModule",{value:!0});fN.fnTrunc=void 0;var tc=Pe();function Fke(){let t=(0,tc.makeParam)("value",(0,tc.anyExprType)("number")),e=(0,tc.makeParam)("precision",(0,tc.anyExprType)("number"));return[(0,tc.overload)((0,tc.minScalar)("number"),[t.param],(0,tc.sql)`TRUNC(${t.arg})`),(0,tc.overload)((0,tc.minScalar)("number"),[t.param,e.param],(0,tc.sql)`TRUNC(${t.arg}, ${e.arg})`)]}fN.fnTrunc=Fke});var nfe=v(xN=>{"use strict";Object.defineProperty(xN,"__esModule",{value:!0});xN.fnStddev=void 0;var lb=Pe();function wke(){let t=(0,lb.makeParam)("value",(0,lb.maxScalar)("number"));return[(0,lb.overload)((0,lb.minAggregate)("number"),[t.param],(0,lb.sql)`STDDEV(${t.arg})`)]}xN.fnStddev=wke});var ife=v(dN=>{"use strict";Object.defineProperty(dN,"__esModule",{value:!0});dN.fnRound=void 0;var rc=Pe();function Lke(){let t=(0,rc.makeParam)("value",(0,rc.anyExprType)("number")),e=(0,rc.makeParam)("precision",(0,rc.anyExprType)("number"));return[(0,rc.overload)((0,rc.minScalar)("number"),[t.param],(0,rc.sql)`ROUND(${t.arg})`),(0,rc.overload)((0,rc.minScalar)("number"),[t.param,e.param],(0,rc.sql)`ROUND(${t.arg}, ${e.arg})`)]}dN.fnRound=Lke});var sfe=v(hN=>{"use strict";Object.defineProperty(hN,"__esModule",{value:!0});hN.fnLower=void 0;var cb=Pe();function Ike(){let t=(0,cb.makeParam)("base",(0,cb.anyExprType)("string"));return[(0,cb.overload)((0,cb.minScalar)("string"),[t.param],(0,cb.sql)`LOWER(${t.arg})`)]}hN.fnLower=Ike});var ofe=v(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});jd.fnUnicode=jd.fnAscii=jd.fnChr=void 0;var ii=Pe();function Mke(){return[(0,ii.overload)((0,ii.minScalar)("string"),[(0,ii.param)("value",(0,ii.anyExprType)("number"))],(0,ii.sql)`CASE WHEN ${(0,ii.arg)("value")} = 0 THEN '' ELSE CHR(${(0,ii.arg)("value")}) END`)]}jd.fnChr=Mke;function Pke(){return[(0,ii.overload)((0,ii.minScalar)("number"),[(0,ii.param)("value",(0,ii.anyExprType)("string"))],(0,ii.sql)`ASCII(${(0,ii.arg)("value")})`)]}jd.fnAscii=Pke;function kke(){return[(0,ii.overload)((0,ii.minScalar)("number"),[(0,ii.param)("value",(0,ii.anyExprType)("string"))],(0,ii.sql)`UNICODE(${(0,ii.arg)("value")})`)]}jd.fnUnicode=kke});var afe=v(pN=>{"use strict";Object.defineProperty(pN,"__esModule",{value:!0});pN.fnUpper=void 0;var fb=Pe();function Bke(){let t=(0,fb.makeParam)("value",(0,fb.anyExprType)("string"));return[(0,fb.overload)((0,fb.minScalar)("string"),[t.param],(0,fb.sql)`UPPER(${t.arg})`)]}pN.fnUpper=Bke});var ufe=v(mN=>{"use strict";Object.defineProperty(mN,"__esModule",{value:!0});mN.fnSubstr=void 0;var wu=Pe();function qke(){let t=(0,wu.makeParam)("value",(0,wu.anyExprType)("string")),e=(0,wu.makeParam)("position",(0,wu.anyExprType)("number")),r=(0,wu.makeParam)("length",(0,wu.anyExprType)("number"));return[(0,wu.overload)((0,wu.minScalar)("string"),[t.param,e.param],(0,wu.sql)`SUBSTR(${t.arg}, ${e.arg})`),(0,wu.overload)((0,wu.minScalar)("string"),[t.param,e.param,r.param],(0,wu.sql)`SUBSTR(${t.arg}, ${e.arg}, ${r.arg})`)]}mN.fnSubstr=qke});var lfe=v(gN=>{"use strict";Object.defineProperty(gN,"__esModule",{value:!0});gN.fnRegexpExtract=void 0;var _1=Pe();function Uke(){let t=(0,_1.makeParam)("value",(0,_1.anyExprType)("string")),e=(0,_1.makeParam)("pattern",(0,_1.anyExprType)("regular expression"));return[(0,_1.overload)((0,_1.minScalar)("string"),[t.param,e.param],(0,_1.sql)`REGEXP_EXTRACT(${t.arg}, ${e.arg})`)]}gN.fnRegexpExtract=Uke});var cfe=v(yN=>{"use strict";Object.defineProperty(yN,"__esModule",{value:!0});yN.fnReplace=void 0;var Xo=Pe();function $ke(){let t=(0,Xo.makeParam)("value",(0,Xo.anyExprType)("string")),e=(0,Xo.makeParam)("pattern",(0,Xo.anyExprType)("string")),r=(0,Xo.makeParam)("pattern",(0,Xo.anyExprType)("regular expression")),n=(0,Xo.makeParam)("replacement",(0,Xo.anyExprType)("string"));return[(0,Xo.overload)((0,Xo.minScalar)("string"),[t.param,e.param,n.param],(0,Xo.sql)`REPLACE(${t.arg}, ${e.arg}, ${n.arg})`),(0,Xo.overload)((0,Xo.minScalar)("string"),[t.param,r.param,n.param],(0,Xo.sql)`REGEXP_REPLACE(${t.arg}, ${r.arg}, ${n.arg})`)]}yN.fnReplace=$ke});var ffe=v(X3=>{"use strict";Object.defineProperty(X3,"__esModule",{value:!0});X3.fnByteLength=X3.fnLength=void 0;var Lu=Pe();function jke(){return[(0,Lu.overload)((0,Lu.minScalar)("number"),[(0,Lu.param)("value",(0,Lu.anyExprType)("string"))],(0,Lu.sql)`LENGTH(${(0,Lu.arg)("value")})`)]}X3.fnLength=jke;function Hke(){return[(0,Lu.overload)((0,Lu.minScalar)("number"),[(0,Lu.param)("value",(0,Lu.anyExprType)("string"))],(0,Lu.sql)`BYTE_LENGTH(${(0,Lu.arg)("value")})`)]}X3.fnByteLength=Hke});var xfe=v(EN=>{"use strict";Object.defineProperty(EN,"__esModule",{value:!0});EN.fnIfnull=void 0;var Kf=Pe(),zke=["string","number","timestamp","date","json"];function Gke(){return zke.map(t=>(0,Kf.overload)((0,Kf.minScalar)(t),[(0,Kf.param)("value",(0,Kf.anyExprType)(t)),(0,Kf.param)("default",(0,Kf.anyExprType)(t))],(0,Kf.sql)`IFNULL(${(0,Kf.arg)("value")}, ${(0,Kf.arg)("default")})`))}EN.fnIfnull=Gke});var dfe=v(AN=>{"use strict";Object.defineProperty(AN,"__esModule",{value:!0});AN.fnNullif=void 0;var b1=Pe(),Qke=["string","number","timestamp","date","json"];function Vke(){return Qke.map(t=>{let e=(0,b1.makeParam)("value1",(0,b1.anyExprType)(t)),r=(0,b1.makeParam)("value2",(0,b1.anyExprType)(t));return(0,b1.overload)((0,b1.minScalar)(t),[e.param,r.param],(0,b1.sql)`NULLIF(${e.arg}, ${r.arg})`)})}AN.fnNullif=Vke});var hfe=v(SN=>{"use strict";Object.defineProperty(SN,"__esModule",{value:!0});SN.fnRowNumber=void 0;var eG=Pe();function Wke(){return[(0,eG.overload)((0,eG.minAnalytic)("number"),[],(0,eG.sql)`ROW_NUMBER()`,{needsWindowOrderBy:!0})]}SN.fnRowNumber=Wke});var pfe=v(vN=>{"use strict";Object.defineProperty(vN,"__esModule",{value:!0});vN.fnLag=void 0;var _i=Pe(),Yke=["string","number","timestamp","date","json","boolean"];function Kke(){return Yke.flatMap(t=>{let e=(0,_i.makeParam)("value",(0,_i.output)((0,_i.maxAggregate)(t))),r=(0,_i.makeParam)("offset",(0,_i.literal)((0,_i.maxScalar)("number"))),n=(0,_i.makeParam)("default",(0,_i.constant)((0,_i.maxAggregate)(t)));return[(0,_i.overload)((0,_i.minAnalytic)(t),[e.param],(0,_i.sql)`LAG(${e.arg})`,{needsWindowOrderBy:!0}),(0,_i.overload)((0,_i.minAnalytic)(t),[e.param,r.param],(0,_i.sql)`LAG(${e.arg}, ${r.arg})`,{needsWindowOrderBy:!0}),(0,_i.overload)((0,_i.minAnalytic)(t),[e.param,r.param,n.param],(0,_i.sql)`LAG(${e.arg}, ${r.arg}, ${n.arg})`,{needsWindowOrderBy:!0})]})}vN.fnLag=Kke});var mfe=v(_N=>{"use strict";Object.defineProperty(_N,"__esModule",{value:!0});_N.fnLead=void 0;var bi=Pe(),Xke=["string","number","timestamp","date","json","boolean"];function Jke(){return Xke.flatMap(t=>{let e=(0,bi.makeParam)("value",(0,bi.output)((0,bi.maxAggregate)(t))),r=(0,bi.makeParam)("offset",(0,bi.literal)((0,bi.maxScalar)("number"))),n=(0,bi.makeParam)("default",(0,bi.constant)((0,bi.maxAggregate)(t)));return[(0,bi.overload)((0,bi.minAnalytic)(t),[e.param],(0,bi.sql)`LEAD(${e.arg})`,{needsWindowOrderBy:!0}),(0,bi.overload)((0,bi.minAnalytic)(t),[e.param,r.param],(0,bi.sql)`LEAD(${e.arg}, ${r.arg})`,{needsWindowOrderBy:!0}),(0,bi.overload)((0,bi.minAnalytic)(t),[e.param,r.param,n.param],(0,bi.sql)`LEAD(${e.arg}, ${r.arg}, ${n.arg})`,{needsWindowOrderBy:!0})]})}_N.fnLead=Jke});var gfe=v(bN=>{"use strict";Object.defineProperty(bN,"__esModule",{value:!0});bN.fnRank=void 0;var tG=Pe();function Zke(){return[(0,tG.overload)((0,tG.minAnalytic)("number"),[],(0,tG.sql)`RANK()`,{needsWindowOrderBy:!0})]}bN.fnRank=Zke});var Efe=v(J3=>{"use strict";Object.defineProperty(J3,"__esModule",{value:!0});J3.fnLastValueWindow=J3.fnFirstValueWindow=void 0;var Jo=Pe(),yfe=["string","number","timestamp","date","json"];function eBe(){return yfe.flatMap(t=>[(0,Jo.overload)((0,Jo.minAnalytic)(t),[(0,Jo.param)("value",(0,Jo.output)((0,Jo.maxAggregate)(t)))],(0,Jo.sql)`FIRST_VALUE(${(0,Jo.arg)("value")})`,{needsWindowOrderBy:!0})])}J3.fnFirstValueWindow=eBe;function tBe(){return yfe.flatMap(t=>[(0,Jo.overload)((0,Jo.minAnalytic)(t),[(0,Jo.param)("value",(0,Jo.output)((0,Jo.maxAggregate)(t)))],(0,Jo.sql)`LAST_VALUE(${(0,Jo.arg)("value")})`,{needsWindowOrderBy:!0,between:{preceding:-1,following:-1}})])}J3.fnLastValueWindow=tBe});var Afe=v(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.fnSumWindow=Zo.fnMaxWindow=Zo.fnMinWindow=Zo.fnSumCumulative=Zo.fnMaxCumulative=Zo.fnMinCumulative=void 0;var Ft=Pe(),Z3=["string","number","timestamp","date"];function rBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MIN(${e.arg})`,{needsWindowOrderBy:!0})]})}Zo.fnMinCumulative=rBe;function nBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MAX(${e.arg})`,{needsWindowOrderBy:!0})]})}Zo.fnMaxCumulative=nBe;function iBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`SUM(${e.arg})`,{needsWindowOrderBy:!0})]})}Zo.fnSumCumulative=iBe;function sBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MIN(${e.arg})`,{needsWindowOrderBy:!1})]})}Zo.fnMinWindow=sBe;function oBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`MAX(${e.arg})`,{needsWindowOrderBy:!1})]})}Zo.fnMaxWindow=oBe;function aBe(){return Z3.flatMap(t=>{let e=(0,Ft.makeParam)("value",(0,Ft.output)((0,Ft.maxAggregate)(t)));return[(0,Ft.overload)((0,Ft.minAnalytic)(t),[e.param],(0,Ft.sql)`SUM(${e.arg})`,{needsWindowOrderBy:!1})]})}Zo.fnSumWindow=aBe});var Sfe=v(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});ey.fnEndsWith=ey.fnStartsWith=void 0;var ea=Pe();function uBe(){let t=(0,ea.makeParam)("value",(0,ea.anyExprType)("string")),e=(0,ea.makeParam)("prefix",(0,ea.anyExprType)("string"));return[(0,ea.overload)((0,ea.minScalar)("boolean"),[t.param,e.param],(0,ea.sql)`COALESCE(STARTS_WITH(${t.arg}, ${e.arg}), false)`)]}ey.fnStartsWith=uBe;function lBe(){let t=(0,ea.makeParam)("value",(0,ea.anyExprType)("string")),e=(0,ea.makeParam)("suffix",(0,ea.anyExprType)("string"));return[(0,ea.overload)((0,ea.minScalar)("boolean"),[t.param,e.param],(0,ea.sql)`COALESCE(ENDS_WITH(${t.arg}, ${e.arg}), false)`)]}ey.fnEndsWith=lBe});var vfe=v(TN=>{"use strict";Object.defineProperty(TN,"__esModule",{value:!0});TN.fnIsInf=void 0;var ty=Pe();function cBe(){return[(0,ty.overload)((0,ty.minScalar)("boolean"),[(0,ty.param)("value",(0,ty.anyExprType)("number"))],(0,ty.sql)`COALESCE(IS_INF(${(0,ty.arg)("value")}), false)`)]}TN.fnIsInf=cBe});var _fe=v(CN=>{"use strict";Object.defineProperty(CN,"__esModule",{value:!0});CN.fnIsNan=void 0;var ry=Pe();function fBe(){return[(0,ry.overload)((0,ry.minScalar)("boolean"),[(0,ry.param)("value",(0,ry.anyExprType)("number"))],(0,ry.sql)`COALESCE(IS_NAN(${(0,ry.arg)("value")}), false)`)]}CN.fnIsNan=fBe});var bfe=v(RN=>{"use strict";Object.defineProperty(RN,"__esModule",{value:!0});RN.fnAtan2=void 0;var Xf=Pe();function xBe(){return[(0,Xf.overload)((0,Xf.minScalar)("number"),[(0,Xf.param)("y",(0,Xf.anyExprType)("number")),(0,Xf.param)("x",(0,Xf.anyExprType)("number"))],(0,Xf.sql)`ATAN2(${(0,Xf.arg)("y")}, ${(0,Xf.arg)("x")})`)]}RN.fnAtan2=xBe});var Tfe=v(ON=>{"use strict";Object.defineProperty(ON,"__esModule",{value:!0});ON.fnPow=void 0;var T1=Pe();function dBe(){let t=(0,T1.makeParam)("base",(0,T1.anyExprType)("number")),e=(0,T1.makeParam)("exponent",(0,T1.anyExprType)("number"));return[(0,T1.overload)((0,T1.minScalar)("number"),[t.param,e.param],(0,T1.sql)`POW(${t.arg}, ${e.arg})`)]}ON.fnPow=dBe});var Cfe=v(DN=>{"use strict";Object.defineProperty(DN,"__esModule",{value:!0});DN.fnLog=void 0;var C1=Pe();function hBe(){let t=(0,C1.makeParam)("value",(0,C1.anyExprType)("number")),e=(0,C1.makeParam)("base",(0,C1.anyExprType)("number"));return[(0,C1.overload)((0,C1.minScalar)("number"),[t.param,e.param],(0,C1.sql)`LOG(${t.arg}, ${e.arg})`)]}DN.fnLog=hBe});var Rfe=v(NN=>{"use strict";Object.defineProperty(NN,"__esModule",{value:!0});NN.fnStrpos=void 0;var R1=Pe();function pBe(){let t=(0,R1.makeParam)("test_string",(0,R1.anyExprType)("string")),e=(0,R1.makeParam)("search_string",(0,R1.anyExprType)("string"));return[(0,R1.overload)((0,R1.minScalar)("number"),[t.param,e.param],(0,R1.sql)`STRPOS(${t.arg}, ${e.arg})`)]}NN.fnStrpos=pBe});var Ofe=v(FN=>{"use strict";Object.defineProperty(FN,"__esModule",{value:!0});FN.fnDiv=void 0;var Jf=Pe();function mBe(){return[(0,Jf.overload)((0,Jf.minScalar)("number"),[(0,Jf.param)("dividend",(0,Jf.anyExprType)("number")),(0,Jf.param)("divisor",(0,Jf.anyExprType)("number"))],(0,Jf.sql)`DIV(${(0,Jf.arg)("dividend")}, ${(0,Jf.arg)("divisor")})`)]}FN.fnDiv=mBe});var Nfe=v(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});ny.fnLeast=ny.fnGreatest=void 0;var O1=Pe(),gBe=["string","number","timestamp","date","json"];function Dfe(t){return gBe.map(e=>(0,O1.overload)((0,O1.minScalar)(e),[(0,O1.params)("values",(0,O1.anyExprType)(e))],[(0,O1.sqlFragment)(`${t}(`,(0,O1.spread)((0,O1.arg)("values")),")")]))}var yBe=()=>Dfe("GREATEST");ny.fnGreatest=yBe;var EBe=()=>Dfe("LEAST");ny.fnLeast=EBe});var Ffe=v(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});Hd.fnRtrim=Hd.fnLtrim=Hd.fnTrim=void 0;var go=Pe();function rG(t){return[(0,go.overload)((0,go.minScalar)("string"),[(0,go.param)("value",(0,go.anyExprType)("string"))],[(0,go.sqlFragment)(`${t}(`,(0,go.arg)("value"),")")]),(0,go.overload)((0,go.minScalar)("string"),[(0,go.param)("value",(0,go.anyExprType)("string")),(0,go.param)("trim_characters",(0,go.anyExprType)("string"))],[(0,go.sqlFragment)(`${t}(`,(0,go.arg)("value"),",",(0,go.arg)("trim_characters"),")")])]}var ABe=()=>rG("TRIM");Hd.fnTrim=ABe;var SBe=()=>rG("LTRIM");Hd.fnLtrim=SBe;var vBe=()=>rG("RTRIM");Hd.fnRtrim=vBe});var wfe=v(wN=>{"use strict";Object.defineProperty(wN,"__esModule",{value:!0});wN.fnRand=void 0;var nG=Pe();function _Be(){return[(0,nG.overload)((0,nG.minScalar)("number"),[],(0,nG.sql)`RAND()`)]}wN.fnRand=_Be});var Lfe=v(LN=>{"use strict";Object.defineProperty(LN,"__esModule",{value:!0});LN.fnPi=void 0;var iG=Pe();function bBe(){return[(0,iG.overload)((0,iG.minScalar)("number"),[],(0,iG.sql)`PI()`)]}LN.fnPi=bBe});var Ife=v(IN=>{"use strict";Object.defineProperty(IN,"__esModule",{value:!0});IN.fnRepeat=void 0;var D1=Pe();function TBe(){let t=(0,D1.makeParam)("value",(0,D1.anyExprType)("string")),e=(0,D1.makeParam)("count",(0,D1.anyExprType)("number"));return[(0,D1.overload)((0,D1.minScalar)("string"),[t.param,e.param],(0,D1.sql)`REPEAT(${t.arg}, ${e.arg})`)]}IN.fnRepeat=TBe});var Mfe=v(MN=>{"use strict";Object.defineProperty(MN,"__esModule",{value:!0});MN.fnReverse=void 0;var xb=Pe();function CBe(){let t=(0,xb.makeParam)("value",(0,xb.anyExprType)("string"));return[(0,xb.overload)((0,xb.minScalar)("string"),[t.param],(0,xb.sql)`REVERSE(${t.arg})`)]}MN.fnReverse=CBe});var Pfe=v(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.fnExp=Xt.fnLn=Xt.fnSqrt=Xt.fnAbs=Xt.fnFloor=Xt.fnCeil=Xt.fnSign=Xt.fnAtan=Xt.fnTan=Xt.fnAsin=Xt.fnSin=Xt.fnAcos=Xt.fnCos=Xt.simple=void 0;var iy=Pe();function ta(t){return[(0,iy.overload)((0,iy.minScalar)("number"),[(0,iy.param)("value",(0,iy.anyExprType)("number"))],[(0,iy.sqlFragment)(`${t}(`,(0,iy.arg)("value"),")")])]}Xt.simple=ta;var RBe=()=>ta("COS");Xt.fnCos=RBe;var OBe=()=>ta("ACOS");Xt.fnAcos=OBe;var DBe=()=>ta("SIN");Xt.fnSin=DBe;var NBe=()=>ta("ASIN");Xt.fnAsin=NBe;var FBe=()=>ta("TAN");Xt.fnTan=FBe;var wBe=()=>ta("ATAN");Xt.fnAtan=wBe;var LBe=()=>ta("SIGN");Xt.fnSign=LBe;var IBe=()=>ta("CEIL");Xt.fnCeil=IBe;var MBe=()=>ta("FLOOR");Xt.fnFloor=MBe;var PBe=()=>ta("ABS");Xt.fnAbs=PBe;var kBe=()=>ta("SQRT");Xt.fnSqrt=kBe;var BBe=()=>ta("LN");Xt.fnLn=BBe;var qBe=()=>ta("EXP");Xt.fnExp=qBe});var kfe=v(PN=>{"use strict";Object.defineProperty(PN,"__esModule",{value:!0});PN.fnAvgRolling=void 0;var yo=Pe(),UBe=["string","number","timestamp","date"];function $Be(){return UBe.flatMap(t=>{let e=(0,yo.makeParam)("value",(0,yo.output)((0,yo.maxAggregate)(t))),r=(0,yo.makeParam)("preceding",(0,yo.literal)((0,yo.maxScalar)("number"))),n=(0,yo.makeParam)("following",(0,yo.literal)((0,yo.maxScalar)("number")));return[(0,yo.overload)((0,yo.minAnalytic)(t),[e.param,r.param],(0,yo.sql)`AVG(${e.arg})`,{needsWindowOrderBy:!0,between:{preceding:"preceding",following:0}}),(0,yo.overload)((0,yo.minAnalytic)(t),[e.param,r.param,n.param],(0,yo.sql)`AVG(${e.arg})`,{needsWindowOrderBy:!0,between:{preceding:"preceding",following:"following"}})]})}PN.fnAvgRolling=$Be});var Bfe=v(kN=>{"use strict";Object.defineProperty(kN,"__esModule",{value:!0});kN.FunctionMap=void 0;var sG=class t{constructor(e){this.functions=new Map,this.sealed=!1,this.getters=e??new Map}clone(){return new t(new Map(this.getters))}add(e,r){this.ensureNotSealed(),this.getters.set(e,r)}get(e){this.ensureSealed();let r=this.functions.get(e);if(r)return r;let n=this.getters.get(e);if(n===void 0)return;let i=n();return this.functions.set(e,i),i}delete(e){this.ensureNotSealed(),this.functions.delete(e),this.getters.delete(e)}seal(){this.sealed=!0}ensureNotSealed(){if(this.sealed)throw new Error("Cannot update sealed FunctionMap")}ensureSealed(){if(!this.sealed)throw new Error("Cannot get from unsealed FunctionMap")}};kN.FunctionMap=sG});var qfe=v(BN=>{"use strict";Object.defineProperty(BN,"__esModule",{value:!0});BN.fnCoalesce=void 0;var N1=Pe(),jBe=["string","number","timestamp","date","json"];function HBe(){return jBe.map(t=>(0,N1.overload)((0,N1.minScalar)(t),[(0,N1.params)("values",(0,N1.anyExprType)(t))],(0,N1.sql)`COALESCE(${(0,N1.spread)((0,N1.arg)("values"))})`))}BN.fnCoalesce=HBe});var Ufe=v(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});sy.fnStringAggDistinct=sy.fnStringAgg=void 0;var fn=Pe();function zBe(){let t=(0,fn.makeParam)("value",(0,fn.maxScalar)("string")),e=(0,fn.makeParam)("separator",(0,fn.literal)((0,fn.maxScalar)("string"))),r={type:"aggregate_order_by"};return[(0,fn.overload)((0,fn.minAggregate)("string"),[t.param],(0,fn.sql)`STRING_AGG(${t.arg}${r})`,{supportsOrderBy:!0,defaultOrderByArgIndex:0}),(0,fn.overload)((0,fn.minAggregate)("string"),[t.param,e.param],(0,fn.sql)`STRING_AGG(${t.arg}, ${e.arg}${r})`,{supportsOrderBy:!0,defaultOrderByArgIndex:0})]}sy.fnStringAgg=zBe;function GBe(){let t=(0,fn.makeParam)("value",(0,fn.maxScalar)("string")),e=(0,fn.makeParam)("separator",(0,fn.literal)((0,fn.maxScalar)("string"))),r={type:"aggregate_order_by"};return[(0,fn.overload)((0,fn.minAggregate)("string"),[t.param],(0,fn.sql)`STRING_AGG(DISTINCT ${t.arg}${r})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,fn.overload)((0,fn.minAggregate)("string"),[t.param,e.param],(0,fn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${r})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}sy.fnStringAggDistinct=GBe});var $fe=v(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.fnSqlBoolean=Iu.fnSqlTimestamp=Iu.fnSqlDate=Iu.fnSqlString=Iu.fnSqlNumber=void 0;var Or=Pe();function QBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("number"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlNumber=QBe;function VBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("string"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlString=VBe;function WBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("date"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlDate=WBe;function YBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("timestamp"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlTimestamp=YBe;function KBe(){let t=(0,Or.makeParam)("value",(0,Or.literal)((0,Or.maxScalar)("string")));return[(0,Or.overload)((0,Or.minScalar)("boolean"),[t.param],[{type:"sql-string",e:[t.arg]}])]}Iu.fnSqlBoolean=KBe});var Vfe=v(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.FUNCTIONS=void 0;var XBe=tfe(),JBe=rfe(),ZBe=nfe(),eqe=ife(),tqe=sfe(),oG=ofe(),rqe=afe(),nqe=ufe(),iqe=lfe(),sqe=cfe(),jfe=ffe(),oqe=xfe(),aqe=dfe(),uqe=hfe(),lqe=pfe(),cqe=mfe(),fqe=gfe(),Hfe=Efe(),oy=Afe(),zfe=Sfe(),xqe=vfe(),dqe=_fe(),hqe=bfe(),pqe=Tfe(),mqe=Cfe(),gqe=Rfe(),yqe=Ofe(),Gfe=Nfe(),aG=Ffe(),Eqe=wfe(),Aqe=Lfe(),Sqe=Ife(),vqe=Mfe(),$a=Pfe(),_qe=kfe(),bqe=Bfe(),Tqe=qfe(),Qfe=Ufe(),db=$fe();Ne.FUNCTIONS=new bqe.FunctionMap;Ne.FUNCTIONS.add("concat",XBe.fnConcat);Ne.FUNCTIONS.add("round",eqe.fnRound);Ne.FUNCTIONS.add("trunc",JBe.fnTrunc);Ne.FUNCTIONS.add("floor",$a.fnFloor);Ne.FUNCTIONS.add("ceil",$a.fnCeil);Ne.FUNCTIONS.add("cos",$a.fnCos);Ne.FUNCTIONS.add("acos",$a.fnAcos);Ne.FUNCTIONS.add("sin",$a.fnSin);Ne.FUNCTIONS.add("asin",$a.fnAsin);Ne.FUNCTIONS.add("tan",$a.fnTan);Ne.FUNCTIONS.add("atan",$a.fnAtan);Ne.FUNCTIONS.add("atan2",hqe.fnAtan2);Ne.FUNCTIONS.add("lower",tqe.fnLower);Ne.FUNCTIONS.add("upper",rqe.fnUpper);Ne.FUNCTIONS.add("sqrt",$a.fnSqrt);Ne.FUNCTIONS.add("pow",pqe.fnPow);Ne.FUNCTIONS.add("abs",$a.fnAbs);Ne.FUNCTIONS.add("sign",$a.fnSign);Ne.FUNCTIONS.add("is_inf",xqe.fnIsInf);Ne.FUNCTIONS.add("is_nan",dqe.fnIsNan);Ne.FUNCTIONS.add("greatest",Gfe.fnGreatest);Ne.FUNCTIONS.add("least",Gfe.fnLeast);Ne.FUNCTIONS.add("div",yqe.fnDiv);Ne.FUNCTIONS.add("strpos",gqe.fnStrpos);Ne.FUNCTIONS.add("starts_with",zfe.fnStartsWith);Ne.FUNCTIONS.add("ends_with",zfe.fnEndsWith);Ne.FUNCTIONS.add("trim",aG.fnTrim);Ne.FUNCTIONS.add("ltrim",aG.fnLtrim);Ne.FUNCTIONS.add("rtrim",aG.fnRtrim);Ne.FUNCTIONS.add("rand",Eqe.fnRand);Ne.FUNCTIONS.add("pi",Aqe.fnPi);Ne.FUNCTIONS.add("substr",nqe.fnSubstr);Ne.FUNCTIONS.add("regexp_extract",iqe.fnRegexpExtract);Ne.FUNCTIONS.add("replace",sqe.fnReplace);Ne.FUNCTIONS.add("length",jfe.fnLength);Ne.FUNCTIONS.add("byte_length",jfe.fnByteLength);Ne.FUNCTIONS.add("ifnull",oqe.fnIfnull);Ne.FUNCTIONS.add("coalesce",Tqe.fnCoalesce);Ne.FUNCTIONS.add("nullif",aqe.fnNullif);Ne.FUNCTIONS.add("chr",oG.fnChr);Ne.FUNCTIONS.add("ascii",oG.fnAscii);Ne.FUNCTIONS.add("unicode",oG.fnUnicode);Ne.FUNCTIONS.add("repeat",Sqe.fnRepeat);Ne.FUNCTIONS.add("reverse",vqe.fnReverse);Ne.FUNCTIONS.add("log",mqe.fnLog);Ne.FUNCTIONS.add("ln",$a.fnLn);Ne.FUNCTIONS.add("exp",$a.fnExp);Ne.FUNCTIONS.add("stddev",ZBe.fnStddev);Ne.FUNCTIONS.add("string_agg",Qfe.fnStringAgg);Ne.FUNCTIONS.add("string_agg_distinct",Qfe.fnStringAggDistinct);Ne.FUNCTIONS.add("row_number",uqe.fnRowNumber);Ne.FUNCTIONS.add("lag",lqe.fnLag);Ne.FUNCTIONS.add("lead",cqe.fnLead);Ne.FUNCTIONS.add("rank",fqe.fnRank);Ne.FUNCTIONS.add("first_value",Hfe.fnFirstValueWindow);Ne.FUNCTIONS.add("last_value",Hfe.fnLastValueWindow);Ne.FUNCTIONS.add("min_cumulative",oy.fnMinCumulative);Ne.FUNCTIONS.add("max_cumulative",oy.fnMaxCumulative);Ne.FUNCTIONS.add("sum_cumulative",oy.fnSumCumulative);Ne.FUNCTIONS.add("min_window",oy.fnMinWindow);Ne.FUNCTIONS.add("max_window",oy.fnMaxWindow);Ne.FUNCTIONS.add("sum_window",oy.fnSumWindow);Ne.FUNCTIONS.add("avg_moving",_qe.fnAvgRolling);Ne.FUNCTIONS.add("sql_number",db.fnSqlNumber);Ne.FUNCTIONS.add("sql_string",db.fnSqlString);Ne.FUNCTIONS.add("sql_date",db.fnSqlDate);Ne.FUNCTIONS.add("sql_timestamp",db.fnSqlTimestamp);Ne.FUNCTIONS.add("sql_boolean",db.fnSqlBoolean);Ne.FUNCTIONS.seal()});var hb=v(qN=>{"use strict";Object.defineProperty(qN,"__esModule",{value:!0});qN.FUNCTIONS=void 0;var Cqe=Vfe();Object.defineProperty(qN,"FUNCTIONS",{enumerable:!0,get:function(){return Cqe.FUNCTIONS}})});var Wfe=v(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});ay.fnStringAggDistinct=ay.fnStringAgg=void 0;var xn=Pe();function Rqe(){let t=(0,xn.makeParam)("value",(0,xn.maxScalar)("string")),e=(0,xn.makeParam)("separator",(0,xn.literal)((0,xn.maxScalar)("string"))),r={type:"aggregate_order_by"},n={type:"aggregate_limit"};return[(0,xn.overload)((0,xn.minAggregate)("string"),[t.param],(0,xn.sql)`STRING_AGG(${t.arg}${r}${n})`,{supportsOrderBy:!0,supportsLimit:!0,defaultOrderByArgIndex:0}),(0,xn.overload)((0,xn.minAggregate)("string"),[t.param,e.param],(0,xn.sql)`STRING_AGG(${t.arg}, ${e.arg}${r}${n})`,{supportsOrderBy:!0,supportsLimit:!0,defaultOrderByArgIndex:0})]}ay.fnStringAgg=Rqe;function Oqe(){let t=(0,xn.makeParam)("value",(0,xn.maxScalar)("string")),e=(0,xn.makeParam)("separator",(0,xn.literal)((0,xn.maxScalar)("string"))),r={type:"aggregate_order_by"},n={type:"aggregate_limit"};return[(0,xn.overload)((0,xn.minAggregate)("string"),[t.param],(0,xn.sql)`STRING_AGG(DISTINCT ${t.arg}${r}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",supportsLimit:!0,defaultOrderByArgIndex:0}),(0,xn.overload)((0,xn.minAggregate)("string"),[t.param,e.param],(0,xn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${r}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",supportsLimit:!0,defaultOrderByArgIndex:0})]}ay.fnStringAggDistinct=Oqe});var Yfe=v(UN=>{"use strict";Object.defineProperty(UN,"__esModule",{value:!0});UN.fnChr=void 0;var pb=Pe();function Dqe(){let t=(0,pb.makeParam)("value",(0,pb.anyExprType)("number"));return[(0,pb.overload)((0,pb.minScalar)("string"),[t.param],(0,pb.sql)`CASE WHEN IFNULL(${t.arg}, 1) = 0 THEN '' ELSE CHR(${t.arg}) END`)]}UN.fnChr=Dqe});var Kfe=v($N=>{"use strict";Object.defineProperty($N,"__esModule",{value:!0});$N.fnPi=void 0;var uG=Pe();function Nqe(){return[(0,uG.overload)((0,uG.minScalar)("number"),[],(0,uG.sql)`ACOS(-1)`)]}$N.fnPi=Nqe});var Jfe=v(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.STANDARDSQL_FUNCTIONS=void 0;var Fqe=hb(),Xfe=Wfe(),wqe=Yfe(),Lqe=Kfe();Zf.STANDARDSQL_FUNCTIONS=Fqe.FUNCTIONS.clone();Zf.STANDARDSQL_FUNCTIONS.add("pi",Lqe.fnPi);Zf.STANDARDSQL_FUNCTIONS.add("chr",wqe.fnChr);Zf.STANDARDSQL_FUNCTIONS.add("string_agg",Xfe.fnStringAgg);Zf.STANDARDSQL_FUNCTIONS.add("string_agg_distinct",Xfe.fnStringAggDistinct);Zf.STANDARDSQL_FUNCTIONS.seal()});var Zfe=v(jN=>{"use strict";Object.defineProperty(jN,"__esModule",{value:!0});jN.STANDARDSQL_FUNCTIONS=void 0;var Iqe=Jfe();Object.defineProperty(jN,"STANDARDSQL_FUNCTIONS",{enumerable:!0,get:function(){return Iqe.STANDARDSQL_FUNCTIONS}})});var cG=v(zN=>{"use strict";Object.defineProperty(zN,"__esModule",{value:!0});zN.StandardSQLDialect=void 0;var exe=$d(),qn=Ke(),Mqe=Zfe(),Pqe=sb();function txe(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function kqe(t){return["day","week","month","quarter","year"].includes(t)}var Bqe={day_of_week:"dayofweek",day_of_year:"dayofyear"};function HN(t){let e=t.queryTimezone;if(e&&e!=="UTC")return e}var qqe={DATE:{type:"date"},STRING:{type:"string"},INTEGER:{type:"number",numberType:"integer"},INT64:{type:"number",numberType:"integer"},FLOAT:{type:"number",numberType:"float"},FLOAT64:{type:"number",numberType:"float"},NUMERIC:{type:"number",numberType:"float"},BIGNUMERIC:{type:"number",numberType:"float"},TIMESTAMP:{type:"timestamp"},BOOLEAN:{type:"boolean"},BOOL:{type:"boolean"},JSON:{type:"json"}},lG=class extends Pqe.Dialect{constructor(){super(...arguments),this.name="standardsql",this.defaultNumberType="FLOAT64",this.defaultDecimalType="NUMERIC",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!0,this.keywords=`
29
29
  ALL
30
30
  AND
31
31
  ANY
@@ -678,7 +678,7 @@ ${n} ${s}: [`,o.length>0&&(i+=`
678
678
  `)+`
679
679
  ${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=Tp;var oY=class extends Tp{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}};$n.Unimplemented=oY;var YC=class extends Tp{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=YC;var aY=class extends Tp{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}};$n.ExperimentalExperiment=aY;function Xge(t){return t.execute!==void 0}$n.isDocStatement=Xge;function VJe(t){return t instanceof KC||Xge(t)}$n.isDocStatementOrDocStatementList=VJe;var aL=class extends Tp{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=aL;var KC=class t extends aL{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Kge.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,Kge.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=KC;var WJe="5a79a191-06bc-43cf-9b12-58741cd82970";function Jge(t){let e=t.inherits?Jge(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 YJe(t){let e=Jge(t).join("");return(0,QJe.v5)(e,WJe)}var XC=class extends Tp{constructor(e){super(),this.elementType="document",this.globalNameSpace=new GJe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new zJe.Tag({}),this.modelAnnotationTodoList=[],this.statements=new KC(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=YJe(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=XC});var uL=v(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});gS.canMakeEntry=gS.SpaceEntry=void 0;var uY=class{};gS.SpaceEntry=uY;function KJe(t){return"makeEntry"in t}gS.canMakeEntry=KJe});var ua=v(lL=>{"use strict";Object.defineProperty(lL,"__esModule",{value:!0});lL.SpaceField=void 0;var XJe=Ke(),JJe=uL(),lY=class extends JJe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){let r={dataType:e.type,expressionType:"scalar",evalSpace:"input"};return(0,XJe.isFieldTypeDef)(e)&&e.expressionType&&(r.expressionType=e.expressionType),r.dataType==="unsupported"&&e.type==="unsupported"&&e.rawType&&(r.rawType=e.rawType),r}getQueryFieldDef(e){}fieldDef(){}};lL.SpaceField=lY});var fL=v(cL=>{"use strict";Object.defineProperty(cL,"__esModule",{value:!0});cL.ViewField=void 0;var ZJe=ua(),cY=class extends ZJe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){return{dataType:"turtle",expressionType:"scalar",evalSpace:"input"}}};cL.ViewField=cY});var Zge=v(xL=>{"use strict";Object.defineProperty(xL,"__esModule",{value:!0});xL.ASTViewField=void 0;var eZe=fL(),fY=class extends eZe.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)}};xL.ASTViewField=fY});var dY=v(dL=>{"use strict";Object.defineProperty(dL,"__esModule",{value:!0});dL.ViewFieldDeclaration=void 0;var tZe=mt(),rZe=Vc(),nZe=K9(),iZe=Zge(),xY=class extends tZe.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=rZe.extendNoteMethod}makeEntry(e){let r=new iZe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getFieldDef(e){let{pipeline:r,annotation:n}=this.view.pipelineComp(e),i=(0,nZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:n},location:this.location}}};dL.ViewFieldDeclaration=xY});var Ii=v(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});yS.LegalRefinementStage=yS.QueryClass=void 0;var e3e;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(e3e||(yS.QueryClass=e3e={}));var t3e;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(t3e||(yS.LegalRefinementStage=t3e={}))});var pY=v(hL=>{"use strict";Object.defineProperty(hL,"__esModule",{value:!0});hL.NestFieldDeclaration=void 0;var sZe=K9(),oZe=dY(),r3e=Ii(),hY=class extends oZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=r3e.LegalRefinementStage.Single,this.forceQueryClass=r3e.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,sZe.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")}};hL.NestFieldDeclaration=hY});var la=v(pL=>{"use strict";Object.defineProperty(pL,"__esModule",{value:!0});pL.ErrorFactory=void 0;var n3e={type:"struct",name:"~malformed~",dialect:"~malformed~",structSource:{type:"table",tablePath:"//undefined_error_table_path"},structRelationship:{type:"basetable",connectionName:"//undefined_error_connection"},fields:[]},mY=class t{static get structDef(){return{...n3e}}static isErrorStructDef(e){return e.name.includes(n3e.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:[]}}};pL.ErrorFactory=mY});var yY=v(mL=>{"use strict";Object.defineProperty(mL,"__esModule",{value:!0});mL.HasParameter=void 0;var aZe=Ke(),uZe=mt(),gY=class extends uZe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,this.isCondition=e.isCondition,e.type&&(0,aZe.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}}};mL.HasParameter=gY});var s3e=v(ES=>{"use strict";Object.defineProperty(ES,"__esModule",{value:!0});ES.DefineSourceList=ES.DefineSource=void 0;var lZe=la(),cZe=yY(),i3e=mt(),fZe=Vc(),EY=class extends i3e.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=fZe.extendNoteMethod,r&&this.has({sourceExpr:r}),i){this.parameters=[];for(let s of i)s instanceof cZe.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(lZe.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})}}};ES.DefineSource=EY;var AY=class extends i3e.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}};ES.DefineSourceList=AY});var a3e=v(AS=>{"use strict";Object.defineProperty(AS,"__esModule",{value:!0});AS.DefineQueryList=AS.DefineQuery=void 0;var o3e=mt(),xZe=Vc(),SY=class extends o3e.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=xZe.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})}};AS.DefineQuery=SY;var vY=class extends o3e.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}};AS.DefineQueryList=vY});var Mx=v(gL=>{"use strict";Object.defineProperty(gL,"__esModule",{value:!0});gL.Source=void 0;var dZe=mt(),_Y=class extends dZe.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}};gL.Source=_Y});var yL=v(SS=>{"use strict";Object.defineProperty(SS,"__esModule",{value:!0});SS.mergeFields=SS.nameFromDef=void 0;function bY(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}SS.nameFromDef=bY;function hZe(t,e){if(t===void 0)return e;let r=new Set(e.map(i=>bY(i))),n=t.filter(i=>!r.has(bY(i)));return n.push(...e),n}SS.mergeFields=hZe});var EL=v(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});Cp.DefinedParameter=Cp.AbstractParameter=Cp.SpaceParam=void 0;var pZe=uL(),JC=class extends pZe.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}};Cp.SpaceParam=JC;var TY=class extends JC{constructor(e){super(),this.astParam=e}parameter(){return this.astParam.parameter()}typeDesc(){return{dataType:this.astParam.type||"error",expressionType:"scalar",evalSpace:"input"}}};Cp.AbstractParameter=TY;var CY=class extends JC{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{dataType:this.paramDef.type,expressionType:"scalar",evalSpace:"input"}}};Cp.DefinedParameter=CY});var ZC=v(AL=>{"use strict";Object.defineProperty(AL,"__esModule",{value:!0});AL.StructSpaceFieldBase=void 0;var mZe=ua(),RY=class extends mZe.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"}}};AL.StructSpaceFieldBase=RY});var DY=v(SL=>{"use strict";Object.defineProperty(SL,"__esModule",{value:!0});SL.ColumnSpaceField=void 0;var gZe=ua(),OY=class extends gZe.SpaceField{constructor(e){super(),this.haveFieldDef=e}fieldDef(){return this.haveFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.haveFieldDef)}};SL.ColumnSpaceField=OY});var u3e=v(vL=>{"use strict";Object.defineProperty(vL,"__esModule",{value:!0});vL.IRViewField=void 0;var yZe=fL(),NY=class extends yZe.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()}};vL.IRViewField=NY});var el=v(vS=>{"use strict";Object.defineProperty(vS,"__esModule",{value:!0});vS.StructSpaceField=vS.StaticSpace=void 0;var EZe=AF(),AZe=Ke(),SZe=EL(),vZe=ua(),_L=ZC(),_Ze=DY(),bZe=u3e(),bL=class{constructor(e){this.type="fieldSpace",this.fromStruct=e}dialectObj(){try{return(0,EZe.getDialect)(this.fromStruct.dialect)}catch{return}}defToSpaceField(e){return e.type==="struct"?new TL(e):(0,AZe.isTurtleDef)(e)?new bZe.IRViewField(this,e):new _Ze.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 SZe.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 vZe.SpaceField){let o=i.fieldDef();o&&r.addReference({type:i instanceof _L.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:r.location,text:r.refString})}let s=i instanceof _L.StructSpaceFieldBase?[{name:r.refString,structRelationship:i.structRelationship}]:[];if(n.length){if(i instanceof _L.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}};vS.StaticSpace=bL;var TL=class extends _L.StructSpaceFieldBase{constructor(e){super(e)}get fieldSpace(){return new bL(this.sourceDef)}};vS.StructSpaceField=TL});var wY=v(CL=>{"use strict";Object.defineProperty(CL,"__esModule",{value:!0});CL.JoinSpaceField=void 0;var TZe=el(),FY=class extends TZe.StructSpaceField{constructor(e){super(e.structDef()),this.join=e}};CL.JoinSpaceField=FY});var IY=v(RL=>{"use strict";Object.defineProperty(RL,"__esModule",{value:!0});RL.SpaceSeed=void 0;var CZe=el();function l3e(t){return t.type==="fieldSpace"}var LY=class{constructor(e){this.sourceSpec=e,this.spaceSpec=e}get structDef(){return l3e(this.spaceSpec)?(this.asStruct||(this.asStruct=this.spaceSpec.structDef()),this.asStruct):this.spaceSpec}get fieldSpace(){return l3e(this.spaceSpec)?this.spaceSpec:(this.asFS||(this.asFS=new CZe.StaticSpace(this.spaceSpec)),this.asFS)}};RL.SpaceSeed=LY});var f3e=v(OL=>{"use strict";Object.defineProperty(OL,"__esModule",{value:!0});OL.DynamicSpace=void 0;var RZe=yL(),OZe=la(),DZe=ua(),NZe=wY(),FZe=fL(),c3e=EL(),wZe=IY(),LZe=el(),IZe=ZC(),MY=class extends LZe.StaticSpace{constructor(e){let r=new wZe.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 c3e.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,RZe.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 IZe.StructSpaceFieldBase?n.push([a,u]):u instanceof FZe.ViewField?i.push([a,u]):u instanceof DZe.SpaceField?r.push([a,u]):u instanceof c3e.SpaceParam&&(e[a]=u.parameter());let o=[...r,...n,...i];for(let[,a]of o)if(a instanceof NZe.JoinSpaceField){let u=a.join.structDef();OZe.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}};OL.DynamicSpace=MY});var NL=v(DL=>{"use strict";Object.defineProperty(DL,"__esModule",{value:!0});DL.RefinedSpace=void 0;var MZe=f3e(),PZe=uL(),PY=class t extends MZe.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,PZe.canMakeEntry)(r)?r.makeEntry(this):r.log(`Internal error, ${r.elementType} not expected in this context`)}};DL.RefinedSpace=PY});var r0=v(FL=>{"use strict";Object.defineProperty(FL,"__esModule",{value:!0});FL.DefinitionList=void 0;var kZe=mt(),x3e=Vc(),kY=class extends kZe.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,x3e.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(let e of this.elements)(0,x3e.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}};FL.DefinitionList=kY});var _S=v(wL=>{"use strict";Object.defineProperty(wL,"__esModule",{value:!0});wL.DeclareFields=void 0;var BZe=r0(),qZe=Ii(),BY=class extends BZe.DefinitionList{constructor(e){super(e),this.elementType="declareFields",this.queryRefinementStage=qZe.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(let r of this.list)e.inputFS.extendSource(r)}};wL.DeclareFields=BY});var hs=v(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});Rp.nullsafeNot=Rp.compressExpr=Rp.compose=void 0;var UZe=Ke();function d3e(t){return t.length>1?["(",...t,")"]:t.length===0?["__MISSING_VALUE__"]:t}function $Ze(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[...d3e(t),o,...d3e(r)]}Rp.compose=$Ze;function jZe(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}Rp.compressExpr=jZe;function HZe(t,e){return e===void 0||e==="!="||e==="!~"?(0,UZe.mkExpr)`COALESCE(NOT(${t}),FALSE)`:t}Rp.nullsafeNot=HZe});var Wm=v(bS=>{"use strict";Object.defineProperty(bS,"__esModule",{value:!0});bS.Filter=bS.FilterElement=void 0;var h3e=Ke(),zZe=hs(),p3e=mt(),qY=Ii(),UY=class extends p3e.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,zZe.compressExpr)(r.value),expressionType:r.expressionType}}};bS.FilterElement=UY;var $Y=class extends p3e.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=qY.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?qY.LegalRefinementStage.Tail:qY.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,h3e.expressionIsAggregate)(i.expressionType),o=(0,h3e.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}};bS.Filter=$Y});var TS=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.Joins=Wc.ExpressionJoin=Wc.KeyJoin=Wc.Join=void 0;var GZe=Ke(),QZe=hs(),VZe=wY(),WZe=r0(),YZe=mt(),KZe=Vc(),XZe=Ii(),m3e=la(),e5=class extends YZe.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=KZe.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new VZe.JoinSpaceField(this))}getStructDefFromExpr(){let e=this.sourceExpr.getSource();return e?e.structDef():(this.sourceExpr.sqLog("Cannot great a source to join from"),m3e.ErrorFactory.structDef)}};Wc.Join=e5;var jY=class extends e5{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=jY;var HY=class extends e5{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,GZe.isJoinOn)(i)&&(i.onExpression=(0,QZe.compressExpr)(n.value))}structDef(){var e;let r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("Cannot create a source to join from"),m3e.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=HY;var zY=class extends WZe.DefinitionList{constructor(e){super(e),this.elementType="joinList",this.forceQueryClass=void 0,this.queryRefinementStage=XZe.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)e.inputFS.extendSource(r)}};Wc.Joins=zY});var IL=v(LL=>{"use strict";Object.defineProperty(LL,"__esModule",{value:!0});LL.FieldListEdit=void 0;var JZe=mt(),GY=class extends JZe.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}};LL.FieldListEdit=GY});var PL=v(ML=>{"use strict";Object.defineProperty(ML,"__esModule",{value:!0});ML.PrimaryKey=void 0;var ZZe=mt(),QY=class extends ZZe.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}};ML.PrimaryKey=QY});var BL=v(kL=>{"use strict";Object.defineProperty(kL,"__esModule",{value:!0});kL.Views=void 0;var eet=r0(),VY=class extends eet.DefinitionList{constructor(){super(...arguments),this.elementType="turtleDefList"}};kL.Views=VY});var UL=v(qL=>{"use strict";Object.defineProperty(qL,"__esModule",{value:!0});qL.TimezoneStatement=void 0;var tet=mt(),WY=class extends tet.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)}};qL.TimezoneStatement=WY});var jL=v(CS=>{"use strict";Object.defineProperty(CS,"__esModule",{value:!0});CS.ModelAnnotation=CS.ObjectAnnotation=void 0;var ret=Vm(),net=mt(),$L=class extends net.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}};CS.ObjectAnnotation=$L;var YY=class extends $L{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){let n=ret.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)}};CS.ModelAnnotation=YY});var g3e=v(HL=>{"use strict";Object.defineProperty(HL,"__esModule",{value:!0});HL.RenameSpaceField=void 0;var iet=ua(),KY=class extends iet.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()}};HL.RenameSpaceField=KY});var zL=v(RS=>{"use strict";Object.defineProperty(RS,"__esModule",{value:!0});RS.Renames=RS.RenameField=void 0;var set=g3e(),y3e=mt(),oet=ua(),XY=class extends y3e.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 oet.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new set.RenameSpaceField(r.found,this.newName,this.location)):this.log(`'${this.oldName}' cannot be renamed`):this.log(`Can't rename '${this.oldName}', no such field`)}};RS.RenameField=XY;var JY=class extends y3e.ListOf{constructor(){super(...arguments),this.elementType="renameFields"}};RS.Renames=JY});var eK=v(GL=>{"use strict";Object.defineProperty(GL,"__esModule",{value:!0});GL.RefinedSource=void 0;var aet=Ke(),uet=NL(),cet=_S(),fet=Wm(),xet=TS(),det=IL(),het=PL(),pet=BL(),met=Mx(),get=UL(),yet=jL(),Eet=zL(),ZY=class extends met.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 yet.ObjectAnnotation)continue;let h=d;d instanceof het.PrimaryKey?(n&&(n.log("Primary key already defined"),d.log("Primary key redefined")),n=d):d instanceof det.FieldListEdit?(i&&(i.log("Too many accept/except statements"),d.log("Too many accept/except statements")),i=d):d instanceof cet.DeclareFields||d instanceof xet.Joins||d instanceof pet.Views||d instanceof Eet.Renames?s.push(...d.list):d instanceof fet.Filter?o.push(d):d instanceof get.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=uet.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,aet.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)}};GL.RefinedSource=ZY});var Op=v(QL=>{"use strict";Object.defineProperty(QL,"__esModule",{value:!0});QL.SourceQueryElement=void 0;var Aet=mt(),tK=class t extends Aet.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}};QL.SourceQueryElement=tK});var t5=v(VL=>{"use strict";Object.defineProperty(VL,"__esModule",{value:!0});VL.QuerySource=void 0;var vet=Mx(),rK=class extends vet.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}};VL.QuerySource=rK});var iK=v(WL=>{"use strict";Object.defineProperty(WL,"__esModule",{value:!0});WL.QueryBase=void 0;var _et=K9(),bet=mt(),nK=class extends bet.MalloyElement{query(){let e=this.queryComp(!0).query;return{...e,pipeline:(0,_et.detectAndRemovePartialStages)(e.pipeline,this)}}};WL.QueryBase=nK});var KL=v(YL=>{"use strict";Object.defineProperty(YL,"__esModule",{value:!0});YL.QueryArrow=void 0;var Tet=Ke(),Cet=Mx(),E3e=el(),Ret=iK(),sK=class extends Ret.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 Cet.Source){let l=e?this.source.structRef():this.source.structDef();n={type:"query",structRef:l,pipeline:[],location:this.location},r=(0,Tet.refIsStructDef)(l)?l:this.source.structDef(),i=new E3e.StaticSpace(r)}else{let l=this.source.queryComp(e);n=l.query,r=l.outputStruct,i=new E3e.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}}};YL.QueryArrow=sK});var A3e=v(XL=>{"use strict";Object.defineProperty(XL,"__esModule",{value:!0});XL.SQArrow=void 0;var Oet=Op(),Det=t5(),Net=KL(),oK=class extends Oet.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 Net.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 Det.QuerySource(e);return this.has({asSource:r}),r}};XL.SQArrow=oK});var Ym=v(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});Dp.getStructFieldDef=Dp.getFinalStruct=Dp.opOutputStruct=void 0;var Fet=Qd(),wet=qG(),Let=Ke(),S3e=la();function v3e(t,e,r){let n=S3e.ErrorFactory.isErrorStructDef(e);if((0,Let.isPartialSegment)(r)&&(r={...r,type:"reduce"}),!n)try{return wet.Segment.nextStructDef(e,r)}catch(i){t.log(`INTERNAL ERROR model/Segment.nextStructDef: ${i.message}
680
680
  QUERY: ${(0,Fet.inspect)(r,{breakLength:72,depth:1/0})}`)}return{...S3e.ErrorFactory.structDef,dialect:e.dialect}}Dp.opOutputStruct=v3e;function Iet(t,e,r){for(let n of r)e=v3e(t,e,n);return e}Dp.getFinalStruct=Iet;function Met(t,e){return t.fields.find(r=>(r.as||r.name)===e)}Dp.getStructFieldDef=Met});var ZL=v(JL=>{"use strict";Object.defineProperty(JL,"__esModule",{value:!0});JL.QueryRefine=void 0;var Pet=el(),ket=Ym(),Bet=iK(),aK=class extends Bet.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 Pet.StaticSpace(r.inputStruct),i=this.refinement.refine(n,r.query.pipeline,void 0);return{query:{...r.query,pipeline:i},outputStruct:(0,ket.getFinalStruct)(this.refinement,r.inputStruct,i),inputStruct:r.inputStruct}}};JL.QueryRefine=aK});var OS=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 qet=Ke(),_3e=hs();function Uet(t,e,r,n,i){return[{type:"dialect",function:"delta",base:{valueType:t,value:e},op:r,delta:n,units:i}]}Mi.timeOffset=Uet;function $et(t,e,r,n=!1){let i={type:"dialect",function:"cast",dstType:t,expr:e,safe:n};return(0,qet.isAtomicFieldType)(r)&&(i.srcType=r),[i]}Mi.castTo=$et;function jet(t,e=!1){return[{type:"dialect",function:"cast",dstType:"date",srcType:"timestamp",expr:t,safe:e}]}Mi.castTimestampToDate=jet;function Het(t,e=!1){return[{type:"dialect",function:"cast",dstType:"timestamp",srcType:"date",expr:t,safe:e}]}Mi.castDateToTimestamp=Het;function zet(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Mi.resolution=zet;function Get(t,e){return e?{...t,timeframe:e}:t}Mi.timeResult=Get;function Qet(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,_3e.compressExpr)([`TIMESTAMP${o}(`,...u,",INTERVAL ",...r,` ${a})`])}Mi.timestampOffset=Qet;function Vet(t,e,r,n){let i=e==="+"?"_ADD":"_SUB",s=n.toUpperCase();return(0,_3e.compressExpr)([`DATE${i}(`,...t,",INTERVAL ",...r,` ${s})`])}Mi.dateOffset=Vet});var r5=v(DS=>{"use strict";Object.defineProperty(DS,"__esModule",{value:!0});DS.NamedSource=DS.IsValueBlock=void 0;var eI=Ke(),Wet=Mx(),Yet=la(),Ket=OS(),tI=mt(),rI=class extends tI.MalloyElement{constructor(e){super(),this.isMap=e,this.elementType="isValueBlock",this.has(e)}};DS.IsValueBlock=rI;var uK=class extends Wet.Source{constructor(e,r={}){super(),this.ref=e,this.elementType="namedSource",r&&Object.keys(r).length>0&&(this.isBlock=new rI(r),this.has({parameterValues:this.isBlock})),e instanceof tI.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof tI.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 tI.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,eI.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=Yet.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,eI.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,eI.isCastType)(u.type)&&(c=(0,Ket.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,eI.paramHasValue)(i[o])||this.log(`Value not provided for required parameter ${o}`);return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(n),n}};DS.NamedSource=uK});var b3e=v(nI=>{"use strict";Object.defineProperty(nI,"__esModule",{value:!0});nI.QueryHeadStruct=void 0;var Xet=Ke(),Jet=Mx(),Zet=r5(),lK=class extends Jet.Source{constructor(e){super(),this.fromRef=e,this.elementType="internalOnlyQueryHead"}structRef(){return this.fromRef}structDef(){if((0,Xet.refIsStructDef)(this.fromRef))return this.fromRef;let e=new Zet.NamedSource(this.fromRef);return this.has({exploreReference:e}),e.structDef()}};nI.QueryHeadStruct=lK});var xK=v(iI=>{"use strict";Object.defineProperty(iI,"__esModule",{value:!0});iI.QueryReference=void 0;var cK=la(),ett=mt(),ttt=b3e(),rtt=Ke(),ntt=Ym(),fK=class extends ett.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:cK.ErrorFactory.structDef,outputStruct:cK.ErrorFactory.structDef,query:cK.ErrorFactory.query}};if(!n)return this.log(`Reference to undefined query '${this.name.refString}'`),i();if(n.type==="query"){let s=new ttt.QueryHeadStruct(n.structRef);this.has({queryHead:s});let o=s.structDef(),a=(0,ntt.getFinalStruct)(this,o,n.pipeline);return{query:e||(0,rtt.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}};iI.QueryReference=fK});var hK=v(sI=>{"use strict";Object.defineProperty(sI,"__esModule",{value:!0});sI.SQReference=void 0;var itt=Op(),stt=t5(),ott=r5(),T3e=xK(),dK=class extends itt.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 T3e.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 T3e.QueryReference(this.ref);this.asSource=new stt.QuerySource(r)}else if(e.type==="struct")this.asSource=new ott.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}};sI.SQReference=dK});var C3e=v(oI=>{"use strict";Object.defineProperty(oI,"__esModule",{value:!0});oI.SQRefine=void 0;var att=Op(),utt=t5(),ltt=ZL(),ctt=hK(),pK=class extends att.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 ctt.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 ltt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){let e=this.getQuery();if(e){let r=new utt.QuerySource(e);return this.has({queryAsSource:r}),r}}};oI.SQRefine=pK});var gK=v(aI=>{"use strict";Object.defineProperty(aI,"__esModule",{value:!0});aI.QueryRaw=void 0;var ftt=Ke(),xtt=mt(),mK=class extends xtt.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,ftt.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}};aI.QueryRaw=mK});var yK=v(uI=>{"use strict";Object.defineProperty(uI,"__esModule",{value:!0});uI.makeSQLBlock=void 0;var dtt=Ke(),htt=$d();function ptt(t,e){let r={name:`md5:/${e||"$default"}//${mtt(t)}`,select:t};return e&&(r.connection=e),r}uI.makeSQLBlock=ptt;function mtt(t){let e=t.map(r=>(0,dtt.isSQLFragment)(r)?r.sql:JSON.stringify(r));return(0,htt.generateHash)(e.join(";"))}});var AK=v(cI=>{"use strict";Object.defineProperty(cI,"__esModule",{value:!0});cI.SQLSource=void 0;var gtt=yK(),ytt=Mx(),lI=la(),EK=class extends ytt.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,gtt.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 lI.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"),lI.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(`
681
- `)),lI.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"),lI.ErrorFactory.structDef}};cI.SQLSource=EK});var R3e=v(fI=>{"use strict";Object.defineProperty(fI,"__esModule",{value:!0});fI.SQSource=void 0;var Ett=Op(),Att=gK(),Stt=AK(),SK=class extends Ett.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 Stt.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")}};fI.SQSource=SK});var O3e=v(xI=>{"use strict";Object.defineProperty(xI,"__esModule",{value:!0});xI.SQExtend=void 0;var vtt=eK(),_tt=Op(),vK=class extends _tt.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 vtt.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}};xI.SQExtend=vK});var dI=v(NS=>{"use strict";Object.defineProperty(NS,"__esModule",{value:!0});NS.isComparison=NS.Comparison=void 0;var _K;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(_K||(NS.Comparison=_K={}));function btt(t){return Object.values(_K).includes(t)}NS.isComparison=btt});var pn=v(hI=>{"use strict";Object.defineProperty(hI,"__esModule",{value:!0});hI.FT=void 0;var Ttt=uc();function Km(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,Ttt.expressionIsScalar)(n.expressionType)||(i=`${n.expressionType} ${i}`),i}return"undefined"}).join(",")}};hI.FT=$s;$s.nullT=Km("null");$s.numberT=Km("number");$s.stringT=Km("string");$s.dateT=Km("date");$s.timestampT=Km("timestamp");$s.boolT=Km("boolean");$s.anyAtomicT=[$s.numberT,$s.stringT,$s.dateT,$s.timestampT,$s.boolT];$s.aggregateBoolT=Km("boolean","aggregate")});var mI=v(pI=>{"use strict";Object.defineProperty(pI,"__esModule",{value:!0});pI.isGranularResult=void 0;function Ctt(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}pI.isGranularResult=Ctt});var js=v(gI=>{"use strict";Object.defineProperty(gI,"__esModule",{value:!0});gI.errorFor=void 0;function Rtt(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}gI.errorFor=Rtt});var D3e=v(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});FS.isEquality=FS.Equality=void 0;var bK;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(bK||(FS.Equality=bK={}));function Ott(t){return Object.values(bK).includes(t)}FS.isEquality=Ott});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(),wS=js(),Px=hs(),Xm=pn(),yI=OS(),Dtt=dI(),Ntt=D3e(),w3e=mI(),Ftt=mt(),CK=class extends Error{},EI=class extends Ftt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Xm.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.dataType!=="error"&&!Xm.FT.in(r,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${Xm.FT.inspect(r)}`),!1):!0}apply(e,r,n){return M3e(e,n,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,mn.expressionIsAggregate)(e.expressionType)}};Yc.ExpressionDef=EI;var n5=class extends EI{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Xm.FT.timestampT,Xm.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(!Xm.FT.typeEq(s,Xm.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,wS.errorFor)("illegal unit expression");let o;if((0,w3e.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){let a=(0,yI.timeOffset)("timestamp",i.value,r,s.value,this.timeframe);return(0,yI.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,yI.timeResult)({dataType:"date",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,yI.timeOffset)("date",i.value,r,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,wS.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=n5;function N3e(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function wtt(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}Yc.getMorphicValue=wtt;function L3e(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=N3e(e,"timestamp"),a=N3e(n,"timestamp");if(o&&a)return(0,Px.compose)(o,r,a)}else return(0,Px.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 F3e(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 Ltt(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 Itt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=i5("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=s5(e,i,n,s);if(f)return{...f,dataType:"boolean"}}}let u=L3e(e,i,r,s)||(0,Px.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,Px.compose)(i.value,"LIKE",s.value);else{let l=F3e(i,s);if(l===void 0)throw new CK("Incompatible types for match('~') operator");u=l}u=(0,Px.nullsafeNot)(u,r);break}case"=":case"!=":{let l=Ltt(i,r,s);l?u=l:u=(0,Px.nullsafeNot)(F3e(i,s)||(0,Px.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 Mtt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=i5("boolean",i,s);if(o)return o;let a=(0,mn.maxExpressionType)(i.expressionType,s.expressionType),u=s5(e,i,n,s);if(u)return{...u,dataType:"boolean"};let l=L3e(e,i,r,s)||(0,Px.compose)(i.value,r,s.value);return{dataType:"boolean",expressionType:a,evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function TK(t,...e){return e.includes(t)}function Ptt(t,...e){for(let r of e)if(r.dataType!==t)return!1;return!0}function I3e(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=i5("number",i,s);if(o)return o;let a=s5(e,i,n,s);if(a)return a;let u=(0,mn.maxExpressionType)(i.expressionType,s.expressionType);return Ptt("number",i,s)?{dataType:"number",expressionType:u,value:(0,Px.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,wS.errorFor)("numbers required"))}function ktt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5(e,i,n,s);if(o)return o;let a=(0,mn.isTimeFieldType)(i.dataType),u=i5(a?"error":"number",i,s);if(u)return u;if(a){let l=n;if(s.dataType!=="duration")if((0,w3e.isGranularResult)(i))l=new n5(n,i.timeframe);else if(i.dataType==="date")l=new n5(n,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,wS.errorFor)(`time plus ${s.dataType}`);return l.apply(t,r,e)}return I3e(t,e,r,n)}function M3e(t,e,r,n){if((0,Ntt.isEquality)(r))return Itt(t,e,r,n);if((0,Dtt.isComparison)(r))return Mtt(t,e,r,n);if(TK(r,"+","-"))return ktt(t,e,r,n);if(TK(r,"*","%"))return I3e(t,e,r,n);if(TK(r,"/")){let i=e.getExpression(t),s=n.getExpression(t),o=s5(e,i,n,s);if(o)return e.log("Cannot operate with unsupported type"),o;let a=i5("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,wS.errorFor)("divide type mismatch")}return e.log(`Cannot use ${r} operator here`),(0,wS.errorFor)("applybinary bad operator")}Yc.applyBinary=M3e;function i5(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 s5(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 SI=v(AI=>{"use strict";Object.defineProperty(AI,"__esModule",{value:!0});AI.BinaryBoolean=void 0;var P3e=Ke(),Btt=js(),qtt=pn(),Utt=ir(),$tt=hs(),RK=class extends Utt.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=[qtt.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,P3e.mergeEvalSpaces)(r.evalSpace,n.evalSpace);return{dataType:"boolean",expressionType:(0,P3e.maxExpressionType)(r.expressionType,n.expressionType),evalSpace:i,value:(0,$tt.compose)(r.value,this.op,n.value)}}return(0,Btt.errorFor)("logial required boolean")}};AI.BinaryBoolean=RK});var _I=v(vI=>{"use strict";Object.defineProperty(vI,"__esModule",{value:!0});vI.ExprTime=void 0;var jtt=Ke(),Htt=hs(),ztt=ir(),OK=class t extends ztt.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,jtt.isTimeFieldType)(r.dataType)&&(i.srcType=r.dataType),n=(0,Htt.compressExpr)([i])}return new t(e,n,r.expressionType)}};vI.ExprTime=OK});var LS=v(bI=>{"use strict";Object.defineProperty(bI,"__esModule",{value:!0});bI.Range=void 0;var k3e=Ke(),Gtt=js(),Qtt=ir(),Vtt=hs(),DK=class extends Qtt.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,k3e.maxExpressionType)(a.expressionType,u.expressionType),evalSpace:(0,k3e.mergeEvalSpaces)(a.evalSpace,u.evalSpace),value:(0,Vtt.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,Gtt.errorFor)("a range is not a value")}};bI.Range=DK});var wK=v(CI=>{"use strict";Object.defineProperty(CI,"__esModule",{value:!0});CI.ExprGranularTime=void 0;var NK=Ke(),Wtt=js(),B3e=pn(),q3e=OS(),Ytt=ir(),TI=_I(),U3e=LS(),FK=class extends Ytt.ExpressionDef{constructor(e,r,n){super({expr:e}),this.expr=e,this.units=r,this.truncate=n,this.elementType="granularTime",this.legalChildTypes=[B3e.FT.timestampT,B3e.FT.dateT]}granular(){return!0}getExpression(e){let r=this.units,n=this.expr.getExpression(e);if((0,NK.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,NK.isDateUnit)(r)?"date":"timestamp":n.dataType;return{...n,dataType:i,value:(0,Wtt.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=TI.ExprTime.fromValue("timestamp",r),a=new TI.ExprTime("timestamp",(0,q3e.timeOffset)("timestamp",r.value,"+",(0,NK.mkExpr)`1`,this.units),r.expressionType);return new U3e.Range(o,a)}let n=new TI.ExprTime("date",r.value,r.expressionType),i=(0,q3e.timeOffset)("date",r.value,"+",["1"],this.units),s=new TI.ExprTime("date",i,r.expressionType);return new U3e.Range(n,s)}};CI.ExprGranularTime=FK});var IK=v(RI=>{"use strict";Object.defineProperty(RI,"__esModule",{value:!0});RI.ExprCompare=void 0;var Cr=pn(),Ktt=mI(),Xtt=SI(),Jtt=wK(),Ztt={"~":[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]},LK=class extends Xtt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="a<=>b",this.legalChildTypes=Ztt[r]}getExpression(e){if(!this.right.granular()){let r=this.right.requestExpression(e);if(r&&(0,Ktt.isGranularResult)(r))return new Jtt.ExprGranularTime(this.right,r.timeframe,!1).apply(e,this.op,this.left)}return this.right.apply(e,this.op,this.left)}};RI.ExprCompare=LK});var $3e=v(OI=>{"use strict";Object.defineProperty(OI,"__esModule",{value:!0});OI.Apply=void 0;var ert=dI(),trt=IK(),MK=class extends trt.ExprCompare{constructor(e,r){super(e,ert.Comparison.EqualTo,r),this.left=e,this.right=r,this.elementType="apply"}};OI.Apply=MK});var NI=v(DI=>{"use strict";Object.defineProperty(DI,"__esModule",{value:!0});DI.BinaryNumeric=void 0;var rrt=pn(),nrt=ir(),PK=class extends nrt.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=[rrt.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}};DI.BinaryNumeric=PK});var j3e=v(FI=>{"use strict";Object.defineProperty(FI,"__esModule",{value:!0});FI.Boolean=void 0;var irt=ir(),srt=pn(),kK=class extends irt.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...srt.FT.boolT,value:[this.value]}}};FI.Boolean=kK});var LI=v(wI=>{"use strict";Object.defineProperty(wI,"__esModule",{value:!0});wI.ExprIdReference=void 0;var BK=Ke(),ort=js(),art=EL(),urt=ir(),qK=class extends urt.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,BK.expressionIsAggregate)(n.expressionType)?"output":n.evalSpace;return{...n,value:i,evalSpace:s}}return this.log(r.error),(0,ort.errorFor)(r.error)}apply(e,r,n){let i=this.fieldReference.getField(e).found;if(i instanceof art.SpaceParam){let s=i.parameter();if((0,BK.isConditionParameter)(s)){let o=n.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,BK.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,r,n)}};wI.ExprIdReference=qK});var II=v(IS=>{"use strict";Object.defineProperty(IS,"__esModule",{value:!0});IS.FunctionOrdering=IS.FunctionOrderBy=void 0;var UK=Ke(),H3e=mt(),lrt=LI(),$K=class extends H3e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.log("analytic `order_by` must specify an aggregate expression or output field reference"),{e:["error"],dir:this.dir};let r=this.field.getExpression(e);return(0,UK.expressionIsAggregate)(r.expressionType)||((0,UK.expressionIsScalar)(r.expressionType)?(!(this.field instanceof lrt.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,r){if(this.field){let n=this.field.getExpression(e);return(0,UK.expressionIsScalar)(n.expressionType)||this.field.log("aggregate `order_by` must be scalar"),r||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:n.value,dir:this.dir}}else return this.dir===void 0?(this.log("field or order direction must be specified"),{e:void 0,dir:"asc"}):{e:void 0,dir:this.dir}}};IS.FunctionOrderBy=$K;var jK=class extends H3e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(n=>n.getAggregateOrderBy(e,r))}};IS.FunctionOrdering=jK});var z3e=v(MI=>{"use strict";Object.defineProperty(MI,"__esModule",{value:!0});MI.ExprAddSub=void 0;var crt=NI(),HK=class extends crt.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}};MI.ExprAddSub=HK});var GK=v(PI=>{"use strict";Object.defineProperty(PI,"__esModule",{value:!0});PI.ReferenceField=void 0;var G3e=ua(),zK=class extends G3e.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 G3e.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"}}};PI.ReferenceField=zK});var QK=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=uc();function frt(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=frt;function xrt(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=xrt;function drt(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=drt;function hrt(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=hrt;function prt(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=prt;function mrt(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=mrt;function grt(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=grt;function yrt(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=yrt});var MS=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 Ert=GK(),Art=r0(),Q3e=mt(),V3e=Vc(),Np=QK(),Co=class extends Q3e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=V3e.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 Ert.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 VK=class extends Co{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}};Gt.AcceptExceptFieldReference=VK;var WK=class extends Co{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}};Gt.ExpressionFieldReference=WK;var YK=class extends Co{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}};Gt.PartitionByFieldReference=YK;var KK=class extends Co{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Np.typecheckCalculate)(e,this)}};Gt.CalculateFieldReference=KK;var XK=class t extends Co{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Np.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return t.indexOutputName(this.path)}};Gt.IndexFieldReference=XK;var JK=class extends Co{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Np.typecheckAggregate)(e,this)}};Gt.AggregateFieldReference=JK;var ZK=class extends Co{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Np.typecheckGroupBy)(e,this)}};Gt.GroupByFieldReference=ZK;var eX=class extends Co{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Np.typecheckProject)(e,this)}};Gt.ProjectFieldReference=eX;var tX=class extends Co{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Np.typecheckDeclare)(e,this)}};Gt.DeclareFieldReference=tX;var rX=class extends Co{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Np.typecheckMeasure)(e,this)}};Gt.MeasureFieldReference=rX;var nX=class extends Co{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Np.typecheckDimension)(e,this)}};Gt.DimensionFieldReference=nX;var iX=class extends Co{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}};Gt.ViewOrScalarFieldReference=iX;var sX=class extends Q3e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=V3e.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=sX;var oX=class extends Art.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}};Gt.FieldReferences=oX});var Jm=v(kI=>{"use strict";Object.defineProperty(kI,"__esModule",{value:!0});kI.ExprAggregateFunction=void 0;var W3e=Ke(),Srt=$d(),o5=js(),vrt=el(),_rt=ZC(),brt=pn(),Trt=MS(),Crt=ir(),Rrt=ua(),Ort=LI(),aX=class extends Crt.ExpressionDef{constructor(e,r,n){super(),this.func=e,this.legalChildTypes=[brt.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,W3e.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.length>1&&d.slice(1).every(p=>Drt(p,d[0])))&&(a=d[0].map(p=>p.name),u=d[0])}else if(!(f instanceof _rt.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,o5.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,o5.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,o5.errorFor)("agggregate without expression");if((0,W3e.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,o5.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=lX(u,c),h=cX(this.elementType,d),p=f?h:"Join path is required for this calculation";if(p){let m=Nrt(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,o5.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(...uX(e,i))}if(this.expr){let n=this.expr.getExpression(e).value;r.push(...uX(e,n))}return r}};kI.ExprAggregateFunction=aX;function Drt(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 uX(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 vrt.StructSpaceField&&a.length>0){let l=n(u.fieldSpace,a);return{...l,relationship:[{name:o,structRelationship:u.structRelationship},...l.relationship]}}else if(u instanceof Rrt.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,Srt.exprWalk)(e,i=>{if(typeof i!="string"){if(i.type==="field"){let s=n(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){let o=uX(s.fs,s.def.e);r.push(...o.map(a=>[...s.relationship,...a]))}else r.push(s.relationship)}else if(i.type==="source-reference")if(i.path){let s=n(t,i.path);r.push(s.relationship)}else r.push([])}}),r}function lX(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 cX(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 Nrt(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=lX(i,e),o=cX(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=lX(l,e),f=cX(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 Trt.FieldReference?`${r.refString}.${n}()`:r instanceof Ort.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 K3e=v(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.ExprAlternationTree=void 0;var Y3e=Ke(),Frt=js(),wrt=SI(),Lrt=hs(),fX=class extends wrt.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,Y3e.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Y3e.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,Lrt.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,Frt.errorFor)("no value from alternation tree")}};BI.ExprAlternationTree=fX});var UI=v(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.ExprAsymmetric=void 0;var Irt=Jm(),xX=class extends Irt.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}`}}}};qI.ExprAsymmetric=xX});var X3e=v($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.ExprAvg=void 0;var Mrt=UI(),dX=class extends Mrt.ExprAsymmetric{constructor(e,r,n){super("avg",e,r,n),this.has({source:r})}};$I.ExprAvg=dX});var J3e=v(jI=>{"use strict";Object.defineProperty(jI,"__esModule",{value:!0});jI.ExprCast=void 0;var Prt=OS(),krt=ir(),Brt=hs(),hX=class extends krt.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,Brt.compressExpr)((0,Prt.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}};jI.ExprCast=hX});var eye=v(HI=>{"use strict";Object.defineProperty(HI,"__esModule",{value:!0});HI.ExprCoalesce=void 0;var pX=uc(),Z3e=pn(),qrt=ir(),mX=class extends qrt.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=Z3e.FT.anyAtomicT}getExpression(e){let r=this.expr.getExpression(e),n=this.altExpr.getExpression(e);return r.dataType==="null"?n:(Z3e.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,pX.maxExpressionType)(r.expressionType,n.expressionType),value:(0,pX.mkExpr)`COALESCE(${r.value},${n.value})`,evalSpace:(0,pX.mergeEvalSpaces)(r.evalSpace,n.evalSpace)})}};HI.ExprCoalesce=mX});var tye=v(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.ExprCount=void 0;var Urt=Jm(),gX=class extends Urt.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"}}};zI.ExprCount=gX});var rye=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.ExprCountDistinct=void 0;var GI=pn(),$rt=Jm(),yX=class extends $rt.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[GI.FT.numberT,GI.FT.stringT,GI.FT.dateT,GI.FT.timestampT]}};QI.ExprCountDistinct=yX});var PS=v(VI=>{"use strict";Object.defineProperty(VI,"__esModule",{value:!0});VI.Limit=void 0;var jrt=mt(),Hrt=Ii(),EX=class extends jrt.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Hrt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}};VI.Limit=EX});var YI=v(WI=>{"use strict";Object.defineProperty(WI,"__esModule",{value:!0});WI.PartitionBy=void 0;var zrt=mt(),AX=class extends zrt.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}};WI.PartitionBy=AX});var vX=v(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.ExprFunc=void 0;var n0=Ke(),kx=js(),Grt=ZC(),Qrt=ir(),nye=hs(),SX=class extends Qrt.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,k=[`${this.name}(`];for(let H of u)O=(0,n0.maxExpressionType)(O,H.expressionType),N?k.push(","):N=H.dataType,k.push(...H.value);return k.push(")"),{dataType:(i=(n=this.rawType)!==null&&n!==void 0?n:N)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,nye.compressExpr)(k),evalSpace:(0,n0.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,kx.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,kx.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,n0.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 Grt.StructSpaceFieldBase)){let k=`Aggregate source cannot be a ${N.dataType}`;return this.log(k),(0,kx.errorFor)(k)}}else{let N=`Reference to undefined value ${this.source.refString}`;return this.log(N),(0,kx.errorFor)(N)}}let x=[...c?[c]:[],...u],d=Vrt(l,x);if(d===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,kx.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),k=(0,n0.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${k}, but received ${O.actualExpressionType}`)}for(let O of m){let N=O.argIndex-(c?1:0),k=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 ${k}, 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,A=(0,n0.maxOfExpressionTypes)([y.expressionType,...x.map(O=>O.expressionType)]);if(!(0,n0.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,kx.errorFor)("cannot call with source");let S={type:"function_call",overload:h,name:this.name,args:x.map(O=>O.value),expressionType:A,structPath:f},T=[S],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,n0.expressionIsAnalytic)(h.returnType.expressionType);if(_.supportsOrderBy||O){let N=_.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(P=>O?P.getAnalyticOrderBy(e):P.getAggregateOrderBy(e,N));S.orderBy=k}else r.orderBys[0].log(`Function ${this.name} does not support order_by`)}r?.limit!==void 0&&(_.supportsLimit?S.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 k of N.partitionFields){let P=k.getField(e);P.found===void 0?k.log(`${k.refString} is not defined`):(0,n0.expressionIsScalar)(P.found.typeDesc().expressionType)?O.push(k.nameString):k.log("Partition expression must be scalar")}S.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,kx.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,k=Wrt(N),P=k.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(P.length>0){let H=P.length===1?`'.' paths are not yet supported in sql interpolations, found ${P.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${P.join(", ")}]`;return this.log(H),(0,kx.errorFor)(`${H}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}T=[{type:"sql-string",e:k.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,kx.errorFor)("invalid return type");let R=(0,n0.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),D=R==="constant"?"constant":(0,n0.expressionIsScalar)(A)?R:"output";return{dataType:y.dataType,expressionType:A,value:(0,nye.compressExpr)(T),evalSpace:D}}};KI.ExprFunc=SX;function Vrt(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,n0.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 Wrt(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 iye=v(XI=>{"use strict";Object.defineProperty(XI,"__esModule",{value:!0});XI.ExprProps=void 0;var Yrt=Ke(),Krt=js(),Xrt=pn(),Jrt=II(),Zrt=PS(),ent=YI(),tnt=ir(),rnt=vX(),_X=class extends tnt.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=Xrt.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,Yrt.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,Krt.errorFor)("cannot filter type"))}return r}getExpression(e){let r=[],n,i=[],s=[];for(let a of this.statements)a instanceof ent.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.log("`partition_by` is not supported for this kind of expression"):a instanceof Zrt.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 Jrt.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 rnt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:n,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}};XI.ExprProps=_X});var oye=v(JI=>{"use strict";Object.defineProperty(JI,"__esModule",{value:!0});JI.ExprLogicalOp=void 0;var nnt=SI(),sye=pn(),bX=class extends nnt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[sye.FT.boolT,sye.FT.aggregateBoolT]}};JI.ExprLogicalOp=bX});var aye=v(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.ExprMax=void 0;var ZI=pn(),int=Jm(),TX=class extends int.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[ZI.FT.numberT,ZI.FT.stringT,ZI.FT.dateT,ZI.FT.timestampT]}returns(e){return e.dataType}};eM.ExprMax=TX});var uye=v(rM=>{"use strict";Object.defineProperty(rM,"__esModule",{value:!0});rM.ExprMin=void 0;var tM=pn(),snt=Jm(),CX=class extends snt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[tM.FT.numberT,tM.FT.stringT,tM.FT.dateT,tM.FT.timestampT]}returns(e){return e.dataType}};rM.ExprMin=CX});var lye=v(nM=>{"use strict";Object.defineProperty(nM,"__esModule",{value:!0});nM.ExprMinus=void 0;var ont=js(),ant=pn(),unt=ir(),RX=class extends unt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[ant.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,ont.errorFor)("negate requires number")}};nM.ExprMinus=RX});var cye=v(iM=>{"use strict";Object.defineProperty(iM,"__esModule",{value:!0});iM.ExprMulDiv=void 0;var lnt=NI(),OX=class extends lnt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}};iM.ExprMulDiv=OX});var NX=v(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.Unary=void 0;var cnt=ir(),DX=class extends cnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}};sM.Unary=DX});var xye=v(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.ExprNot=void 0;var fye=pn(),fnt=NX(),xnt=hs(),FX=class extends fnt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[fye.FT.boolT,fye.FT.nullT]}getExpression(e){let r=this.expr.getExpression(e),n=this.typeCheck(this.expr,r);return{...r,dataType:"boolean",value:n?(0,xnt.nullsafeNot)(r.value):["false"]}}};oM.ExprNot=FX});var dye=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.ExprNow=void 0;var dnt=ir(),wX=class extends dnt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}};aM.ExprNow=wX});var hye=v(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.ExprNULL=void 0;var hnt=ir(),LX=class extends hnt.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}};uM.ExprNULL=LX});var pye=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.ExprNumber=void 0;var pnt=pn(),mnt=ir(),IX=class extends mnt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...pnt.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}};lM.ExprNumber=IX});var mye=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0});cM.ExprParens=void 0;var gnt=ir(),MX=class extends gnt.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,")"]}}};cM.ExprParens=MX});var gye=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0});fM.ExprRegEx=void 0;var ynt=ir(),PX=class extends ynt.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"}}};fM.ExprRegEx=PX});var yye=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.ExprString=void 0;var Ent=ir(),Ant=pn(),kX=class extends Ent.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"}}};xM.ExprString=kX});var Eye=v(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.ExprSum=void 0;var Snt=UI(),BX=class extends Snt.ExprAsymmetric{constructor(e,r,n){super("sum",e,r,n),this.has({source:r})}};dM.ExprSum=BX});var Aye=v(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.ExprTimeExtract=void 0;var Zm=Ke(),Fp=js(),qX=ir(),vnt=LS(),hM=class t extends qX.ExpressionDef{static extractor(e){let r=t.pluralMap[e];if(r)return r;if((0,Zm.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,Fp.errorFor)("{this.name} arg count");let n=this.args[0];if(n instanceof vnt.Range){let i=n.first.getExpression(e),s=n.last.getExpression(e),o=(0,Zm.maxExpressionType)(i.expressionType,s.expressionType),a=(0,Zm.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:a,value:(0,Fp.errorFor)("extract from error").value};if(!(0,Zm.isTimeFieldType)(i.dataType))return n.first.log(`Can't extract ${r} from '${i.dataType}'`),(0,Fp.errorFor)(`${r} bad type ${i.dataType}`);if(!(0,Zm.isTimeFieldType)(s.dataType))return n.last.log(`Cannot extract ${r} from '${s.dataType}'`),(0,Fp.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,qX.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{let c=(0,qX.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return n.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,Fp.errorFor)(`${r} range mismatch`)}return["week","month","quarter","year"].includes(r)?(this.log(`Cannot measure interval using '${r}'`),(0,Fp.errorFor)(`${r} civil extraction`)):(0,Zm.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,Fp.errorFor)(`${r} bad extraction`))}else{let i=n.getExpression(e);return(0,Zm.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,Fp.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}};pM.ExprTimeExtract=hM;hM.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"}});var a5=v(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.FieldName=void 0;var _nt=mt(),UX=class extends _nt.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])}};mM.FieldName=UX});var Sye=v(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0});gM.QueryInputSpace=void 0;var bnt=TS(),Tnt=IY(),Cnt=NL(),$X=class extends Cnt.RefinedSpace{constructor(e,r){let n=new Tnt.SpaceSeed(e);super(n.structDef),this.queryOutput=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof bnt.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}};gM.QueryInputSpace=$X});var u5=v(ca=>{"use strict";var Rnt=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]}),Ont=ca&&ca.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dnt=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)&&Rnt(e,t,r);return Ont(e,t),e};Object.defineProperty(ca,"__esModule",{value:!0});ca.ReduceFieldSpace=ca.QuerySpace=ca.QueryOperationSpace=void 0;var yM=Dnt(Ke()),jX=yL(),Nnt=a5(),Fnt=ua(),wnt=MS(),Lnt=NL(),Int=DY(),Mnt=el(),Pnt=Sye(),EM=class extends Lnt.RefinedSpace{constructor(e,r,n,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=n,this.astEl=i,this.expandedWild={},this.exprSpace=new Pnt.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 Mnt.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();yM.isAtomicFieldType(l.dataType)&&yM.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=EM;var AM=class extends EM{addRefineFromFields(e){var r;if(yM.isQuerySegment(e))for(let n of e.queryFields)if(n.type==="fieldref"){let i=this.exprSpace.lookup(n.path.map(s=>new Nnt.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 Int.ColumnSpaceField(n))}pushFields(...e){for(let r of e)r instanceof wnt.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){let e=[];for(let[r,n]of this.entries())if(n instanceof Fnt.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)&&!knt(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){let r=this.getPipeSegment(e);if(yM.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,jX.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,jX.nameFromDef)(a)===s);o&&n.push(o)}r.extendSource=(0,jX.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=AM;var HX=class extends AM{constructor(){super(...arguments),this.segmentType="reduce"}};ca.ReduceFieldSpace=HX;function knt(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}});var _ye=v(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.ExprUngroup=void 0;var vye=Ke(),zX=js(),Bnt=u5(),qnt=pn(),Unt=ir(),GX=class extends Unt.ExpressionDef{constructor(e,r,n){super({expr:r,fields:n}),this.control=e,this.expr=r,this.fields=n,this.legalChildTypes=qnt.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){let r=this.expr.getExpression(e);if(!(0,vye.expressionIsAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,zX.errorFor)("ungrouped scalar");if((0,vye.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,zX.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 Bnt.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,zX.errorFor)("ungrouped type check")}};SM.ExprUngroup=GX});var Rye=v(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.ForRange=void 0;var bye=uc(),QX=js(),Tye=pn(),vM=OS(),$nt=ir(),_M=_I(),Cye=LS(),VX=class extends $nt.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=[Tye.FT.timestampT,Tye.FT.dateT]}apply(e,r,n){let i=this.from.getExpression(e),s=n.getExpression(e);if(!this.typeCheck(n,s))return(0,QX.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,bye.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,bye.maxExpressionType)(i.expressionType,s.expressionType),value:(0,QX.errorFor)("for not number").value};let a=this.timeframe.text,u=(0,vM.resolution)(a);if(i.dataType==="timestamp"&&(u="timestamp"),s.dataType==="date"&&u==="date"){let h=this.from,p=(0,vM.timeOffset)("date",i.value,"+",o.value,a),m=new _M.ExprTime("date",p);return new Cye.Range(h,m).apply(e,r,n)}let l=_M.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,vM.castDateToTimestamp)(f),c=new _M.ExprTime("timestamp",f,i.expressionType)}let x=(0,vM.timeOffset)("timestamp",f,"+",o.value,a),d=new _M.ExprTime("timestamp",x,i.expressionType);return new Cye.Range(c,d).apply(e,r,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,QX.errorFor)("range has no value")}};bM.ForRange=VX});var vJ=v(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var qx=class extends Error{},rJ=class extends qx{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},nJ=class extends qx{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},iJ=class extends qx{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ng=class extends qx{},FM=class extends qx{constructor(e){super(`Invalid unit ${e}`)}},fa=class extends qx{},Kc=class extends qx{constructor(){super("Zone is an abstract class")}},Re="numeric",a0="short",uu="long",sJ={year:Re,month:Re,day:Re},Jye={year:Re,month:a0,day:Re},jnt={year:Re,month:a0,day:Re,weekday:a0},Zye={year:Re,month:uu,day:Re},eEe={year:Re,month:uu,day:Re,weekday:uu},tEe={hour:Re,minute:Re},rEe={hour:Re,minute:Re,second:Re},nEe={hour:Re,minute:Re,second:Re,timeZoneName:a0},iEe={hour:Re,minute:Re,second:Re,timeZoneName:uu},sEe={hour:Re,minute:Re,hourCycle:"h23"},oEe={hour:Re,minute:Re,second:Re,hourCycle:"h23"},aEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:a0},uEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:uu},lEe={year:Re,month:Re,day:Re,hour:Re,minute:Re},cEe={year:Re,month:Re,day:Re,hour:Re,minute:Re,second:Re},fEe={year:Re,month:a0,day:Re,hour:Re,minute:Re},xEe={year:Re,month:a0,day:Re,hour:Re,minute:Re,second:Re},Hnt={year:Re,month:a0,day:Re,weekday:a0,hour:Re,minute:Re},dEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,timeZoneName:a0},hEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,second:Re,timeZoneName:a0},pEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,timeZoneName:uu},mEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,second:Re,timeZoneName:uu};function kt(t){return typeof t>"u"}function sg(t){return typeof t=="number"}function kM(t){return typeof t=="number"&&t%1===0}function znt(t){return typeof t=="string"}function Gnt(t){return Object.prototype.toString.call(t)==="[object Date]"}function gEe(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Qnt(t){return Array.isArray(t)?t:[t]}function Oye(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 Vnt(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function qS(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Bx(t,e,r){return kM(t)&&t>=e&&t<=r}function Wnt(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 wp(t){if(!(kt(t)||t===null||t===""))return parseInt(t,10)}function eg(t){if(!(kt(t)||t===null||t===""))return parseFloat(t)}function pJ(t){if(!(kt(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function mJ(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function m5(t){return t%4===0&&(t%100!==0||t%400===0)}function h5(t){return m5(t)?366:365}function wM(t,e){let r=Wnt(e-1,12)+1,n=t+(e-r)/12;return r===2?m5(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function gJ(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 LM(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 oJ(t){return t>99?t:t>60?1900+t:2e3+t}function yEe(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 BM(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 EEe(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new fa(`Invalid unit value ${t}`);return e}function IM(t,e){let r={};for(let n in t)if(qS(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=EEe(i)}return r}function p5(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 qM(t){return Vnt(t,["hour","minute","second","millisecond"])}var AEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,Ynt=["January","February","March","April","May","June","July","August","September","October","November","December"],SEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Knt=["J","F","M","A","M","J","J","A","S","O","N","D"];function vEe(t){switch(t){case"narrow":return[...Knt];case"short":return[...SEe];case"long":return[...Ynt];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 _Ee=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],bEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Xnt=["M","T","W","T","F","S","S"];function TEe(t){switch(t){case"narrow":return[...Xnt];case"short":return[...bEe];case"long":return[..._Ee];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var CEe=["AM","PM"],Jnt=["Before Christ","Anno Domini"],Znt=["BC","AD"],eit=["B","A"];function REe(t){switch(t){case"narrow":return[...eit];case"short":return[...Znt];case"long":return[...Jnt];default:return null}}function tit(t){return CEe[t.hour<12?0:1]}function rit(t,e){return TEe(e)[t.weekday-1]}function nit(t,e){return vEe(e)[t.month-1]}function iit(t,e){return REe(e)[t.year<0?0:1]}function sit(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 Dye(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var oit={D:sJ,DD:Jye,DDD:Zye,DDDD:eEe,t:tEe,tt:rEe,ttt:nEe,tttt:iEe,T:sEe,TT:oEe,TTT:aEe,TTTT:uEe,f:lEe,ff:fEe,fff:dEe,ffff:pEe,F:cEe,FF:xEe,FFF:hEe,FFFF:mEe},o0=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 oit[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?tit(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(d,h)=>n?nit(e,d):s(h?{month:d}:{month:d,day:"numeric"},"month"),l=(d,h)=>n?rit(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?iit(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 Dye(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 Dye(s,i(a))}},au=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},Ip=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}},WX=null,MM=class t extends Ip{static get instance(){return WX===null&&(WX=new t),WX}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return yEe(e,r,n)}formatOffset(e,r){return p5(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},DM={};function ait(t){return DM[t]||(DM[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"})),DM[t]}var uit={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function lit(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 cit(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=uit[s];s==="era"?n[a]=o:kt(a)||(n[a]=parseInt(o,10))}return n}var TM={},Ux=class t extends Ip{static create(e){return TM[e]||(TM[e]=new t(e)),TM[e]}static resetCache(){TM={},DM={}}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 yEe(e,r,n,this.name)}formatOffset(e,r){return p5(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=ait(this.name),[i,s,o,a,u,l,c]=n.formatToParts?cit(n,r):lit(n,r);a==="BC"&&(i=-Math.abs(i)+1);let x=gJ({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}},YX=null,lu=class t extends Ip{static get utcInstance(){return YX===null&&(YX=new t(0)),YX}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(BM(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${p5(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${p5(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return p5(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}},PM=class extends Ip{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 Lp(t,e){if(kt(t)||t===null)return e;if(t instanceof Ip)return t;if(znt(t)){let r=t.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?lu.utcInstance:lu.parseSpecifier(r)||Ux.create(t)}else return sg(t)?lu.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new PM(t)}var Nye=()=>Date.now(),Fye="system",wye=null,Lye=null,Iye=null,Mye,yn=class{static get now(){return Nye}static set now(e){Nye=e}static set defaultZone(e){Fye=e}static get defaultZone(){return Lp(Fye,MM.instance)}static get defaultLocale(){return wye}static set defaultLocale(e){wye=e}static get defaultNumberingSystem(){return Lye}static set defaultNumberingSystem(e){Lye=e}static get defaultOutputCalendar(){return Iye}static set defaultOutputCalendar(e){Iye=e}static get throwOnInvalid(){return Mye}static set throwOnInvalid(e){Mye=e}static resetCaches(){Hn.resetCache(),Ux.resetCache()}},Pye={};function fit(t,e={}){let r=JSON.stringify([t,e]),n=Pye[r];return n||(n=new Intl.ListFormat(t,e),Pye[r]=n),n}var aJ={};function uJ(t,e={}){let r=JSON.stringify([t,e]),n=aJ[r];return n||(n=new Intl.DateTimeFormat(t,e),aJ[r]=n),n}var lJ={};function xit(t,e={}){let r=JSON.stringify([t,e]),n=lJ[r];return n||(n=new Intl.NumberFormat(t,e),lJ[r]=n),n}var cJ={};function dit(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=cJ[i];return s||(s=new Intl.RelativeTimeFormat(t,e),cJ[i]=s),s}var d5=null;function hit(){return d5||(d5=new Intl.DateTimeFormat().resolvedOptions().locale,d5)}function pit(t){let e=t.indexOf("-u-");if(e===-1)return[t];{let r,n=t.substring(0,e);try{r=uJ(t).resolvedOptions()}catch{r=uJ(n).resolvedOptions()}let{numberingSystem:i,calendar:s}=r;return[n,i,s]}}function mit(t,e,r){return(r||e)&&(t+="-u",r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function git(t){let e=[];for(let r=1;r<=12;r++){let n=En.utc(2016,r,1);e.push(t(n))}return e}function yit(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 CM(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function Eit(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 fJ=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=xit(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):mJ(e,3);return jn(r,this.padTo)}}},xJ=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&&Ux.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=uJ(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},dJ=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&gEe()&&(this.rtf=dit(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):sit(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":hit()),a=r||yn.defaultNumberingSystem,u=n||yn.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){d5=null,aJ={},lJ={},cJ={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=pit(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=mit(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=Eit(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 CM(this,e,n,vEe,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=git(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return CM(this,e,n,TEe,()=>{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]=yit(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return CM(this,void 0,e,()=>CEe,()=>{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 CM(this,e,r,REe,()=>{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 fJ(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new xJ(e,this.intl,r)}relFormatter(e={}){return new dJ(this.intl,this.isEnglish(),e)}listFormatter(e={}){return fit(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 US(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function $S(...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 jS(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 OEe(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=wp(e[r+i]);return[n,null,r+i]}}var DEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Ait=`(?:${DEe.source}?(?:\\[(${AEe.source})\\])?)?`,yJ=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,NEe=RegExp(`${yJ.source}${Ait}`),EJ=RegExp(`(?:T${NEe.source})?`),Sit=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,vit=/(\d{4})-?W(\d\d)(?:-?(\d))?/,_it=/(\d{4})-?(\d{3})/,bit=OEe("weekYear","weekNumber","weekDay"),Tit=OEe("year","ordinal"),Cit=/(\d{4})-(\d\d)-(\d\d)/,FEe=RegExp(`${yJ.source} ?(?:${DEe.source}|(${AEe.source}))?`),Rit=RegExp(`(?: ${FEe.source})?`);function BS(t,e,r){let n=t[e];return kt(n)?r:wp(n)}function Oit(t,e){return[{year:BS(t,e),month:BS(t,e+1,1),day:BS(t,e+2,1)},null,e+3]}function HS(t,e){return[{hours:BS(t,e,0),minutes:BS(t,e+1,0),seconds:BS(t,e+2,0),milliseconds:pJ(t[e+3])},null,e+4]}function g5(t,e){let r=!t[e]&&!t[e+1],n=BM(t[e+1],t[e+2]),i=r?null:lu.instance(n);return[{},i,e+3]}function y5(t,e){let r=t[e]?Ux.create(t[e]):null;return[{},r,e+1]}var Dit=RegExp(`^T?${yJ.source}$`),Nit=/^-?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 Fit(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(eg(r)),months:x(eg(n)),weeks:x(eg(i)),days:x(eg(s)),hours:x(eg(o)),minutes:x(eg(a)),seconds:x(eg(u),u==="-0"),milliseconds:x(pJ(l),f)}]}var wit={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?oJ(wp(e)):wp(e),month:SEe.indexOf(r)+1,day:wp(n),hour:wp(i),minute:wp(s)};return o&&(a.second=wp(o)),t&&(a.weekday=t.length>3?_Ee.indexOf(t)+1:bEe.indexOf(t)+1),a}var Lit=/^(?:(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 Iit(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=wit[u]:l?d=0:d=BM(c,f),[x,new lu(d)]}function Mit(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var Pit=/^(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$/,kit=/^(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$/,Bit=/^(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 kye(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,i,n,r,s,o,a),lu.utcInstance]}function qit(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,a,r,n,i,s,o),lu.utcInstance]}var Uit=US(Sit,EJ),$it=US(vit,EJ),jit=US(_it,EJ),Hit=US(NEe),wEe=$S(Oit,HS,g5,y5),zit=$S(bit,HS,g5,y5),Git=$S(Tit,HS,g5,y5),Qit=$S(HS,g5,y5);function Vit(t){return jS(t,[Uit,wEe],[$it,zit],[jit,Git],[Hit,Qit])}function Wit(t){return jS(Mit(t),[Lit,Iit])}function Yit(t){return jS(t,[Pit,kye],[kit,kye],[Bit,qit])}function Kit(t){return jS(t,[Nit,Fit])}var Xit=$S(HS);function Jit(t){return jS(t,[Dit,Xit])}var Zit=US(Cit,Rit),est=US(FEe),tst=$S(HS,g5,y5);function rst(t){return jS(t,[Zit,wEe],[est,tst])}var nst="Invalid Duration",LEe={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}},ist={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},...LEe},tl=146097/400,kS=146097/4800,sst={years:{quarters:4,months:12,weeks:tl/7,days:tl,hours:tl*24,minutes:tl*24*60,seconds:tl*24*60*60,milliseconds:tl*24*60*60*1e3},quarters:{months:3,weeks:tl/28,days:tl/4,hours:tl*24/4,minutes:tl*24*60/4,seconds:tl*24*60*60/4,milliseconds:tl*24*60*60*1e3/4},months:{weeks:kS/7,days:kS,hours:kS*24,minutes:kS*24*60,seconds:kS*24*60*60,milliseconds:kS*24*60*60*1e3},...LEe},rg=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ost=rg.slice(0).reverse();function tg(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 ast(t){return t<0?Math.floor(t):Math.ceil(t)}function IEe(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?ast(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function ust(t,e){ost.reduce((r,n)=>kt(e[n])?r:(r&&IEe(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?sst:ist,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:IM(e,t.normalizeUnit),loc:Hn.fromObject(r),conversionAccuracy:r.conversionAccuracy})}static fromDurationLike(e){if(sg(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]=Kit(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]=Jit(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 iJ(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 FM(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?o0.create(this.loc,n).formatDurationFromString(this,e):nst}toHuman(e={}){let r=rg.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+=mJ(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 rg)(qS(r.values,i)||qS(this.values,i))&&(n[i]=r.get(i)+this.get(i));return tg(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]=EEe(e(this.values[n],n));return tg(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...IM(e,t.normalizeUnit)};return tg(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),tg(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return ust(this.matrix,e),tg(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 rg)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;sg(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)rg.indexOf(l)>rg.indexOf(o)&&IEe(this.matrix,i,l,r,o)}else sg(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 tg(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 tg(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 rg)if(!r(this.values[n],e.values[n]))return!1;return!0}},l5="Invalid Interval";function lst(t,e){return!t||!t.isValid?og.invalid("missing or invalid start"):!e||!e.isValid?og.invalid("missing or invalid end"):e<t?og.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 og=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 nJ(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=x5(e),i=x5(r),s=lst(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=ci.fromDurationLike(r),i=x5(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ci.fromDurationLike(r),i=x5(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(x5).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()})`:l5}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:l5}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:l5}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:l5}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:l5}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))}},ig=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 Ux.isValidZone(e)}static normalizeZone(e){return Lp(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:gEe()}}};function Bye(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 cst(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=Bye(a,u);return(l-l%7)/7}],["days",Bye]],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 fst(t,e,r,n){let[i,s,o,a]=cst(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 SJ={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"},qye={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]},xst=SJ.hanidec.replace(/[\[|\]]/g,"").split("");function dst(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(SJ.hanidec)!==-1)e+=xst.indexOf(t[r]);else for(let i in qye){let[s,o]=qye[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function i0({numberingSystem:t},e=""){return new RegExp(`${SJ[t||"latn"]}${e}`)}var hst="missing Intl.DateTimeFormat.formatToParts support";function Yt(t,e=r=>r){return{regex:t,deser:([r])=>e(dst(r))}}var pst="\xA0",MEe=`[ ${pst}]`,PEe=new RegExp(MEe,"g");function mst(t){return t.replace(/\./g,"\\.?").replace(PEe,MEe)}function Uye(t){return t.replace(/\./g,"").replace(PEe," ").toLowerCase()}function s0(t,e){return t===null?null:{regex:RegExp(t.map(mst).join("|")),deser:([r])=>t.findIndex(n=>Uye(r)===Uye(n))+e}}function $ye(t,e){return{regex:t,deser:([,r,n])=>BM(r,n),groups:e}}function KX(t){return{regex:t,deser:([e])=>e}}function gst(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function yst(t,e){let r=i0(e),n=i0(e,"{2}"),i=i0(e,"{3}"),s=i0(e,"{4}"),o=i0(e,"{6}"),a=i0(e,"{1,2}"),u=i0(e,"{1,3}"),l=i0(e,"{1,6}"),c=i0(e,"{1,9}"),f=i0(e,"{2,4}"),x=i0(e,"{4,6}"),d=m=>({regex:RegExp(gst(m.val)),deser:([g])=>g,literal:!0}),p=(m=>{if(t.literal)return d(m);switch(m.val){case"G":return s0(e.eras("short",!1),0);case"GG":return s0(e.eras("long",!1),0);case"y":return Yt(l);case"yy":return Yt(f,oJ);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 s0(e.months("short",!0,!1),1);case"MMMM":return s0(e.months("long",!0,!1),1);case"L":return Yt(a);case"LL":return Yt(n);case"LLL":return s0(e.months("short",!1,!1),1);case"LLLL":return s0(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 KX(c);case"uu":return KX(a);case"uuu":return Yt(r);case"a":return s0(e.meridiems(),0);case"kkkk":return Yt(s);case"kk":return Yt(f,oJ);case"W":return Yt(a);case"WW":return Yt(n);case"E":case"c":return Yt(r);case"EEE":return s0(e.weekdays("short",!1,!1),1);case"EEEE":return s0(e.weekdays("long",!1,!1),1);case"ccc":return s0(e.weekdays("short",!0,!1),1);case"cccc":return s0(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return $ye(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return $ye(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return KX(/[a-z_+-/]{1,256}?/i);default:return d(m)}})(t)||{invalidReason:hst};return p.token=t,p}var Est={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=Est[n];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function Sst(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function vst(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(qS(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 _st(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=Ux.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=pJ(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var XX=null;function bst(){return XX||(XX=En.fromMillis(1555555555555)),XX}function Tst(t,e){if(t.literal)return t;let r=o0.macroTokenToFormatOpts(t.val);if(!r)return t;let s=o0.create(e,r).formatDateTimeParts(bst()).map(o=>Ast(o,e,r));return s.includes(void 0)?t:s}function Cst(t,e){return Array.prototype.concat(...t.map(r=>Tst(r,e)))}function kEe(t,e,r){let n=Cst(o0.parseFormat(r),t),i=n.map(o=>yst(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=Sst(i),u=RegExp(o,"i"),[l,c]=vst(e,u,a),[f,x,d]=c?_st(c):[null,null,void 0];if(qS(c,"a")&&qS(c,"H"))throw new ng("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 Rst(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=kEe(t,e,r);return[n,i,s,o]}var BEe=[0,31,59,90,120,151,181,212,243,273,304,334],qEe=[0,31,60,91,121,152,182,213,244,274,305,335];function rl(t,e){return new au("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function UEe(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 $Ee(t,e,r){return r+(m5(t)?qEe:BEe)[e-1]}function jEe(t,e){let r=m5(t)?qEe:BEe,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function hJ(t){let{year:e,month:r,day:n}=t,i=$Ee(e,r,n),s=UEe(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=LM(a)):o>LM(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...qM(t)}}function jye(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=UEe(e,1,4),s=h5(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=h5(a)):o>s?(a=e+1,o-=h5(e)):a=e;let{month:u,day:l}=jEe(a,o);return{year:a,month:u,day:l,...qM(t)}}function JX(t){let{year:e,month:r,day:n}=t,i=$Ee(e,r,n);return{year:e,ordinal:i,...qM(t)}}function Hye(t){let{year:e,ordinal:r}=t,{month:n,day:i}=jEe(e,r);return{year:e,month:n,day:i,...qM(t)}}function Ost(t){let e=kM(t.weekYear),r=Bx(t.weekNumber,1,LM(t.weekYear)),n=Bx(t.weekday,1,7);return e?r?n?!1:rl("weekday",t.weekday):rl("week",t.week):rl("weekYear",t.weekYear)}function Dst(t){let e=kM(t.year),r=Bx(t.ordinal,1,h5(t.year));return e?r?!1:rl("ordinal",t.ordinal):rl("year",t.year)}function HEe(t){let e=kM(t.year),r=Bx(t.month,1,12),n=Bx(t.day,1,wM(t.year,t.month));return e?r?n?!1:rl("day",t.day):rl("month",t.month):rl("year",t.year)}function zEe(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=Bx(e,0,23)||e===24&&r===0&&n===0&&i===0,o=Bx(r,0,59),a=Bx(n,0,59),u=Bx(i,0,999);return s?o?a?u?!1:rl("millisecond",i):rl("second",n):rl("minute",r):rl("hour",e)}var ZX="Invalid DateTime",zye=864e13;function RM(t){return new au("unsupported zone",`the zone "${t.name}" is not supported`)}function eJ(t){return t.weekData===null&&(t.weekData=hJ(t.c)),t.weekData}function c5(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 GEe(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 Gye(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 NM(t,e,r){return GEe(gJ(t),e,r)}function Qye(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,wM(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=gJ(s),[u,l]=GEe(a,r,t.zone);return o!==0&&(u+=o,l=t.zone.offset(u)),{ts:u,o:l}}function f5(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 OM(t,e,r=!0){return t.isValid?o0.create(Hn.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function tJ(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 Vye(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 QEe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Nst={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Fst={ordinal:1,hour:0,minute:0,second:0,millisecond:0},VEe=["year","month","day","hour","minute","second","millisecond"],wst=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Lst=["year","ordinal","hour","minute","second","millisecond"];function Wye(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 FM(t);return e}function Yye(t,e){let r=Lp(e.zone,yn.defaultZone),n=Hn.fromObject(e),i=yn.now(),s,o;if(kt(t.year))s=i;else{for(let l of VEe)kt(t[l])&&(t[l]=QEe[l]);let a=HEe(t)||zEe(t);if(a)return En.invalid(a);let u=r.offset(i);[s,o]=NM(t,u,r)}return new En({ts:s,zone:r,loc:n,o})}function Kye(t,e,r){let n=kt(r.round)?!0:r.round,i=(o,a)=>(o=mJ(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 Xye(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:RM(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=Gye(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]=Xye(arguments),[n,i,s,o,a,u,l]=r;return Yye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,r]=Xye(arguments),[n,i,s,o,a,u,l]=r;return e.zone=lu.utcInstance,Yye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,r={}){let n=Gnt(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Lp(r.zone,yn.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:Hn.fromObject(r)}):t.invalid(RM(i))}static fromMillis(e,r={}){if(sg(e))return e<-zye||e>zye?t.invalid("Timestamp out of range"):new t({ts:e,zone:Lp(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(sg(e))return new t({ts:e*1e3,zone:Lp(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new fa("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Lp(r.zone,yn.defaultZone);if(!n.isValid)return t.invalid(RM(n));let i=yn.now(),s=kt(r.specificOffset)?n.offset(i):r.specificOffset,o=IM(e,Wye),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 ng("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new ng("Can't mix ordinal dates with month/day");let d=f||o.weekday&&!c,h,p,m=Gye(i,s);d?(h=wst,p=Nst,m=hJ(m)):a?(h=Lst,p=Fst,m=JX(m)):(h=VEe,p=QEe);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?Ost(o):a?Dst(o):HEe(o),A=y||zEe(o);if(A)return t.invalid(A);let S=d?jye(o):a?Hye(o):o,[T,b]=NM(S,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]=Vit(e);return f5(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Wit(e);return f5(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Yit(e);return f5(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]=Rst(o,e,r);return c?t.invalid(c):f5(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]=rst(e);return f5(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 rJ(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?eJ(this).weekYear:NaN}get weekNumber(){return this.isValid?eJ(this).weekNumber:NaN}get weekday(){return this.isValid?eJ(this).weekday:NaN}get ordinal(){return this.isValid?JX(this.c).ordinal:NaN}get monthShort(){return this.isValid?ig.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?ig.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?ig.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?ig.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 m5(this.year)}get daysInMonth(){return wM(this.year,this.month)}get daysInYear(){return this.isValid?h5(this.year):NaN}get weeksInWeekYear(){return this.isValid?LM(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=o0.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=Lp(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]=NM(o,s,e)}return c5(this,{ts:i,zone:e})}else return t.invalid(RM(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return c5(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=IM(e,Wye),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 ng("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new ng("Can't mix ordinal dates with month/day");let l;n?l=jye({...hJ(this.c),...r}):kt(r.ordinal)?(l={...this.toObject(),...r},kt(r.day)&&(l.day=Math.min(wM(l.year,l.month),l.day))):l=Hye({...JX(this.c),...r});let[c,f]=NM(l,this.o,this.zone);return c5(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e);return c5(this,Qye(this,r))}minus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e).negate();return c5(this,Qye(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?o0.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):ZX}toLocaleString(e=sJ,r={}){return this.isValid?o0.create(this.loc.clone(r),e).formatDateTime(this):ZX}toLocaleParts(e={}){return this.isValid?o0.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=tJ(this,o);return a+="T",a+=Vye(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?tJ(this,e==="extended"):null}toISOWeekDate(){return OM(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":"")+Vye(this,o==="extended",r,e,n,s):null}toRFC2822(){return OM(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return OM(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?tJ(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")),OM(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ZX}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=Qnt(r).map(ci.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=fst(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?og.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),Kye(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?Kye(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 Oye(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new fa("max requires all arguments be DateTimes");return Oye(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 kEe(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return sJ}static get DATE_MED(){return Jye}static get DATE_MED_WITH_WEEKDAY(){return jnt}static get DATE_FULL(){return Zye}static get DATE_HUGE(){return eEe}static get TIME_SIMPLE(){return tEe}static get TIME_WITH_SECONDS(){return rEe}static get TIME_WITH_SHORT_OFFSET(){return nEe}static get TIME_WITH_LONG_OFFSET(){return iEe}static get TIME_24_SIMPLE(){return sEe}static get TIME_24_WITH_SECONDS(){return oEe}static get TIME_24_WITH_SHORT_OFFSET(){return aEe}static get TIME_24_WITH_LONG_OFFSET(){return uEe}static get DATETIME_SHORT(){return lEe}static get DATETIME_SHORT_WITH_SECONDS(){return cEe}static get DATETIME_MED(){return fEe}static get DATETIME_MED_WITH_SECONDS(){return xEe}static get DATETIME_MED_WITH_WEEKDAY(){return Hnt}static get DATETIME_FULL(){return dEe}static get DATETIME_FULL_WITH_SECONDS(){return hEe}static get DATETIME_HUGE(){return pEe}static get DATETIME_HUGE_WITH_SECONDS(){return mEe}};function x5(t){if(En.isDateTime(t))return t;if(t&&t.valueOf&&sg(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 Ist="2.5.2";cu.DateTime=En;cu.Duration=ci;cu.FixedOffsetZone=lu;cu.IANAZone=Ux;cu.Info=ig;cu.Interval=og;cu.InvalidZone=PM;cu.Settings=yn;cu.SystemZone=MM;cu.VERSION=Ist;cu.Zone=Ip});var ZEe=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 Mp=vJ(),Mst=Ke(),Pst=LS(),WEe=_I(),_J=ir(),bJ=class extends Error{};ki.TimeFormatError=bJ;function ug(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 YEe="yyyy",KEe=`${YEe}-LL`,nl=`${KEe}-dd`,XEe=`${nl} HH`,JEe=`${XEe}:mm`,TJ=`${JEe}:ss`,UM=class extends _J.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}},CJ=class t extends UM{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r,n=ug(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=Mp.DateTime.fromFormat(e,TJ);if(s.isValid)return new t(n,r);if(s=Mp.DateTime.fromFormat(e,JEe),s.isValid){n.text=n.text+":00",r="minute";let o=s.plus({minute:1}).toFormat(TJ);return new E5(n,r,"timestamp",o)}}};ki.LiteralTimestamp=CJ;var E5=class extends UM{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,_J.getMorphicValue)(i,"timestamp"),u=(0,_J.getMorphicValue)(s,"timestamp");if(a&&u)i=a,s=u;else return super.apply(e,r,n)}if((0,Mst.isTimeFieldType)(o.dataType)){let a=o.dataType;return new Pst.Range(new WEe.ExprTime(a,i.value),new WEe.ExprTime(a,s.value)).apply(e,r,n)}}return super.apply(e,r,n)}},RJ=class t extends E5{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,XEe);if(i.isValid)return r.text=r.text+":00:00",n=i.plus({hour:1}).toFormat(TJ),new t(r,n)}};ki.LiteralHour=RJ;var ag=class extends E5{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}}}},OJ=class t extends ag{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,nl);if(i.isValid)return n=i.plus({day:1}).toFormat(nl),new t(r,n)}};ki.LiteralDay=OJ;var DJ=class t extends ag{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){let r=ug(e,!1),n=r.text,i=r.text.slice(0,10),s=Mp.DateTime.fromFormat(i,nl);if(s.isValid&&s.weekday===7){let a=s.plus({days:7});return r.text=s.toFormat(nl),n=a.toFormat(nl),new t(r,n)}}};ki.LiteralWeek=DJ;var NJ=class t extends ag{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,KEe);if(i.isValid){let s=i.plus({months:1});return r.text=i.toFormat(nl),n=s.toFormat(nl),new t(r,n)}}};ki.LiteralMonth=NJ;var FJ=class t extends ag{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){let r=ug(e,!1),n=r.text,i=r.text.match(/(^\d{4})-[qQ](\d)$/);if(i){let s=Number.parseInt(i[2])-1,o=Mp.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));let a=o.plus({quarter:1});return r.text=o.toFormat(nl),n=a.toFormat(nl),new t(r,n)}}};ki.LiteralQuarter=FJ;var wJ=class t extends ag{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,YEe);if(i.isValid){let s=i.plus({year:1});return r.text=i.toFormat(nl),n=s.toFormat(nl),new t(r,n)}}};ki.LiteralYear=wJ});var eAe=v($M=>{"use strict";Object.defineProperty($M,"__esModule",{value:!0});$M.PartialCompare=void 0;var kst=js(),Bst=ir(),LJ=class extends Bst.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,kst.errorFor)("no value for partial compare")}};$M.PartialCompare=LJ});var rAe=v(zS=>{"use strict";Object.defineProperty(zS,"__esModule",{value:!0});zS.PickWhen=zS.Pick=void 0;var Xc=Ke(),Pp=js(),u0=pn(),qst=ir(),Ust=mt(),tAe=hs();function jM(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}var IJ=class extends qst.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&&!u0.FT.typeEq(s,x,!0)){let d=u0.FT.inspect(x);return this.log(`pick type '${d}', expected '${s.dataType}'`),(0,Pp.errorFor)("pick when type")}s=jM(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}let l=(this.elsePick||n).getExpression(e);if(s=jM(s,l),!u0.FT.typeEq(s,l,!0)){let c=this.elsePick?"else":"pick default";return this.log(`${c} type '${u0.FT.inspect(l)}', expected '${s.dataType}'`),(0,Pp.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Xc.maxExpressionType)(o,l.expressionType),evalSpace:(0,Xc.mergeEvalSpaces)(a,l.evalSpace),value:(0,tAe.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,Pp.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,Pp.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,Pp.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(!u0.FT.typeEq(u.when,u0.FT.boolT))return this.log(`when expression must be boolean, not '${u0.FT.inspect(u.when)}`),(0,Pp.errorFor)("pick when type");if(n&&!u0.FT.typeEq(n,u.pick,!0)){let l=u0.FT.inspect(u.pick);return this.log(`pick type '${l}', expected '${n.dataType}'`),(0,Pp.errorFor)("pick value type")}n=jM(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=jM(n,a),u0.FT.typeEq(n,a,!0)?(i.push(" ELSE ",...a.value," END"),{dataType:n.dataType,expressionType:s,value:(0,tAe.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${u0.FT.inspect(a)}', expected '${n.dataType}'`),(0,Pp.errorFor)("pick value type mismatch"))}};zS.Pick=IJ;var MJ=class extends Ust.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="pickWhen",this.has({pick:e})}};zS.PickWhen=MJ});var nAe=v(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.Timeframe=void 0;var $st=Ke(),jst=mt(),PJ=class extends jst.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,$st.isTimestampUnit)(r)?r:"second"}};HM.Timeframe=PJ});var sAe=v(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.TopBy=void 0;var Hst=Ke(),iAe=ir(),zst=mt(),Gst=hs(),kJ=class extends zst.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof iAe.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof iAe.ExpressionDef){let r=this.by.getExpression(e);return(0,Hst.expressionIsAggregate)(r.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,Gst.compressExpr)(r.value)}}return{by:"name",name:this.by}}};zM.TopBy=kJ});var oAe=v(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});kp.ImportStatement=kp.ImportSelect=kp.ImportSourceName=void 0;var $J=mt(),BJ=class extends $J.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}};kp.ImportSourceName=BJ;var qJ=class extends $J.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}};kp.ImportSelect=qJ;var UJ=class extends $J.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}'`)}}};kp.ImportStatement=UJ});var HJ=v(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});GM.ExtendBlock=void 0;var Qst=mt(),Vst=Ii(),jJ=class extends Qst.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Vst.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)for(let n of r.list)e.inputFS.extendSource(n)}};GM.ExtendBlock=jJ});var aAe=v(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.AnonymousQuery=void 0;var Wst=mt(),Yst=Vc(),zJ=class extends Wst.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Yst.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)}};QM.AnonymousQuery=zJ});var GS=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.View=void 0;var Kst=mt(),GJ=class extends Kst.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}};VM.View=GJ});var uAe=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.ViewArrow=void 0;var Xst=el(),Jst=GS(),QJ=class extends Jst.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 Xst.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"),[]}getImplicitName(){return this.operation.getImplicitName()}};WM.ViewArrow=QJ});var YJ=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.refine=void 0;var VJ=uc(),WJ=yL();function Zst(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,VJ.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,VJ.isQuerySegment)(o)&&(0,VJ.isQuerySegment)(s)){let a=[],u=[],l=new Map(s.queryFields.map(c=>[(0,WJ.nameFromDef)(c),c]));for(let c of o.queryFields)l.has((0,WJ.nameFromDef)(c))?a.push(c):u.push(c);s.queryFields=[...s.queryFields,...u],a.length>0&&t.log(`overlapping fields in refinement: ${a.map(WJ.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}YM.refine=Zst});var lAe=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.ViewRefine=void 0;var eot=la(),tot=Ym(),rot=YJ(),not=GS(),KJ=class extends not.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,tot.getFinalStruct)(this.refinement,e.structDef(),i):eot.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,rot.refine)(this,r,i[0])}getImplicitName(){return this.base.getImplicitName()}};KM.ViewRefine=KJ});var xAe=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.ReferenceView=void 0;var cAe=Ke(),fAe=la(),iot=Ym(),sot=ua(),oot=YJ(),aot=GS(),XJ=class extends aot.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:fAe.ErrorFactory.structDef,outputStruct:fAe.ErrorFactory.structDef,pipeline:[],error:!0}};if(!n.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(n.found instanceof sot.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,cAe.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,cAe.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,iot.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,oot.refine)(this,r,i):r}getImplicitName(){return this.reference.nameString}};XM.ReferenceView=XJ});var ZJ=v(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.Index=void 0;var uot=mt(),lot=Ii(),JJ=class extends uot.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=lot.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};JM.Index=JJ});var tZ=v(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.SampleProperty=void 0;var cot=mt(),dAe=Ii(),eZ=class extends cot.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=dAe.LegalRefinementStage.Tail,this.forceQueryClass=dAe.QueryClass.Index}sampling(){return this.sample}};ZM.SampleProperty=eZ});var pAe=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0});eP.IndexFieldSpace=void 0;var hAe=Ke(),rZ=MS(),fot=ua(),xot=u5(),dot=GK(),hot=el(),nZ=class extends xot.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(let r of e)r instanceof rZ.FieldReference?super.pushFields(r):r instanceof rZ.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 fot.SpaceField){let s=this.expandedWild[n];if(s){r.push({type:"fieldref",path:s});continue}if(i instanceof dot.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 hot.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=rZ.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,hAe.isAtomicFieldType)(c.dataType)&&(0,hAe.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)}};eP.IndexFieldSpace=nZ});var mAe=v(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.IndexBuilder=void 0;var iZ=Ke(),pot=la(),mot=Wm(),got=ZJ(),yot=PS(),Eot=tZ(),Aot=pAe(),sZ=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 mot.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof yot.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof got.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Eot.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,iZ.isIndexSegment)(e)&&!(0,iZ.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),pot.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,iZ.isIndexSegment)(e)&&e?.sample&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),r}};tP.IndexBuilder=sZ});var aZ=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0});rP.GroupBy=void 0;var Sot=r0(),gAe=Ii(),oZ=class extends Sot.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=gAe.LegalRefinementStage.Single,this.forceQueryClass=gAe.QueryClass.Grouping}};rP.GroupBy=oZ});var yAe=v(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.ProjectFieldSpace=void 0;var uZ=Ke(),vot=u5(),lZ=class extends vot.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,uZ.expressionIsAggregate)(e.expressionType)?!1:(0,uZ.expressionInvolvesAggregate)(e.expressionType)&&(0,uZ.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}};nP.ProjectFieldSpace=lZ});var xZ=v(QS=>{"use strict";Object.defineProperty(QS,"__esModule",{value:!0});QS.Ordering=QS.OrderBy=void 0;var _ot=Ke(),EAe=a5(),AAe=mt(),bot=Ii(),cZ=class extends AAe.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof EAe.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 EAe.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,_ot.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}};QS.OrderBy=cZ;var fZ=class extends AAe.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=bot.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}};QS.Ordering=fZ});var hZ=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0});iP.Top=void 0;var SAe=Ke(),Tot=hs(),Cot=a5(),Rot=mt(),Oot=Ii(),dZ=class extends Rot.MalloyElement{constructor(e,r){super(),this.limit=e,this.by=r,this.elementType="top",this.queryRefinementStage=Oot.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:r})}getBy(e){var r;if(this.by)if(this.by instanceof Cot.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,SAe.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,SAe.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,Tot.compressExpr)(n.value)}}}};iP.Top=dZ});var oP=v(VS=>{"use strict";Object.defineProperty(VS,"__esModule",{value:!0});VS.ReduceBuilder=VS.QuerySegmentBuilder=void 0;var vAe=Ke(),Dot=la(),Not=Wm(),Fot=PS(),_Ae=xZ(),bAe=hZ(),wot=u5(),Lot=r0(),sP=class{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof Lot.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof Not.Filter){let r=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(r))}else e instanceof bAe.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 Fot.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof _Ae.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 bAe.Top){let i=this.order.getBy(this.inputFS);i&&(r.by=i)}this.order instanceof _Ae.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])}};VS.QuerySegmentBuilder=sP;var pZ=class extends sP{constructor(e,r,n,i){super(),this.type="grouping",this.resultFS=new wot.ReduceFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,vAe.isReduceSegment)(e)||(0,vAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),Dot.ErrorFactory.reduceSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};VS.ReduceBuilder=pZ});var CAe=v(aP=>{"use strict";Object.defineProperty(aP,"__esModule",{value:!0});aP.ProjectBuilder=void 0;var TAe=Ke(),Iot=la(),Mot=aZ(),Pot=yAe(),kot=oP(),mZ=class extends kot.QuerySegmentBuilder{constructor(e,r,n,i){super(),this.type="project",this.resultFS=new Pot.ProjectFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Mot.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,TAe.isProjectSegment)(e)||(0,TAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),Iot.ErrorFactory.projectSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};aP.ProjectBuilder=mZ});var RAe=v(uP=>{"use strict";Object.defineProperty(uP,"__esModule",{value:!0});uP.PartialBuilder=void 0;var Bot=uc(),qot=oP(),gZ=class extends qot.ReduceBuilder{finalize(e){let r=super.finalize(e);if((0,Bot.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}};uP.PartialBuilder=gZ});var EZ=v(lP=>{"use strict";Object.defineProperty(lP,"__esModule",{value:!0});lP.QOpDesc=void 0;var Uot=mAe(),$ot=CAe(),jot=oP(),Hot=mt(),zot=Ym(),Got=el(),lg=Ii(),Qot=RAe(),yZ=class extends Hot.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,n=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=lg.QueryClass.Grouping:this.refineThis.type==="project"?r=lg.QueryClass.Project:this.refineThis.type==="index"&&(r=lg.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=lg.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,n){switch(this.computeType()){case lg.QueryClass.Grouping:return new jot.ReduceBuilder(e,this.refineThis,r,n);case lg.QueryClass.Project:return new $ot.ProjectBuilder(e,this.refineThis,r,n);case lg.QueryClass.Index:return new Uot.IndexBuilder(e,this.refineThis,r,n);case void 0:return new Qot.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 Got.StaticSpace((0,zot.opOutputStruct)(this,e.structDef(),i))}}};lP.QOpDesc=yZ});var DAe=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0});cP.QOpDescView=void 0;var Vot=Ke(),Wot=el(),OAe=EZ(),Yot=Ym(),AZ=Ii(),Kot=GS(),SZ=class extends Kot.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,Vot.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 OAe.QOpDesc([]),o=new OAe.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,Yot.getFinalStruct)(this,e.structDef(),i.slice(-1));i[a]=this.getOp(new Wot.StaticSpace(u),void 0,o,i[a])}return i}getImplicitName(){}};cP.QOpDescView=SZ});var DZ=v(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.FieldDefinitionValue=An.DefSpace=An.DimensionFieldDeclaration=An.MeasureFieldDeclaration=An.DeclareFieldDeclaration=An.ProjectFieldDeclaration=An.GroupByFieldDeclaration=An.AggregateFieldDeclaration=An.CalculateFieldDeclaration=An.AtomicFieldDeclaration=void 0;var Xot=Ke(),Jot=hs(),Zot=pn(),eat=mI(),tat=mt(),cg=QK(),rat=Vc(),nat=ua(),Jc=class extends tat.MalloyElement{constructor(e,r,n){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=n,this.isNoteableObj=!0,this.extendNote=rat.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,Jot.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,Xot.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,eat.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=Zot.FT.inspect(n);this.log(`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new fP(e,this))}};An.AtomicFieldDeclaration=Jc;var vZ=class extends Jc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}};An.CalculateFieldDeclaration=vZ;var _Z=class extends Jc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckAggregate)(e,this)}};An.AggregateFieldDeclaration=_Z;var bZ=class extends Jc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckGroupBy)(e,this)}};An.GroupByFieldDeclaration=bZ;var TZ=class extends Jc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckProject)(e,this)}};An.ProjectFieldDeclaration=TZ;var CZ=class extends Jc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckDeclare)(e,this)}};An.DeclareFieldDeclaration=CZ;var RZ=class extends Jc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckMeasure)(e,this)}};An.MeasureFieldDeclaration=RZ;var OZ=class extends Jc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckDimension)(e,this)}};An.DimensionFieldDeclaration=OZ;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")}};An.DefSpace=A5;var fP=class extends nat.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)}};An.FieldDefinitionValue=fP});var FAe=v(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.Aggregate=void 0;var iat=r0(),NAe=Ii(),NZ=class extends iat.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=NAe.LegalRefinementStage.Single,this.forceQueryClass=NAe.QueryClass.Grouping}};xP.Aggregate=NZ});var wAe=v(dP=>{"use strict";Object.defineProperty(dP,"__esModule",{value:!0});dP.Calculate=void 0;var sat=r0(),oat=Ii(),FZ=class extends sat.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=oat.LegalRefinementStage.Single}};dP.Calculate=FZ});var LZ=v(hP=>{"use strict";Object.defineProperty(hP,"__esModule",{value:!0});hP.Dimensions=void 0;var aat=_S(),wZ=class extends aat.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}};hP.Dimensions=wZ});var MZ=v(pP=>{"use strict";Object.defineProperty(pP,"__esModule",{value:!0});pP.Measures=void 0;var uat=_S(),IZ=class extends uat.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}};pP.Measures=IZ});var IAe=v(mP=>{"use strict";Object.defineProperty(mP,"__esModule",{value:!0});mP.Nests=void 0;var lat=r0(),LAe=Ii(),PZ=class extends lat.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=LAe.LegalRefinementStage.Single,this.forceQueryClass=LAe.QueryClass.Grouping}};mP.Nests=PZ});var PAe=v(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.ProjectStatement=void 0;var cat=r0(),MAe=Ii(),kZ=class extends cat.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=MAe.QueryClass.Project,this.queryRefinementStage=MAe.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}};gP.ProjectStatement=kZ});var BAe=v(yP=>{"use strict";Object.defineProperty(yP,"__esModule",{value:!0});yP.FromSQLSource=void 0;var kAe=Ke(),fat=r5(),BZ=class extends fat.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,kAe.isSQLBlockStruct)(r)&&r.declaredSQLBlock){let{declaredSQLBlock:n,...i}=r;return i}else if(!(0,kAe.isSQLBlockStruct)(r)){this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`);return}this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`)}};yP.FromSQLSource=BZ});var jZ=v(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});Bp.findReferences=Bp.deprecatedParseTableURI=Bp.constructTableKey=void 0;var xat=vp(),UZ=VC();function qZ(t){let e=(0,UZ.getStringIfShort)(t);if(e)return e;let r=[],n=t.string().sqlString();if(n){for(let i of(0,UZ.getStringParts)(n))typeof i=="string"&&r.push(i);return r.join("")}return""}var $Z=class{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,n){let i=qAe(e,r);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:r,firstReference:n})}enterTableMethod(e){let r=(0,UZ.getId)(e.connectionId()),n=qZ(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(r,n,i)}enterTableFunction(e){let r=qZ(e.tableURI()),{connectionName:n,tablePath:i}=UAe(r),s=this.trans.rangeFromContext(e);this.registerTableReference(n,i,s)}enterImportURL(e){let r=qZ(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}};function qAe(t,e){return t===void 0?e:`${t}:${e}`}Bp.constructTableKey=qAe;function UAe(t){let e=t.match(/^([^:]*):(.*)$/);if(e){let[,r,n]=e;return{connectionName:r,tablePath:n}}else return{tablePath:t}}Bp.deprecatedParseTableURI=UAe;function dat(t,e,r){let n=new $Z(t,e),i=n;return xat.ParseTreeWalker.DEFAULT.walk(i,r),{tables:n.needTables,urls:n.needImports}}Bp.findReferences=dat});var HAe=v(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.TableFunctionSource=qp.TableMethodSource=qp.TableSource=void 0;var jAe=jZ(),hat=Mx(),$Ae=la(),S5=class extends hat.Source{structDef(){var e,r;let n=this.getTableInfo();if(n===void 0)return $Ae.ErrorFactory.structDef;let{tablePath:i,connectionName:s}=n,o=(0,jAe.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),$Ae.ErrorFactory.structDef}};qp.TableSource=S5;var HZ=class extends S5{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}}};qp.TableMethodSource=HZ;var zZ=class extends S5{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,jAe.deprecatedParseTableURI)(this.tableURI)}};qp.TableFunctionSource=zZ});var zAe=v(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.SQLStatement=void 0;var pat=yK(),mat=mt(),GZ=class extends mat.MalloyElement{constructor(e){super(),this.select=e,this.elementType="sqlStatement",this.has({select:e})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,pat.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(`
681
+ `)),lI.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"),lI.ErrorFactory.structDef}};cI.SQLSource=EK});var R3e=v(fI=>{"use strict";Object.defineProperty(fI,"__esModule",{value:!0});fI.SQSource=void 0;var Ett=Op(),Att=gK(),Stt=AK(),SK=class extends Ett.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 Stt.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")}};fI.SQSource=SK});var O3e=v(xI=>{"use strict";Object.defineProperty(xI,"__esModule",{value:!0});xI.SQExtend=void 0;var vtt=eK(),_tt=Op(),vK=class extends _tt.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 vtt.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}};xI.SQExtend=vK});var dI=v(NS=>{"use strict";Object.defineProperty(NS,"__esModule",{value:!0});NS.isComparison=NS.Comparison=void 0;var _K;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(_K||(NS.Comparison=_K={}));function btt(t){return Object.values(_K).includes(t)}NS.isComparison=btt});var pn=v(hI=>{"use strict";Object.defineProperty(hI,"__esModule",{value:!0});hI.FT=void 0;var Ttt=uc();function Km(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,Ttt.expressionIsScalar)(n.expressionType)||(i=`${n.expressionType} ${i}`),i}return"undefined"}).join(",")}};hI.FT=$s;$s.nullT=Km("null");$s.numberT=Km("number");$s.stringT=Km("string");$s.dateT=Km("date");$s.timestampT=Km("timestamp");$s.boolT=Km("boolean");$s.anyAtomicT=[$s.numberT,$s.stringT,$s.dateT,$s.timestampT,$s.boolT];$s.aggregateBoolT=Km("boolean","aggregate")});var mI=v(pI=>{"use strict";Object.defineProperty(pI,"__esModule",{value:!0});pI.isGranularResult=void 0;function Ctt(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}pI.isGranularResult=Ctt});var js=v(gI=>{"use strict";Object.defineProperty(gI,"__esModule",{value:!0});gI.errorFor=void 0;function Rtt(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}gI.errorFor=Rtt});var D3e=v(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});FS.isEquality=FS.Equality=void 0;var bK;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(bK||(FS.Equality=bK={}));function Ott(t){return Object.values(bK).includes(t)}FS.isEquality=Ott});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(),wS=js(),Px=hs(),Xm=pn(),yI=OS(),Dtt=dI(),Ntt=D3e(),w3e=mI(),Ftt=mt(),CK=class extends Error{},EI=class extends Ftt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Xm.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.dataType!=="error"&&!Xm.FT.in(r,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${Xm.FT.inspect(r)}`),!1):!0}apply(e,r,n){return M3e(e,n,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,mn.expressionIsAggregate)(e.expressionType)}};Yc.ExpressionDef=EI;var n5=class extends EI{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Xm.FT.timestampT,Xm.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(!Xm.FT.typeEq(s,Xm.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,wS.errorFor)("illegal unit expression");let o;if((0,w3e.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){let a=(0,yI.timeOffset)("timestamp",i.value,r,s.value,this.timeframe);return(0,yI.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,yI.timeResult)({dataType:"date",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,yI.timeOffset)("date",i.value,r,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,wS.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=n5;function N3e(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function wtt(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}Yc.getMorphicValue=wtt;function L3e(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=N3e(e,"timestamp"),a=N3e(n,"timestamp");if(o&&a)return(0,Px.compose)(o,r,a)}else return(0,Px.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 F3e(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 Ltt(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 Itt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=i5("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=s5(e,i,n,s);if(f)return{...f,dataType:"boolean"}}}let u=L3e(e,i,r,s)||(0,Px.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,Px.compose)(i.value,"LIKE",s.value);else{let l=F3e(i,s);if(l===void 0)throw new CK("Incompatible types for match('~') operator");u=l}u=(0,Px.nullsafeNot)(u,r);break}case"=":case"!=":{let l=Ltt(i,r,s);l?u=l:u=(0,Px.nullsafeNot)(F3e(i,s)||(0,Px.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 Mtt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=i5("boolean",i,s);if(o)return o;let a=(0,mn.maxExpressionType)(i.expressionType,s.expressionType),u=s5(e,i,n,s);if(u)return{...u,dataType:"boolean"};let l=L3e(e,i,r,s)||(0,Px.compose)(i.value,r,s.value);return{dataType:"boolean",expressionType:a,evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function TK(t,...e){return e.includes(t)}function Ptt(t,...e){for(let r of e)if(r.dataType!==t)return!1;return!0}function I3e(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=i5("number",i,s);if(o)return o;let a=s5(e,i,n,s);if(a)return a;let u=(0,mn.maxExpressionType)(i.expressionType,s.expressionType);return Ptt("number",i,s)?{dataType:"number",expressionType:u,value:(0,Px.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,wS.errorFor)("numbers required"))}function ktt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5(e,i,n,s);if(o)return o;let a=(0,mn.isTimeFieldType)(i.dataType),u=i5(a?"error":"number",i,s);if(u)return u;if(a){let l=n;if(s.dataType!=="duration")if((0,w3e.isGranularResult)(i))l=new n5(n,i.timeframe);else if(i.dataType==="date")l=new n5(n,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,wS.errorFor)(`time plus ${s.dataType}`);return l.apply(t,r,e)}return I3e(t,e,r,n)}function M3e(t,e,r,n){if((0,Ntt.isEquality)(r))return Itt(t,e,r,n);if((0,Dtt.isComparison)(r))return Mtt(t,e,r,n);if(TK(r,"+","-"))return ktt(t,e,r,n);if(TK(r,"*","%"))return I3e(t,e,r,n);if(TK(r,"/")){let i=e.getExpression(t),s=n.getExpression(t),o=s5(e,i,n,s);if(o)return e.log("Cannot operate with unsupported type"),o;let a=i5("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,wS.errorFor)("divide type mismatch")}return e.log(`Cannot use ${r} operator here`),(0,wS.errorFor)("applybinary bad operator")}Yc.applyBinary=M3e;function i5(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 s5(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 SI=v(AI=>{"use strict";Object.defineProperty(AI,"__esModule",{value:!0});AI.BinaryBoolean=void 0;var P3e=Ke(),Btt=js(),qtt=pn(),Utt=ir(),$tt=hs(),RK=class extends Utt.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=[qtt.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,P3e.mergeEvalSpaces)(r.evalSpace,n.evalSpace);return{dataType:"boolean",expressionType:(0,P3e.maxExpressionType)(r.expressionType,n.expressionType),evalSpace:i,value:(0,$tt.compose)(r.value,this.op,n.value)}}return(0,Btt.errorFor)("logial required boolean")}};AI.BinaryBoolean=RK});var _I=v(vI=>{"use strict";Object.defineProperty(vI,"__esModule",{value:!0});vI.ExprTime=void 0;var jtt=Ke(),Htt=hs(),ztt=ir(),OK=class t extends ztt.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,jtt.isTimeFieldType)(r.dataType)&&(i.srcType=r.dataType),n=(0,Htt.compressExpr)([i])}return new t(e,n,r.expressionType)}};vI.ExprTime=OK});var LS=v(bI=>{"use strict";Object.defineProperty(bI,"__esModule",{value:!0});bI.Range=void 0;var k3e=Ke(),Gtt=js(),Qtt=ir(),Vtt=hs(),DK=class extends Qtt.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,k3e.maxExpressionType)(a.expressionType,u.expressionType),evalSpace:(0,k3e.mergeEvalSpaces)(a.evalSpace,u.evalSpace),value:(0,Vtt.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,Gtt.errorFor)("a range is not a value")}};bI.Range=DK});var wK=v(CI=>{"use strict";Object.defineProperty(CI,"__esModule",{value:!0});CI.ExprGranularTime=void 0;var NK=Ke(),Wtt=js(),B3e=pn(),q3e=OS(),Ytt=ir(),TI=_I(),U3e=LS(),FK=class extends Ytt.ExpressionDef{constructor(e,r,n){super({expr:e}),this.expr=e,this.units=r,this.truncate=n,this.elementType="granularTime",this.legalChildTypes=[B3e.FT.timestampT,B3e.FT.dateT]}granular(){return!0}getExpression(e){let r=this.units,n=this.expr.getExpression(e);if((0,NK.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,NK.isDateUnit)(r)?"date":"timestamp":n.dataType;return{...n,dataType:i,value:(0,Wtt.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=TI.ExprTime.fromValue("timestamp",r),a=new TI.ExprTime("timestamp",(0,q3e.timeOffset)("timestamp",r.value,"+",(0,NK.mkExpr)`1`,this.units),r.expressionType);return new U3e.Range(o,a)}let n=new TI.ExprTime("date",r.value,r.expressionType),i=(0,q3e.timeOffset)("date",r.value,"+",["1"],this.units),s=new TI.ExprTime("date",i,r.expressionType);return new U3e.Range(n,s)}};CI.ExprGranularTime=FK});var IK=v(RI=>{"use strict";Object.defineProperty(RI,"__esModule",{value:!0});RI.ExprCompare=void 0;var Cr=pn(),Ktt=mI(),Xtt=SI(),Jtt=wK(),Ztt={"~":[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]},LK=class extends Xtt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="a<=>b",this.legalChildTypes=Ztt[r]}getExpression(e){if(!this.right.granular()){let r=this.right.requestExpression(e);if(r&&(0,Ktt.isGranularResult)(r))return new Jtt.ExprGranularTime(this.right,r.timeframe,!1).apply(e,this.op,this.left)}return this.right.apply(e,this.op,this.left)}};RI.ExprCompare=LK});var $3e=v(OI=>{"use strict";Object.defineProperty(OI,"__esModule",{value:!0});OI.Apply=void 0;var ert=dI(),trt=IK(),MK=class extends trt.ExprCompare{constructor(e,r){super(e,ert.Comparison.EqualTo,r),this.left=e,this.right=r,this.elementType="apply"}};OI.Apply=MK});var NI=v(DI=>{"use strict";Object.defineProperty(DI,"__esModule",{value:!0});DI.BinaryNumeric=void 0;var rrt=pn(),nrt=ir(),PK=class extends nrt.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=[rrt.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}};DI.BinaryNumeric=PK});var j3e=v(FI=>{"use strict";Object.defineProperty(FI,"__esModule",{value:!0});FI.Boolean=void 0;var irt=ir(),srt=pn(),kK=class extends irt.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...srt.FT.boolT,value:[this.value]}}};FI.Boolean=kK});var LI=v(wI=>{"use strict";Object.defineProperty(wI,"__esModule",{value:!0});wI.ExprIdReference=void 0;var BK=Ke(),ort=js(),art=EL(),urt=ir(),qK=class extends urt.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,BK.expressionIsAggregate)(n.expressionType)?"output":n.evalSpace;return{...n,value:i,evalSpace:s}}return this.log(r.error),(0,ort.errorFor)(r.error)}apply(e,r,n){let i=this.fieldReference.getField(e).found;if(i instanceof art.SpaceParam){let s=i.parameter();if((0,BK.isConditionParameter)(s)){let o=n.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,BK.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,r,n)}};wI.ExprIdReference=qK});var II=v(IS=>{"use strict";Object.defineProperty(IS,"__esModule",{value:!0});IS.FunctionOrdering=IS.FunctionOrderBy=void 0;var UK=Ke(),H3e=mt(),lrt=LI(),$K=class extends H3e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.log("analytic `order_by` must specify an aggregate expression or output field reference"),{e:["error"],dir:this.dir};let r=this.field.getExpression(e);return(0,UK.expressionIsAggregate)(r.expressionType)||((0,UK.expressionIsScalar)(r.expressionType)?(!(this.field instanceof lrt.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,r){if(this.field){let n=this.field.getExpression(e);return(0,UK.expressionIsScalar)(n.expressionType)||this.field.log("aggregate `order_by` must be scalar"),r||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:n.value,dir:this.dir}}else return this.dir===void 0?(this.log("field or order direction must be specified"),{e:void 0,dir:"asc"}):{e:void 0,dir:this.dir}}};IS.FunctionOrderBy=$K;var jK=class extends H3e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(n=>n.getAggregateOrderBy(e,r))}};IS.FunctionOrdering=jK});var z3e=v(MI=>{"use strict";Object.defineProperty(MI,"__esModule",{value:!0});MI.ExprAddSub=void 0;var crt=NI(),HK=class extends crt.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}};MI.ExprAddSub=HK});var GK=v(PI=>{"use strict";Object.defineProperty(PI,"__esModule",{value:!0});PI.ReferenceField=void 0;var G3e=ua(),zK=class extends G3e.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 G3e.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"}}};PI.ReferenceField=zK});var QK=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=uc();function frt(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=frt;function xrt(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=xrt;function drt(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=drt;function hrt(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=hrt;function prt(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=prt;function mrt(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=mrt;function grt(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=grt;function yrt(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=yrt});var MS=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 Ert=GK(),Art=r0(),Q3e=mt(),V3e=Vc(),Np=QK(),Co=class extends Q3e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=V3e.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 Ert.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 VK=class extends Co{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}};Gt.AcceptExceptFieldReference=VK;var WK=class extends Co{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}};Gt.ExpressionFieldReference=WK;var YK=class extends Co{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}};Gt.PartitionByFieldReference=YK;var KK=class extends Co{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Np.typecheckCalculate)(e,this)}};Gt.CalculateFieldReference=KK;var XK=class t extends Co{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Np.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return t.indexOutputName(this.path)}};Gt.IndexFieldReference=XK;var JK=class extends Co{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Np.typecheckAggregate)(e,this)}};Gt.AggregateFieldReference=JK;var ZK=class extends Co{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Np.typecheckGroupBy)(e,this)}};Gt.GroupByFieldReference=ZK;var eX=class extends Co{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Np.typecheckProject)(e,this)}};Gt.ProjectFieldReference=eX;var tX=class extends Co{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Np.typecheckDeclare)(e,this)}};Gt.DeclareFieldReference=tX;var rX=class extends Co{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Np.typecheckMeasure)(e,this)}};Gt.MeasureFieldReference=rX;var nX=class extends Co{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Np.typecheckDimension)(e,this)}};Gt.DimensionFieldReference=nX;var iX=class extends Co{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}};Gt.ViewOrScalarFieldReference=iX;var sX=class extends Q3e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=V3e.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=sX;var oX=class extends Art.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}};Gt.FieldReferences=oX});var Jm=v(kI=>{"use strict";Object.defineProperty(kI,"__esModule",{value:!0});kI.ExprAggregateFunction=void 0;var W3e=Ke(),Srt=$d(),o5=js(),vrt=el(),_rt=ZC(),brt=pn(),Trt=MS(),Crt=ir(),Rrt=ua(),Ort=LI(),aX=class extends Crt.ExpressionDef{constructor(e,r,n){super(),this.func=e,this.legalChildTypes=[brt.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,W3e.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=>Drt(p,d[0])))&&(a=d[0].map(p=>p.name),u=d[0])}else if(!(f instanceof _rt.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,o5.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,o5.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,o5.errorFor)("agggregate without expression");if((0,W3e.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,o5.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=lX(u,c),h=cX(this.elementType,d),p=f?h:"Join path is required for this calculation";if(p){let m=Nrt(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,o5.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(...uX(e,i))}if(this.expr){let n=this.expr.getExpression(e).value;r.push(...uX(e,n))}return r}};kI.ExprAggregateFunction=aX;function Drt(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 uX(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 vrt.StructSpaceField&&a.length>0){let l=n(u.fieldSpace,a);return{...l,relationship:[{name:o,structRelationship:u.structRelationship},...l.relationship]}}else if(u instanceof Rrt.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,Srt.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=uX(s.fs,s.def.e);r.push(...o.map(a=>[...s.relationship,...a]))}else r.push(s.relationship)}}),r}function lX(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 cX(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 Nrt(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=lX(i,e),o=cX(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=lX(l,e),f=cX(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 Trt.FieldReference?`${r.refString}.${n}()`:r instanceof Ort.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 K3e=v(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.ExprAlternationTree=void 0;var Y3e=Ke(),Frt=js(),wrt=SI(),Lrt=hs(),fX=class extends wrt.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,Y3e.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Y3e.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,Lrt.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,Frt.errorFor)("no value from alternation tree")}};BI.ExprAlternationTree=fX});var UI=v(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.ExprAsymmetric=void 0;var Irt=Jm(),xX=class extends Irt.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}`}}}};qI.ExprAsymmetric=xX});var X3e=v($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.ExprAvg=void 0;var Mrt=UI(),dX=class extends Mrt.ExprAsymmetric{constructor(e,r,n){super("avg",e,r,n),this.has({source:r})}};$I.ExprAvg=dX});var J3e=v(jI=>{"use strict";Object.defineProperty(jI,"__esModule",{value:!0});jI.ExprCast=void 0;var Prt=OS(),krt=ir(),Brt=hs(),hX=class extends krt.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,Brt.compressExpr)((0,Prt.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}};jI.ExprCast=hX});var eye=v(HI=>{"use strict";Object.defineProperty(HI,"__esModule",{value:!0});HI.ExprCoalesce=void 0;var pX=uc(),Z3e=pn(),qrt=ir(),mX=class extends qrt.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=Z3e.FT.anyAtomicT}getExpression(e){let r=this.expr.getExpression(e),n=this.altExpr.getExpression(e);return r.dataType==="null"?n:(Z3e.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,pX.maxExpressionType)(r.expressionType,n.expressionType),value:(0,pX.mkExpr)`COALESCE(${r.value},${n.value})`,evalSpace:(0,pX.mergeEvalSpaces)(r.evalSpace,n.evalSpace)})}};HI.ExprCoalesce=mX});var tye=v(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.ExprCount=void 0;var Urt=Jm(),gX=class extends Urt.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"}}};zI.ExprCount=gX});var rye=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.ExprCountDistinct=void 0;var GI=pn(),$rt=Jm(),yX=class extends $rt.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[GI.FT.numberT,GI.FT.stringT,GI.FT.dateT,GI.FT.timestampT]}};QI.ExprCountDistinct=yX});var PS=v(VI=>{"use strict";Object.defineProperty(VI,"__esModule",{value:!0});VI.Limit=void 0;var jrt=mt(),Hrt=Ii(),EX=class extends jrt.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Hrt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}};VI.Limit=EX});var YI=v(WI=>{"use strict";Object.defineProperty(WI,"__esModule",{value:!0});WI.PartitionBy=void 0;var zrt=mt(),AX=class extends zrt.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}};WI.PartitionBy=AX});var vX=v(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.ExprFunc=void 0;var n0=Ke(),kx=js(),Grt=ZC(),Qrt=ir(),nye=hs(),SX=class extends Qrt.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,k=[`${this.name}(`];for(let H of u)O=(0,n0.maxExpressionType)(O,H.expressionType),N?k.push(","):N=H.dataType,k.push(...H.value);return k.push(")"),{dataType:(i=(n=this.rawType)!==null&&n!==void 0?n:N)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,nye.compressExpr)(k),evalSpace:(0,n0.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,kx.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,kx.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,n0.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 Grt.StructSpaceFieldBase)){let k=`Aggregate source cannot be a ${N.dataType}`;return this.log(k),(0,kx.errorFor)(k)}}else{let N=`Reference to undefined value ${this.source.refString}`;return this.log(N),(0,kx.errorFor)(N)}}let x=[...c?[c]:[],...u],d=Vrt(l,x);if(d===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,kx.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),k=(0,n0.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${k}, but received ${O.actualExpressionType}`)}for(let O of m){let N=O.argIndex-(c?1:0),k=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 ${k}, 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,A=(0,n0.maxOfExpressionTypes)([y.expressionType,...x.map(O=>O.expressionType)]);if(!(0,n0.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,kx.errorFor)("cannot call with source");let S={type:"function_call",overload:h,name:this.name,args:x.map(O=>O.value),expressionType:A,structPath:f},T=[S],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,n0.expressionIsAnalytic)(h.returnType.expressionType);if(_.supportsOrderBy||O){let N=_.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(P=>O?P.getAnalyticOrderBy(e):P.getAggregateOrderBy(e,N));S.orderBy=k}else r.orderBys[0].log(`Function ${this.name} does not support order_by`)}r?.limit!==void 0&&(_.supportsLimit?S.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 k of N.partitionFields){let P=k.getField(e);P.found===void 0?k.log(`${k.refString} is not defined`):(0,n0.expressionIsScalar)(P.found.typeDesc().expressionType)?O.push(k.nameString):k.log("Partition expression must be scalar")}S.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,kx.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,k=Wrt(N),P=k.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(P.length>0){let H=P.length===1?`'.' paths are not yet supported in sql interpolations, found ${P.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${P.join(", ")}]`;return this.log(H),(0,kx.errorFor)(`${H}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}T=[{type:"sql-string",e:k.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,kx.errorFor)("invalid return type");let R=(0,n0.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),D=R==="constant"?"constant":(0,n0.expressionIsScalar)(A)?R:"output";return{dataType:y.dataType,expressionType:A,value:(0,nye.compressExpr)(T),evalSpace:D}}};KI.ExprFunc=SX;function Vrt(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,n0.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 Wrt(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 iye=v(XI=>{"use strict";Object.defineProperty(XI,"__esModule",{value:!0});XI.ExprProps=void 0;var Yrt=Ke(),Krt=js(),Xrt=pn(),Jrt=II(),Zrt=PS(),ent=YI(),tnt=ir(),rnt=vX(),_X=class extends tnt.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=Xrt.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,Yrt.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,Krt.errorFor)("cannot filter type"))}return r}getExpression(e){let r=[],n,i=[],s=[];for(let a of this.statements)a instanceof ent.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.log("`partition_by` is not supported for this kind of expression"):a instanceof Zrt.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 Jrt.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 rnt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:n,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}};XI.ExprProps=_X});var oye=v(JI=>{"use strict";Object.defineProperty(JI,"__esModule",{value:!0});JI.ExprLogicalOp=void 0;var nnt=SI(),sye=pn(),bX=class extends nnt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[sye.FT.boolT,sye.FT.aggregateBoolT]}};JI.ExprLogicalOp=bX});var aye=v(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.ExprMax=void 0;var ZI=pn(),int=Jm(),TX=class extends int.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[ZI.FT.numberT,ZI.FT.stringT,ZI.FT.dateT,ZI.FT.timestampT]}returns(e){return e.dataType}};eM.ExprMax=TX});var uye=v(rM=>{"use strict";Object.defineProperty(rM,"__esModule",{value:!0});rM.ExprMin=void 0;var tM=pn(),snt=Jm(),CX=class extends snt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[tM.FT.numberT,tM.FT.stringT,tM.FT.dateT,tM.FT.timestampT]}returns(e){return e.dataType}};rM.ExprMin=CX});var lye=v(nM=>{"use strict";Object.defineProperty(nM,"__esModule",{value:!0});nM.ExprMinus=void 0;var ont=js(),ant=pn(),unt=ir(),RX=class extends unt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[ant.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,ont.errorFor)("negate requires number")}};nM.ExprMinus=RX});var cye=v(iM=>{"use strict";Object.defineProperty(iM,"__esModule",{value:!0});iM.ExprMulDiv=void 0;var lnt=NI(),OX=class extends lnt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}};iM.ExprMulDiv=OX});var NX=v(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.Unary=void 0;var cnt=ir(),DX=class extends cnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}};sM.Unary=DX});var xye=v(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.ExprNot=void 0;var fye=pn(),fnt=NX(),xnt=hs(),FX=class extends fnt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[fye.FT.boolT,fye.FT.nullT]}getExpression(e){let r=this.expr.getExpression(e),n=this.typeCheck(this.expr,r);return{...r,dataType:"boolean",value:n?(0,xnt.nullsafeNot)(r.value):["false"]}}};oM.ExprNot=FX});var dye=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.ExprNow=void 0;var dnt=ir(),wX=class extends dnt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}};aM.ExprNow=wX});var hye=v(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.ExprNULL=void 0;var hnt=ir(),LX=class extends hnt.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}};uM.ExprNULL=LX});var pye=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.ExprNumber=void 0;var pnt=pn(),mnt=ir(),IX=class extends mnt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...pnt.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}};lM.ExprNumber=IX});var mye=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0});cM.ExprParens=void 0;var gnt=ir(),MX=class extends gnt.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,")"]}}};cM.ExprParens=MX});var gye=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0});fM.ExprRegEx=void 0;var ynt=ir(),PX=class extends ynt.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"}}};fM.ExprRegEx=PX});var yye=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.ExprString=void 0;var Ent=ir(),Ant=pn(),kX=class extends Ent.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"}}};xM.ExprString=kX});var Eye=v(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.ExprSum=void 0;var Snt=UI(),BX=class extends Snt.ExprAsymmetric{constructor(e,r,n){super("sum",e,r,n),this.has({source:r})}};dM.ExprSum=BX});var Aye=v(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.ExprTimeExtract=void 0;var Zm=Ke(),Fp=js(),qX=ir(),vnt=LS(),hM=class t extends qX.ExpressionDef{static extractor(e){let r=t.pluralMap[e];if(r)return r;if((0,Zm.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,Fp.errorFor)("{this.name} arg count");let n=this.args[0];if(n instanceof vnt.Range){let i=n.first.getExpression(e),s=n.last.getExpression(e),o=(0,Zm.maxExpressionType)(i.expressionType,s.expressionType),a=(0,Zm.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:a,value:(0,Fp.errorFor)("extract from error").value};if(!(0,Zm.isTimeFieldType)(i.dataType))return n.first.log(`Can't extract ${r} from '${i.dataType}'`),(0,Fp.errorFor)(`${r} bad type ${i.dataType}`);if(!(0,Zm.isTimeFieldType)(s.dataType))return n.last.log(`Cannot extract ${r} from '${s.dataType}'`),(0,Fp.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,qX.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{let c=(0,qX.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return n.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,Fp.errorFor)(`${r} range mismatch`)}return["week","month","quarter","year"].includes(r)?(this.log(`Cannot measure interval using '${r}'`),(0,Fp.errorFor)(`${r} civil extraction`)):(0,Zm.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,Fp.errorFor)(`${r} bad extraction`))}else{let i=n.getExpression(e);return(0,Zm.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,Fp.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}};pM.ExprTimeExtract=hM;hM.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"}});var a5=v(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.FieldName=void 0;var _nt=mt(),UX=class extends _nt.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])}};mM.FieldName=UX});var Sye=v(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0});gM.QueryInputSpace=void 0;var bnt=TS(),Tnt=IY(),Cnt=NL(),$X=class extends Cnt.RefinedSpace{constructor(e,r){let n=new Tnt.SpaceSeed(e);super(n.structDef),this.queryOutput=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof bnt.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}};gM.QueryInputSpace=$X});var u5=v(ca=>{"use strict";var Rnt=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]}),Ont=ca&&ca.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dnt=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)&&Rnt(e,t,r);return Ont(e,t),e};Object.defineProperty(ca,"__esModule",{value:!0});ca.ReduceFieldSpace=ca.QuerySpace=ca.QueryOperationSpace=void 0;var yM=Dnt(Ke()),jX=yL(),Nnt=a5(),Fnt=ua(),wnt=MS(),Lnt=NL(),Int=DY(),Mnt=el(),Pnt=Sye(),EM=class extends Lnt.RefinedSpace{constructor(e,r,n,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=n,this.astEl=i,this.expandedWild={},this.exprSpace=new Pnt.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 Mnt.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();yM.isAtomicFieldType(l.dataType)&&yM.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=EM;var AM=class extends EM{addRefineFromFields(e){var r;if(yM.isQuerySegment(e))for(let n of e.queryFields)if(n.type==="fieldref"){let i=this.exprSpace.lookup(n.path.map(s=>new Nnt.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 Int.ColumnSpaceField(n))}pushFields(...e){for(let r of e)r instanceof wnt.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){let e=[];for(let[r,n]of this.entries())if(n instanceof Fnt.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)&&!knt(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){let r=this.getPipeSegment(e);if(yM.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,jX.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,jX.nameFromDef)(a)===s);o&&n.push(o)}r.extendSource=(0,jX.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=AM;var HX=class extends AM{constructor(){super(...arguments),this.segmentType="reduce"}};ca.ReduceFieldSpace=HX;function knt(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}});var _ye=v(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.ExprUngroup=void 0;var vye=Ke(),zX=js(),Bnt=u5(),qnt=pn(),Unt=ir(),GX=class extends Unt.ExpressionDef{constructor(e,r,n){super({expr:r,fields:n}),this.control=e,this.expr=r,this.fields=n,this.legalChildTypes=qnt.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){let r=this.expr.getExpression(e);if(!(0,vye.expressionIsAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,zX.errorFor)("ungrouped scalar");if((0,vye.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,zX.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 Bnt.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,zX.errorFor)("ungrouped type check")}};SM.ExprUngroup=GX});var Rye=v(bM=>{"use strict";Object.defineProperty(bM,"__esModule",{value:!0});bM.ForRange=void 0;var bye=uc(),QX=js(),Tye=pn(),vM=OS(),$nt=ir(),_M=_I(),Cye=LS(),VX=class extends $nt.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=[Tye.FT.timestampT,Tye.FT.dateT]}apply(e,r,n){let i=this.from.getExpression(e),s=n.getExpression(e);if(!this.typeCheck(n,s))return(0,QX.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,bye.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,bye.maxExpressionType)(i.expressionType,s.expressionType),value:(0,QX.errorFor)("for not number").value};let a=this.timeframe.text,u=(0,vM.resolution)(a);if(i.dataType==="timestamp"&&(u="timestamp"),s.dataType==="date"&&u==="date"){let h=this.from,p=(0,vM.timeOffset)("date",i.value,"+",o.value,a),m=new _M.ExprTime("date",p);return new Cye.Range(h,m).apply(e,r,n)}let l=_M.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,vM.castDateToTimestamp)(f),c=new _M.ExprTime("timestamp",f,i.expressionType)}let x=(0,vM.timeOffset)("timestamp",f,"+",o.value,a),d=new _M.ExprTime("timestamp",x,i.expressionType);return new Cye.Range(c,d).apply(e,r,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,QX.errorFor)("range has no value")}};bM.ForRange=VX});var vJ=v(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var qx=class extends Error{},rJ=class extends qx{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},nJ=class extends qx{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},iJ=class extends qx{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ng=class extends qx{},FM=class extends qx{constructor(e){super(`Invalid unit ${e}`)}},fa=class extends qx{},Kc=class extends qx{constructor(){super("Zone is an abstract class")}},Re="numeric",a0="short",uu="long",sJ={year:Re,month:Re,day:Re},Jye={year:Re,month:a0,day:Re},jnt={year:Re,month:a0,day:Re,weekday:a0},Zye={year:Re,month:uu,day:Re},eEe={year:Re,month:uu,day:Re,weekday:uu},tEe={hour:Re,minute:Re},rEe={hour:Re,minute:Re,second:Re},nEe={hour:Re,minute:Re,second:Re,timeZoneName:a0},iEe={hour:Re,minute:Re,second:Re,timeZoneName:uu},sEe={hour:Re,minute:Re,hourCycle:"h23"},oEe={hour:Re,minute:Re,second:Re,hourCycle:"h23"},aEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:a0},uEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:uu},lEe={year:Re,month:Re,day:Re,hour:Re,minute:Re},cEe={year:Re,month:Re,day:Re,hour:Re,minute:Re,second:Re},fEe={year:Re,month:a0,day:Re,hour:Re,minute:Re},xEe={year:Re,month:a0,day:Re,hour:Re,minute:Re,second:Re},Hnt={year:Re,month:a0,day:Re,weekday:a0,hour:Re,minute:Re},dEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,timeZoneName:a0},hEe={year:Re,month:uu,day:Re,hour:Re,minute:Re,second:Re,timeZoneName:a0},pEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,timeZoneName:uu},mEe={year:Re,month:uu,day:Re,weekday:uu,hour:Re,minute:Re,second:Re,timeZoneName:uu};function kt(t){return typeof t>"u"}function sg(t){return typeof t=="number"}function kM(t){return typeof t=="number"&&t%1===0}function znt(t){return typeof t=="string"}function Gnt(t){return Object.prototype.toString.call(t)==="[object Date]"}function gEe(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Qnt(t){return Array.isArray(t)?t:[t]}function Oye(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 Vnt(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function qS(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Bx(t,e,r){return kM(t)&&t>=e&&t<=r}function Wnt(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 wp(t){if(!(kt(t)||t===null||t===""))return parseInt(t,10)}function eg(t){if(!(kt(t)||t===null||t===""))return parseFloat(t)}function pJ(t){if(!(kt(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function mJ(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function m5(t){return t%4===0&&(t%100!==0||t%400===0)}function h5(t){return m5(t)?366:365}function wM(t,e){let r=Wnt(e-1,12)+1,n=t+(e-r)/12;return r===2?m5(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function gJ(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 LM(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 oJ(t){return t>99?t:t>60?1900+t:2e3+t}function yEe(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 BM(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 EEe(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new fa(`Invalid unit value ${t}`);return e}function IM(t,e){let r={};for(let n in t)if(qS(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=EEe(i)}return r}function p5(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 qM(t){return Vnt(t,["hour","minute","second","millisecond"])}var AEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,Ynt=["January","February","March","April","May","June","July","August","September","October","November","December"],SEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Knt=["J","F","M","A","M","J","J","A","S","O","N","D"];function vEe(t){switch(t){case"narrow":return[...Knt];case"short":return[...SEe];case"long":return[...Ynt];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 _Ee=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],bEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Xnt=["M","T","W","T","F","S","S"];function TEe(t){switch(t){case"narrow":return[...Xnt];case"short":return[...bEe];case"long":return[..._Ee];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var CEe=["AM","PM"],Jnt=["Before Christ","Anno Domini"],Znt=["BC","AD"],eit=["B","A"];function REe(t){switch(t){case"narrow":return[...eit];case"short":return[...Znt];case"long":return[...Jnt];default:return null}}function tit(t){return CEe[t.hour<12?0:1]}function rit(t,e){return TEe(e)[t.weekday-1]}function nit(t,e){return vEe(e)[t.month-1]}function iit(t,e){return REe(e)[t.year<0?0:1]}function sit(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 Dye(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var oit={D:sJ,DD:Jye,DDD:Zye,DDDD:eEe,t:tEe,tt:rEe,ttt:nEe,tttt:iEe,T:sEe,TT:oEe,TTT:aEe,TTTT:uEe,f:lEe,ff:fEe,fff:dEe,ffff:pEe,F:cEe,FF:xEe,FFF:hEe,FFFF:mEe},o0=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 oit[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?tit(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(d,h)=>n?nit(e,d):s(h?{month:d}:{month:d,day:"numeric"},"month"),l=(d,h)=>n?rit(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?iit(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 Dye(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 Dye(s,i(a))}},au=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},Ip=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}},WX=null,MM=class t extends Ip{static get instance(){return WX===null&&(WX=new t),WX}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return yEe(e,r,n)}formatOffset(e,r){return p5(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},DM={};function ait(t){return DM[t]||(DM[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"})),DM[t]}var uit={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function lit(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 cit(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=uit[s];s==="era"?n[a]=o:kt(a)||(n[a]=parseInt(o,10))}return n}var TM={},Ux=class t extends Ip{static create(e){return TM[e]||(TM[e]=new t(e)),TM[e]}static resetCache(){TM={},DM={}}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 yEe(e,r,n,this.name)}formatOffset(e,r){return p5(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=ait(this.name),[i,s,o,a,u,l,c]=n.formatToParts?cit(n,r):lit(n,r);a==="BC"&&(i=-Math.abs(i)+1);let x=gJ({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}},YX=null,lu=class t extends Ip{static get utcInstance(){return YX===null&&(YX=new t(0)),YX}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(BM(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${p5(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${p5(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return p5(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}},PM=class extends Ip{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 Lp(t,e){if(kt(t)||t===null)return e;if(t instanceof Ip)return t;if(znt(t)){let r=t.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?lu.utcInstance:lu.parseSpecifier(r)||Ux.create(t)}else return sg(t)?lu.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new PM(t)}var Nye=()=>Date.now(),Fye="system",wye=null,Lye=null,Iye=null,Mye,yn=class{static get now(){return Nye}static set now(e){Nye=e}static set defaultZone(e){Fye=e}static get defaultZone(){return Lp(Fye,MM.instance)}static get defaultLocale(){return wye}static set defaultLocale(e){wye=e}static get defaultNumberingSystem(){return Lye}static set defaultNumberingSystem(e){Lye=e}static get defaultOutputCalendar(){return Iye}static set defaultOutputCalendar(e){Iye=e}static get throwOnInvalid(){return Mye}static set throwOnInvalid(e){Mye=e}static resetCaches(){Hn.resetCache(),Ux.resetCache()}},Pye={};function fit(t,e={}){let r=JSON.stringify([t,e]),n=Pye[r];return n||(n=new Intl.ListFormat(t,e),Pye[r]=n),n}var aJ={};function uJ(t,e={}){let r=JSON.stringify([t,e]),n=aJ[r];return n||(n=new Intl.DateTimeFormat(t,e),aJ[r]=n),n}var lJ={};function xit(t,e={}){let r=JSON.stringify([t,e]),n=lJ[r];return n||(n=new Intl.NumberFormat(t,e),lJ[r]=n),n}var cJ={};function dit(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=cJ[i];return s||(s=new Intl.RelativeTimeFormat(t,e),cJ[i]=s),s}var d5=null;function hit(){return d5||(d5=new Intl.DateTimeFormat().resolvedOptions().locale,d5)}function pit(t){let e=t.indexOf("-u-");if(e===-1)return[t];{let r,n=t.substring(0,e);try{r=uJ(t).resolvedOptions()}catch{r=uJ(n).resolvedOptions()}let{numberingSystem:i,calendar:s}=r;return[n,i,s]}}function mit(t,e,r){return(r||e)&&(t+="-u",r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function git(t){let e=[];for(let r=1;r<=12;r++){let n=En.utc(2016,r,1);e.push(t(n))}return e}function yit(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 CM(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function Eit(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 fJ=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=xit(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):mJ(e,3);return jn(r,this.padTo)}}},xJ=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&&Ux.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=uJ(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},dJ=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&gEe()&&(this.rtf=dit(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):sit(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":hit()),a=r||yn.defaultNumberingSystem,u=n||yn.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){d5=null,aJ={},lJ={},cJ={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=pit(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=mit(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=Eit(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 CM(this,e,n,vEe,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=git(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return CM(this,e,n,TEe,()=>{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]=yit(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return CM(this,void 0,e,()=>CEe,()=>{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 CM(this,e,r,REe,()=>{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 fJ(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new xJ(e,this.intl,r)}relFormatter(e={}){return new dJ(this.intl,this.isEnglish(),e)}listFormatter(e={}){return fit(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 US(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function $S(...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 jS(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 OEe(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=wp(e[r+i]);return[n,null,r+i]}}var DEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Ait=`(?:${DEe.source}?(?:\\[(${AEe.source})\\])?)?`,yJ=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,NEe=RegExp(`${yJ.source}${Ait}`),EJ=RegExp(`(?:T${NEe.source})?`),Sit=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,vit=/(\d{4})-?W(\d\d)(?:-?(\d))?/,_it=/(\d{4})-?(\d{3})/,bit=OEe("weekYear","weekNumber","weekDay"),Tit=OEe("year","ordinal"),Cit=/(\d{4})-(\d\d)-(\d\d)/,FEe=RegExp(`${yJ.source} ?(?:${DEe.source}|(${AEe.source}))?`),Rit=RegExp(`(?: ${FEe.source})?`);function BS(t,e,r){let n=t[e];return kt(n)?r:wp(n)}function Oit(t,e){return[{year:BS(t,e),month:BS(t,e+1,1),day:BS(t,e+2,1)},null,e+3]}function HS(t,e){return[{hours:BS(t,e,0),minutes:BS(t,e+1,0),seconds:BS(t,e+2,0),milliseconds:pJ(t[e+3])},null,e+4]}function g5(t,e){let r=!t[e]&&!t[e+1],n=BM(t[e+1],t[e+2]),i=r?null:lu.instance(n);return[{},i,e+3]}function y5(t,e){let r=t[e]?Ux.create(t[e]):null;return[{},r,e+1]}var Dit=RegExp(`^T?${yJ.source}$`),Nit=/^-?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 Fit(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(eg(r)),months:x(eg(n)),weeks:x(eg(i)),days:x(eg(s)),hours:x(eg(o)),minutes:x(eg(a)),seconds:x(eg(u),u==="-0"),milliseconds:x(pJ(l),f)}]}var wit={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?oJ(wp(e)):wp(e),month:SEe.indexOf(r)+1,day:wp(n),hour:wp(i),minute:wp(s)};return o&&(a.second=wp(o)),t&&(a.weekday=t.length>3?_Ee.indexOf(t)+1:bEe.indexOf(t)+1),a}var Lit=/^(?:(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 Iit(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=wit[u]:l?d=0:d=BM(c,f),[x,new lu(d)]}function Mit(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var Pit=/^(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$/,kit=/^(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$/,Bit=/^(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 kye(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,i,n,r,s,o,a),lu.utcInstance]}function qit(t){let[,e,r,n,i,s,o,a]=t;return[AJ(e,a,r,n,i,s,o),lu.utcInstance]}var Uit=US(Sit,EJ),$it=US(vit,EJ),jit=US(_it,EJ),Hit=US(NEe),wEe=$S(Oit,HS,g5,y5),zit=$S(bit,HS,g5,y5),Git=$S(Tit,HS,g5,y5),Qit=$S(HS,g5,y5);function Vit(t){return jS(t,[Uit,wEe],[$it,zit],[jit,Git],[Hit,Qit])}function Wit(t){return jS(Mit(t),[Lit,Iit])}function Yit(t){return jS(t,[Pit,kye],[kit,kye],[Bit,qit])}function Kit(t){return jS(t,[Nit,Fit])}var Xit=$S(HS);function Jit(t){return jS(t,[Dit,Xit])}var Zit=US(Cit,Rit),est=US(FEe),tst=$S(HS,g5,y5);function rst(t){return jS(t,[Zit,wEe],[est,tst])}var nst="Invalid Duration",LEe={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}},ist={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},...LEe},tl=146097/400,kS=146097/4800,sst={years:{quarters:4,months:12,weeks:tl/7,days:tl,hours:tl*24,minutes:tl*24*60,seconds:tl*24*60*60,milliseconds:tl*24*60*60*1e3},quarters:{months:3,weeks:tl/28,days:tl/4,hours:tl*24/4,minutes:tl*24*60/4,seconds:tl*24*60*60/4,milliseconds:tl*24*60*60*1e3/4},months:{weeks:kS/7,days:kS,hours:kS*24,minutes:kS*24*60,seconds:kS*24*60*60,milliseconds:kS*24*60*60*1e3},...LEe},rg=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ost=rg.slice(0).reverse();function tg(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 ast(t){return t<0?Math.floor(t):Math.ceil(t)}function IEe(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?ast(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function ust(t,e){ost.reduce((r,n)=>kt(e[n])?r:(r&&IEe(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?sst:ist,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:IM(e,t.normalizeUnit),loc:Hn.fromObject(r),conversionAccuracy:r.conversionAccuracy})}static fromDurationLike(e){if(sg(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]=Kit(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]=Jit(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 iJ(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 FM(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?o0.create(this.loc,n).formatDurationFromString(this,e):nst}toHuman(e={}){let r=rg.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+=mJ(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 rg)(qS(r.values,i)||qS(this.values,i))&&(n[i]=r.get(i)+this.get(i));return tg(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]=EEe(e(this.values[n],n));return tg(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...IM(e,t.normalizeUnit)};return tg(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),tg(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return ust(this.matrix,e),tg(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 rg)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;sg(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)rg.indexOf(l)>rg.indexOf(o)&&IEe(this.matrix,i,l,r,o)}else sg(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 tg(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 tg(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 rg)if(!r(this.values[n],e.values[n]))return!1;return!0}},l5="Invalid Interval";function lst(t,e){return!t||!t.isValid?og.invalid("missing or invalid start"):!e||!e.isValid?og.invalid("missing or invalid end"):e<t?og.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 og=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 nJ(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=x5(e),i=x5(r),s=lst(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=ci.fromDurationLike(r),i=x5(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ci.fromDurationLike(r),i=x5(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(x5).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()})`:l5}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:l5}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:l5}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:l5}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:l5}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))}},ig=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 Ux.isValidZone(e)}static normalizeZone(e){return Lp(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:gEe()}}};function Bye(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 cst(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=Bye(a,u);return(l-l%7)/7}],["days",Bye]],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 fst(t,e,r,n){let[i,s,o,a]=cst(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 SJ={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"},qye={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]},xst=SJ.hanidec.replace(/[\[|\]]/g,"").split("");function dst(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(SJ.hanidec)!==-1)e+=xst.indexOf(t[r]);else for(let i in qye){let[s,o]=qye[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function i0({numberingSystem:t},e=""){return new RegExp(`${SJ[t||"latn"]}${e}`)}var hst="missing Intl.DateTimeFormat.formatToParts support";function Yt(t,e=r=>r){return{regex:t,deser:([r])=>e(dst(r))}}var pst="\xA0",MEe=`[ ${pst}]`,PEe=new RegExp(MEe,"g");function mst(t){return t.replace(/\./g,"\\.?").replace(PEe,MEe)}function Uye(t){return t.replace(/\./g,"").replace(PEe," ").toLowerCase()}function s0(t,e){return t===null?null:{regex:RegExp(t.map(mst).join("|")),deser:([r])=>t.findIndex(n=>Uye(r)===Uye(n))+e}}function $ye(t,e){return{regex:t,deser:([,r,n])=>BM(r,n),groups:e}}function KX(t){return{regex:t,deser:([e])=>e}}function gst(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function yst(t,e){let r=i0(e),n=i0(e,"{2}"),i=i0(e,"{3}"),s=i0(e,"{4}"),o=i0(e,"{6}"),a=i0(e,"{1,2}"),u=i0(e,"{1,3}"),l=i0(e,"{1,6}"),c=i0(e,"{1,9}"),f=i0(e,"{2,4}"),x=i0(e,"{4,6}"),d=m=>({regex:RegExp(gst(m.val)),deser:([g])=>g,literal:!0}),p=(m=>{if(t.literal)return d(m);switch(m.val){case"G":return s0(e.eras("short",!1),0);case"GG":return s0(e.eras("long",!1),0);case"y":return Yt(l);case"yy":return Yt(f,oJ);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 s0(e.months("short",!0,!1),1);case"MMMM":return s0(e.months("long",!0,!1),1);case"L":return Yt(a);case"LL":return Yt(n);case"LLL":return s0(e.months("short",!1,!1),1);case"LLLL":return s0(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 KX(c);case"uu":return KX(a);case"uuu":return Yt(r);case"a":return s0(e.meridiems(),0);case"kkkk":return Yt(s);case"kk":return Yt(f,oJ);case"W":return Yt(a);case"WW":return Yt(n);case"E":case"c":return Yt(r);case"EEE":return s0(e.weekdays("short",!1,!1),1);case"EEEE":return s0(e.weekdays("long",!1,!1),1);case"ccc":return s0(e.weekdays("short",!0,!1),1);case"cccc":return s0(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return $ye(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return $ye(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return KX(/[a-z_+-/]{1,256}?/i);default:return d(m)}})(t)||{invalidReason:hst};return p.token=t,p}var Est={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=Est[n];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function Sst(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function vst(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(qS(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 _st(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=Ux.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=pJ(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var XX=null;function bst(){return XX||(XX=En.fromMillis(1555555555555)),XX}function Tst(t,e){if(t.literal)return t;let r=o0.macroTokenToFormatOpts(t.val);if(!r)return t;let s=o0.create(e,r).formatDateTimeParts(bst()).map(o=>Ast(o,e,r));return s.includes(void 0)?t:s}function Cst(t,e){return Array.prototype.concat(...t.map(r=>Tst(r,e)))}function kEe(t,e,r){let n=Cst(o0.parseFormat(r),t),i=n.map(o=>yst(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=Sst(i),u=RegExp(o,"i"),[l,c]=vst(e,u,a),[f,x,d]=c?_st(c):[null,null,void 0];if(qS(c,"a")&&qS(c,"H"))throw new ng("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 Rst(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=kEe(t,e,r);return[n,i,s,o]}var BEe=[0,31,59,90,120,151,181,212,243,273,304,334],qEe=[0,31,60,91,121,152,182,213,244,274,305,335];function rl(t,e){return new au("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function UEe(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 $Ee(t,e,r){return r+(m5(t)?qEe:BEe)[e-1]}function jEe(t,e){let r=m5(t)?qEe:BEe,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function hJ(t){let{year:e,month:r,day:n}=t,i=$Ee(e,r,n),s=UEe(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=LM(a)):o>LM(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...qM(t)}}function jye(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=UEe(e,1,4),s=h5(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=h5(a)):o>s?(a=e+1,o-=h5(e)):a=e;let{month:u,day:l}=jEe(a,o);return{year:a,month:u,day:l,...qM(t)}}function JX(t){let{year:e,month:r,day:n}=t,i=$Ee(e,r,n);return{year:e,ordinal:i,...qM(t)}}function Hye(t){let{year:e,ordinal:r}=t,{month:n,day:i}=jEe(e,r);return{year:e,month:n,day:i,...qM(t)}}function Ost(t){let e=kM(t.weekYear),r=Bx(t.weekNumber,1,LM(t.weekYear)),n=Bx(t.weekday,1,7);return e?r?n?!1:rl("weekday",t.weekday):rl("week",t.week):rl("weekYear",t.weekYear)}function Dst(t){let e=kM(t.year),r=Bx(t.ordinal,1,h5(t.year));return e?r?!1:rl("ordinal",t.ordinal):rl("year",t.year)}function HEe(t){let e=kM(t.year),r=Bx(t.month,1,12),n=Bx(t.day,1,wM(t.year,t.month));return e?r?n?!1:rl("day",t.day):rl("month",t.month):rl("year",t.year)}function zEe(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=Bx(e,0,23)||e===24&&r===0&&n===0&&i===0,o=Bx(r,0,59),a=Bx(n,0,59),u=Bx(i,0,999);return s?o?a?u?!1:rl("millisecond",i):rl("second",n):rl("minute",r):rl("hour",e)}var ZX="Invalid DateTime",zye=864e13;function RM(t){return new au("unsupported zone",`the zone "${t.name}" is not supported`)}function eJ(t){return t.weekData===null&&(t.weekData=hJ(t.c)),t.weekData}function c5(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 GEe(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 Gye(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 NM(t,e,r){return GEe(gJ(t),e,r)}function Qye(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,wM(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=gJ(s),[u,l]=GEe(a,r,t.zone);return o!==0&&(u+=o,l=t.zone.offset(u)),{ts:u,o:l}}function f5(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 OM(t,e,r=!0){return t.isValid?o0.create(Hn.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function tJ(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 Vye(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 QEe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Nst={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Fst={ordinal:1,hour:0,minute:0,second:0,millisecond:0},VEe=["year","month","day","hour","minute","second","millisecond"],wst=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Lst=["year","ordinal","hour","minute","second","millisecond"];function Wye(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 FM(t);return e}function Yye(t,e){let r=Lp(e.zone,yn.defaultZone),n=Hn.fromObject(e),i=yn.now(),s,o;if(kt(t.year))s=i;else{for(let l of VEe)kt(t[l])&&(t[l]=QEe[l]);let a=HEe(t)||zEe(t);if(a)return En.invalid(a);let u=r.offset(i);[s,o]=NM(t,u,r)}return new En({ts:s,zone:r,loc:n,o})}function Kye(t,e,r){let n=kt(r.round)?!0:r.round,i=(o,a)=>(o=mJ(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 Xye(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:RM(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=Gye(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]=Xye(arguments),[n,i,s,o,a,u,l]=r;return Yye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,r]=Xye(arguments),[n,i,s,o,a,u,l]=r;return e.zone=lu.utcInstance,Yye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,r={}){let n=Gnt(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Lp(r.zone,yn.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:Hn.fromObject(r)}):t.invalid(RM(i))}static fromMillis(e,r={}){if(sg(e))return e<-zye||e>zye?t.invalid("Timestamp out of range"):new t({ts:e,zone:Lp(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(sg(e))return new t({ts:e*1e3,zone:Lp(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new fa("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Lp(r.zone,yn.defaultZone);if(!n.isValid)return t.invalid(RM(n));let i=yn.now(),s=kt(r.specificOffset)?n.offset(i):r.specificOffset,o=IM(e,Wye),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 ng("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new ng("Can't mix ordinal dates with month/day");let d=f||o.weekday&&!c,h,p,m=Gye(i,s);d?(h=wst,p=Nst,m=hJ(m)):a?(h=Lst,p=Fst,m=JX(m)):(h=VEe,p=QEe);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?Ost(o):a?Dst(o):HEe(o),A=y||zEe(o);if(A)return t.invalid(A);let S=d?jye(o):a?Hye(o):o,[T,b]=NM(S,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]=Vit(e);return f5(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Wit(e);return f5(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Yit(e);return f5(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]=Rst(o,e,r);return c?t.invalid(c):f5(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]=rst(e);return f5(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 rJ(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?eJ(this).weekYear:NaN}get weekNumber(){return this.isValid?eJ(this).weekNumber:NaN}get weekday(){return this.isValid?eJ(this).weekday:NaN}get ordinal(){return this.isValid?JX(this.c).ordinal:NaN}get monthShort(){return this.isValid?ig.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?ig.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?ig.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?ig.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 m5(this.year)}get daysInMonth(){return wM(this.year,this.month)}get daysInYear(){return this.isValid?h5(this.year):NaN}get weeksInWeekYear(){return this.isValid?LM(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=o0.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=Lp(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]=NM(o,s,e)}return c5(this,{ts:i,zone:e})}else return t.invalid(RM(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return c5(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=IM(e,Wye),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 ng("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new ng("Can't mix ordinal dates with month/day");let l;n?l=jye({...hJ(this.c),...r}):kt(r.ordinal)?(l={...this.toObject(),...r},kt(r.day)&&(l.day=Math.min(wM(l.year,l.month),l.day))):l=Hye({...JX(this.c),...r});let[c,f]=NM(l,this.o,this.zone);return c5(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e);return c5(this,Qye(this,r))}minus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e).negate();return c5(this,Qye(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?o0.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):ZX}toLocaleString(e=sJ,r={}){return this.isValid?o0.create(this.loc.clone(r),e).formatDateTime(this):ZX}toLocaleParts(e={}){return this.isValid?o0.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=tJ(this,o);return a+="T",a+=Vye(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?tJ(this,e==="extended"):null}toISOWeekDate(){return OM(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":"")+Vye(this,o==="extended",r,e,n,s):null}toRFC2822(){return OM(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return OM(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?tJ(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")),OM(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ZX}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=Qnt(r).map(ci.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=fst(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?og.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),Kye(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?Kye(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 Oye(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new fa("max requires all arguments be DateTimes");return Oye(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 kEe(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return sJ}static get DATE_MED(){return Jye}static get DATE_MED_WITH_WEEKDAY(){return jnt}static get DATE_FULL(){return Zye}static get DATE_HUGE(){return eEe}static get TIME_SIMPLE(){return tEe}static get TIME_WITH_SECONDS(){return rEe}static get TIME_WITH_SHORT_OFFSET(){return nEe}static get TIME_WITH_LONG_OFFSET(){return iEe}static get TIME_24_SIMPLE(){return sEe}static get TIME_24_WITH_SECONDS(){return oEe}static get TIME_24_WITH_SHORT_OFFSET(){return aEe}static get TIME_24_WITH_LONG_OFFSET(){return uEe}static get DATETIME_SHORT(){return lEe}static get DATETIME_SHORT_WITH_SECONDS(){return cEe}static get DATETIME_MED(){return fEe}static get DATETIME_MED_WITH_SECONDS(){return xEe}static get DATETIME_MED_WITH_WEEKDAY(){return Hnt}static get DATETIME_FULL(){return dEe}static get DATETIME_FULL_WITH_SECONDS(){return hEe}static get DATETIME_HUGE(){return pEe}static get DATETIME_HUGE_WITH_SECONDS(){return mEe}};function x5(t){if(En.isDateTime(t))return t;if(t&&t.valueOf&&sg(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 Ist="2.5.2";cu.DateTime=En;cu.Duration=ci;cu.FixedOffsetZone=lu;cu.IANAZone=Ux;cu.Info=ig;cu.Interval=og;cu.InvalidZone=PM;cu.Settings=yn;cu.SystemZone=MM;cu.VERSION=Ist;cu.Zone=Ip});var ZEe=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 Mp=vJ(),Mst=Ke(),Pst=LS(),WEe=_I(),_J=ir(),bJ=class extends Error{};ki.TimeFormatError=bJ;function ug(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 YEe="yyyy",KEe=`${YEe}-LL`,nl=`${KEe}-dd`,XEe=`${nl} HH`,JEe=`${XEe}:mm`,TJ=`${JEe}:ss`,UM=class extends _J.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}},CJ=class t extends UM{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r,n=ug(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=Mp.DateTime.fromFormat(e,TJ);if(s.isValid)return new t(n,r);if(s=Mp.DateTime.fromFormat(e,JEe),s.isValid){n.text=n.text+":00",r="minute";let o=s.plus({minute:1}).toFormat(TJ);return new E5(n,r,"timestamp",o)}}};ki.LiteralTimestamp=CJ;var E5=class extends UM{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,_J.getMorphicValue)(i,"timestamp"),u=(0,_J.getMorphicValue)(s,"timestamp");if(a&&u)i=a,s=u;else return super.apply(e,r,n)}if((0,Mst.isTimeFieldType)(o.dataType)){let a=o.dataType;return new Pst.Range(new WEe.ExprTime(a,i.value),new WEe.ExprTime(a,s.value)).apply(e,r,n)}}return super.apply(e,r,n)}},RJ=class t extends E5{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,XEe);if(i.isValid)return r.text=r.text+":00:00",n=i.plus({hour:1}).toFormat(TJ),new t(r,n)}};ki.LiteralHour=RJ;var ag=class extends E5{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}}}},OJ=class t extends ag{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,nl);if(i.isValid)return n=i.plus({day:1}).toFormat(nl),new t(r,n)}};ki.LiteralDay=OJ;var DJ=class t extends ag{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){let r=ug(e,!1),n=r.text,i=r.text.slice(0,10),s=Mp.DateTime.fromFormat(i,nl);if(s.isValid&&s.weekday===7){let a=s.plus({days:7});return r.text=s.toFormat(nl),n=a.toFormat(nl),new t(r,n)}}};ki.LiteralWeek=DJ;var NJ=class t extends ag{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,KEe);if(i.isValid){let s=i.plus({months:1});return r.text=i.toFormat(nl),n=s.toFormat(nl),new t(r,n)}}};ki.LiteralMonth=NJ;var FJ=class t extends ag{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){let r=ug(e,!1),n=r.text,i=r.text.match(/(^\d{4})-[qQ](\d)$/);if(i){let s=Number.parseInt(i[2])-1,o=Mp.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));let a=o.plus({quarter:1});return r.text=o.toFormat(nl),n=a.toFormat(nl),new t(r,n)}}};ki.LiteralQuarter=FJ;var wJ=class t extends ag{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){let r=ug(e,!1),n=r.text,i=Mp.DateTime.fromFormat(r.text,YEe);if(i.isValid){let s=i.plus({year:1});return r.text=i.toFormat(nl),n=s.toFormat(nl),new t(r,n)}}};ki.LiteralYear=wJ});var eAe=v($M=>{"use strict";Object.defineProperty($M,"__esModule",{value:!0});$M.PartialCompare=void 0;var kst=js(),Bst=ir(),LJ=class extends Bst.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,kst.errorFor)("no value for partial compare")}};$M.PartialCompare=LJ});var rAe=v(zS=>{"use strict";Object.defineProperty(zS,"__esModule",{value:!0});zS.PickWhen=zS.Pick=void 0;var Xc=Ke(),Pp=js(),u0=pn(),qst=ir(),Ust=mt(),tAe=hs();function jM(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}var IJ=class extends qst.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&&!u0.FT.typeEq(s,x,!0)){let d=u0.FT.inspect(x);return this.log(`pick type '${d}', expected '${s.dataType}'`),(0,Pp.errorFor)("pick when type")}s=jM(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}let l=(this.elsePick||n).getExpression(e);if(s=jM(s,l),!u0.FT.typeEq(s,l,!0)){let c=this.elsePick?"else":"pick default";return this.log(`${c} type '${u0.FT.inspect(l)}', expected '${s.dataType}'`),(0,Pp.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Xc.maxExpressionType)(o,l.expressionType),evalSpace:(0,Xc.mergeEvalSpaces)(a,l.evalSpace),value:(0,tAe.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,Pp.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,Pp.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,Pp.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(!u0.FT.typeEq(u.when,u0.FT.boolT))return this.log(`when expression must be boolean, not '${u0.FT.inspect(u.when)}`),(0,Pp.errorFor)("pick when type");if(n&&!u0.FT.typeEq(n,u.pick,!0)){let l=u0.FT.inspect(u.pick);return this.log(`pick type '${l}', expected '${n.dataType}'`),(0,Pp.errorFor)("pick value type")}n=jM(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=jM(n,a),u0.FT.typeEq(n,a,!0)?(i.push(" ELSE ",...a.value," END"),{dataType:n.dataType,expressionType:s,value:(0,tAe.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${u0.FT.inspect(a)}', expected '${n.dataType}'`),(0,Pp.errorFor)("pick value type mismatch"))}};zS.Pick=IJ;var MJ=class extends Ust.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="pickWhen",this.has({pick:e})}};zS.PickWhen=MJ});var nAe=v(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.Timeframe=void 0;var $st=Ke(),jst=mt(),PJ=class extends jst.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,$st.isTimestampUnit)(r)?r:"second"}};HM.Timeframe=PJ});var sAe=v(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.TopBy=void 0;var Hst=Ke(),iAe=ir(),zst=mt(),Gst=hs(),kJ=class extends zst.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof iAe.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof iAe.ExpressionDef){let r=this.by.getExpression(e);return(0,Hst.expressionIsAggregate)(r.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,Gst.compressExpr)(r.value)}}return{by:"name",name:this.by}}};zM.TopBy=kJ});var oAe=v(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});kp.ImportStatement=kp.ImportSelect=kp.ImportSourceName=void 0;var $J=mt(),BJ=class extends $J.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}};kp.ImportSourceName=BJ;var qJ=class extends $J.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}};kp.ImportSelect=qJ;var UJ=class extends $J.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}'`)}}};kp.ImportStatement=UJ});var HJ=v(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});GM.ExtendBlock=void 0;var Qst=mt(),Vst=Ii(),jJ=class extends Qst.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Vst.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)for(let n of r.list)e.inputFS.extendSource(n)}};GM.ExtendBlock=jJ});var aAe=v(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.AnonymousQuery=void 0;var Wst=mt(),Yst=Vc(),zJ=class extends Wst.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Yst.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)}};QM.AnonymousQuery=zJ});var GS=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.View=void 0;var Kst=mt(),GJ=class extends Kst.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}};VM.View=GJ});var uAe=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.ViewArrow=void 0;var Xst=el(),Jst=GS(),QJ=class extends Jst.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 Xst.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"),[]}getImplicitName(){return this.operation.getImplicitName()}};WM.ViewArrow=QJ});var YJ=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.refine=void 0;var VJ=uc(),WJ=yL();function Zst(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,VJ.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,VJ.isQuerySegment)(o)&&(0,VJ.isQuerySegment)(s)){let a=[],u=[],l=new Map(s.queryFields.map(c=>[(0,WJ.nameFromDef)(c),c]));for(let c of o.queryFields)l.has((0,WJ.nameFromDef)(c))?a.push(c):u.push(c);s.queryFields=[...s.queryFields,...u],a.length>0&&t.log(`overlapping fields in refinement: ${a.map(WJ.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}YM.refine=Zst});var lAe=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.ViewRefine=void 0;var eot=la(),tot=Ym(),rot=YJ(),not=GS(),KJ=class extends not.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,tot.getFinalStruct)(this.refinement,e.structDef(),i):eot.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,rot.refine)(this,r,i[0])}getImplicitName(){return this.base.getImplicitName()}};KM.ViewRefine=KJ});var xAe=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.ReferenceView=void 0;var cAe=Ke(),fAe=la(),iot=Ym(),sot=ua(),oot=YJ(),aot=GS(),XJ=class extends aot.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:fAe.ErrorFactory.structDef,outputStruct:fAe.ErrorFactory.structDef,pipeline:[],error:!0}};if(!n.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(n.found instanceof sot.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,cAe.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,cAe.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,iot.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,oot.refine)(this,r,i):r}getImplicitName(){return this.reference.nameString}};XM.ReferenceView=XJ});var ZJ=v(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.Index=void 0;var uot=mt(),lot=Ii(),JJ=class extends uot.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=lot.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};JM.Index=JJ});var tZ=v(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.SampleProperty=void 0;var cot=mt(),dAe=Ii(),eZ=class extends cot.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=dAe.LegalRefinementStage.Tail,this.forceQueryClass=dAe.QueryClass.Index}sampling(){return this.sample}};ZM.SampleProperty=eZ});var pAe=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0});eP.IndexFieldSpace=void 0;var hAe=Ke(),rZ=MS(),fot=ua(),xot=u5(),dot=GK(),hot=el(),nZ=class extends xot.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(let r of e)r instanceof rZ.FieldReference?super.pushFields(r):r instanceof rZ.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 fot.SpaceField){let s=this.expandedWild[n];if(s){r.push({type:"fieldref",path:s});continue}if(i instanceof dot.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 hot.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=rZ.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,hAe.isAtomicFieldType)(c.dataType)&&(0,hAe.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)}};eP.IndexFieldSpace=nZ});var mAe=v(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.IndexBuilder=void 0;var iZ=Ke(),pot=la(),mot=Wm(),got=ZJ(),yot=PS(),Eot=tZ(),Aot=pAe(),sZ=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 mot.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof yot.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof got.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Eot.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,iZ.isIndexSegment)(e)&&!(0,iZ.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),pot.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,iZ.isIndexSegment)(e)&&e?.sample&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),r}};tP.IndexBuilder=sZ});var aZ=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0});rP.GroupBy=void 0;var Sot=r0(),gAe=Ii(),oZ=class extends Sot.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=gAe.LegalRefinementStage.Single,this.forceQueryClass=gAe.QueryClass.Grouping}};rP.GroupBy=oZ});var yAe=v(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.ProjectFieldSpace=void 0;var uZ=Ke(),vot=u5(),lZ=class extends vot.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,uZ.expressionIsAggregate)(e.expressionType)?!1:(0,uZ.expressionInvolvesAggregate)(e.expressionType)&&(0,uZ.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}};nP.ProjectFieldSpace=lZ});var xZ=v(QS=>{"use strict";Object.defineProperty(QS,"__esModule",{value:!0});QS.Ordering=QS.OrderBy=void 0;var _ot=Ke(),EAe=a5(),AAe=mt(),bot=Ii(),cZ=class extends AAe.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof EAe.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 EAe.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,_ot.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}};QS.OrderBy=cZ;var fZ=class extends AAe.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=bot.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}};QS.Ordering=fZ});var hZ=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0});iP.Top=void 0;var SAe=Ke(),Tot=hs(),Cot=a5(),Rot=mt(),Oot=Ii(),dZ=class extends Rot.MalloyElement{constructor(e,r){super(),this.limit=e,this.by=r,this.elementType="top",this.queryRefinementStage=Oot.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:r})}getBy(e){var r;if(this.by)if(this.by instanceof Cot.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,SAe.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,SAe.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,Tot.compressExpr)(n.value)}}}};iP.Top=dZ});var oP=v(VS=>{"use strict";Object.defineProperty(VS,"__esModule",{value:!0});VS.ReduceBuilder=VS.QuerySegmentBuilder=void 0;var vAe=Ke(),Dot=la(),Not=Wm(),Fot=PS(),_Ae=xZ(),bAe=hZ(),wot=u5(),Lot=r0(),sP=class{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof Lot.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof Not.Filter){let r=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(r))}else e instanceof bAe.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 Fot.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof _Ae.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 bAe.Top){let i=this.order.getBy(this.inputFS);i&&(r.by=i)}this.order instanceof _Ae.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])}};VS.QuerySegmentBuilder=sP;var pZ=class extends sP{constructor(e,r,n,i){super(),this.type="grouping",this.resultFS=new wot.ReduceFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,vAe.isReduceSegment)(e)||(0,vAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),Dot.ErrorFactory.reduceSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};VS.ReduceBuilder=pZ});var CAe=v(aP=>{"use strict";Object.defineProperty(aP,"__esModule",{value:!0});aP.ProjectBuilder=void 0;var TAe=Ke(),Iot=la(),Mot=aZ(),Pot=yAe(),kot=oP(),mZ=class extends kot.QuerySegmentBuilder{constructor(e,r,n,i){super(),this.type="project",this.resultFS=new Pot.ProjectFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Mot.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,TAe.isProjectSegment)(e)||(0,TAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),Iot.ErrorFactory.projectSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};aP.ProjectBuilder=mZ});var RAe=v(uP=>{"use strict";Object.defineProperty(uP,"__esModule",{value:!0});uP.PartialBuilder=void 0;var Bot=uc(),qot=oP(),gZ=class extends qot.ReduceBuilder{finalize(e){let r=super.finalize(e);if((0,Bot.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}};uP.PartialBuilder=gZ});var EZ=v(lP=>{"use strict";Object.defineProperty(lP,"__esModule",{value:!0});lP.QOpDesc=void 0;var Uot=mAe(),$ot=CAe(),jot=oP(),Hot=mt(),zot=Ym(),Got=el(),lg=Ii(),Qot=RAe(),yZ=class extends Hot.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,n=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=lg.QueryClass.Grouping:this.refineThis.type==="project"?r=lg.QueryClass.Project:this.refineThis.type==="index"&&(r=lg.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=lg.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,n){switch(this.computeType()){case lg.QueryClass.Grouping:return new jot.ReduceBuilder(e,this.refineThis,r,n);case lg.QueryClass.Project:return new $ot.ProjectBuilder(e,this.refineThis,r,n);case lg.QueryClass.Index:return new Uot.IndexBuilder(e,this.refineThis,r,n);case void 0:return new Qot.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 Got.StaticSpace((0,zot.opOutputStruct)(this,e.structDef(),i))}}};lP.QOpDesc=yZ});var DAe=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0});cP.QOpDescView=void 0;var Vot=Ke(),Wot=el(),OAe=EZ(),Yot=Ym(),AZ=Ii(),Kot=GS(),SZ=class extends Kot.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,Vot.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 OAe.QOpDesc([]),o=new OAe.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,Yot.getFinalStruct)(this,e.structDef(),i.slice(-1));i[a]=this.getOp(new Wot.StaticSpace(u),void 0,o,i[a])}return i}getImplicitName(){}};cP.QOpDescView=SZ});var DZ=v(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.FieldDefinitionValue=An.DefSpace=An.DimensionFieldDeclaration=An.MeasureFieldDeclaration=An.DeclareFieldDeclaration=An.ProjectFieldDeclaration=An.GroupByFieldDeclaration=An.AggregateFieldDeclaration=An.CalculateFieldDeclaration=An.AtomicFieldDeclaration=void 0;var Xot=Ke(),Jot=hs(),Zot=pn(),eat=mI(),tat=mt(),cg=QK(),rat=Vc(),nat=ua(),Jc=class extends tat.MalloyElement{constructor(e,r,n){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=n,this.isNoteableObj=!0,this.extendNote=rat.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,Jot.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,Xot.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,eat.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=Zot.FT.inspect(n);this.log(`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new fP(e,this))}};An.AtomicFieldDeclaration=Jc;var vZ=class extends Jc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}};An.CalculateFieldDeclaration=vZ;var _Z=class extends Jc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckAggregate)(e,this)}};An.AggregateFieldDeclaration=_Z;var bZ=class extends Jc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckGroupBy)(e,this)}};An.GroupByFieldDeclaration=bZ;var TZ=class extends Jc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckProject)(e,this)}};An.ProjectFieldDeclaration=TZ;var CZ=class extends Jc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckDeclare)(e,this)}};An.DeclareFieldDeclaration=CZ;var RZ=class extends Jc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckMeasure)(e,this)}};An.MeasureFieldDeclaration=RZ;var OZ=class extends Jc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,cg.typecheckDimension)(e,this)}};An.DimensionFieldDeclaration=OZ;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")}};An.DefSpace=A5;var fP=class extends nat.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)}};An.FieldDefinitionValue=fP});var FAe=v(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.Aggregate=void 0;var iat=r0(),NAe=Ii(),NZ=class extends iat.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=NAe.LegalRefinementStage.Single,this.forceQueryClass=NAe.QueryClass.Grouping}};xP.Aggregate=NZ});var wAe=v(dP=>{"use strict";Object.defineProperty(dP,"__esModule",{value:!0});dP.Calculate=void 0;var sat=r0(),oat=Ii(),FZ=class extends sat.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=oat.LegalRefinementStage.Single}};dP.Calculate=FZ});var LZ=v(hP=>{"use strict";Object.defineProperty(hP,"__esModule",{value:!0});hP.Dimensions=void 0;var aat=_S(),wZ=class extends aat.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}};hP.Dimensions=wZ});var MZ=v(pP=>{"use strict";Object.defineProperty(pP,"__esModule",{value:!0});pP.Measures=void 0;var uat=_S(),IZ=class extends uat.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}};pP.Measures=IZ});var IAe=v(mP=>{"use strict";Object.defineProperty(mP,"__esModule",{value:!0});mP.Nests=void 0;var lat=r0(),LAe=Ii(),PZ=class extends lat.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=LAe.LegalRefinementStage.Single,this.forceQueryClass=LAe.QueryClass.Grouping}};mP.Nests=PZ});var PAe=v(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.ProjectStatement=void 0;var cat=r0(),MAe=Ii(),kZ=class extends cat.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=MAe.QueryClass.Project,this.queryRefinementStage=MAe.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}};gP.ProjectStatement=kZ});var BAe=v(yP=>{"use strict";Object.defineProperty(yP,"__esModule",{value:!0});yP.FromSQLSource=void 0;var kAe=Ke(),fat=r5(),BZ=class extends fat.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,kAe.isSQLBlockStruct)(r)&&r.declaredSQLBlock){let{declaredSQLBlock:n,...i}=r;return i}else if(!(0,kAe.isSQLBlockStruct)(r)){this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`);return}this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`)}};yP.FromSQLSource=BZ});var jZ=v(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});Bp.findReferences=Bp.deprecatedParseTableURI=Bp.constructTableKey=void 0;var xat=vp(),UZ=VC();function qZ(t){let e=(0,UZ.getStringIfShort)(t);if(e)return e;let r=[],n=t.string().sqlString();if(n){for(let i of(0,UZ.getStringParts)(n))typeof i=="string"&&r.push(i);return r.join("")}return""}var $Z=class{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,n){let i=qAe(e,r);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:r,firstReference:n})}enterTableMethod(e){let r=(0,UZ.getId)(e.connectionId()),n=qZ(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(r,n,i)}enterTableFunction(e){let r=qZ(e.tableURI()),{connectionName:n,tablePath:i}=UAe(r),s=this.trans.rangeFromContext(e);this.registerTableReference(n,i,s)}enterImportURL(e){let r=qZ(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}};function qAe(t,e){return t===void 0?e:`${t}:${e}`}Bp.constructTableKey=qAe;function UAe(t){let e=t.match(/^([^:]*):(.*)$/);if(e){let[,r,n]=e;return{connectionName:r,tablePath:n}}else return{tablePath:t}}Bp.deprecatedParseTableURI=UAe;function dat(t,e,r){let n=new $Z(t,e),i=n;return xat.ParseTreeWalker.DEFAULT.walk(i,r),{tables:n.needTables,urls:n.needImports}}Bp.findReferences=dat});var HAe=v(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.TableFunctionSource=qp.TableMethodSource=qp.TableSource=void 0;var jAe=jZ(),hat=Mx(),$Ae=la(),S5=class extends hat.Source{structDef(){var e,r;let n=this.getTableInfo();if(n===void 0)return $Ae.ErrorFactory.structDef;let{tablePath:i,connectionName:s}=n,o=(0,jAe.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),$Ae.ErrorFactory.structDef}};qp.TableSource=S5;var HZ=class extends S5{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}}};qp.TableMethodSource=HZ;var zZ=class extends S5{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,jAe.deprecatedParseTableURI)(this.tableURI)}};qp.TableFunctionSource=zZ});var zAe=v(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.SQLStatement=void 0;var pat=yK(),mat=mt(),GZ=class extends mat.MalloyElement{constructor(e){super(),this.select=e,this.elementType="sqlStatement",this.has({select:e})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,pat.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(`
682
682
  `));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}}};EP.SQLStatement=GZ});var QAe=v(AP=>{"use strict";Object.defineProperty(AP,"__esModule",{value:!0});AP.SQLString=void 0;var gat=mt(),GAe=Op(),QZ=class extends gat.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(yat)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof GAe.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}};AP.SQLString=QZ;function yat(t){return t instanceof GAe.SourceQueryElement}});var VAe=v(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.SourceDesc=void 0;var Eat=mt(),VZ=class extends Eat.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}};SP.SourceDesc=VZ});var WAe=v(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.isSourceProperty=void 0;var Aat=Wm(),Sat=TS(),vat=_S(),_at=IL(),bat=zL(),Tat=PL(),Cat=BL(),Rat=UL(),Oat=jL();function Dat(t){return t instanceof Aat.Filter||t instanceof Sat.Joins||t instanceof vat.DeclareFields||t instanceof _at.FieldListEdit||t instanceof bat.Renames||t instanceof Tat.PrimaryKey||t instanceof Oat.ObjectAnnotation||t instanceof Cat.Views||t instanceof Rat.TimezoneStatement}vP.isSourceProperty=Dat});var KAe=v(_P=>{"use strict";Object.defineProperty(_P,"__esModule",{value:!0});_P.isFieldCollectionMember=void 0;var Nat=DZ(),YAe=MS();function Fat(t){return t instanceof YAe.FieldReference||t instanceof YAe.WildcardFieldReference||t instanceof Nat.AtomicFieldDeclaration}_P.isFieldCollectionMember=Fat});var XAe=v(bP=>{"use strict";Object.defineProperty(bP,"__esModule",{value:!0});bP.isQueryElement=void 0;var wat=KL(),Lat=ZL(),Iat=xK(),Mat=gK();function Pat(t){return t instanceof wat.QueryArrow||t instanceof Lat.QueryRefine||t instanceof Iat.QueryReference||t instanceof Mat.QueryRaw}bP.isQueryElement=Pat});var ZAe=v(JAe=>{"use strict";Object.defineProperty(JAe,"__esModule",{value:!0})});var eSe=v(TP=>{"use strict";Object.defineProperty(TP,"__esModule",{value:!0});TP.isQueryProperty=void 0;function kat(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}TP.isQueryProperty=kat});var tSe=v(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.isQueryExtendProperty=void 0;var Bat=LZ(),qat=TS(),Uat=MZ();function $at(t){return t instanceof Bat.Dimensions||t instanceof Uat.Measures||t instanceof qat.Joins}CP.isQueryExtendProperty=$at});var rSe=v(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.isFieldPropStatement=void 0;var jat=II(),Hat=Wm(),zat=PS(),Gat=YI();function Qat(t){return t instanceof Hat.Filter||t instanceof zat.Limit||t instanceof Gat.PartitionBy||t instanceof jat.FunctionOrdering}RP.isFieldPropStatement=Qat});var OP=v(ne=>{"use strict";var Vat=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)&&Vat(e,t,r)};Object.defineProperty(ne,"__esModule",{value:!0});ie(pY(),ne);ie(s3e(),ne);ie(a3e(),ne);ie(Mx(),ne);ie(eK(),ne);ie(Op(),ne);ie(A3e(),ne);ie(C3e(),ne);ie(R3e(),ne);ie(hK(),ne);ie(O3e(),ne);ie(IL(),ne);ie(PL(),ne);ie(zL(),ne);ie(BL(),ne);ie(UL(),ne);ie($3e(),ne);ie(NI(),ne);ie(j3e(),ne);ie(II(),ne);ie(z3e(),ne);ie(Jm(),ne);ie(K3e(),ne);ie(UI(),ne);ie(X3e(),ne);ie(J3e(),ne);ie(eye(),ne);ie(IK(),ne);ie(tye(),ne);ie(rye(),ne);ie(iye(),ne);ie(vX(),ne);ie(wK(),ne);ie(LI(),ne);ie(oye(),ne);ie(aye(),ne);ie(uye(),ne);ie(lye(),ne);ie(cye(),ne);ie(xye(),ne);ie(dye(),ne);ie(hye(),ne);ie(pye(),ne);ie(mye(),ne);ie(gye(),ne);ie(yye(),ne);ie(Eye(),ne);ie(Aye(),ne);ie(_ye(),ne);ie(Rye(),ne);ie(ZEe(),ne);ie(eAe(),ne);ie(YI(),ne);ie(rAe(),ne);ie(LS(),ne);ie(nAe(),ne);ie(sAe(),ne);ie(NX(),ne);ie(hs(),ne);ie(oAe(),ne);ie(HJ(),ne);ie(yY(),ne);ie(aAe(),ne);ie(ZL(),ne);ie(KL(),ne);ie(GS(),ne);ie(uAe(),ne);ie(lAe(),ne);ie(xAe(),ne);ie(DAe(),ne);ie(DZ(),ne);ie(MS(),ne);ie(FAe(),ne);ie(wAe(),ne);ie(_S(),ne);ie(LZ(),ne);ie(HJ(),ne);ie(Wm(),ne);ie(aZ(),ne);ie(ZJ(),ne);ie(TS(),ne);ie(dY(),ne);ie(PS(),ne);ie(MZ(),ne);ie(pY(),ne);ie(IAe(),ne);ie(xZ(),ne);ie(PAe(),ne);ie(EZ(),ne);ie(tZ(),ne);ie(hZ(),ne);ie(r5(),ne);ie(t5(),ne);ie(BAe(),ne);ie(AK(),ne);ie(HAe(),ne);ie(zAe(),ne);ie(QAe(),ne);ie(jL(),ne);ie(dI(),ne);ie(VAe(),ne);ie(WAe(),ne);ie(ir(),ne);ie(KAe(),ne);ie(a5(),ne);ie(mt(),ne);ie(XAe(),ne);ie(ZAe(),ne);ie(eSe(),ne);ie(tSe(),ne);ie(rSe(),ne)});var iSe=v(Zc=>{"use strict";var Wat=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]}),Yat=Zc&&Zc.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kat=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)&&Wat(e,t,r);return Yat(e,t),e};Object.defineProperty(Zc,"__esModule",{value:!0});Zc.MalloyToAST=void 0;var nSe=g8(),Xat=JW(),M=Kat(OP()),Jat=Is(),Zat=OP(),zn=VC(),WZ=Ke(),eut=Vm(),DP=class extends M.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}},v5=class extends M.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}},tut=["##! m4warnings=error"],YZ=class extends Xat.AbstractParseTreeVisitor{constructor(e,r,n){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=n;for(let i of tut){let s=eut.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 v5||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 M.FieldName((0,zn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new M.ModelEntryReference((0,zn.getId)(e)),e.id())}defaultResult(){return new M.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 Jat.Interval(r,n.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){let r=this.getFieldExpr(e),n=new M.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 M.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 M.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 nSe.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 nSe.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 M.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=>M.isDocStatementOrDocStatementList(n)&&n,"statement");return new M.Document(r)}visitDefineSourceStatement(e){let n=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new M.DefineSourceList(n);return s.extendNote({blockNotes:i}),s}visitSourceDefinition(e){let r=this.visit(e.sqExplore()),n=new M.DefineSource((0,zn.getId)(e.sourceNameDef()),r instanceof M.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=>M.isSourceProperty(s)&&s,"source property"),i=new M.SourceDesc(n);return r&&i.push(this.getFilterShortcut(r)),i}visitTableFunction(e){let r=this.getPlainString(e.tableURI()),n=this.astAt(new M.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 M.TableMethodSource(n,i),e)}getLegacySQLSouce(e){let r=this.getModelEntryName(e);return this.astAt(new M.FromSQLSource(r),e)}visitSqlSource(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=new M.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);let o=e.shortString();o&&i.push((0,zn.getShortString)(o));let a=new M.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 M.Join&&(r.push(s),s instanceof M.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof M.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}let n=new M.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 M.Join&&(n.push(s),s instanceof M.ExpressionJoin&&(s.joinType="one"));let i=new M.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 M.Join&&(n.push(s),s instanceof M.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));let i=new M.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 M.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 M.ExpressionJoin(n,i),a=e.joinExpression(),u=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,WZ.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 M.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(),M.DimensionFieldDeclaration),n=new M.Dimensions(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitDefMeasures(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.MeasureFieldDeclaration),n=new M.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(M.isQueryExtendProperty(s))r.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);let i=new M.ExtendBlock(r);return this.astAt(i,e)}visitDeclareStatement(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.DeclareFieldDeclaration),n=new M.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 M.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 M.Renames(n);return this.astAt(i,e)}visitFilterClauseList(e){return new M.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 M.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 M.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}visitFieldNameList(e){let r=e.fieldName().map(n=>new M.AcceptExceptFieldReference([this.getFieldName(n)]));return new M.FieldReferences(r)}visitDefExploreEditField(e){let r=e.ACCEPT()?"accept":"except";return new M.FieldListEdit(r,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){let r=this.getPlainString(e),n=this.astAt(new M.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=>M.isQueryProperty(i)&&i,"query statement"),n=e.filterShortcut();return n&&r.push(this.getFilterShortcut(n)),new M.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 M.FieldReference||i instanceof M.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){let r=new M.Aggregate(this.getQueryItems(e.queryFieldList(),M.AggregateFieldDeclaration,M.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){let r=new M.GroupBy(this.getQueryItems(e.queryFieldList(),M.GroupByFieldDeclaration,M.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){let r=new M.Calculate(this.getQueryItems(e.queryFieldList(),M.CalculateFieldDeclaration,M.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(),M.ExpressionFieldReference),a,u=i.timeframe();u&&(a=new M.ExprGranularTime(new M.ExprIdReference(o),this.visitTimeframe(u).text,!0));let l=i.aggregate();if(l){let f=l.text.toLowerCase();if(f==="sum")a=new M.ExprSum(void 0,o);else return this.contextError(l,`\`${f}\` 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,M.ProjectFieldDeclaration,M.ProjectFieldReference));return this.astAt(new M.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,M.ProjectFieldReference):void 0,s=this.astAt(new M.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 M.WildcardFieldReference(void 0),e);let s=this.getFieldPath(i,M.IndexFieldReference);return n.STAR()?this.astAt(new M.WildcardFieldReference(s),e):this.astAt(s,e)});return new M.FieldReferences(r)}visitIndexStatement(e){let r=this.visitIndexFields(e.indexFields()),n=new M.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 M.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.fieldExpr(),i=n?this.getFieldExpr(n):void 0;return this.astAt(new M.FunctionOrderBy(i,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 M.FunctionOrdering(r),e)}visitOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.INTEGER_LITERAL();if(n)return new M.OrderBy(this.getNumber(n),r);let i=e.fieldName();if(i)return new M.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 M.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 M.Top(n,a)}let o=r.fieldExpr();o&&(i=new M.Top(n,this.getFieldExpr(o)))}return i||(i=new M.Top(n,void 0)),this.astAt(i,e)}visitSourceID(e){return this.astAt(new M.NamedSource((0,zn.getId)(e)),e)}visitTopLevelQueryDefs(e){let r=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),n=this.getNotes(e.tags()),i=new M.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 M.SourceQueryElement){let s=new M.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 M.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 M.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 M.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof M.NestFieldDeclaration&&r,"query"))}visitNestDef(e){let r=e.queryName(),n,i=this.getVExpr(e.vExpr());if(r)n=(0,zn.getId)(r);else{let a=i.getImplicitName();a===void 0&&this.contextError(e,"`nest:` view requires a name (add `nest_name is ...`)"),n=a??"__unnamed__"}let s=new M.NestFieldDeclaration(n,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){let r=(0,zn.getId)(e.exploreQueryNameDef()),n=new M.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 M.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new M.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 M.ExprLogicalOp(r,"or",n)}visitExprLogicalAnd(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new M.ExprLogicalOp(r,"and",n)}visitExprOrTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new M.ExprAlternationTree(r,"|",n),e)}visitExprAndTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new M.ExprAlternationTree(r,"&",n),e)}visitExprCoalesce(e){let r=this.getFieldExpr(e.fieldExpr()[0]),n=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new M.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(M.isComparison(i))return this.astAt(new M.PartialCompare(i,n),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return n}visitExprString(e){let r=this.getPlainString(e);return new M.ExprString(r)}visitExprRegex(e){let r=e.HACKY_REGEX().text;return new M.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new M.ExprNow}visitExprNumber(e){return new M.ExprNumber(e.text)}visitExprFieldPath(e){let r=new M.ExprIdReference(this.getFieldPath(e.fieldPath(),M.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new M.ExprNULL}visitExprExpr(e){return new M.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new M.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 M.ExprAddSub(r,i,n)}visitExprMulDiv(e){let r=e.STAR()?"*":e.SLASH()?"/":"%";return new M.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){let r=e.compareOp().text;if(M.isComparison(r))return new M.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 M.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 M.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,M.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 M.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 M.ExprIdReference(n),r);return s==="min"?new M.ExprMin(u):new M.ExprMax(u)}else{if(s==="avg")return new M.ExprAvg(a,i);if(s==="sum")return new M.ExprSum(a,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new M.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 M.ExprCountDistinct(n):new M.ExprCount,e);if(s==="min"){if(n)return new M.ExprMin(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(n)return new M.ExprMax(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(n===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new M.ExprNULL;let o=e.SOURCE_KW()!==void 0;if(s==="avg")return new M.ExprAvg(n,i,o);if(s==="sum")return new M.ExprSum(n,i,o)}return new M.ExprNULL}visitExprApply(e){return new M.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new M.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new M.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyOrSQLType(e){let r=e.malloyType();if(r){let i=r.text;if((0,WZ.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 M.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new M.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new M.Timeframe(e.text)}visitExprForRange(e){let r=this.getFieldExpr(e._startAt),n=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new M.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,M.ExpressionFieldReference):void 0,a=s&&o?this.astAt(o,s):void 0;return M.ExprTimeExtract.extractor(i)?this.astAt(new M.ExprTimeExtract(i,n),e):this.astAt(new M.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,WZ.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"),M.ExprTimeExtract.extractor(l)?this.astAt(new M.ExprTimeExtract(l,s),e):this.astAt(new M.ExprFunc(l,s,o,u),e)}visitExprDuration(e){return new M.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 M.PickWhen(i,this.getFieldExpr(n._pickWhen))});return e.ELSE()?new M.Pick(r,this.getFieldExpr(e._pickElse)):new M.Pick(r)}visitExprFieldProps(e){let r=this.only(e.fieldProperties().fieldPropertyStatement().map(n=>this.visit(n)),n=>M.isFieldPropStatement(n)&&n,"field property statement");return new M.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.inExperiment("partition_by",e),this.astAt(new M.PartitionBy(e.id().map(r=>this.astAt(new M.PartitionByFieldReference([this.astAt(new M.FieldName((0,zn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,M.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,M.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,M.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,M.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,M.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,M.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,M.LiteralYear.parse)}visitImportStatement(e){let r=this.getPlainString(e.importURL()),n=this.astAt(new M.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 M.ImportSourceName((0,zn.idToStr)(o[1])),o[1]):void 0;n.push(this.astAt(new M.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 M.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 M.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 M.SampleProperty({rows:this.getNumber(r)});let n=e.sampleSpec().PERCENT_LITERAL();if(n)return new M.SampleProperty({percent:this.getNumber(n)});let i=e.sampleSpec().TRUE()!==void 0;return new M.SampleProperty({enable:i})}visitDocAnnotations(e){let r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),n=new M.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 v5(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new v5(e.text)}visitDefExploreAnnotation(e){let r=this.getNotes(e);return new M.ObjectAnnotation(r)}visitSQID(e){let r=this.getModelEntryName(e);return this.astAt(new M.SQReference(r),e.id())}getSqExpr(e){let r=this.visit(e);return r instanceof M.SourceQueryElement?r:(this.contextError(e,`Expected a source/query expression, not '${r.elementType}'`),new DP)}visitSQExtendedSource(e){let r=this.getSqExpr(e.sqExpr()),n=new M.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 M.SQArrow(r,this.getVExpr(n));return this.astAt(i,e)}getVExpr(e){let r=this.visit(e);if(r instanceof M.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new M.ReferenceView(this.getFieldPath(e.fieldPath(),M.ViewOrScalarFieldReference))}visitSegOps(e){return new M.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new M.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new M.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new M.SQRefine(r,this.getVExpr(n));return this.astAt(i,e)}visitSQTable(e){let r=this.visit(e.exploreTable());if(r instanceof Zat.TableSource){let n=new M.SQSource(r);return this.astAt(n,e)}return new DP}visitSQSQL(e){let r=new M.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new M.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}};Zc.MalloyToAST=YZ});var sSe=v(NP=>{"use strict";Object.defineProperty(NP,"__esModule",{value:!0});NP.MessageLog=void 0;var KZ=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}};NP.MessageLog=KZ});var oSe=v(FP=>{"use strict";Object.defineProperty(FP,"__esModule",{value:!0});FP.Zone=void 0;var XZ=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})}};FP.Zone=XZ});var aSe=v(wP=>{"use strict";Object.defineProperty(wP,"__esModule",{value:!0});wP.walkForDocumentSymbols=void 0;var rut=vp(),nut=VC(),JZ=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()}getNestDefName(e){let r=e.queryName();if(r)return r.id().text;let n,i=!1,s={enterVArrow(a){a.vExpr().enterRule(s)},enterVSeg(a){a.segExpr().enterRule(o)}},o={enterSegField(a){let u=a.fieldPath().fieldName();i||(n??(n=u[u.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(s)},enterSegRefine(a){a._lhs.enterRule(o)},enterSegOps(){n=void 0,i=!0}};return e.vExpr().enterRule(s),n}handleNestEntry(e){let r=this.getNestDefName(e);if(r===void 0)return;let n={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(n),n}enterNestDef(e){let r=this.handleNestEntry(e);r&&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,nut.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 iut(t,e,r){let n=new JZ(t,e,[],[]),i=n;return rut.ParseTreeWalker.DEFAULT.walk(i,r),n.symbols}wP.walkForDocumentSymbols=iut});var eee=v(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.sortHighlights=Ue.walkForDocumentHighlights=Ue.passForHighlights=Ue.HighlightType=void 0;var sut=vp(),Te=XW();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 out(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(`
683
683
  `))||[],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=out;var ZZ=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 aut(t,e){let r=new ZZ(t,[]),n=r;return sut.ParseTreeWalker.DEFAULT.walk(n,e),r.highlights}Ue.walkForDocumentHighlights=aut;function uut(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=uut});var uSe=v(LP=>{"use strict";Object.defineProperty(LP,"__esModule",{value:!0});LP.walkForDocumentCompletions=void 0;var lut=vp(),cut=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],fut=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],xut=["source","explore","query","sql"],tee=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 cut)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 fut)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 xut)this.completions.push({type:"model_property",text:`${n}: `})}}};function dut(t,e,r){let n=new tee(t,[],r),i=n;return lut.ParseTreeWalker.DEFAULT.walk(i,e),n.completions}LP.walkForDocumentCompletions=dut});var lSe=v(IP=>{"use strict";Object.defineProperty(IP,"__esModule",{value:!0});IP.walkForDocumentHelpContext=void 0;var hut=eY(),ree=class extends hut.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 put(t,e){return new ree(e).visit(t)}IP.walkForDocumentHelpContext=put});var nee=v(MP=>{"use strict";Object.defineProperty(MP,"__esModule",{value:!0});MP.locationContainsPosition=void 0;function mut(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)}MP.locationContainsPosition=mut});var cSe=v(PP=>{"use strict";Object.defineProperty(PP,"__esModule",{value:!0});PP.ReferenceList=void 0;var gut=nee(),iee=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,gut.locationContainsPosition)(n.location,e))return n}};PP.ReferenceList=iee});var fSe=v(kP=>{"use strict";Object.defineProperty(kP,"__esModule",{value:!0});kP.isNeedResponse=void 0;function yut(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}kP.isNeedResponse=yut});var xSe=v(BP=>{"use strict";Object.defineProperty(BP,"__esModule",{value:!0});BP.walkForModelAnnotation=void 0;var Eut=vp(),see=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 Aut(t,e,r){let n=new see(t,e,r),i=n;return Eut.ParseTreeWalker.DEFAULT.walk(i,r.root),n.annotation}BP.walkForModelAnnotation=Aut});var pSe=v(Hs=>{"use strict";var Sut=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]}),vut=Hs&&Hs.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ut=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)&&Sut(e,t,r);return vut(e,t),e};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.MalloyParserErrorHandler=Hs.MalloyTranslator=Hs.MalloyChildTranslator=Hs.MalloyTranslation=void 0;var dSe=g8(),but=bge(),Tut=XW(),qP=_ut(OP()),Cut=iSe(),Rut=sSe(),Out=jZ(),oee=oSe(),Dut=aSe(),aee=eee(),Nut=uSe(),Fut=lSe(),wut=cSe(),UP=fSe(),Lut=nee(),hSe=Vm(),Iut=xSe(),uee=class extends but.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}},lee=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===""?`
684
684
  `: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=dSe.CharStreams.fromString(e),i=new uee(n),s=new dSe.CommonTokenStream(i),o=new Tut.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new jP(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"}}},cee=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,Out.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,UP.isNeedResponse)(n))return n;for(let o of e.childTranslators.values()){let a=o.importsAndTablesStep.step(o);if((0,UP.isNeedResponse)(a))return a}return null}},fee=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 Cut.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 qP.FromSQLSource?(a[u.refName]||(a[u.refName]={}),a[u.refName].ref=u):u instanceof qP.SQLStatement&&u.is?(a[u.is]||(a[u.is]={}),a[u.is].def=u):u instanceof qP.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,UP.isNeedResponse)(l))return l}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}},xee=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,Dut.walkForDocumentSymbols)(e,r.parse.tokenStream,r.parse.root)}catch{}let i;try{i=(0,aee.walkForDocumentHighlights)(r.parse.tokenStream,r.parse.root)}catch{i=[]}this.response={symbols:n,highlights:(0,aee.sortHighlights)([...(0,aee.passForHighlights)(r.parse.tokenStream),...i]),final:!0}}else return r}return this.response}},dee=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,Nut.walkForDocumentCompletions)(n.parse.tokenStream,n.parse.root,r)}catch{}return{...n,completions:i}}else return n}},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,Fut.walkForDocumentHelpContext)(n.parse.root,r)}catch{}return{...n,helpContext:i}}else return n}},pee=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,Iut.walkForModelAnnotation)(e,n.parse.tokenStream,n.parse);this.response={modelAnnotation:{...i,inherits:r?.annotation}}}}return this.response}},mee=class{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,r){if(this.response)return this.response;if(r&&!this.importedAnnotations){let i=hSe.Tag.annotationToTag(r.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}let n=this.astStep.step(e);if((0,UP.isNeedResponse)(n))return n;if(!n.ast)return this.response=n,this.response;if(e.grammarRule==="malloyDocument")if(n.ast instanceof qP.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}},_5=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 hSe.Tag,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new lee,this.modelAnnotationStep=new pee(this.parseStep),this.metadataStep=new xee(this.parseStep),this.completionsStep=new dee(this.parseStep),this.helpContextStep=new hee(this.parseStep),this.importsAndTablesStep=new cee(this.parseStep),this.astStep=new fee(this.importsAndTablesStep),this.translateStep=new mee(this.astStep),this.references=new wut.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new $P(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}