@malloydata/render 0.0.224-dev241217161218 → 0.0.224-dev241217193641

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.
@@ -75,7 +75,7 @@ ${(0,txe.indent)(n)}
75
75
  EXTRACT('epoch_${i}', ${r.sql}) - EXTRACT('epoch_${i}', ${n.sql}),
76
76
  '1970-01-01 00:00:00'::TIMESTAMP_NTZ
77
77
  )
78
- )`}sqlRegexpMatch(e){return`REGEXP_INSTR(${e.kids.expr.sql}, ${e.kids.regex.sql}) != 0`}sqlSampleTable(e,n){if(n!==void 0){if((0,es.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,es.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,es.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.percent}))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getDialectFunctionOverrides(){return(0,$k.expandOverrideMap)(rxe.SNOWFLAKE_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,$k.expandBlueprintMap)(nxe.SNOWFLAKE_DIALECT_FUNCTIONS)}malloyTypeToSQLType(e){if(e.type==="string")return"VARCHAR";if(e.type==="number")return e.numberType==="integer"?"INTEGER":"DOUBLE";if(e.type==="record"||(0,es.isRepeatedRecord)(e)){const r=`OBJECT(${e.fields.reduce((i,s)=>{var o;if((0,es.isAtomic)(s)){const u=(o=s.as)!==null&&o!==void 0?o:s.name,a=`${this.sqlMaybeQuoteIdentifier(u)} ${this.malloyTypeToSQLType(s)}`;i.push(a)}return i},[]).join(",")})`;return e.type==="record"?r:`ARRAY(${r})`}else if((0,es.isScalarArray)(e))return`ARRAY(${this.malloyTypeToSQLType(e.elementTypeDef)})`;return e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^([\w\s]+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return sxe[i.trim().toLowerCase()]||{type:"sql native",rawType:e}}castToString(e){return`TO_VARCHAR(${e})`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlLiteralRecord(e){var n,r;const i=[];for(const s of e.typeDef.fields){const o=(n=s.as)!==null&&n!==void 0?n:s.name,u=`'${o}'`,a=(r=e.kids[o].sql)!==null&&r!==void 0?r:"internal-error-record-literal";i.push(`${u},${a}`)}return`OBJECT_CONSTRUCT_KEEP_NULL(${i.join(",")})`}sqlLiteralArray(e){return`[${e.kids.values.map(i=>i.sql).join(",")}]`}}EE.SnowflakeDialect=oxe,function(t){var e=T&&T.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=T&&T.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(EE,t)}(A6);var v6={},nd={},SE={};Object.defineProperty(SE,"__esModule",{value:!0}),SE.TRINO_DIALECT_FUNCTIONS=void 0;const uxe={takes:{value:"number",percentage:"number"},returns:{measure:"number"},impl:{function:"APPROX_PERCENTILE"}},axe={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}}},returns:{measure:{generic:"T"}},impl:{function:"ARBITRARY"}},lxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_OR_AGG"}},cxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_AND_AGG"}},fxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_XOR_AGG"}},xxe={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_AND"}},dxe={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_OR"}},hxe={takes:{y:{dimension:"number"},x:{dimension:"number"}},returns:{measure:"number"},impl:{sql:"CORR(${y}, ${x})"}},pxe={takes:{value:{dimension:"any"}},returns:{measure:"number"},impl:{function:"APPROX_DISTINCT"},isSymmetric:!0},gxe={default:{generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}}},returns:{measure:"string"},isSymmetric:!0,impl:{function:"APPROX_SET"}},with_percent:{generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}},accuracy:"number"},returns:{measure:"string"},isSymmetric:!0,impl:{function:"APPROX_SET"}}},mxe={takes:{value:"string"},returns:{measure:"string"},impl:{function:"MERGE"},isSymmetric:!0},yxe={takes:{value:"string"},returns:{dimension:"number"},impl:{function:"CARDINALITY"}},Exe={takes:{value:"string"},returns:{dimension:"string"},impl:{sql:"CAST(${value} AS VARBINARY)"}},Axe={takes:{value:"string"},returns:{dimension:"string"},impl:{sql:"CAST(${value} AS HyperLogLog)"}},_xe={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}},order_by_val:{dimension:"any"}},returns:{measure:{generic:"T"}},impl:{function:"MAX_BY"},isSymmetric:!0},vxe={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}},order_by_val:{dimension:"any"}},returns:{measure:{generic:"T"}},impl:{function:"MIN_BY"},isSymmetric:!0},S6={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(${value} ${order_by:}), ',')"}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(${value} ${order_by:}), ${separator})"}}},Sxe={default_separator:{...S6.default_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ',')"}},with_separator:{...S6.with_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ${separator})"}}},Cxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"VARIANCE"}},bxe={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_AND"}},Txe={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_OR"}},Rxe={takes:{ts_val:"timestamp",format:"string"},returns:"string",impl:{function:"DATE_FORMAT"}},Oxe={takes:{ts_string:"string",format:"string"},returns:"timestamp",impl:{sql:"DATE_PARSE(${ts_string}, ${format})"}},Dxe={takes:{unixtime:"number"},returns:"timestamp",impl:{function:"FROM_UNIXTIME"}},wxe={takes:{json_val:"string",json_path:"string"},returns:"string",impl:{function:"JSON_EXTRACT_SCALAR"}},Fxe={takes:{str:"string",pattern:["string","regular expression"]},returns:"boolean",impl:{function:"REGEXP_LIKE"}},Nxe={remove_matches:{takes:{input_val:"string",regexp_pattern:["string","regular expression"]},returns:"string",impl:{function:"REGEXP_REPLACE"}},replace_matches:{takes:{input_val:"string",regexp_pattern:["string","regular expression"],replacement:"string"},returns:"string",impl:{function:"REGEXP_REPLACE"}}},Lxe={takes:{ts_val:"timestamp"},returns:"number",impl:{function:"TO_UNIXTIME"}},Ixe={takes:{},returns:{calculation:"number"},impl:{function:"PERCENT_RANK",needsWindowOrderBy:!0}},Bxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_FRAGMENT"}},$xe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_HOST"}},kxe={takes:{url:"string",parameter:"string"},returns:"string",impl:{function:"URL_EXTRACT_PARAMETER"}},Pxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PATH"}},Mxe={takes:{url:"string"},returns:"number",impl:{function:"URL_EXTRACT_PORT"}},jxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PROTOCOL"}},Uxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_QUERY"}},qxe={takes:{src:"string",splitChar:"string"},returns:{array:"string"},impl:{function:"SPLIT"}};SE.TRINO_DIALECT_FUNCTIONS={approx_percentile:uxe,arbitrary:axe,bitwise_and_agg:lxe,bitwise_or_agg:cxe,bitwise_xor_agg:fxe,bool_and:xxe,bool_or:dxe,corr:hxe,count_approx:pxe,hll_accumulate:gxe,hll_combine:mxe,max_by:_xe,min_by:vxe,string_agg:S6,string_agg_distinct:Sxe,variance:Cxe,bitwise_and:bxe,bitwise_or:Txe,date_format:Rxe,date_parse:Oxe,from_unixtime:Dxe,hll_estimate:yxe,hll_export:Exe,hll_import:Axe,json_extract_scalar:wxe,regexp_like:Fxe,regexp_replace:Nxe,to_unixtime:Lxe,url_extract_fragment:Bxe,url_extract_host:$xe,url_extract_parameter:kxe,url_extract_path:Pxe,url_extract_port:Mxe,url_extract_protocol:jxe,url_extract_query:Uxe,percent_rank:Ixe,split:qxe};var CE={};Object.defineProperty(CE,"__esModule",{value:!0}),CE.TRINO_MALLOY_STANDARD_OVERLOADS=void 0;const C6=at;CE.TRINO_MALLOY_STANDARD_OVERLOADS={byte_length:{sql:"(LENGTH(CAST(${value} AS VARBINARY)))"},chr:{sql:"CASE WHEN ${value} = 0 THEN '' ELSE CHR(${value}) END"},ascii:{sql:"CODEPOINT(NULLIF(CAST(${value} as VARCHAR(1)),''))"},unicode:{sql:"CODEPOINT(NULLIF(CAST(${value} as VARCHAR(1)),''))"},concat:{variadic:{expr:(0,C6.sql)`CONCAT(${(0,C6.spread)((0,C6.arg)("values"),"CAST(","AS VARCHAR)")})`}},div:{sql:"FLOOR(${dividend} / ${divisor})"},ifnull:{sql:"COALESCE(${value}, ${default})"},is_inf:{sql:"COALESCE(IS_INFINITE(${value}), false)"},log:{sql:"(LN(${value}) / LN(${base}))"},repeat:{sql:"ARRAY_JOIN(REPEAT(${value}, CASE WHEN ${value} IS NOT NULL THEN ${count} END),'')"},reverse:{sql:"REVERSE(CAST(${value} AS VARCHAR))"},starts_with:{sql:"COALESCE(STARTS_WITH(${value}, ${prefix}), false)"},ends_with:{sql:"COALESCE(STARTS_WITH(REVERSE(CAST(${value} AS VARCHAR)), REVERSE(CAST(${suffix} AS VARCHAR))), false)"},trunc:{to_integer:{sql:"CASE WHEN ${value} < 0 THEN CEIL(${value}) ELSE FLOOR(${value}) END"},to_precision:{sql:"CASE WHEN ${value} < 0 THEN CEIL(${value} * POW(10, ${precision})) / POW(10, ${precision}) ELSE FLOOR(${value} * POW(10, ${precision})) / POW(10, ${precision}) END"}}},Object.defineProperty(nd,"__esModule",{value:!0}),nd.PrestoDialect=nd.TrinoDialect=void 0;const kk=Nt,iu=Ke,Pk=ql,Hxe=jl,Mk=dE,zxe=SE,Qxe=CE;function Gxe(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function b6(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const Wxe={string:"VARCHAR",number:"DOUBLE"},Vxe={varchar:{type:"string"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},double:{type:"number",numberType:"float"},decimal:{type:"number",numberType:"float"},string:{type:"string"},date:{type:"date"},timestamp:{type:"timestamp"},boolean:{type:"boolean"}};class Hl extends Mk.PostgresBase{constructor(){super(...arguments),this.name="trino",this.experimental=!1,this.defaultNumberType="DOUBLE",this.defaultDecimalType="DECIMAL",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!0,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=!1,this.orderByClause="output_name",this.nullMatchesFunctionSignature=!1,this.supportsSelectReplace=!1,this.supportsComplexFilteredSources=!1,this.supportsTempTables=!1,this.supportsCountApprox=!0,this.supportsHyperLogLog=!0,this.keywords=`
78
+ )`}sqlRegexpMatch(e){return`REGEXP_INSTR(${e.kids.expr.sql}, ${e.kids.regex.sql}) != 0`}sqlSampleTable(e,n){if(n!==void 0){if((0,es.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,es.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,es.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.percent}))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getDialectFunctionOverrides(){return(0,$k.expandOverrideMap)(rxe.SNOWFLAKE_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,$k.expandBlueprintMap)(nxe.SNOWFLAKE_DIALECT_FUNCTIONS)}malloyTypeToSQLType(e){if(e.type==="string")return"VARCHAR";if(e.type==="number")return e.numberType==="integer"?"INTEGER":"DOUBLE";if(e.type==="record"||(0,es.isRepeatedRecord)(e)){const r=`OBJECT(${e.fields.reduce((i,s)=>{var o;if((0,es.isAtomic)(s)){const u=(o=s.as)!==null&&o!==void 0?o:s.name,a=`${this.sqlMaybeQuoteIdentifier(u)} ${this.malloyTypeToSQLType(s)}`;i.push(a)}return i},[]).join(",")})`;return e.type==="record"?r:`ARRAY(${r})`}else if((0,es.isScalarArray)(e))return`ARRAY(${this.malloyTypeToSQLType(e.elementTypeDef)})`;return e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^([\w\s]+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return sxe[i.trim().toLowerCase()]||{type:"sql native",rawType:e}}castToString(e){return`TO_VARCHAR(${e})`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlLiteralRecord(e){var n,r;const i=[];for(const s of e.typeDef.fields){const o=(n=s.as)!==null&&n!==void 0?n:s.name,u=`'${o}'`,a=(r=e.kids[o].sql)!==null&&r!==void 0?r:"internal-error-record-literal";i.push(`${u},${a}`)}return`OBJECT_CONSTRUCT_KEEP_NULL(${i.join(",")})`}sqlLiteralArray(e){return`[${e.kids.values.map(i=>i.sql).join(",")}]`}}EE.SnowflakeDialect=oxe,function(t){var e=T&&T.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=T&&T.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(EE,t)}(A6);var v6={},nd={},SE={};Object.defineProperty(SE,"__esModule",{value:!0}),SE.TRINO_DIALECT_FUNCTIONS=void 0;const uxe={takes:{value:"number",percentage:"number"},returns:{measure:"number"},impl:{function:"APPROX_PERCENTILE"}},axe={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}}},returns:{measure:{generic:"T"}},impl:{function:"ARBITRARY"}},lxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_OR_AGG"}},cxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_AND_AGG"}},fxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_XOR_AGG"}},xxe={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_AND"}},dxe={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_OR"}},hxe={takes:{y:{dimension:"number"},x:{dimension:"number"}},returns:{measure:"number"},impl:{sql:"CORR(${y}, ${x})"}},pxe={takes:{value:{dimension:"any"}},returns:{measure:"number"},impl:{function:"APPROX_DISTINCT"},isSymmetric:!0},gxe={default:{generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}}},returns:{measure:{sql_native:"hyperloglog"}},isSymmetric:!0,impl:{function:"APPROX_SET"}},with_percent:{generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}},accuracy:"number"},returns:{measure:{sql_native:"hyperloglog"}},isSymmetric:!0,impl:{function:"APPROX_SET"}}},mxe={takes:{value:{sql_native:"hyperloglog"}},returns:{measure:{sql_native:"hyperloglog"}},impl:{function:"MERGE"},isSymmetric:!0},yxe={takes:{value:{sql_native:"hyperloglog"}},returns:{dimension:"number"},impl:{function:"CARDINALITY"}},Exe={takes:{value:{sql_native:"hyperloglog"}},returns:{dimension:{sql_native:"varbinary"}},impl:{sql:"CAST(${value} AS VARBINARY)"}},Axe={takes:{value:{sql_native:"varbinary"}},returns:{dimension:{sql_native:"hyperloglog"}},impl:{sql:"CAST(${value} AS HyperLogLog)"}},_xe={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}},order_by_val:{dimension:"any"}},returns:{measure:{generic:"T"}},impl:{function:"MAX_BY"},isSymmetric:!0},vxe={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}},order_by_val:{dimension:"any"}},returns:{measure:{generic:"T"}},impl:{function:"MIN_BY"},isSymmetric:!0},S6={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(${value} ${order_by:}), ',')"}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(${value} ${order_by:}), ${separator})"}}},Sxe={default_separator:{...S6.default_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ',')"}},with_separator:{...S6.with_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ${separator})"}}},Cxe={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"VARIANCE"}},bxe={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_AND"}},Txe={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_OR"}},Rxe={takes:{ts_val:"timestamp",format:"string"},returns:"string",impl:{function:"DATE_FORMAT"}},Oxe={takes:{ts_string:"string",format:"string"},returns:"timestamp",impl:{sql:"DATE_PARSE(${ts_string}, ${format})"}},Dxe={takes:{unixtime:"number"},returns:"timestamp",impl:{function:"FROM_UNIXTIME"}},wxe={takes:{json_val:"string",json_path:"string"},returns:"string",impl:{function:"JSON_EXTRACT_SCALAR"}},Fxe={takes:{str:"string",pattern:["string","regular expression"]},returns:"boolean",impl:{function:"REGEXP_LIKE"}},Nxe={remove_matches:{takes:{input_val:"string",regexp_pattern:["string","regular expression"]},returns:"string",impl:{function:"REGEXP_REPLACE"}},replace_matches:{takes:{input_val:"string",regexp_pattern:["string","regular expression"],replacement:"string"},returns:"string",impl:{function:"REGEXP_REPLACE"}}},Lxe={takes:{ts_val:"timestamp"},returns:"number",impl:{function:"TO_UNIXTIME"}},Ixe={takes:{},returns:{calculation:"number"},impl:{function:"PERCENT_RANK",needsWindowOrderBy:!0}},Bxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_FRAGMENT"}},$xe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_HOST"}},kxe={takes:{url:"string",parameter:"string"},returns:"string",impl:{function:"URL_EXTRACT_PARAMETER"}},Pxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PATH"}},Mxe={takes:{url:"string"},returns:"number",impl:{function:"URL_EXTRACT_PORT"}},jxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PROTOCOL"}},Uxe={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_QUERY"}},qxe={takes:{src:"string",splitChar:"string"},returns:{array:"string"},impl:{function:"SPLIT"}};SE.TRINO_DIALECT_FUNCTIONS={approx_percentile:uxe,arbitrary:axe,bitwise_and_agg:lxe,bitwise_or_agg:cxe,bitwise_xor_agg:fxe,bool_and:xxe,bool_or:dxe,corr:hxe,count_approx:pxe,hll_accumulate:gxe,hll_combine:mxe,max_by:_xe,min_by:vxe,string_agg:S6,string_agg_distinct:Sxe,variance:Cxe,bitwise_and:bxe,bitwise_or:Txe,date_format:Rxe,date_parse:Oxe,from_unixtime:Dxe,hll_estimate:yxe,hll_export:Exe,hll_import:Axe,json_extract_scalar:wxe,regexp_like:Fxe,regexp_replace:Nxe,to_unixtime:Lxe,url_extract_fragment:Bxe,url_extract_host:$xe,url_extract_parameter:kxe,url_extract_path:Pxe,url_extract_port:Mxe,url_extract_protocol:jxe,url_extract_query:Uxe,percent_rank:Ixe,split:qxe};var CE={};Object.defineProperty(CE,"__esModule",{value:!0}),CE.TRINO_MALLOY_STANDARD_OVERLOADS=void 0;const C6=at;CE.TRINO_MALLOY_STANDARD_OVERLOADS={byte_length:{sql:"(LENGTH(CAST(${value} AS VARBINARY)))"},chr:{sql:"CASE WHEN ${value} = 0 THEN '' ELSE CHR(${value}) END"},ascii:{sql:"CODEPOINT(NULLIF(CAST(${value} as VARCHAR(1)),''))"},unicode:{sql:"CODEPOINT(NULLIF(CAST(${value} as VARCHAR(1)),''))"},concat:{variadic:{expr:(0,C6.sql)`CONCAT(${(0,C6.spread)((0,C6.arg)("values"),"CAST(","AS VARCHAR)")})`}},div:{sql:"FLOOR(${dividend} / ${divisor})"},ifnull:{sql:"COALESCE(${value}, ${default})"},is_inf:{sql:"COALESCE(IS_INFINITE(${value}), false)"},log:{sql:"(LN(${value}) / LN(${base}))"},repeat:{sql:"ARRAY_JOIN(REPEAT(${value}, CASE WHEN ${value} IS NOT NULL THEN ${count} END),'')"},reverse:{sql:"REVERSE(CAST(${value} AS VARCHAR))"},starts_with:{sql:"COALESCE(STARTS_WITH(${value}, ${prefix}), false)"},ends_with:{sql:"COALESCE(STARTS_WITH(REVERSE(CAST(${value} AS VARCHAR)), REVERSE(CAST(${suffix} AS VARCHAR))), false)"},trunc:{to_integer:{sql:"CASE WHEN ${value} < 0 THEN CEIL(${value}) ELSE FLOOR(${value}) END"},to_precision:{sql:"CASE WHEN ${value} < 0 THEN CEIL(${value} * POW(10, ${precision})) / POW(10, ${precision}) ELSE FLOOR(${value} * POW(10, ${precision})) / POW(10, ${precision}) END"}}},Object.defineProperty(nd,"__esModule",{value:!0}),nd.PrestoDialect=nd.TrinoDialect=void 0;const kk=Nt,iu=Ke,Pk=ql,Hxe=jl,Mk=dE,zxe=SE,Qxe=CE;function Gxe(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function b6(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const Wxe={string:"VARCHAR",number:"DOUBLE"},Vxe={varchar:{type:"string"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},double:{type:"number",numberType:"float"},decimal:{type:"number",numberType:"float"},string:{type:"string"},date:{type:"date"},timestamp:{type:"timestamp"},boolean:{type:"boolean"}};class Hl extends Mk.PostgresBase{constructor(){super(...arguments),this.name="trino",this.experimental=!1,this.defaultNumberType="DOUBLE",this.defaultDecimalType="DECIMAL",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!0,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=!1,this.orderByClause="output_name",this.nullMatchesFunctionSignature=!1,this.supportsSelectReplace=!1,this.supportsComplexFilteredSources=!1,this.supportsTempTables=!1,this.supportsCountApprox=!0,this.supportsHyperLogLog=!0,this.keywords=`
79
79
  ALL
80
80
  AND
81
81
  ANY
@@ -1252,9 +1252,9 @@ xyyzz{{||}}~~~Ҹ
1252
1252
  ${r} ${s}: [`,o.length>0&&(i+=`
1253
1253
  `+o.map(u=>u.stringify("",n+4)).join(`
1254
1254
  `)+`
1255
- ${r} `),i+="]")}return i}*walk(){for(const e of Object.keys(this.children)){const n=this.children[e];if(n instanceof Ou)yield n;else for(const r of n)yield r}}varInfo(){let e="";for(const[n,r]of Object.entries(this))n!=="elementType"&&(typeof r=="boolean"?e+=r?` ${n}`:` !${n}`:(typeof r=="string"||typeof r=="number")&&(e+=` ${n}=${r}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const n of this.walk()){const r=n.needs(e);if(r)return r}}inExperiment(e,n=!1){var r;const i=(r=this.translator())===null||r===void 0?void 0:r.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(n||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}Ye.MalloyElement=Ou;class c3e extends Ou{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Ye.Unimplemented=c3e;class p7 extends Ou{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}}Ye.ModelEntryReference=p7;class f3e extends Ou{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Ye.ExperimentalExperiment=f3e;function jH(t){return t.execute!==void 0}Ye.isDocStatement=jH;function x3e(t){return t instanceof fg||jH(t)}Ye.isDocStatementOrDocStatementList=x3e;class UH extends Ou{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const n of this.elements){const r=n.needs(e);if(r)return r}}}Ye.ListOf=UH;class fg extends UH{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=MH.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const n=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,MH.isNoteable)(n)&&n.extendNote(this.note),this.noteCursor+=1),n instanceof fg){const r=n.executeList(e);if(r)return r}else{const r=n.needs(e);if(r)return r;n.execute(e)}this.execCursor+=1}}}Ye.DocStatementList=fg;const d3e="5a79a191-06bc-43cf-9b12-58741cd82970";function qH(t){const e=t.inherits?qH(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(n=>n.text)),t.notes&&e.push(...t.notes.map(n=>n.text)),e}function h3e(t){const e=qH(t).join("");return(0,l3e.v5)(e,d3e)}class g7 extends Ou{constructor(e){super(),this.elementType="document",this.globalNameSpace=new a3e.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new i3e.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new fg(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],this.sqlBlocks=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[n,r]of Object.entries(e.contents)){const i=structuredClone(r);if((0,V_.isSourceDef)(i)||i.type==="query"||i.type==="function"){const s=e.exports.includes(n);this.setEntry(n,{entry:i,exported:s})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),n=this.modelDef();if(e===void 0){for(const i of this.queryList)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation);for(const i of this.sqlBlocks)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation)}if(n.annotation)for(const i of this.modelAnnotationTodoList)i.modelAnnotation||(i.modelAnnotation=n.annotation);return{modelDef:n,queryList:this.queryList,sqlBlocks:this.sqlBlocks,needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=h3e(e),e}}modelDef(){const e={name:"",exports:[],contents:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const n in this.documentModel){const r=this.documentModel[n].entry;if((0,V_.isSourceDef)(r)||r.type==="query"){this.documentModel[n].exported&&e.exports.push(n);const i=structuredClone(r);i.modelAnnotation===void 0&&e.annotation&&(i.modelAnnotation=e.annotation),e.contents[n]=i}}return e}defineSQL(e,n){const r={...e,as:`$${this.sqlBlocks.length}`};if(n){if(this.getEntry(n))return!1;r.as=n,this.setEntry(n,{entry:r})}return this.sqlBlocks.push(r),!0}getEntry(e){var n;return(n=this.globalNameSpace.getEntry(e))!==null&&n!==void 0?n:this.documentModel[e]}setEntry(e,n){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,V_.isSourceDef)(n.entry)&&this.checkExperimentalDialect(this,n.entry.dialect),this.documentModel[e]=n}checkExperimentalDialect(e,n){const r=this.translator();r&&r.firstReferenceToDialect(n)&&(0,PH.getDialect)(n).experimental&&!r.experimentalDialectEnabled(n)&&e.logError("experimental-dialect-not-enabled",{dialect:n})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const n=(0,PH.getDialect)(e),r=new u3e.DialectNameSpace(n);return this.dialectNameSpaces.set(e,r),r}}Ye.Document=g7;var Y_={},Wd={},Wt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=ts,n=ut;function r(c,f="scalar",x="constant"){return{type:c,expressionType:f,evalSpace:x,compositeFieldUsage:(0,n.emptyCompositeFieldUsage)()}}t.nullT=r("null"),t.numberT=r("number"),t.stringT=r("string"),t.dateT=r("date"),t.timestampT=r("timestamp"),t.boolT=r("boolean"),t.errorT=r("error"),t.viewT=r("turtle"),t.aggregateBoolT=r("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function i(c,f){return c?f.find(h=>s(h,c))!==void 0:!1}t.any=i;function s(c,f){return f!==void 0&&e.TD.eq(c,f)&&c.expressionType===f.expressionType}t.eq=s;function o(c,f){return c?f.find(h=>u(h,c))!==void 0:!1}t.typeIn=o;function u(c,f,x=!1,h=!0){const p=e.TD.eq(c,f),m=x&&(c.type==="null"||f.type==="null"),g=h&&(c.type==="error"||f.type==="error");return p||m||g}t.typeEq=u;function a(...c){return c.map(x=>{if(x){let h=x.type;return(0,e.expressionIsScalar)(x.expressionType)||(h=`${x.expressionType} ${h}`),h}return"undefined"}).join(",")}t.inspect=a;function l(c){if(e.TD.isAtomic(c))switch(c.type){case"array":return(0,e.isRepeatedRecord)(c)?{type:"array",elementTypeDef:c.elementTypeDef,fields:c.fields}:{type:"array",elementTypeDef:c.elementTypeDef};case"record":return{type:"record",fields:c.fields};case"number":return c.numberType?{type:"number",numberType:c.numberType}:{type:"number"};case"sql native":return c.rawType?{type:"sql native",rawType:c.rawType}:{type:"sql native"};default:return{type:c.type}}return{type:"error"}}t.atomicDef=l})(Wt);var Cr={},l0={};Object.defineProperty(l0,"__esModule",{value:!0}),l0.canMakeEntry=l0.SpaceEntry=void 0;class p3e{}l0.SpaceEntry=p3e;function g3e(t){return"makeEntry"in t}l0.canMakeEntry=g3e,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.SpaceField=void 0;const m3e=l0,y3e=ut;class E3e extends m3e.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var n,r,i;const s=e.expressionType||"scalar";return{...e,expressionType:s,evalSpace:"input",compositeFieldUsage:(n=e.compositeFieldUsage)!==null&&n!==void 0?n:((r=e.e)===null||r===void 0?void 0:r.node)==="compositeField"?{fields:[(i=e.as)!==null&&i!==void 0?i:e.name],joinedUsage:{}}:(0,y3e.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Cr.SpaceField=E3e;var A3e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),_3e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),v3e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&A3e(e,t,n);return _3e(e,t),e};Object.defineProperty(Wd,"__esModule",{value:!0}),Wd.ViewField=void 0;const S3e=ut,C3e=v3e(Wt),b3e=Cr;class T3e extends b3e.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const n=this.fieldDef();return{...C3e.viewT,compositeFieldUsage:(e=n.compositeFieldUsage)!==null&&e!==void 0?e:(0,S3e.emptyCompositeFieldUsage)()}}}Wd.ViewField=T3e,Object.defineProperty(Y_,"__esModule",{value:!0}),Y_.ASTViewField=void 0;const R3e=Wd;class O3e extends R3e.ViewField{constructor(e,n,r){super(e),this.view=n,this.name=r,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}Y_.ASTViewField=O3e,Object.defineProperty(cg,"__esModule",{value:!0}),cg.ViewFieldDeclaration=void 0;const D3e=Ye,w3e=Sr,F3e=Qd,N3e=Y_;class L3e extends D3e.MalloyElement{constructor(e,n){super({view:n}),this.name=e,this.view=n,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=w3e.extendNoteMethod}makeEntry(e){const n=new N3e.ASTViewField(e,this,this.name);e.newEntry(this.name,this,n)}getName(){return this.name}getFieldDef(e){const{pipeline:n,annotation:r}=this.view.pipelineComp(e),i=(0,F3e.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}}cg.ViewFieldDeclaration=L3e;var Dn={};Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.LegalRefinementStage=Dn.QueryClass=void 0;var HH;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(HH||(Dn.QueryClass=HH={}));var zH;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(zH||(Dn.LegalRefinementStage=zH={}));var I3e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),B3e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$3e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&I3e(e,t,n);return B3e(e,t),e};Object.defineProperty(lg,"__esModule",{value:!0}),lg.NestFieldDeclaration=void 0;const k3e=$3e(Ke),P3e=Qd,M3e=cg,QH=Dn;class j3e extends M3e.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=QH.LegalRefinementStage.Single,this.forceQueryClass=QH.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:n,annotation:r}=this.view.pipelineComp(e,e.outputSpace()),i=n[0]&&k3e.isQuerySegment(n[0])?n[0].compositeFieldUsage:void 0,s=(0,P3e.detectAndRemovePartialStages)(n,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:r},location:this.location,compositeFieldUsage:i},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}lg.NestFieldDeclaration=j3e;var Vd={},Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.ErrorFactory=void 0;const GH="~malformed~";class m7{static get structDef(){return{type:"table",name:GH,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:GH,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:m7.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}Ur.ErrorFactory=m7,Object.defineProperty(Vd,"__esModule",{value:!0}),Vd.DefineSourceList=Vd.DefineSource=void 0;const U3e=Ur,WH=Ye,q3e=Sr;class H3e extends WH.MalloyElement{constructor(e,n,r,i){super(),this.name=e,this.sourceExpr=n,this.exported=r,this.parameters=i,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=q3e.extendNoteMethod,n&&this.has({sourceExpr:n}),i&&this.has({parameters:i})}execute(e){var n;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const r=(n=this.sourceExpr)===null||n===void 0?void 0:n.getSource();if(r===void 0)return;const i=this.deduplicatedParameters(),s=r.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(i,s),U3e.ErrorFactory.didCreate(s))return;const o={...s,as:this.name,location:this.location};this.note&&(o.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:o,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},n=[];for(const r of this.parameters)r.name in e&&r.logError("parameter-name-conflict",`Cannot redefine parameter \`${r.name}\``),e[r.name]=!0,n.push(r);return n}validateParameterShadowing(e,n){for(const r of e)n.fields.find(i=>{var s;return((s=i.as)!==null&&s!==void 0?s:i.name)===r.name})&&r.logError("parameter-shadowing-field",`Illegal shadowing of field \`${r.name}\` by parameter with the same name`)}}Vd.DefineSource=H3e;class z3e extends WH.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Vd.DefineSourceList=z3e;var Yd={};Object.defineProperty(Yd,"__esModule",{value:!0}),Yd.DefineQueryList=Yd.DefineQuery=void 0;const VH=Ye,Q3e=Sr;class G3e extends VH.MalloyElement{constructor(e,n){super({queryExpr:n}),this.name=e,this.queryExpr=n,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=Q3e.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const i={...r.query(),type:"query",name:this.name,location:this.location};this.note&&(i.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:i,exported:!0})}}Yd.DefineQuery=G3e;class W3e extends VH.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}Yd.DefineQueryList=W3e;var ks={};Object.defineProperty(ks,"__esModule",{value:!0}),ks.Source=void 0;const V3e=Ye;class Y3e extends V3e.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const n={};for(const r of e){const i=r.parameter();n[i.name]=i}return n}withParameters(e,n){return{...this.getSourceDef(e),parameters:this.packParameters(n)}}}ks.Source=Y3e;var xg={},Kd={},K_={},c0={};Object.defineProperty(c0,"__esModule",{value:!0}),c0.mergeFields=c0.nameFromDef=void 0;function y7(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}c0.nameFromDef=y7;function K3e(t,e){if(t===void 0)return e;const n=new Set(e.map(i=>y7(i))),r=t.filter(i=>!n.has(y7(i)));return r.push(...e),r}c0.mergeFields=K3e;var dg={},br={},Du={},X3e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),J3e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Z3e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&X3e(e,t,n);return J3e(e,t),e};Object.defineProperty(Du,"__esModule",{value:!0}),Du.DefinedParameter=Du.AbstractParameter=Du.SpaceParam=void 0;const eye=l0,YH=Z3e(Wt),KH=ut;class E7 extends eye.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Du.SpaceParam=E7;class tye extends E7{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){return{...YH.atomicDef(this.parameter()),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,KH.emptyCompositeFieldUsage)()}}entryType(){return this.parameter().type}}Du.AbstractParameter=tye;class nye extends E7{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{...YH.atomicDef(this.paramDef),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,KH.emptyCompositeFieldUsage)()}}entryType(){return this.paramDef.type}}Du.DefinedParameter=nye;var Ef={},rye=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),iye=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sye=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&rye(e,t,n);return iye(e,t),e};Object.defineProperty(Ef,"__esModule",{value:!0}),Ef.StructSpaceFieldBase=void 0;const XH=ut,oye=Ke,uye=sye(Wt),aye=Cr;class lye extends aye.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,n;return(0,oye.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,XH.emptyCompositeFieldUsage)()}:{...uye.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(n=this.structDef.onCompositeFieldUsage)!==null&&n!==void 0?n:(0,XH.emptyCompositeFieldUsage)()}}}Ef.StructSpaceFieldBase=lye;var hg={};Object.defineProperty(hg,"__esModule",{value:!0}),hg.ColumnSpaceField=void 0;const cye=Cr;class fye extends cye.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}hg.ColumnSpaceField=fye;var X_={};Object.defineProperty(X_,"__esModule",{value:!0}),X_.IRViewField=void 0;const xye=Wd;class dye extends xye.ViewField{constructor(e,n){super(e),this.turtleDef=n}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}X_.IRViewField=dye,Object.defineProperty(br,"__esModule",{value:!0}),br.StaticSourceSpace=br.StructSpaceField=br.StaticSpace=void 0;const hye=su,Xd=Ke,pye=Du,gye=Cr,pg=Ef,mye=hg,yye=X_;class A7{constructor(e,n){this.type="fieldSpace",this.fromStruct=e,this.structDialect=n}dialectName(){return this.structDialect}dialectObj(){try{return(0,hye.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,Xd.isJoined)(e)?new _7(e,this.structDialect):(0,Xd.isTurtle)(e)?new yye.IRViewField(this,e):new mye.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const n=e.as||e.name;this.memoMap[n]=this.defToSpaceField(e)}if((0,Xd.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,n]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new pye.DefinedParameter(n))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,n){this.map[e]=n}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,Xd.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const n=e[0],r=e.slice(1);let i=this.entry(n.refString);if(!i)return{error:{message:`'${n}' is not defined`,code:"field-not-found"},found:i};if(i instanceof gye.SpaceField){const o=i.fieldDef();if(o&&(!(i instanceof pg.StructSpaceFieldBase)&&(0,Xd.isJoined)(o)&&(i=new _7(o,this.structDialect)),n.addReference({type:i instanceof pg.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:n.location,text:n.refString})),o!=null&&o.accessModifier&&!(this.isProtectedAccessSpace()&&o.accessModifier==="internal"&&e.length===1))return{error:{message:`'${n}' is ${o==null?void 0:o.accessModifier}`,code:"field-not-accessible"},found:void 0}}const s=i instanceof pg.StructSpaceFieldBase?[{...i.joinPathElement,name:n.refString}]:[];if(r.length){if(i instanceof pg.StructSpaceFieldBase){const o=i.fieldSpace.lookup(r);return o.found?{...o,joinPath:[...s,...o.joinPath]}:o}return{error:{message:`'${n}' cannot contain a '${r[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:i,error:void 0,joinPath:s,isOutputField:!1}}isQueryFieldSpace(){return!1}}br.StaticSpace=A7;class _7 extends pg.StructSpaceFieldBase{constructor(e,n){super(e),this.forDialect=n}get fieldSpace(){return(0,Xd.isSourceDef)(this.structDef)?new JH(this.structDef):new A7(this.structDef,this.forDialect)}}br.StructSpaceField=_7;class JH extends A7{constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}br.StaticSourceSpace=JH,Object.defineProperty(dg,"__esModule",{value:!0}),dg.JoinSpaceField=void 0;const Eye=br;class Aye extends Eye.StructSpaceField{constructor(e,n,r){super(n.structDef(e),r),this.parameterSpace=e,this.join=n}}dg.JoinSpaceField=Aye;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.ParameterSpace=void 0;const _ye=Du;class vye{constructor(e){this.type="fieldSpace",this._map={};for(const n of e)this._map[n.name]=new _ye.AbstractParameter(n)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const n=e[0];if(n===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const r=this.entry(n.refString);return r===void 0?{error:{message:`\`${n}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${n}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:r,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}Jd.ParameterSpace=vye;var Sye=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Cye=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bye=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Sye(e,t,n);return Cye(e,t),e};Object.defineProperty(K_,"__esModule",{value:!0}),K_.DynamicSpace=void 0;const Tye=bye(Ke),Rye=c0,Oye=Ur,Dye=Cr,wye=dg,Fye=Wd,ZH=Du,Nye=br,Lye=Ef,Iye=Jd;class Bye extends Nye.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,n){if(this.complete)throw new Error("Space already final");super.setEntry(e,n)}addParameters(e){for(const n of e)this.entry(n.name)===void 0&&(this.parameters.push(n),this.setEntry(n.name,new ZH.AbstractParameter(n)));return this}parameterSpace(){return new Iye.ParameterSpace(this.parameters)}newEntry(e,n,r){if(this.entry(e)){n.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,r)}renameEntry(e,n,r){this.dropEntry(e),this.setEntry(n,r)}addFieldDef(e){this.setEntry((0,Rye.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof ZH.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const n=new Map,r=[],i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof Lye.StructSpaceFieldBase?i.push([l,c]):c instanceof Fye.ViewField?s.push([l,c]):c instanceof Dye.SpaceField&&r.push([l,c]);const u=[...r,...i,...s],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof wye.JoinSpaceField){const f=c.join.structDef(a);Oye.ErrorFactory.didCreate(f)||(n.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),o.push([c.join,f]))}else{const f=c.fieldDef();f&&(n.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of o)l.fixupJoinOn(this,c);for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&Tye.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}K_.DynamicSpace=Bye;var gg={};Object.defineProperty(gg,"__esModule",{value:!0}),gg.RenameSpaceField=void 0;const $ye=Cr;class kye extends $ye.SpaceField{constructor(e,n,r){super(),this.otherField=e,this.newName=n,this.location=r}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}gg.RenameSpaceField=kye,Object.defineProperty(Kd,"__esModule",{value:!0}),Kd.RefinedSpace=void 0;const Pye=K_,Mye=l0,jye=gg,Uye=Cr;class v7 extends Pye.DynamicSpace{static filteredFrom(e,n,r,i,s){const o=new v7(e),u=new Map;for(const a of i??[])u.has(a.name.refString)?a.name.logError("already-renamed",`${a.name.refString} already renamed to ${a.as}`):u.set(a.name.refString,{as:a.as,location:a.location,logTo:a.name});if(r!==void 0){const a=o.entries();o.dropEntries();for(const[l,c]of a)if(r.has(l)){const f=u.get(l);f?c instanceof Uye.SpaceField?o.setEntry(f.as,new jye.RenameSpaceField(c,f.as,f.location)):f.logTo.logError("cannot-rename-non-field",`Cannot rename \`${l}\` which is not a field`):o.setEntry(l,c)}n!==void 0&&n.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(n){const a=n.refs.list,l=o.entries();for(const c of a)l.find(([x])=>x===c.refString)===void 0&&(s!=null&&s.entry(c.refString)?c.logError(`${n.edit}-parameter`,`Illegal \`${n.edit}:\` of parameter`):c.logError("field-list-edit-not-found",`\`${c.refString}\` is not defined`));o.dropEntries();for(const[c,f]of l){const x=!!a.find(p=>p.refString===c),h=n.edit==="accept";x===h&&o.setEntry(c,f)}}return o}pushFields(...e){for(const n of e)this.addField(n)}addField(e){(0,Mye.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[n,r]of e)this.newAccessModifiers.set(n,r)}addNotes(e){for(const[n,r]of e)this.newNotes.set(n,r)}isProtectedAccessSpace(){return!0}}Kd.RefinedSpace=v7;var f0={},xs={};Object.defineProperty(xs,"__esModule",{value:!0}),xs.DefinitionList=void 0;const qye=Ye,ez=Sr;class Hye extends qye.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,ez.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,ez.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}xs.DefinitionList=Hye,Object.defineProperty(f0,"__esModule",{value:!0}),f0.DeclareFields=void 0;const zye=xs,Qye=Dn;class Gye extends zye.DefinitionList{constructor(e,n){super(e),this.accessModifier=n,this.elementType="declareFields",this.queryRefinementStage=Qye.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}get delarationNames(){return this.list.map(e=>e.defineName)}}f0.DeclareFields=Gye;var wu={};Object.defineProperty(wu,"__esModule",{value:!0}),wu.Filter=wu.FilterElement=void 0;const tz=Ke,Wye=Ru,nz=Ye,S7=Dn;class Vye extends nz.MalloyElement{constructor(e,n){super({expr:e}),this.expr=e,this.exprSrc=n,this.elementType="filterElement"}filterCondition(e){const n=this.expr.getExpression(e);return n.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:n.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:n.value,expressionType:n.expressionType,compositeFieldUsage:n.compositeFieldUsage}}}wu.FilterElement=Vye;let Yye=class extends nz.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=S7.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?S7.LegalRefinementStage.Tail:S7.LegalRefinementStage.Head}checkedFilterCondition(e,n){const r=n.filterCondition(e);if(this.havingClause!==void 0){const i=(0,tz.expressionIsAggregate)(r.expressionType),s=(0,tz.expressionIsAnalytic)(r.expressionType);if(this.havingClause){if(s){n.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(s){n.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else i&&n.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return r}getFilterList(e){return this.list.map(n=>this.checkedFilterCondition(e,n)).filter(Wye.isNotUndefined)}queryExecute(e){const n=this.havingClause?e.resultFS:e.inputFS;for(const r of this.list){const i=this.checkedFilterCondition(n,r);i!==void 0&&(e.filters.push(i),e.resultFS.addCompositeFieldUserFromFilter(i,r))}}};wu.Filter=Yye;var Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.FieldListEdit=void 0;const Kye=Ye;class Xye extends Kye.MalloyElement{constructor(e,n){super({refs:n}),this.edit=e,this.refs=n,this.elementType="fieldListEdit"}}Zd.FieldListEdit=Xye;var eh={};Object.defineProperty(eh,"__esModule",{value:!0}),eh.PrimaryKey=void 0;const Jye=Ye;class Zye extends Jye.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}eh.PrimaryKey=Zye;var th={};Object.defineProperty(th,"__esModule",{value:!0}),th.Views=void 0;const eEe=xs;class tEe extends eEe.DefinitionList{constructor(e,n){super(e),this.accessModifier=n,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}th.Views=tEe;var nh={};Object.defineProperty(nh,"__esModule",{value:!0}),nh.TimezoneStatement=void 0;const nEe=Ye;class rEe extends nEe.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)}}nh.TimezoneStatement=rEe;var x0={};Object.defineProperty(x0,"__esModule",{value:!0}),x0.ModelAnnotation=x0.ObjectAnnotation=void 0;const iEe=ou,sEe=Ye;class rz extends sEe.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}x0.ObjectAnnotation=rz;class oEe extends rz{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,n){const r=iEe.Tag.annotationToTag({notes:this.notes},{prefix:/^##! /,extending:e});return r.log.forEach(i=>n.log(i)),r.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}x0.ModelAnnotation=oEe;var d0={};Object.defineProperty(d0,"__esModule",{value:!0}),d0.Renames=d0.RenameField=void 0;const uEe=gg,iz=Ye,aEe=Cr;class lEe extends iz.MalloyElement{constructor(e,n){super(),this.newName=e,this.oldName=n,this.elementType="renameField",this.has({oldName:n})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const n=this.oldName.getField(e);n.found?n.found instanceof aEe.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new uEe.RenameSpaceField(n.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}d0.RenameField=lEe;class cEe extends iz.ListOf{constructor(e,n){super(e),this.accessModifier=n,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}d0.Renames=cEe;var Fi={};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.JoinStatement=Fi.ExpressionJoin=Fi.KeyJoin=Fi.Join=void 0;const C7=Ke,fEe=dg,xEe=xs,dEe=Ye,hEe=Sr,sz=Ur,pEe=Dn;class b7 extends dEe.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=hEe.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new fEe.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const n=this.sourceExpr.getSource();return n?n.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),sz.ErrorFactory.structDef)}}Fi.Join=b7;class gEe extends b7{constructor(e,n,r){super({name:e,sourceExpr:n,keyExpr:r}),this.name=e,this.sourceExpr=n,this.keyExpr=r,this.elementType="joinOnKey"}structDef(e){var n;const r=this.getStructDefFromExpr(e);if(!(0,C7.isJoinable)(r))throw this.internalError(`Cannot join struct type '${r.type}'`);const i={...r,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete i.as,this.note&&(i.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(i),i}fixupJoinOn(e,n){const r=this.keyExpr.getExpression(e);if((0,C7.isSourceDef)(n)&&n.primaryKey){const i=n.fields.find(s=>(s.as||s.name)===n.primaryKey);if(i)if(i.type===r.type){n.join="one",n.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,n.primaryKey]},right:r.value}},n.onCompositeFieldUsage=r.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${r.type}/${i.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${i}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}Fi.KeyJoin=gEe;class mEe extends b7{constructor(e,n){super({name:e,sourceExpr:n}),this.name=e,this.sourceExpr=n,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,n){if(this.expr===void 0)return;const r=this.expr.getExpression(e);if(r.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}n.onExpression=r.value,n.onCompositeFieldUsage=r.compositeFieldUsage}structDef(e){var n;const r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),sz.ErrorFactory.joinDef;const i=r.getSourceDef(e);let s="left";if(this.inExperiment("join_types",!0)&&(s=this.matrixOperation),!(0,C7.isJoinable)(i))throw this.internalError(`Can't join struct type ${i.type}`);const o={...i,name:this.name.refString,join:this.joinType,matrixOperation:s,location:this.location};return delete o.as,this.note&&(o.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(o),o}}Fi.ExpressionJoin=mEe;class yEe extends xEe.DefinitionList{constructor(e,n){super(e),this.accessModifier=n,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=pEe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n),e.alwaysJoins.push(n.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}Fi.JoinStatement=yEe;var vo={};Object.defineProperty(vo,"__esModule",{value:!0}),vo.IncludeListItem=vo.IncludeExceptItem=vo.IncludeAccessItem=vo.IncludeItem=void 0;const oz=Ye,uz=Sr;class T7 extends oz.MalloyElement{}vo.IncludeItem=T7;class EEe extends T7{constructor(e,n){super(),this.kind=e,this.fields=n,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=uz.extendNoteMethod,this.has({fields:n})}}vo.IncludeAccessItem=EEe;class AEe extends T7{constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}vo.IncludeExceptItem=AEe;class _Ee extends oz.MalloyElement{constructor(e,n){super({name:e}),this.name=e,this.as=n,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=uz.extendNoteMethod}}vo.IncludeListItem=_Ee;var ht={},mg={},vEe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),SEe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),CEe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&vEe(e,t,n);return SEe(e,t),e};Object.defineProperty(mg,"__esModule",{value:!0}),mg.ReferenceField=void 0;const az=Ke,lz=CEe(Wt),cz=Cr,bEe=ut;class TEe extends cz.SpaceField{constructor(e,n){super(),this.fieldRef=e,this.inFS=n,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const n=this.fieldRef.getField(e);n.error&&this.fieldRef.logError(n.error.code,n.error.message);const r=this.fieldRef.path;if(n.found&&n.found.refType==="parameter"){const s=n.found.typeDesc();if(az.TD.isAtomic(s))this.queryFieldDef={...(0,az.mkFieldDef)(lz.atomicDef(s),r[0]),e:{node:"parameter",path:r}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:r};const i=this.referenceTo;if(i instanceof cz.SpaceField){const s=i.constructorFieldDef();if(s){const o=this.fieldRef.note;if(s.annotation||o){const u=o||{};s.annotation&&(u.inherits=s.annotation),this.queryFieldDef.annotation=u}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const n=this.fieldRef.list.slice(0,-1).map(i=>i.refString),r=e.typeDesc();return this.memoTypeDesc={...r,compositeFieldUsage:(0,bEe.joinedCompositeFieldUsage)(n,r.compositeFieldUsage)},this.memoTypeDesc}return lz.errorT}}mg.ReferenceField=TEe;var qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.typecheckGroupBy=qn.typecheckAggregate=qn.typecheckCalculate=qn.typecheckDeclare=qn.typecheckMeasure=qn.typecheckDimension=qn.typecheckIndex=qn.typecheckProject=void 0;const Sn=ts;function REe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="select-of-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="select-of-analytic";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}qn.typecheckProject=REe;function OEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsScalar)(t.expressionType)){let n,r;if(t.type==="turtle")n="a view",r="index-of-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="an analytic",r="index-of-analytic";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(r,`Cannot use ${n} field in an index operation`)}}qn.typecheckIndex=OEe;function DEe(t,e){if(!(0,Sn.expressionIsScalar)(t.expressionType))if((0,Sn.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,Sn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}qn.typecheckDimension=DEe;function wEe(t,e){if(!(0,Sn.expressionIsAggregate)(t.expressionType))if((0,Sn.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,Sn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}qn.typecheckMeasure=wEe;function FEe(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,Sn.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}qn.typecheckDeclare=FEe;function NEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsAnalytic)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="calculate-of-view";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="calculate-of-aggregate";else if((0,Sn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}qn.typecheckCalculate=NEe;function LEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsAggregate)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="aggregate-of-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="aggregate-of-analytic";else if((0,Sn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(i,`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}qn.typecheckAggregate=LEe;function IEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="group-by-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="group-by-analytic";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}qn.typecheckGroupBy=IEe,Object.defineProperty(ht,"__esModule",{value:!0}),ht.FieldReferences=ht.WildcardFieldReference=ht.ViewOrScalarFieldReference=ht.DimensionFieldReference=ht.MeasureFieldReference=ht.DeclareFieldReference=ht.ProjectFieldReference=ht.GroupByFieldReference=ht.AggregateFieldReference=ht.IndexFieldReference=ht.CalculateFieldReference=ht.ParameterFieldReference=ht.PartitionByFieldReference=ht.ExpressionFieldReference=ht.AccessModifierFieldReference=ht.AcceptExceptFieldReference=ht.FieldReference=void 0;const BEe=mg,$Ee=xs,fz=Ye,xz=Sr,h0=qn;class ii extends fz.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=xz.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.logError("output-name-conflict",`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new BEe.ReferenceField(this,r))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const n=e.lookup(this.list);if(n.found){const r=n.found.typeDesc();this.typecheck(r)}return n}}ht.FieldReference=ii;class kEe extends ii{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}ht.AcceptExceptFieldReference=kEe;class PEe extends ii{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}ht.AccessModifierFieldReference=PEe;class MEe extends ii{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}ht.ExpressionFieldReference=MEe;class jEe extends ii{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}ht.PartitionByFieldReference=jEe;class UEe extends ii{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}ht.ParameterFieldReference=UEe;class qEe extends ii{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,h0.typecheckCalculate)(e,this)}}ht.CalculateFieldReference=qEe;class R7 extends ii{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,h0.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return R7.indexOutputName(this.path)}}ht.IndexFieldReference=R7;class HEe extends ii{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,h0.typecheckAggregate)(e,this)}}ht.AggregateFieldReference=HEe;class zEe extends ii{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,h0.typecheckGroupBy)(e,this)}}ht.GroupByFieldReference=zEe;class QEe extends ii{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,h0.typecheckProject)(e,this)}}ht.ProjectFieldReference=QEe;class GEe extends ii{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,h0.typecheckDeclare)(e,this)}}ht.DeclareFieldReference=GEe;class WEe extends ii{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,h0.typecheckMeasure)(e,this)}}ht.MeasureFieldReference=WEe;class VEe extends ii{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,h0.typecheckDimension)(e,this)}}ht.DimensionFieldReference=VEe;class YEe extends ii{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}ht.ViewOrScalarFieldReference=YEe;class KEe extends fz.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=xz.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}ht.WildcardFieldReference=KEe;class XEe extends $Ee.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}ht.FieldReferences=XEe,Object.defineProperty(xg,"__esModule",{value:!0}),xg.RefinedSource=void 0;const JEe=Ke,ZEe=Kd,eAe=f0,tAe=wu,nAe=Zd,rAe=eh,iAe=th,sAe=ks,oAe=nh,uAe=x0,aAe=d0,lAe=Jd,cAe=Fi,dz=vo,O7=ht;class fAe extends sAe.Source{constructor(e,n,r){super({source:e,refinement:n}),this.source=e,this.refinement=n,this.includeList=r,this.elementType="refinedSource",r&&this.has({includeList:r})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;let i,s;const o=[],u=[];let a;const l=[];for(const _ of this.refinement.list){if(_ instanceof uAe.ObjectAnnotation)continue;const v=_;if(_ instanceof rAe.PrimaryKey){if(i){const S="multiple-primary-keys";i.logError(S,"Primary key already defined"),_.logError(S,"Primary key redefined")}i=_}else if(_ instanceof nAe.FieldListEdit){if(s){const S="multiple-field-list-edits";s.logError(S,"Too many accept/except statements"),_.logError(S,"Too many accept/except statements")}s=_}else _ instanceof eAe.DeclareFields||_ instanceof cAe.JoinStatement||_ instanceof iAe.Views||_ instanceof aAe.Renames?(o.push(..._.list),_.accessModifier&&l.push({fields:_.delarationNames,access:_.accessModifier})):_ instanceof tAe.Filter?u.push(_):_ instanceof oAe.TimezoneStatement?a=_.tz:v.logError("unexpected-source-property",`Unexpected source property: '${v.elementType}'`)}const c=n?new lAe.ParameterSpace(n):void 0,f=structuredClone(this.source.getSourceDef(c)),{fieldsToInclude:x,modifiers:h,renames:p,notes:m}=xAe(this.includeList,f);for(const _ of l)for(const v of _.fields)h.set(v,_.access);i&&(f.primaryKey=i.field.name);const g=ZEe.RefinedSpace.filteredFrom(f,s,x,p,c);if(a&&g.setTimezone(a),n&&g.addParameters(n),g.pushFields(...o),i){const _=i.field.getField(g);_.error&&i.logError(_.error.code,_.error.message)}g.addAccessModifiers(h),g.addNotes(m);const y=g.structDef(),E=y.filterList||[];let A=!1;for(const _ of u)for(const v of _.list){const S=v.filterCondition(g);(0,JEe.expressionIsCalculation)(S.expressionType)?v.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(E.push(S),A=!0)}return A?{...y,filterList:E}:((r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(y),y)}}xg.RefinedSource=fAe;function xAe(t,e){var n,r,i,s,o,u,a,l,c;const f=new Set(e.fields.map(S=>S.name)),x=new Set(e.fields.filter(S=>S.accessModifier==="private").map(S=>S.name));let h;const p=new Set;let m,g;const y=new Map,E=[],A=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:y,renames:E,notes:A};for(const S of t)if(S instanceof dz.IncludeAccessItem)for(const C of S.fields)if(C.name instanceof O7.WildcardFieldReference)C.name.joinPath&&C.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),m!==void 0?S.logError("already-used-star-in-include","Wildcard already used in this include block"):(m=(n=S.kind)!==null&&n!==void 0?n:"inherit",g={notes:(i=(r=C.note)===null||r===void 0?void 0:r.notes)!==null&&i!==void 0?i:[],blockNotes:(o=(s=S.note)===null||s===void 0?void 0:s.blockNotes)!==null&&o!==void 0?o:[]});else{if(h==="exclude"){S.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}h="include";const b=C.name.refString;x.has(b)&&C.logError("cannot-expand-access",`Cannot expand access of \`${b}\` from private to ${S.kind}`),y.has(b)?C.logError("duplicate-include",`Field \`${b}\` already referenced in include list`):(S.kind!==void 0&&y.set(b,S.kind),p.add(b),(C.note||S.note)&&A.set(b,{notes:(a=(u=C.note)===null||u===void 0?void 0:u.notes)!==null&&a!==void 0?a:[],blockNotes:(c=(l=S.note)===null||l===void 0?void 0:l.blockNotes)!==null&&c!==void 0?c:[]})),C.as&&(C.name instanceof O7.WildcardFieldReference?C.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):E.push({name:C.name,as:C.as,location:C.location}))}else if(S instanceof dz.IncludeExceptItem)for(const C of S.fields)C instanceof O7.WildcardFieldReference?C.joinPath?C.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):C.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):h==="include"?S.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(h="exclude",m="inherit",p.add(C.refString));const _=new Set(f);p.forEach(S=>_.delete(S)),x.forEach(S=>_.delete(S));let v;if(m!==void 0)for(const S of _)m!=="inherit"&&y.set(S,m),g&&A.set(S,{...g});return h!=="exclude"?m!==void 0?v=f:v=p:v=_,{fieldsToInclude:v,modifiers:y,renames:E,notes:A}}var So={};Object.defineProperty(So,"__esModule",{value:!0}),So.SourceQueryElement=void 0;const dAe=Ye;class D7 extends dAe.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,n,r){return this.isErrorFree()&&this.logError(e,n,r),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const n of this.walk())if(n instanceof D7&&n.errored){e=!1;break}return e}}So.SourceQueryElement=D7;var J_={},Af={};Object.defineProperty(Af,"__esModule",{value:!0}),Af.QuerySource=void 0;const hAe=ks,pAe=uE;class gAe extends hAe.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,n){var r;const i=this.query.queryComp(!1),s={...i.outputStruct,name:`QuerySource-${(0,pAe.v4)()}`,type:"query_source",query:i.query};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),{...s,parameters:this.packParameters(n)}}}Af.QuerySource=gAe;var rh={},yg={};Object.defineProperty(yg,"__esModule",{value:!0}),yg.QueryBase=void 0;const w7=ut,hz=Ke,mAe=Qd,yAe=Ye;class EAe extends yAe.MalloyElement{query(){var e;const{inputStruct:n,query:r}=this.queryComp(!0);let i;if(r.pipeline[0]&&((0,hz.isQuerySegment)(r.pipeline[0])||(0,hz.isIndexSegment)(r.pipeline[0]))){const s=(e=r.pipeline[0].compositeFieldUsage)!==null&&e!==void 0?e:(0,w7.emptyCompositeFieldUsage)();(!(0,w7.isEmptyCompositeFieldUsage)(s)||n.type==="composite")&&(i=(0,w7.resolveCompositeSources)(n,s).sourceDef)}return{...r,compositeResolvedSourceDef:i,pipeline:(0,mAe.detectAndRemovePartialStages)(r.pipeline,this)}}}yg.QueryBase=EAe,Object.defineProperty(rh,"__esModule",{value:!0}),rh.QueryArrow=void 0;const AAe=Ke,_Ae=ks,pz=br,vAe=yg;class SAe extends vAe.QueryBase{constructor(e,n){super({source:e,view:n}),this.source=e,this.view=n,this.elementType="arrow"}queryComp(e){let n,r,i;if(this.source instanceof _Ae.Source){const l=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};r={type:"query",...l,pipeline:[],location:this.location},n=(0,AAe.refIsStructDef)(l.structRef)?l.structRef:this.source.getSourceDef(void 0),i=new pz.StaticSourceSpace(n)}else{const l=this.source.queryComp(e);r=l.query,n=l.outputStruct,i=new pz.StaticSourceSpace(l.outputStruct)}const{pipeline:s,annotation:o,outputStruct:u,name:a}=this.view.pipelineComp(i);return{query:{...r,name:a,annotation:o,pipeline:[...r.pipeline,...s]},outputStruct:u,inputStruct:n}}}rh.QueryArrow=SAe,Object.defineProperty(J_,"__esModule",{value:!0}),J_.SQArrow=void 0;const CAe=So,bAe=Af,TAe=rh;class RAe extends CAe.SourceQueryElement{constructor(e,n){super({applyTo:e,operation:n}),this.applyTo=e,this.operation=n,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const n=new TAe.QueryArrow(e,this.operation);return this.has({query:n}),n}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const n=new bAe.QuerySource(e);return this.has({asSource:n}),n}}J_.SQArrow=RAe;var Z_={},ih={},ds={};Object.defineProperty(ds,"__esModule",{value:!0}),ds.getStructFieldDef=ds.getFinalStruct=ds.opOutputStruct=void 0;const gz=Yl,OAe=Bc,ev=Ke,mz=Ur;function yz(t,e,n){const r=mz.ErrorFactory.didCreate(e)||(0,ev.structHasErrors)(e);(0,ev.isPartialSegment)(n)&&(n={...n,type:"reduce"});const i=(0,ev.segmentHasErrors)(n);if(!r&&!i)try{const s=OAe.Segment.nextStructDef(e,n);if((0,ev.isSourceDef)(s))return s;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1255
+ ${r} `),i+="]")}return i}*walk(){for(const e of Object.keys(this.children)){const n=this.children[e];if(n instanceof Ou)yield n;else for(const r of n)yield r}}varInfo(){let e="";for(const[n,r]of Object.entries(this))n!=="elementType"&&(typeof r=="boolean"?e+=r?` ${n}`:` !${n}`:(typeof r=="string"||typeof r=="number")&&(e+=` ${n}=${r}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const n of this.walk()){const r=n.needs(e);if(r)return r}}inExperiment(e,n=!1){var r;const i=(r=this.translator())===null||r===void 0?void 0:r.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(n||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}Ye.MalloyElement=Ou;class c3e extends Ou{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Ye.Unimplemented=c3e;class p7 extends Ou{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}}Ye.ModelEntryReference=p7;class f3e extends Ou{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Ye.ExperimentalExperiment=f3e;function jH(t){return t.execute!==void 0}Ye.isDocStatement=jH;function x3e(t){return t instanceof fg||jH(t)}Ye.isDocStatementOrDocStatementList=x3e;class UH extends Ou{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const n of this.elements){const r=n.needs(e);if(r)return r}}}Ye.ListOf=UH;class fg extends UH{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=MH.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const n=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,MH.isNoteable)(n)&&n.extendNote(this.note),this.noteCursor+=1),n instanceof fg){const r=n.executeList(e);if(r)return r}else{const r=n.needs(e);if(r)return r;n.execute(e)}this.execCursor+=1}}}Ye.DocStatementList=fg;const d3e="5a79a191-06bc-43cf-9b12-58741cd82970";function qH(t){const e=t.inherits?qH(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(n=>n.text)),t.notes&&e.push(...t.notes.map(n=>n.text)),e}function h3e(t){const e=qH(t).join("");return(0,l3e.v5)(e,d3e)}class g7 extends Ou{constructor(e){super(),this.elementType="document",this.globalNameSpace=new a3e.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new i3e.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new fg(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],this.sqlBlocks=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[n,r]of Object.entries(e.contents)){const i=structuredClone(r);if((0,V_.isSourceDef)(i)||i.type==="query"||i.type==="function"){const s=e.exports.includes(n);this.setEntry(n,{entry:i,exported:s})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),n=this.modelDef();if(e===void 0){for(const i of this.queryList)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation);for(const i of this.sqlBlocks)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation)}if(n.annotation)for(const i of this.modelAnnotationTodoList)i.modelAnnotation||(i.modelAnnotation=n.annotation);return{modelDef:n,queryList:this.queryList,sqlBlocks:this.sqlBlocks,needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=h3e(e),e}}modelDef(){const e={name:"",exports:[],contents:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const n in this.documentModel){const r=this.documentModel[n].entry;if((0,V_.isSourceDef)(r)||r.type==="query"){this.documentModel[n].exported&&e.exports.push(n);const i=structuredClone(r);i.modelAnnotation===void 0&&e.annotation&&(i.modelAnnotation=e.annotation),e.contents[n]=i}}return e}defineSQL(e,n){const r={...e,as:`$${this.sqlBlocks.length}`};if(n){if(this.getEntry(n))return!1;r.as=n,this.setEntry(n,{entry:r})}return this.sqlBlocks.push(r),!0}getEntry(e){var n;return(n=this.globalNameSpace.getEntry(e))!==null&&n!==void 0?n:this.documentModel[e]}setEntry(e,n){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,V_.isSourceDef)(n.entry)&&this.checkExperimentalDialect(this,n.entry.dialect),this.documentModel[e]=n}checkExperimentalDialect(e,n){const r=this.translator();r&&r.firstReferenceToDialect(n)&&(0,PH.getDialect)(n).experimental&&!r.experimentalDialectEnabled(n)&&e.logError("experimental-dialect-not-enabled",{dialect:n})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const n=(0,PH.getDialect)(e),r=new u3e.DialectNameSpace(n);return this.dialectNameSpaces.set(e,r),r}}Ye.Document=g7;var Y_={},Wd={},Wt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=ts,n=ut;function r(c,f="scalar",x="constant"){return{type:c,expressionType:f,evalSpace:x,compositeFieldUsage:(0,n.emptyCompositeFieldUsage)()}}t.nullT=r("null"),t.numberT=r("number"),t.stringT=r("string"),t.dateT=r("date"),t.timestampT=r("timestamp"),t.boolT=r("boolean"),t.errorT=r("error"),t.viewT=r("turtle"),t.aggregateBoolT=r("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function i(c,f){return c?f.find(h=>s(h,c))!==void 0:!1}t.any=i;function s(c,f){return f!==void 0&&e.TD.eq(c,f)&&c.expressionType===f.expressionType}t.eq=s;function o(c,f){return c?f.find(h=>u(h,c))!==void 0:!1}t.typeIn=o;function u(c,f,x=!1,h=!0){const p=e.TD.eq(c,f),m=x&&(c.type==="null"||f.type==="null"),g=h&&(c.type==="error"||f.type==="error");return p||m||g}t.typeEq=u;function a(...c){return c.map(x=>{if(x){let h=x.type;return(0,e.expressionIsScalar)(x.expressionType)||(h=`${x.expressionType} ${h}`),h}return"undefined"}).join(",")}t.inspect=a;function l(c){if(e.TD.isAtomic(c))switch(c.type){case"array":return(0,e.isRepeatedRecord)(c)?{type:"array",elementTypeDef:c.elementTypeDef,fields:c.fields}:{type:"array",elementTypeDef:c.elementTypeDef};case"record":return{type:"record",fields:c.fields};case"number":return c.numberType?{type:"number",numberType:c.numberType}:{type:"number"};case"sql native":return c.rawType?{type:"sql native",rawType:c.rawType}:{type:"sql native"};default:return{type:c.type}}return{type:"error"}}t.atomicDef=l})(Wt);var Cr={},l0={};Object.defineProperty(l0,"__esModule",{value:!0}),l0.canMakeEntry=l0.SpaceEntry=void 0;class p3e{}l0.SpaceEntry=p3e;function g3e(t){return"makeEntry"in t}l0.canMakeEntry=g3e,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.SpaceField=void 0;const m3e=l0,y3e=ut;class E3e extends m3e.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var n,r,i;const s=e.expressionType||"scalar";return{...e,expressionType:s,evalSpace:"input",compositeFieldUsage:(n=e.compositeFieldUsage)!==null&&n!==void 0?n:((r=e.e)===null||r===void 0?void 0:r.node)==="compositeField"?{fields:[(i=e.as)!==null&&i!==void 0?i:e.name],joinedUsage:{}}:(0,y3e.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Cr.SpaceField=E3e;var A3e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),_3e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),v3e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&A3e(e,t,n);return _3e(e,t),e};Object.defineProperty(Wd,"__esModule",{value:!0}),Wd.ViewField=void 0;const S3e=ut,C3e=v3e(Wt),b3e=Cr;class T3e extends b3e.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const n=this.fieldDef();return{...C3e.viewT,compositeFieldUsage:(e=n.compositeFieldUsage)!==null&&e!==void 0?e:(0,S3e.emptyCompositeFieldUsage)()}}}Wd.ViewField=T3e,Object.defineProperty(Y_,"__esModule",{value:!0}),Y_.ASTViewField=void 0;const R3e=Wd;class O3e extends R3e.ViewField{constructor(e,n,r){super(e),this.view=n,this.name=r,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}Y_.ASTViewField=O3e,Object.defineProperty(cg,"__esModule",{value:!0}),cg.ViewFieldDeclaration=void 0;const D3e=Ye,w3e=Sr,F3e=Qd,N3e=Y_;class L3e extends D3e.MalloyElement{constructor(e,n){super({view:n}),this.name=e,this.view=n,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=w3e.extendNoteMethod}makeEntry(e){const n=new N3e.ASTViewField(e,this,this.name);e.newEntry(this.name,this,n)}getName(){return this.name}getFieldDef(e){const{pipeline:n,annotation:r}=this.view.pipelineComp(e),i=(0,F3e.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}}cg.ViewFieldDeclaration=L3e;var Dn={};Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.LegalRefinementStage=Dn.QueryClass=void 0;var HH;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(HH||(Dn.QueryClass=HH={}));var zH;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(zH||(Dn.LegalRefinementStage=zH={}));var I3e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),B3e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$3e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&I3e(e,t,n);return B3e(e,t),e};Object.defineProperty(lg,"__esModule",{value:!0}),lg.NestFieldDeclaration=void 0;const k3e=$3e(Ke),P3e=Qd,M3e=cg,QH=Dn;class j3e extends M3e.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=QH.LegalRefinementStage.Single,this.forceQueryClass=QH.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:n,annotation:r}=this.view.pipelineComp(e,e.outputSpace()),i=n[0]&&k3e.isQuerySegment(n[0])?n[0].compositeFieldUsage:void 0,s=(0,P3e.detectAndRemovePartialStages)(n,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:r},location:this.location,compositeFieldUsage:i},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}lg.NestFieldDeclaration=j3e;var Vd={},Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.ErrorFactory=void 0;const GH="~malformed~";class m7{static get structDef(){return{type:"table",name:GH,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:GH,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:m7.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}Ur.ErrorFactory=m7,Object.defineProperty(Vd,"__esModule",{value:!0}),Vd.DefineSourceList=Vd.DefineSource=void 0;const U3e=Ur,WH=Ye,q3e=Sr;class H3e extends WH.MalloyElement{constructor(e,n,r,i){super(),this.name=e,this.sourceExpr=n,this.exported=r,this.parameters=i,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=q3e.extendNoteMethod,n&&this.has({sourceExpr:n}),i&&this.has({parameters:i})}execute(e){var n;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const r=(n=this.sourceExpr)===null||n===void 0?void 0:n.getSource();if(r===void 0)return;const i=this.deduplicatedParameters(),s=r.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(i,s),U3e.ErrorFactory.didCreate(s))return;const o={...s,as:this.name,location:this.location};this.note&&(o.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:o,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},n=[];for(const r of this.parameters)r.name in e&&r.logError("parameter-name-conflict",`Cannot redefine parameter \`${r.name}\``),e[r.name]=!0,n.push(r);return n}validateParameterShadowing(e,n){for(const r of e)n.fields.find(i=>{var s;return((s=i.as)!==null&&s!==void 0?s:i.name)===r.name})&&r.logError("parameter-shadowing-field",`Illegal shadowing of field \`${r.name}\` by parameter with the same name`)}}Vd.DefineSource=H3e;class z3e extends WH.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Vd.DefineSourceList=z3e;var Yd={};Object.defineProperty(Yd,"__esModule",{value:!0}),Yd.DefineQueryList=Yd.DefineQuery=void 0;const VH=Ye,Q3e=Sr;class G3e extends VH.MalloyElement{constructor(e,n){super({queryExpr:n}),this.name=e,this.queryExpr=n,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=Q3e.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const i={...r.query(),type:"query",name:this.name,location:this.location};this.note&&(i.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:i,exported:!0})}}Yd.DefineQuery=G3e;class W3e extends VH.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}Yd.DefineQueryList=W3e;var ks={};Object.defineProperty(ks,"__esModule",{value:!0}),ks.Source=void 0;const V3e=Ye;class Y3e extends V3e.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const n={};for(const r of e){const i=r.parameter();n[i.name]=i}return n}withParameters(e,n){return{...this.getSourceDef(e),parameters:this.packParameters(n)}}}ks.Source=Y3e;var xg={},Kd={},K_={},c0={};Object.defineProperty(c0,"__esModule",{value:!0}),c0.mergeFields=c0.nameFromDef=void 0;function y7(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}c0.nameFromDef=y7;function K3e(t,e){if(t===void 0)return e;const n=new Set(e.map(i=>y7(i))),r=t.filter(i=>!n.has(y7(i)));return r.push(...e),r}c0.mergeFields=K3e;var dg={},br={},Du={},X3e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),J3e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Z3e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&X3e(e,t,n);return J3e(e,t),e};Object.defineProperty(Du,"__esModule",{value:!0}),Du.DefinedParameter=Du.AbstractParameter=Du.SpaceParam=void 0;const eye=l0,YH=Z3e(Wt),KH=ut;class E7 extends eye.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Du.SpaceParam=E7;class tye extends E7{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){return{...YH.atomicDef(this.parameter()),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,KH.emptyCompositeFieldUsage)()}}entryType(){return this.parameter().type}}Du.AbstractParameter=tye;class nye extends E7{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{...YH.atomicDef(this.paramDef),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,KH.emptyCompositeFieldUsage)()}}entryType(){return this.paramDef.type}}Du.DefinedParameter=nye;var Ef={},rye=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),iye=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sye=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&rye(e,t,n);return iye(e,t),e};Object.defineProperty(Ef,"__esModule",{value:!0}),Ef.StructSpaceFieldBase=void 0;const XH=ut,oye=Ke,uye=sye(Wt),aye=Cr;class lye extends aye.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,n;return(0,oye.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,XH.emptyCompositeFieldUsage)()}:{...uye.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(n=this.structDef.onCompositeFieldUsage)!==null&&n!==void 0?n:(0,XH.emptyCompositeFieldUsage)()}}}Ef.StructSpaceFieldBase=lye;var hg={};Object.defineProperty(hg,"__esModule",{value:!0}),hg.ColumnSpaceField=void 0;const cye=Cr;class fye extends cye.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}hg.ColumnSpaceField=fye;var X_={};Object.defineProperty(X_,"__esModule",{value:!0}),X_.IRViewField=void 0;const xye=Wd;class dye extends xye.ViewField{constructor(e,n){super(e),this.turtleDef=n}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}X_.IRViewField=dye,Object.defineProperty(br,"__esModule",{value:!0}),br.StaticSourceSpace=br.StructSpaceField=br.StaticSpace=void 0;const hye=su,Xd=Ke,pye=Du,gye=Cr,pg=Ef,mye=hg,yye=X_;class A7{constructor(e,n){this.type="fieldSpace",this.fromStruct=e,this.structDialect=n}dialectName(){return this.structDialect}dialectObj(){try{return(0,hye.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,Xd.isJoined)(e)?new _7(e,this.structDialect):(0,Xd.isTurtle)(e)?new yye.IRViewField(this,e):new mye.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const n=e.as||e.name;this.memoMap[n]=this.defToSpaceField(e)}if((0,Xd.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,n]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new pye.DefinedParameter(n))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,n){this.map[e]=n}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,Xd.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const n=e[0],r=e.slice(1);let i=this.entry(n.refString);if(!i)return{error:{message:`'${n}' is not defined`,code:"field-not-found"},found:i};if(i instanceof gye.SpaceField){const o=i.fieldDef();if(o&&(!(i instanceof pg.StructSpaceFieldBase)&&(0,Xd.isJoined)(o)&&(i=new _7(o,this.structDialect)),n.addReference({type:i instanceof pg.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:n.location,text:n.refString})),o!=null&&o.accessModifier&&!(this.isProtectedAccessSpace()&&o.accessModifier==="internal"&&e.length===1))return{error:{message:`'${n}' is ${o==null?void 0:o.accessModifier}`,code:"field-not-accessible"},found:void 0}}const s=i instanceof pg.StructSpaceFieldBase?[{...i.joinPathElement,name:n.refString}]:[];if(r.length){if(i instanceof pg.StructSpaceFieldBase){const o=i.fieldSpace.lookup(r);return o.found?{...o,joinPath:[...s,...o.joinPath]}:o}return{error:{message:`'${n}' cannot contain a '${r[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:i,error:void 0,joinPath:s,isOutputField:!1}}isQueryFieldSpace(){return!1}}br.StaticSpace=A7;class _7 extends pg.StructSpaceFieldBase{constructor(e,n){super(e),this.forDialect=n}get fieldSpace(){return(0,Xd.isSourceDef)(this.structDef)?new JH(this.structDef):new A7(this.structDef,this.forDialect)}}br.StructSpaceField=_7;class JH extends A7{constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}br.StaticSourceSpace=JH,Object.defineProperty(dg,"__esModule",{value:!0}),dg.JoinSpaceField=void 0;const Eye=br;class Aye extends Eye.StructSpaceField{constructor(e,n,r){super(n.structDef(e),r),this.parameterSpace=e,this.join=n}}dg.JoinSpaceField=Aye;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.ParameterSpace=void 0;const _ye=Du;class vye{constructor(e){this.type="fieldSpace",this._map={};for(const n of e)this._map[n.name]=new _ye.AbstractParameter(n)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const n=e[0];if(n===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const r=this.entry(n.refString);return r===void 0?{error:{message:`\`${n}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${n}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:r,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}Jd.ParameterSpace=vye;var Sye=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Cye=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bye=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Sye(e,t,n);return Cye(e,t),e};Object.defineProperty(K_,"__esModule",{value:!0}),K_.DynamicSpace=void 0;const Tye=bye(Ke),Rye=c0,Oye=Ur,Dye=Cr,wye=dg,Fye=Wd,ZH=Du,Nye=br,Lye=Ef,Iye=Jd;class Bye extends Nye.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,n){if(this.complete)throw new Error("Space already final");super.setEntry(e,n)}addParameters(e){for(const n of e)this.entry(n.name)===void 0&&(this.parameters.push(n),this.setEntry(n.name,new ZH.AbstractParameter(n)));return this}parameterSpace(){return new Iye.ParameterSpace(this.parameters)}newEntry(e,n,r){if(this.entry(e)){n.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,r)}renameEntry(e,n,r){this.dropEntry(e),this.setEntry(n,r)}addFieldDef(e){this.setEntry((0,Rye.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof ZH.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const n=new Map,r=[],i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof Lye.StructSpaceFieldBase?i.push([l,c]):c instanceof Fye.ViewField?s.push([l,c]):c instanceof Dye.SpaceField&&r.push([l,c]);const u=[...r,...i,...s],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof wye.JoinSpaceField){const f=c.join.structDef(a);Oye.ErrorFactory.didCreate(f)||(n.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),o.push([c.join,f]))}else{const f=c.fieldDef();f&&(n.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of o)l.fixupJoinOn(this,c);for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&Tye.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}K_.DynamicSpace=Bye;var gg={};Object.defineProperty(gg,"__esModule",{value:!0}),gg.RenameSpaceField=void 0;const $ye=Cr;class kye extends $ye.SpaceField{constructor(e,n,r){super(),this.otherField=e,this.newName=n,this.location=r}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}gg.RenameSpaceField=kye,Object.defineProperty(Kd,"__esModule",{value:!0}),Kd.RefinedSpace=void 0;const Pye=K_,Mye=l0,jye=gg,Uye=Cr;class v7 extends Pye.DynamicSpace{static filteredFrom(e,n,r,i,s){const o=new v7(e),u=new Map;for(const a of i??[])u.has(a.name.refString)?a.name.logError("already-renamed",`${a.name.refString} already renamed to ${a.as}`):u.set(a.name.refString,{as:a.as,location:a.location,logTo:a.name});if(r!==void 0){const a=o.entries();o.dropEntries();for(const[l,c]of a)if(r.has(l)){const f=u.get(l);f?c instanceof Uye.SpaceField?o.setEntry(f.as,new jye.RenameSpaceField(c,f.as,f.location)):f.logTo.logError("cannot-rename-non-field",`Cannot rename \`${l}\` which is not a field`):o.setEntry(l,c)}n!==void 0&&n.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(n){const a=n.refs.list,l=o.entries();for(const c of a)l.find(([x])=>x===c.refString)===void 0&&(s!=null&&s.entry(c.refString)?c.logError(`${n.edit}-parameter`,`Illegal \`${n.edit}:\` of parameter`):c.logError("field-list-edit-not-found",`\`${c.refString}\` is not defined`));o.dropEntries();for(const[c,f]of l){const x=!!a.find(p=>p.refString===c),h=n.edit==="accept";x===h&&o.setEntry(c,f)}}return o}pushFields(...e){for(const n of e)this.addField(n)}addField(e){(0,Mye.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[n,r]of e)this.newAccessModifiers.set(n,r)}addNotes(e){for(const[n,r]of e)this.newNotes.set(n,r)}isProtectedAccessSpace(){return!0}}Kd.RefinedSpace=v7;var f0={},xs={};Object.defineProperty(xs,"__esModule",{value:!0}),xs.DefinitionList=void 0;const qye=Ye,ez=Sr;class Hye extends qye.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,ez.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,ez.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}xs.DefinitionList=Hye,Object.defineProperty(f0,"__esModule",{value:!0}),f0.DeclareFields=void 0;const zye=xs,Qye=Dn;class Gye extends zye.DefinitionList{constructor(e,n){super(e),this.accessModifier=n,this.elementType="declareFields",this.queryRefinementStage=Qye.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}get delarationNames(){return this.list.map(e=>e.defineName)}}f0.DeclareFields=Gye;var wu={};Object.defineProperty(wu,"__esModule",{value:!0}),wu.Filter=wu.FilterElement=void 0;const tz=Ke,Wye=Ru,nz=Ye,S7=Dn;class Vye extends nz.MalloyElement{constructor(e,n){super({expr:e}),this.expr=e,this.exprSrc=n,this.elementType="filterElement"}filterCondition(e){const n=this.expr.getExpression(e);return n.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:n.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:n.value,expressionType:n.expressionType,compositeFieldUsage:n.compositeFieldUsage}}}wu.FilterElement=Vye;let Yye=class extends nz.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=S7.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?S7.LegalRefinementStage.Tail:S7.LegalRefinementStage.Head}checkedFilterCondition(e,n){const r=n.filterCondition(e);if(this.havingClause!==void 0){const i=(0,tz.expressionIsAggregate)(r.expressionType),s=(0,tz.expressionIsAnalytic)(r.expressionType);if(this.havingClause){if(s){n.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(s){n.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else i&&n.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return r}getFilterList(e){return this.list.map(n=>this.checkedFilterCondition(e,n)).filter(Wye.isNotUndefined)}queryExecute(e){const n=this.havingClause?e.resultFS:e.inputFS;for(const r of this.list){const i=this.checkedFilterCondition(n,r);i!==void 0&&(e.filters.push(i),e.resultFS.addCompositeFieldUserFromFilter(i,r))}}};wu.Filter=Yye;var Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.FieldListEdit=void 0;const Kye=Ye;class Xye extends Kye.MalloyElement{constructor(e,n){super({refs:n}),this.edit=e,this.refs=n,this.elementType="fieldListEdit"}}Zd.FieldListEdit=Xye;var eh={};Object.defineProperty(eh,"__esModule",{value:!0}),eh.PrimaryKey=void 0;const Jye=Ye;class Zye extends Jye.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}eh.PrimaryKey=Zye;var th={};Object.defineProperty(th,"__esModule",{value:!0}),th.Views=void 0;const eEe=xs;class tEe extends eEe.DefinitionList{constructor(e,n){super(e),this.accessModifier=n,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}th.Views=tEe;var nh={};Object.defineProperty(nh,"__esModule",{value:!0}),nh.TimezoneStatement=void 0;const nEe=Ye;class rEe extends nEe.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)}}nh.TimezoneStatement=rEe;var x0={};Object.defineProperty(x0,"__esModule",{value:!0}),x0.ModelAnnotation=x0.ObjectAnnotation=void 0;const iEe=ou,sEe=Ye;class rz extends sEe.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}x0.ObjectAnnotation=rz;class oEe extends rz{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,n){const r=iEe.Tag.annotationToTag({notes:this.notes},{prefix:/^##! /,extending:e});return r.log.forEach(i=>n.log(i)),r.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}x0.ModelAnnotation=oEe;var d0={};Object.defineProperty(d0,"__esModule",{value:!0}),d0.Renames=d0.RenameField=void 0;const uEe=gg,iz=Ye,aEe=Cr;class lEe extends iz.MalloyElement{constructor(e,n){super(),this.newName=e,this.oldName=n,this.elementType="renameField",this.has({oldName:n})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const n=this.oldName.getField(e);n.found?n.found instanceof aEe.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new uEe.RenameSpaceField(n.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}d0.RenameField=lEe;class cEe extends iz.ListOf{constructor(e,n){super(e),this.accessModifier=n,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}d0.Renames=cEe;var Fi={};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.JoinStatement=Fi.ExpressionJoin=Fi.KeyJoin=Fi.Join=void 0;const C7=Ke,fEe=dg,xEe=xs,dEe=Ye,hEe=Sr,sz=Ur,pEe=Dn;class b7 extends dEe.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=hEe.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new fEe.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const n=this.sourceExpr.getSource();return n?n.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),sz.ErrorFactory.structDef)}}Fi.Join=b7;class gEe extends b7{constructor(e,n,r){super({name:e,sourceExpr:n,keyExpr:r}),this.name=e,this.sourceExpr=n,this.keyExpr=r,this.elementType="joinOnKey"}structDef(e){var n;const r=this.getStructDefFromExpr(e);if(!(0,C7.isJoinable)(r))throw this.internalError(`Cannot join struct type '${r.type}'`);const i={...r,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete i.as,this.note&&(i.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(i),i}fixupJoinOn(e,n){const r=this.keyExpr.getExpression(e);if((0,C7.isSourceDef)(n)&&n.primaryKey){const i=n.fields.find(s=>(s.as||s.name)===n.primaryKey);if(i)if(i.type===r.type){n.join="one",n.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,n.primaryKey]},right:r.value}},n.onCompositeFieldUsage=r.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${r.type}/${i.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${i}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}Fi.KeyJoin=gEe;class mEe extends b7{constructor(e,n){super({name:e,sourceExpr:n}),this.name=e,this.sourceExpr=n,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,n){if(this.expr===void 0)return;const r=this.expr.getExpression(e);if(r.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}n.onExpression=r.value,n.onCompositeFieldUsage=r.compositeFieldUsage}structDef(e){var n;const r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),sz.ErrorFactory.joinDef;const i=r.getSourceDef(e);let s="left";if(this.inExperiment("join_types",!0)&&(s=this.matrixOperation),!(0,C7.isJoinable)(i))throw this.internalError(`Can't join struct type ${i.type}`);const o={...i,name:this.name.refString,join:this.joinType,matrixOperation:s,location:this.location};return delete o.as,this.note&&(o.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(o),o}}Fi.ExpressionJoin=mEe;class yEe extends xEe.DefinitionList{constructor(e,n){super(e),this.accessModifier=n,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=pEe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n),e.alwaysJoins.push(n.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}Fi.JoinStatement=yEe;var vo={};Object.defineProperty(vo,"__esModule",{value:!0}),vo.IncludeListItem=vo.IncludeExceptItem=vo.IncludeAccessItem=vo.IncludeItem=void 0;const oz=Ye,uz=Sr;class T7 extends oz.MalloyElement{}vo.IncludeItem=T7;class EEe extends T7{constructor(e,n){super(),this.kind=e,this.fields=n,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=uz.extendNoteMethod,this.has({fields:n})}}vo.IncludeAccessItem=EEe;class AEe extends T7{constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}vo.IncludeExceptItem=AEe;class _Ee extends oz.MalloyElement{constructor(e,n){super({name:e}),this.name=e,this.as=n,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=uz.extendNoteMethod}}vo.IncludeListItem=_Ee;var ht={},mg={},vEe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),SEe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),CEe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&vEe(e,t,n);return SEe(e,t),e};Object.defineProperty(mg,"__esModule",{value:!0}),mg.ReferenceField=void 0;const az=Ke,lz=CEe(Wt),cz=Cr,bEe=ut;class TEe extends cz.SpaceField{constructor(e,n){super(),this.fieldRef=e,this.inFS=n,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const n=this.fieldRef.getField(e);n.error&&this.fieldRef.logError(n.error.code,n.error.message);const r=this.fieldRef.path;if(n.found&&n.found.refType==="parameter"){const s=n.found.typeDesc();if(az.TD.isAtomic(s))this.queryFieldDef={...(0,az.mkFieldDef)(lz.atomicDef(s),r[0]),e:{node:"parameter",path:r}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:r};const i=this.referenceTo;if(i instanceof cz.SpaceField){const s=i.constructorFieldDef();if(s){const o=this.fieldRef.note;if(s.annotation||o){const u=o||{};s.annotation&&(u.inherits=s.annotation),this.queryFieldDef.annotation=u}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const n=this.fieldRef.list.slice(0,-1).map(i=>i.refString),r=e.typeDesc();return this.memoTypeDesc={...r,compositeFieldUsage:(0,bEe.joinedCompositeFieldUsage)(n,r.compositeFieldUsage)},this.memoTypeDesc}return lz.errorT}}mg.ReferenceField=TEe;var qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.typecheckGroupBy=qn.typecheckAggregate=qn.typecheckCalculate=qn.typecheckDeclare=qn.typecheckMeasure=qn.typecheckDimension=qn.typecheckIndex=qn.typecheckProject=void 0;const Sn=ts;function REe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="select-of-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="select-of-analytic";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}qn.typecheckProject=REe;function OEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsScalar)(t.expressionType)){let n,r;if(t.type==="turtle")n="a view",r="index-of-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="an analytic",r="index-of-analytic";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(r,`Cannot use ${n} field in an index operation`)}}qn.typecheckIndex=OEe;function DEe(t,e){if(!(0,Sn.expressionIsScalar)(t.expressionType))if((0,Sn.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,Sn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}qn.typecheckDimension=DEe;function wEe(t,e){if(!(0,Sn.expressionIsAggregate)(t.expressionType))if((0,Sn.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,Sn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}qn.typecheckMeasure=wEe;function FEe(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,Sn.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}qn.typecheckDeclare=FEe;function NEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsAnalytic)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="calculate-of-view";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="calculate-of-aggregate";else if((0,Sn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}qn.typecheckCalculate=NEe;function LEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsAggregate)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="aggregate-of-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="aggregate-of-analytic";else if((0,Sn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar",i="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(i,`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}qn.typecheckAggregate=LEe;function IEe(t,e){if(t.type==="turtle"||!(0,Sn.expressionIsScalar)(t.expressionType)){let n,r,i;if(t.type==="turtle")n="a nest",r="a view",i="group-by-view";else if((0,Sn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic",i="group-by-analytic";else if((0,Sn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate",i="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}qn.typecheckGroupBy=IEe,Object.defineProperty(ht,"__esModule",{value:!0}),ht.FieldReferences=ht.WildcardFieldReference=ht.ViewOrScalarFieldReference=ht.DimensionFieldReference=ht.MeasureFieldReference=ht.DeclareFieldReference=ht.ProjectFieldReference=ht.GroupByFieldReference=ht.AggregateFieldReference=ht.IndexFieldReference=ht.CalculateFieldReference=ht.ParameterFieldReference=ht.PartitionByFieldReference=ht.ExpressionFieldReference=ht.AccessModifierFieldReference=ht.AcceptExceptFieldReference=ht.FieldReference=void 0;const BEe=mg,$Ee=xs,fz=Ye,xz=Sr,h0=qn;class ii extends fz.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=xz.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.logError("output-name-conflict",`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new BEe.ReferenceField(this,r))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const n=e.lookup(this.list);if(n.found){const r=n.found.typeDesc();this.typecheck(r)}return n}}ht.FieldReference=ii;class kEe extends ii{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}ht.AcceptExceptFieldReference=kEe;class PEe extends ii{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}ht.AccessModifierFieldReference=PEe;class MEe extends ii{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}ht.ExpressionFieldReference=MEe;class jEe extends ii{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}ht.PartitionByFieldReference=jEe;class UEe extends ii{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}ht.ParameterFieldReference=UEe;class qEe extends ii{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,h0.typecheckCalculate)(e,this)}}ht.CalculateFieldReference=qEe;class R7 extends ii{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,h0.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return R7.indexOutputName(this.path)}}ht.IndexFieldReference=R7;class HEe extends ii{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,h0.typecheckAggregate)(e,this)}}ht.AggregateFieldReference=HEe;class zEe extends ii{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,h0.typecheckGroupBy)(e,this)}}ht.GroupByFieldReference=zEe;class QEe extends ii{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,h0.typecheckProject)(e,this)}}ht.ProjectFieldReference=QEe;class GEe extends ii{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,h0.typecheckDeclare)(e,this)}}ht.DeclareFieldReference=GEe;class WEe extends ii{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,h0.typecheckMeasure)(e,this)}}ht.MeasureFieldReference=WEe;class VEe extends ii{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,h0.typecheckDimension)(e,this)}}ht.DimensionFieldReference=VEe;class YEe extends ii{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}ht.ViewOrScalarFieldReference=YEe;class KEe extends fz.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=xz.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}ht.WildcardFieldReference=KEe;class XEe extends $Ee.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}ht.FieldReferences=XEe,Object.defineProperty(xg,"__esModule",{value:!0}),xg.RefinedSource=void 0;const JEe=Ke,ZEe=Kd,eAe=f0,tAe=wu,nAe=Zd,rAe=eh,iAe=th,sAe=ks,oAe=nh,uAe=x0,aAe=d0,lAe=Jd,cAe=Fi,dz=vo,O7=ht;class fAe extends sAe.Source{constructor(e,n,r){super({source:e,refinement:n}),this.source=e,this.refinement=n,this.includeList=r,this.elementType="refinedSource",r&&this.has({includeList:r})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;let i,s;const o=[],u=[];let a;const l=[];for(const _ of this.refinement.list){if(_ instanceof uAe.ObjectAnnotation)continue;const v=_;if(_ instanceof rAe.PrimaryKey){if(i){const S="multiple-primary-keys";i.logError(S,"Primary key already defined"),_.logError(S,"Primary key redefined")}i=_}else if(_ instanceof nAe.FieldListEdit){if(s){const S="multiple-field-list-edits";s.logError(S,"Too many accept/except statements"),_.logError(S,"Too many accept/except statements")}s=_}else _ instanceof eAe.DeclareFields||_ instanceof cAe.JoinStatement||_ instanceof iAe.Views||_ instanceof aAe.Renames?(o.push(..._.list),_.accessModifier&&l.push({fields:_.delarationNames,access:_.accessModifier})):_ instanceof tAe.Filter?u.push(_):_ instanceof oAe.TimezoneStatement?a=_.tz:v.logError("unexpected-source-property",`Unexpected source property: '${v.elementType}'`)}const c=n?new lAe.ParameterSpace(n):void 0,f=structuredClone(this.source.getSourceDef(c)),{fieldsToInclude:x,modifiers:h,renames:p,notes:m}=xAe(this.includeList,f);for(const _ of l)for(const v of _.fields)h.set(v,_.access);i&&(f.primaryKey=i.field.name);const g=ZEe.RefinedSpace.filteredFrom(f,s,x,p,c);if(a&&g.setTimezone(a),n&&g.addParameters(n),g.pushFields(...o),i){const _=i.field.getField(g);_.error&&i.logError(_.error.code,_.error.message)}g.addAccessModifiers(h),g.addNotes(m);const y=g.structDef(),E=y.filterList||[];let A=!1;for(const _ of u)for(const v of _.list){const S=v.filterCondition(g);(0,JEe.expressionIsCalculation)(S.expressionType)?v.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(E.push(S),A=!0)}return A?{...y,filterList:E}:((r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(y),y)}}xg.RefinedSource=fAe;function xAe(t,e){var n,r,i,s,o,u,a,l,c;const f=new Set(e.fields.map(S=>S.name)),x=new Set(e.fields.filter(S=>S.accessModifier==="private").map(S=>S.name));let h;const p=new Set;let m,g;const y=new Map,E=[],A=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:y,renames:E,notes:A};for(const S of t)if(S instanceof dz.IncludeAccessItem)for(const C of S.fields)if(C.name instanceof O7.WildcardFieldReference)C.name.joinPath&&C.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),m!==void 0?S.logError("already-used-star-in-include","Wildcard already used in this include block"):(m=(n=S.kind)!==null&&n!==void 0?n:"inherit",g={notes:(i=(r=C.note)===null||r===void 0?void 0:r.notes)!==null&&i!==void 0?i:[],blockNotes:(o=(s=S.note)===null||s===void 0?void 0:s.blockNotes)!==null&&o!==void 0?o:[]});else{if(h==="exclude"){S.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}h="include";const b=C.name.refString;x.has(b)&&C.logError("cannot-expand-access",`Cannot expand access of \`${b}\` from private to ${S.kind}`),y.has(b)?C.logError("duplicate-include",`Field \`${b}\` already referenced in include list`):(S.kind!==void 0&&y.set(b,S.kind),p.add(b),(C.note||S.note)&&A.set(b,{notes:(a=(u=C.note)===null||u===void 0?void 0:u.notes)!==null&&a!==void 0?a:[],blockNotes:(c=(l=S.note)===null||l===void 0?void 0:l.blockNotes)!==null&&c!==void 0?c:[]})),C.as&&(C.name instanceof O7.WildcardFieldReference?C.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):E.push({name:C.name,as:C.as,location:C.location}))}else if(S instanceof dz.IncludeExceptItem)for(const C of S.fields)C instanceof O7.WildcardFieldReference?C.joinPath?C.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):C.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):h==="include"?S.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(h="exclude",m="inherit",p.add(C.refString));const _=new Set(f);p.forEach(S=>_.delete(S)),x.forEach(S=>_.delete(S));let v;if(m!==void 0)for(const S of _)m!=="inherit"&&y.set(S,m),g&&A.set(S,{...g});return h!=="exclude"?m!==void 0?v=f:v=p:v=_,{fieldsToInclude:v,modifiers:y,renames:E,notes:A}}var So={};Object.defineProperty(So,"__esModule",{value:!0}),So.SourceQueryElement=void 0;const dAe=Ye;class D7 extends dAe.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,n,r){return this.isErrorFree()&&this.logError(e,n,r),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const n of this.walk())if(n instanceof D7&&n.errored){e=!1;break}return e}}So.SourceQueryElement=D7;var J_={},Af={};Object.defineProperty(Af,"__esModule",{value:!0}),Af.QuerySource=void 0;const hAe=ks,pAe=uE;class gAe extends hAe.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,n){var r;const i=this.query.queryComp(!1),s={...i.outputStruct,name:`QuerySource-${(0,pAe.v4)()}`,type:"query_source",query:i.query};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),{...s,parameters:this.packParameters(n)}}}Af.QuerySource=gAe;var rh={},yg={};Object.defineProperty(yg,"__esModule",{value:!0}),yg.QueryBase=void 0;const w7=ut,hz=Ke,mAe=Qd,yAe=Ye;class EAe extends yAe.MalloyElement{resolveCompositeSource(e,n){var r;const i=n.pipeline[0];if(i&&((0,hz.isQuerySegment)(i)||(0,hz.isIndexSegment)(i))){const s=(r=i.compositeFieldUsage)!==null&&r!==void 0?r:(0,w7.emptyCompositeFieldUsage)();if(!(0,w7.isEmptyCompositeFieldUsage)(s)||e.type==="composite")return(0,w7.resolveCompositeSources)(e,s).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,mAe.detectAndRemovePartialStages)(e.pipeline,this)}}}yg.QueryBase=EAe,Object.defineProperty(rh,"__esModule",{value:!0}),rh.QueryArrow=void 0;const AAe=Ke,_Ae=ks,pz=br,vAe=yg;class SAe extends vAe.QueryBase{constructor(e,n){super({source:e,view:n}),this.source=e,this.view=n,this.elementType="arrow"}queryComp(e){var n;let r,i,s;if(this.source instanceof _Ae.Source){const x=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};i={type:"query",...x,pipeline:[],location:this.location},r=(0,AAe.refIsStructDef)(x.structRef)?x.structRef:this.source.getSourceDef(void 0),s=new pz.StaticSourceSpace(r)}else{const x=this.source.queryComp(e);i=x.query,r=x.outputStruct,s=new pz.StaticSourceSpace(x.outputStruct)}const{pipeline:o,annotation:u,outputStruct:a,name:l}=this.view.pipelineComp(s),c={...i,name:l,annotation:u,pipeline:[...i.pipeline,...o]},f=(n=c.compositeResolvedSourceDef)!==null&&n!==void 0?n:this.resolveCompositeSource(r,c);return{query:{...c,compositeResolvedSourceDef:f},outputStruct:a,inputStruct:r}}}rh.QueryArrow=SAe,Object.defineProperty(J_,"__esModule",{value:!0}),J_.SQArrow=void 0;const CAe=So,bAe=Af,TAe=rh;class RAe extends CAe.SourceQueryElement{constructor(e,n){super({applyTo:e,operation:n}),this.applyTo=e,this.operation=n,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const n=new TAe.QueryArrow(e,this.operation);return this.has({query:n}),n}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const n=new bAe.QuerySource(e);return this.has({asSource:n}),n}}J_.SQArrow=RAe;var Z_={},ih={},ds={};Object.defineProperty(ds,"__esModule",{value:!0}),ds.getStructFieldDef=ds.getFinalStruct=ds.opOutputStruct=void 0;const gz=Yl,OAe=Bc,ev=Ke,mz=Ur;function yz(t,e,n){const r=mz.ErrorFactory.didCreate(e)||(0,ev.structHasErrors)(e);(0,ev.isPartialSegment)(n)&&(n={...n,type:"reduce"});const i=(0,ev.segmentHasErrors)(n);if(!r&&!i)try{const s=OAe.Segment.nextStructDef(e,n);if((0,ev.isSourceDef)(s))return s;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1256
1256
  STRUCTDEF: ${(0,gz.inspect)(s,{breakLength:72,depth:1/0})}`)}catch(s){t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: ${s.message}
1257
- QUERY: ${(0,gz.inspect)(n,{breakLength:72,depth:1/0})}`)}return mz.ErrorFactory.structDef}ds.opOutputStruct=yz;function DAe(t,e,n){for(const r of n)e=yz(t,e,r);return e}ds.getFinalStruct=DAe;function wAe(t,e){return t.fields.find(n=>(n.as||n.name)===e)}ds.getStructFieldDef=wAe,Object.defineProperty(ih,"__esModule",{value:!0}),ih.QueryRefine=void 0;const FAe=br,NAe=ds,LAe=yg;class IAe extends LAe.QueryBase{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="query-refine"}queryComp(e){const n=this.base.queryComp(e),r=new FAe.StaticSourceSpace(n.inputStruct),i=this.refinement.refine(r,n.query.pipeline,void 0);return{query:{...n.query,pipeline:i},outputStruct:(0,NAe.getFinalStruct)(this.refinement,n.inputStruct,i),inputStruct:n.inputStruct}}}ih.QueryRefine=IAe;var Eg={},sh={},Ni={};Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.mkTimeResult=Ni.resolution=Ni.castTo=Ni.timeOffset=void 0;const F7=Ke;function BAe(t,e,n,r,i){return{node:"delta",kids:{base:(0,F7.mkTemporal)(e,t),delta:r},op:n,units:i}}Ni.timeOffset=BAe;function $Ae(t,e,n,r=!1){let i;return typeof t!="string"?i={node:"cast",dstSQLType:t.raw,e,safe:r}:i={node:"cast",dstType:{type:t},e,safe:r},(0,F7.isCastType)(n)&&(i.srcType={type:n}),i}Ni.castTo=$Ae;function kAe(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Ni.resolution=kAe;function PAe(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,F7.isDateUnit)(e))return{...t,timeframe:e}}return t}Ni.mkTimeResult=PAe;var _f={},ct={},jt={};Object.defineProperty(jt,"__esModule",{value:!0}),jt.literalTimeResult=jt.literalExprValue=jt.computedErrorExprValue=jt.computedTimeResult=jt.computedExprValue=void 0;const Ez=ts,N7=ut;function Ag({value:t,dataType:e,from:n}){return{...e,value:t,expressionType:(0,Ez.maxOfExpressionTypes)(n.map(r=>r.expressionType)),evalSpace:(0,Ez.mergeEvalSpaces)(...n.map(r=>r.evalSpace)),compositeFieldUsage:(0,N7.mergeCompositeFieldUsage)(...n.map(r=>r.compositeFieldUsage))}}jt.computedExprValue=Ag;function MAe({value:t,dataType:e,from:n,timeframe:r}){const i=Ag({value:t,dataType:e,from:n}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,N7.mergeCompositeFieldUsage)(...n.map(o=>o.compositeFieldUsage))};return r&&(s.timeframe=r),s}jt.computedTimeResult=MAe;function jAe({dataType:t,from:e,error:n}){return Ag({dataType:t??{type:"error"},value:{node:"error",message:n},from:e})}jt.computedErrorExprValue=jAe;function UAe(t){return Ag({...t,from:[]})}jt.literalExprValue=UAe;function qAe({value:t,dataType:e,timeframe:n}){const r=Ag({value:t,dataType:e,from:[]}),i={...e,expressionType:r.expressionType,evalSpace:r.evalSpace,value:r.value,compositeFieldUsage:(0,N7.emptyCompositeFieldUsage)()};return n&&(i.timeframe=n),i}jt.literalTimeResult=qAe;var oh={};Object.defineProperty(oh,"__esModule",{value:!0}),oh.isGranularResult=void 0;function HAe(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}oh.isGranularResult=HAe;var Co={};Object.defineProperty(Co,"__esModule",{value:!0}),Co.isComparison=Co.isEquality=Co.getExprNode=void 0;function zAe(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}Co.getExprNode=zAe;function Az(t){return t==="="||t==="!="||t==="~"||t==="!~"}Co.isEquality=Az;function QAe(t){return Az(t)||t===">="||t==="<="||t===">"||t==="<"}Co.isComparison=QAe;var GAe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),WAe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),VAe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&GAe(e,t,n);return WAe(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0}),ct.applyBinary=ct.getMorphicValue=ct.ExprDuration=ct.ExpressionDef=ct.ATNodeType=void 0;const p0=Ke,vf=VAe(Wt),L7=fs,Ua=jt,YAe=Ni,_z=oh,KAe=Ye,_g=Co;class XAe extends Error{}var I7;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(I7||(ct.ATNodeType=I7={}));class vz extends KAe.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=vf.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.type!=="error"&&!vf.any(n,this.legalChildTypes)?(n.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:n.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${vf.inspect(n)}`),!1):!0}apply(e,n,r,i=!1){return Tz(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,p0.expressionIsAggregate)(e.expressionType)}atNodeType(){return I7.Value}atExpr(){return this}}ct.ExpressionDef=vz;class B7 extends vz{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[vf.timestampT,vf.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,p0.isTemporalType)(i.type)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!vf.typeEq(s,vf.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${s.type}`),(0,L7.errorFor)("illegal unit expression");let o;return(0,_z.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.type==="date"&&!(0,p0.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,Ua.computedTimeResult)({dataType:{type:i.type},value:(0,YAe.timeOffset)(i.type,i.value,n,s.value,this.timeframe),timeframe:o,from:[i,s]})}return super.apply(e,n,r)}getExpression(e){const n=this.n.getExpression(e);return(0,Ua.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[n]})}}ct.ExprDuration=B7;function Sz(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function JAe(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,Ua.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}ct.getMorphicValue=JAe;function Cz(t,e,n,r){const i=(0,p0.isTemporalType)(e.type),s=(0,p0.isTemporalType)(r.type),o=(0,_g.getExprNode)(n);if(i&&s)if(e.type!==r.type){const u=Sz(e,"timestamp"),a=Sz(r,"timestamp");if(u&&a)return{node:o,kids:{left:u,right:u}}}else return{node:o,kids:{left:e.value,right:r.value}};if((i||s)&&e.type!=="null"&&r.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${r.type}`),{node:"false"}}function ZAe(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function e_e(t,e,n){const r=e==="!="||e==="!~",i=r?"is-not-null":"is-null";if(t.type==="null"||n.type==="null")return t.type!=="null"?{node:i,e:t.value}:n.type!=="null"?{node:i,e:n.value}:{node:r?"false":"true"}}function t_e(t,e,n,r){var i;const s=e.getExpression(t),o=r.getExpression(t),u=(0,_g.getExprNode)(n),a=vg("boolean",s,o);if(a)return a;const l=p0.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=p0.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=Sg(e,s,r,o);if(h)return{...h,type:"boolean"}}let f=Cz(e,s,n,o)||{node:u,kids:{left:s.value,right:o.value}};if(s.type!=="error"&&o.type!=="error")switch(n){case"~":case"!~":{if(s.type!=="string"||o.type!=="string"){let x=ZAe(s,o);if(x)n[0]==="!"&&(x={node:"not",e:{...x}});else throw new XAe("Incompatible types for match('~') operator");f=x}break}case"=":case"!=":{f=(i=e_e(s,n,o))!==null&&i!==void 0?i:f;break}}return(0,Ua.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function n_e(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=vg("boolean",i,s);if(o)return o;const u=Sg(e,i,r,s);if(u)return{...u,type:"boolean"};const a=Cz(e,i,n,s)||{node:(0,_g.getExprNode)(n),kids:{left:i.value,right:s.value}};return(0,Ua.computedExprValue)({dataType:{type:"boolean"},value:a,from:[i,s]})}function bz(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=vg("number",i,s);if(o)return o;const u=Sg(e,i,r,s);if(u)return u;if(i.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${n}' operator requires a number, not a '${i.type}'`);else if(s.type!=="number")r.logError("arithmetic-operation-type-mismatch",`The '${n}' operator requires a number, not a '${s.type}'`);else return(0,Ua.computedExprValue)({dataType:{type:"number"},value:{node:n,kids:{left:i.value,right:s.value}},from:[i,s]});return(0,L7.errorFor)("numbers required")}function r_e(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Sg(e,i,r,s);if(o)return o;const u=(0,p0.isTemporalType)(i.type),a=vg(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.type!=="duration")if((0,_z.isGranularResult)(i))l=new B7(r,i.timeframe);else if(i.type==="date")l=new B7(r,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${s.type}'`);return l.apply(t,n,e)}return bz(t,e,n,r)}function Tz(t,e,n,r){if((0,_g.isEquality)(n))return t_e(t,e,n,r);if((0,_g.isComparison)(n))return n_e(t,e,n,r);if(n==="+"||n==="-")return r_e(t,e,n,r);if(n==="*")return bz(t,e,n,r);if(n==="/"||n==="%"){const i=e.getExpression(t),s=r.getExpression(t),o=Sg(e,i,r,s);if(o)return o;const u=vg("number",i,s);if(u)return u;if(i.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(s.type!=="number")r.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const a={node:n,kids:{left:i.value,right:s.value}};return(0,Ua.computedExprValue)({dataType:{type:"number"},value:a,from:[i,s]})}return(0,L7.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${n} operator here`)}ct.applyBinary=Tz;function vg(t,...e){if(e.some(n=>n.type==="error"))return(0,Ua.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function Sg(t,e,n,r){const i=(0,Ua.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,r]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),i.type=r.type,i;if(r.type==="sql native")return n.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}),i}Object.defineProperty(_f,"__esModule",{value:!0}),_f.ExprIdReference=void 0;const i_e=Ke,s_e=ct,o_e=ut;class u_e extends s_e.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const n=this.fieldReference.getField(e),r=this.fieldReference.list.map(i=>i.name).slice(0,-1);if(n.found){const i=n.found.typeDesc(),s=(0,o_e.joinedCompositeFieldUsage)(r,i.compositeFieldUsage);if(n.isOutputField)return{...i,evalSpace:i.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:s};const o={node:n.found.refType,path:this.fieldReference.path},u=(0,i_e.expressionIsAggregate)(i.expressionType)?"output":i.evalSpace;return{...i,value:o,evalSpace:u,compositeFieldUsage:s}}return this.loggedErrorExpr(n.error.code,n.error.message)}}_f.ExprIdReference=u_e,Object.defineProperty(sh,"__esModule",{value:!0}),sh.NamedSource=void 0;const $7=Ke,a_e=ks,l_e=Ur,c_e=Ni,Rz=Ye,f_e=_f,x_e=Jd;class d_e extends a_e.Source{constructor(e,n,r){super(),this.ref=e,this.sourceArguments=n,this.args=r,this.elementType="namedSource",r&&this.has({args:r}),e instanceof Rz.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Rz.ModelEntryReference?this.ref.name:this.ref}structRef(e){const n=this.modelEntry(this.ref);return n&&!n.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,n,r){typeof this.ref=="string"?this.logError(e,n,r):this.ref.logError(e,n,r)}modelStruct(){var e;const n=this.modelEntry(this.ref),r=n==null?void 0:n.entry;if(!r){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(r.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(r.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,r.dialect),(0,$7.isSourceDef)(r))return{...r};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const n=this.modelStruct();return n===void 0?{}:this.evaluateArguments(e,n.parameters,[])}evaluateArguments(e,n,r){var i,s;const o={...this.sourceArguments},u=new Set;for(const a of(i=this.args)!==null&&i!==void 0?i:[]){const l=(s=a.id)!==null&&s!==void 0?s:a.value instanceof f_e.ExprIdReference?a.value.fieldReference:void 0;if(l===void 0){a.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const c=l.outputName;if(u.has(c)){a.logError("duplicate-source-argument",`Cannot pass argument for \`${c}\` more than once`);continue}u.add(c);const f=(n??{})[c];if(!f)l.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${l.refString}\``);else{const x=e??new x_e.ParameterSpace(r??[]),h=a.value.getExpression(x);let p=h.value;h.type!==f.type&&(0,$7.isCastType)(f.type)&&(p=(0,c_e.castTo)(f.type,h.value,h.type,!0)),o[c]={...f,value:p}}}for(const a in n)a in o||((0,$7.paramHasValue)(n[a])?o[a]={...n[a]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${a}\``));return o}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;const i=this.modelStruct();if(!i){const a=l_e.ErrorFactory.structDef,l=`${this.refName}-undefined`;return a.name=a.name+l,a.dialect=a.dialect+l,a}const s={};for(const a of n??[]){const l=a.parameter();s[l.name]=l}const o=this.evaluateArguments(e,i.parameters,n),u={...i,parameters:s,arguments:o};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}sh.NamedSource=d_e;var Cg={},tv={};Object.defineProperty(tv,"__esModule",{value:!0}),tv.QueryHeadStruct=void 0;const h_e=Ke,p_e=ks,g_e=sh;class m_e extends p_e.Source{constructor(e,n){super(),this.fromRef=e,this.sourceArguments=n,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,h_e.refIsStructDef)(this.fromRef))return this.fromRef;const n=new g_e.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:n}),n.getSourceDef(e)}}tv.QueryHeadStruct=m_e,Object.defineProperty(Cg,"__esModule",{value:!0}),Cg.QueryReference=void 0;const k7=Ur,y_e=Ye,E_e=tv,A_e=Ke,__e=ds;class v_e extends y_e.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const n=this.modelEntry(this.name),r=n==null?void 0:n.entry,i=function(){return{inputStruct:k7.ErrorFactory.structDef,outputStruct:k7.ErrorFactory.structDef,query:k7.ErrorFactory.query}};if(!r)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),i();if(r.type==="query"){const s=new E_e.QueryHeadStruct(r.structRef,r.sourceArguments);this.has({queryHead:s});const o=s.getSourceDef(void 0),u=(0,__e.getFinalStruct)(this,o,r.pipeline);return{query:e||(0,A_e.refIsStructDef)(r.structRef)?r:{...r,structRef:o},outputStruct:u,inputStruct:o}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}}Cg.QueryReference=v_e,Object.defineProperty(Eg,"__esModule",{value:!0}),Eg.SQReference=void 0;const S_e=So,C_e=Af,b_e=sh,Oz=Cg,Dz=ts;class T_e extends S_e.SourceQueryElement{constructor(e,n){super({ref:e}),this.ref=e,this.args=n,this.elementType="sq-reference",n!==void 0&&this.has({args:n})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const n=new Oz.QueryReference(this.ref);return this.has({query:n}),n}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,Dz.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const n=new Oz.QueryReference(this.ref);this.asSource=new C_e.QuerySource(n)}else if((0,Dz.isSourceDef)(e))this.asSource=new b_e.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}Eg.SQReference=T_e,Object.defineProperty(Z_,"__esModule",{value:!0}),Z_.SQRefine=void 0;const R_e=So,O_e=Af,D_e=ih,w_e=Eg;class F_e extends R_e.SourceQueryElement{constructor(e,n){super({toRefine:e,refine:n}),this.toRefine=e,this.refine=n,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof w_e.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const n=new D_e.QueryRefine(e,this.refine);return this.has({query:n}),n}}getSource(){const e=this.getQuery();if(e){const n=new O_e.QuerySource(e);return this.has({queryAsSource:n}),n}}}Z_.SQRefine=F_e;var nv={},bg={};Object.defineProperty(bg,"__esModule",{value:!0}),bg.QueryRaw=void 0;const N_e=Ke,L_e=Ye;class I_e extends L_e.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const n=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},r=(0,N_e.refIsStructDef)(n.structRef)?n.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...n,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:r,inputStruct:r}}query(){return this.queryComp(!0).query}}bg.QueryRaw=I_e;var Tg={},rv={};Object.defineProperty(rv,"__esModule",{value:!0}),rv.makeSQLSentence=void 0;const B_e=Ke,$_e=Nt;function k_e(t,e){return{name:`sql://${e}/${P_e(t)}`,connection:e,select:t}}rv.makeSQLSentence=k_e;function P_e(t){const e=t.map(n=>(0,B_e.isSegmentSQL)(n)?n.sql:JSON.stringify(n));return(0,$_e.generateHash)(e.join(";"))}Object.defineProperty(Tg,"__esModule",{value:!0}),Tg.SQLSource=void 0;const M_e=rv,j_e=ks,iv=Ur;class U_e extends j_e.Source{constructor(e,n){super({connectionName:e,select:n}),this.connectionName=e,this.select=n,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSentence(){return this.requestBlock||(this.requestBlock=(0,M_e.makeSQLSentence)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var n;if(!this.validateConnectionName())return;const r=super.needs(e);if(r)return r;const i=this.sqlSentence(),s=(n=this.translator())===null||n===void 0?void 0:n.root.sqlQueryZone;if(!s){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}s.reference(i.name,this.location);const o=s.getEntry(i.name);if(o.status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0};o.status==="present"&&e.checkExperimentalDialect(this,o.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return iv.ErrorFactory.structDef;const n=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!n)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),iv.ErrorFactory.structDef;const r=this.sqlSentence();n.reference(r.name,this.location);const i=n.getEntry(r.name);if(i.status==="error"){const s=i.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+s.join(`
1257
+ QUERY: ${(0,gz.inspect)(n,{breakLength:72,depth:1/0})}`)}return mz.ErrorFactory.structDef}ds.opOutputStruct=yz;function DAe(t,e,n){for(const r of n)e=yz(t,e,r);return e}ds.getFinalStruct=DAe;function wAe(t,e){return t.fields.find(n=>(n.as||n.name)===e)}ds.getStructFieldDef=wAe,Object.defineProperty(ih,"__esModule",{value:!0}),ih.QueryRefine=void 0;const FAe=br,NAe=ds,LAe=yg;class IAe extends LAe.QueryBase{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="query-refine"}queryComp(e){const n=this.base.queryComp(e),r=new FAe.StaticSourceSpace(n.inputStruct),i=this.refinement.refine(r,n.query.pipeline,void 0),s={...n.query,pipeline:i},o=this.resolveCompositeSource(n.inputStruct,s);return{query:{...s,compositeResolvedSourceDef:o},outputStruct:(0,NAe.getFinalStruct)(this.refinement,n.inputStruct,i),inputStruct:n.inputStruct}}}ih.QueryRefine=IAe;var Eg={},sh={},Ni={};Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.mkTimeResult=Ni.resolution=Ni.castTo=Ni.timeOffset=void 0;const F7=Ke;function BAe(t,e,n,r,i){return{node:"delta",kids:{base:(0,F7.mkTemporal)(e,t),delta:r},op:n,units:i}}Ni.timeOffset=BAe;function $Ae(t,e,n,r=!1){let i;return typeof t!="string"?i={node:"cast",dstSQLType:t.raw,e,safe:r}:i={node:"cast",dstType:{type:t},e,safe:r},(0,F7.isCastType)(n)&&(i.srcType={type:n}),i}Ni.castTo=$Ae;function kAe(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Ni.resolution=kAe;function PAe(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,F7.isDateUnit)(e))return{...t,timeframe:e}}return t}Ni.mkTimeResult=PAe;var _f={},ct={},jt={};Object.defineProperty(jt,"__esModule",{value:!0}),jt.literalTimeResult=jt.literalExprValue=jt.computedErrorExprValue=jt.computedTimeResult=jt.computedExprValue=void 0;const Ez=ts,N7=ut;function Ag({value:t,dataType:e,from:n}){return{...e,value:t,expressionType:(0,Ez.maxOfExpressionTypes)(n.map(r=>r.expressionType)),evalSpace:(0,Ez.mergeEvalSpaces)(...n.map(r=>r.evalSpace)),compositeFieldUsage:(0,N7.mergeCompositeFieldUsage)(...n.map(r=>r.compositeFieldUsage))}}jt.computedExprValue=Ag;function MAe({value:t,dataType:e,from:n,timeframe:r}){const i=Ag({value:t,dataType:e,from:n}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,N7.mergeCompositeFieldUsage)(...n.map(o=>o.compositeFieldUsage))};return r&&(s.timeframe=r),s}jt.computedTimeResult=MAe;function jAe({dataType:t,from:e,error:n}){return Ag({dataType:t??{type:"error"},value:{node:"error",message:n},from:e})}jt.computedErrorExprValue=jAe;function UAe(t){return Ag({...t,from:[]})}jt.literalExprValue=UAe;function qAe({value:t,dataType:e,timeframe:n}){const r=Ag({value:t,dataType:e,from:[]}),i={...e,expressionType:r.expressionType,evalSpace:r.evalSpace,value:r.value,compositeFieldUsage:(0,N7.emptyCompositeFieldUsage)()};return n&&(i.timeframe=n),i}jt.literalTimeResult=qAe;var oh={};Object.defineProperty(oh,"__esModule",{value:!0}),oh.isGranularResult=void 0;function HAe(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}oh.isGranularResult=HAe;var Co={};Object.defineProperty(Co,"__esModule",{value:!0}),Co.isComparison=Co.isEquality=Co.getExprNode=void 0;function zAe(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}Co.getExprNode=zAe;function Az(t){return t==="="||t==="!="||t==="~"||t==="!~"}Co.isEquality=Az;function QAe(t){return Az(t)||t===">="||t==="<="||t===">"||t==="<"}Co.isComparison=QAe;var GAe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),WAe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),VAe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&GAe(e,t,n);return WAe(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0}),ct.applyBinary=ct.getMorphicValue=ct.ExprDuration=ct.ExpressionDef=ct.ATNodeType=void 0;const p0=Ke,vf=VAe(Wt),L7=fs,Ua=jt,YAe=Ni,_z=oh,KAe=Ye,_g=Co;class XAe extends Error{}var I7;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(I7||(ct.ATNodeType=I7={}));class vz extends KAe.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=vf.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.type!=="error"&&!vf.any(n,this.legalChildTypes)?(n.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:n.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${vf.inspect(n)}`),!1):!0}apply(e,n,r,i=!1){return Tz(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,p0.expressionIsAggregate)(e.expressionType)}atNodeType(){return I7.Value}atExpr(){return this}}ct.ExpressionDef=vz;class B7 extends vz{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[vf.timestampT,vf.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,p0.isTemporalType)(i.type)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!vf.typeEq(s,vf.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${s.type}`),(0,L7.errorFor)("illegal unit expression");let o;return(0,_z.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.type==="date"&&!(0,p0.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,Ua.computedTimeResult)({dataType:{type:i.type},value:(0,YAe.timeOffset)(i.type,i.value,n,s.value,this.timeframe),timeframe:o,from:[i,s]})}return super.apply(e,n,r)}getExpression(e){const n=this.n.getExpression(e);return(0,Ua.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[n]})}}ct.ExprDuration=B7;function Sz(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function JAe(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,Ua.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}ct.getMorphicValue=JAe;function Cz(t,e,n,r){const i=(0,p0.isTemporalType)(e.type),s=(0,p0.isTemporalType)(r.type),o=(0,_g.getExprNode)(n);if(i&&s)if(e.type!==r.type){const u=Sz(e,"timestamp"),a=Sz(r,"timestamp");if(u&&a)return{node:o,kids:{left:u,right:u}}}else return{node:o,kids:{left:e.value,right:r.value}};if((i||s)&&e.type!=="null"&&r.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${r.type}`),{node:"false"}}function ZAe(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function e_e(t,e,n){const r=e==="!="||e==="!~",i=r?"is-not-null":"is-null";if(t.type==="null"||n.type==="null")return t.type!=="null"?{node:i,e:t.value}:n.type!=="null"?{node:i,e:n.value}:{node:r?"false":"true"}}function t_e(t,e,n,r){var i;const s=e.getExpression(t),o=r.getExpression(t),u=(0,_g.getExprNode)(n),a=vg("boolean",s,o);if(a)return a;const l=p0.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=p0.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=Sg(e,s,r,o);if(h)return{...h,type:"boolean"}}let f=Cz(e,s,n,o)||{node:u,kids:{left:s.value,right:o.value}};if(s.type!=="error"&&o.type!=="error")switch(n){case"~":case"!~":{if(s.type!=="string"||o.type!=="string"){let x=ZAe(s,o);if(x)n[0]==="!"&&(x={node:"not",e:{...x}});else throw new XAe("Incompatible types for match('~') operator");f=x}break}case"=":case"!=":{f=(i=e_e(s,n,o))!==null&&i!==void 0?i:f;break}}return(0,Ua.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function n_e(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=vg("boolean",i,s);if(o)return o;const u=Sg(e,i,r,s);if(u)return{...u,type:"boolean"};const a=Cz(e,i,n,s)||{node:(0,_g.getExprNode)(n),kids:{left:i.value,right:s.value}};return(0,Ua.computedExprValue)({dataType:{type:"boolean"},value:a,from:[i,s]})}function bz(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=vg("number",i,s);if(o)return o;const u=Sg(e,i,r,s);if(u)return u;if(i.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${n}' operator requires a number, not a '${i.type}'`);else if(s.type!=="number")r.logError("arithmetic-operation-type-mismatch",`The '${n}' operator requires a number, not a '${s.type}'`);else return(0,Ua.computedExprValue)({dataType:{type:"number"},value:{node:n,kids:{left:i.value,right:s.value}},from:[i,s]});return(0,L7.errorFor)("numbers required")}function r_e(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=Sg(e,i,r,s);if(o)return o;const u=(0,p0.isTemporalType)(i.type),a=vg(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.type!=="duration")if((0,_z.isGranularResult)(i))l=new B7(r,i.timeframe);else if(i.type==="date")l=new B7(r,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${s.type}'`);return l.apply(t,n,e)}return bz(t,e,n,r)}function Tz(t,e,n,r){if((0,_g.isEquality)(n))return t_e(t,e,n,r);if((0,_g.isComparison)(n))return n_e(t,e,n,r);if(n==="+"||n==="-")return r_e(t,e,n,r);if(n==="*")return bz(t,e,n,r);if(n==="/"||n==="%"){const i=e.getExpression(t),s=r.getExpression(t),o=Sg(e,i,r,s);if(o)return o;const u=vg("number",i,s);if(u)return u;if(i.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(s.type!=="number")r.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const a={node:n,kids:{left:i.value,right:s.value}};return(0,Ua.computedExprValue)({dataType:{type:"number"},value:a,from:[i,s]})}return(0,L7.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${n} operator here`)}ct.applyBinary=Tz;function vg(t,...e){if(e.some(n=>n.type==="error"))return(0,Ua.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function Sg(t,e,n,r){const i=(0,Ua.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,r]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),i.type=r.type,i;if(r.type==="sql native")return n.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}),i}Object.defineProperty(_f,"__esModule",{value:!0}),_f.ExprIdReference=void 0;const i_e=Ke,s_e=ct,o_e=ut;class u_e extends s_e.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const n=this.fieldReference.getField(e),r=this.fieldReference.list.map(i=>i.name).slice(0,-1);if(n.found){const i=n.found.typeDesc(),s=(0,o_e.joinedCompositeFieldUsage)(r,i.compositeFieldUsage);if(n.isOutputField)return{...i,evalSpace:i.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:s};const o={node:n.found.refType,path:this.fieldReference.path},u=(0,i_e.expressionIsAggregate)(i.expressionType)?"output":i.evalSpace;return{...i,value:o,evalSpace:u,compositeFieldUsage:s}}return this.loggedErrorExpr(n.error.code,n.error.message)}}_f.ExprIdReference=u_e,Object.defineProperty(sh,"__esModule",{value:!0}),sh.NamedSource=void 0;const $7=Ke,a_e=ks,l_e=Ur,c_e=Ni,Rz=Ye,f_e=_f,x_e=Jd;class d_e extends a_e.Source{constructor(e,n,r){super(),this.ref=e,this.sourceArguments=n,this.args=r,this.elementType="namedSource",r&&this.has({args:r}),e instanceof Rz.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Rz.ModelEntryReference?this.ref.name:this.ref}structRef(e){const n=this.modelEntry(this.ref);return n&&!n.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,n,r){typeof this.ref=="string"?this.logError(e,n,r):this.ref.logError(e,n,r)}modelStruct(){var e;const n=this.modelEntry(this.ref),r=n==null?void 0:n.entry;if(!r){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(r.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(r.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,r.dialect),(0,$7.isSourceDef)(r))return{...r};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const n=this.modelStruct();return n===void 0?{}:this.evaluateArguments(e,n.parameters,[])}evaluateArguments(e,n,r){var i,s;const o={...this.sourceArguments},u=new Set;for(const a of(i=this.args)!==null&&i!==void 0?i:[]){const l=(s=a.id)!==null&&s!==void 0?s:a.value instanceof f_e.ExprIdReference?a.value.fieldReference:void 0;if(l===void 0){a.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const c=l.outputName;if(u.has(c)){a.logError("duplicate-source-argument",`Cannot pass argument for \`${c}\` more than once`);continue}u.add(c);const f=(n??{})[c];if(!f)l.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${l.refString}\``);else{const x=e??new x_e.ParameterSpace(r??[]),h=a.value.getExpression(x);let p=h.value;h.type!==f.type&&(0,$7.isCastType)(f.type)&&(p=(0,c_e.castTo)(f.type,h.value,h.type,!0)),o[c]={...f,value:p}}}for(const a in n)a in o||((0,$7.paramHasValue)(n[a])?o[a]={...n[a]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${a}\``));return o}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;const i=this.modelStruct();if(!i){const a=l_e.ErrorFactory.structDef,l=`${this.refName}-undefined`;return a.name=a.name+l,a.dialect=a.dialect+l,a}const s={};for(const a of n??[]){const l=a.parameter();s[l.name]=l}const o=this.evaluateArguments(e,i.parameters,n),u={...i,parameters:s,arguments:o};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}sh.NamedSource=d_e;var Cg={},tv={};Object.defineProperty(tv,"__esModule",{value:!0}),tv.QueryHeadStruct=void 0;const h_e=Ke,p_e=ks,g_e=sh;class m_e extends p_e.Source{constructor(e,n){super(),this.fromRef=e,this.sourceArguments=n,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,h_e.refIsStructDef)(this.fromRef))return this.fromRef;const n=new g_e.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:n}),n.getSourceDef(e)}}tv.QueryHeadStruct=m_e,Object.defineProperty(Cg,"__esModule",{value:!0}),Cg.QueryReference=void 0;const k7=Ur,y_e=Ye,E_e=tv,A_e=Ke,__e=ds;class v_e extends y_e.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const n=this.modelEntry(this.name),r=n==null?void 0:n.entry,i=function(){return{inputStruct:k7.ErrorFactory.structDef,outputStruct:k7.ErrorFactory.structDef,query:k7.ErrorFactory.query}};if(!r)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),i();if(r.type==="query"){const s=new E_e.QueryHeadStruct(r.structRef,r.sourceArguments);this.has({queryHead:s});const o=s.getSourceDef(void 0),u=(0,__e.getFinalStruct)(this,o,r.pipeline);return{query:e||(0,A_e.refIsStructDef)(r.structRef)?r:{...r,structRef:o},outputStruct:u,inputStruct:o}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}}Cg.QueryReference=v_e,Object.defineProperty(Eg,"__esModule",{value:!0}),Eg.SQReference=void 0;const S_e=So,C_e=Af,b_e=sh,Oz=Cg,Dz=ts;class T_e extends S_e.SourceQueryElement{constructor(e,n){super({ref:e}),this.ref=e,this.args=n,this.elementType="sq-reference",n!==void 0&&this.has({args:n})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const n=new Oz.QueryReference(this.ref);return this.has({query:n}),n}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,Dz.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const n=new Oz.QueryReference(this.ref);this.asSource=new C_e.QuerySource(n)}else if((0,Dz.isSourceDef)(e))this.asSource=new b_e.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}Eg.SQReference=T_e,Object.defineProperty(Z_,"__esModule",{value:!0}),Z_.SQRefine=void 0;const R_e=So,O_e=Af,D_e=ih,w_e=Eg;class F_e extends R_e.SourceQueryElement{constructor(e,n){super({toRefine:e,refine:n}),this.toRefine=e,this.refine=n,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof w_e.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const n=new D_e.QueryRefine(e,this.refine);return this.has({query:n}),n}}getSource(){const e=this.getQuery();if(e){const n=new O_e.QuerySource(e);return this.has({queryAsSource:n}),n}}}Z_.SQRefine=F_e;var nv={},bg={};Object.defineProperty(bg,"__esModule",{value:!0}),bg.QueryRaw=void 0;const N_e=Ke,L_e=Ye;class I_e extends L_e.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const n=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},r=(0,N_e.refIsStructDef)(n.structRef)?n.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...n,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:r,inputStruct:r}}query(){return this.queryComp(!0).query}}bg.QueryRaw=I_e;var Tg={},rv={};Object.defineProperty(rv,"__esModule",{value:!0}),rv.makeSQLSentence=void 0;const B_e=Ke,$_e=Nt;function k_e(t,e){return{name:`sql://${e}/${P_e(t)}`,connection:e,select:t}}rv.makeSQLSentence=k_e;function P_e(t){const e=t.map(n=>(0,B_e.isSegmentSQL)(n)?n.sql:JSON.stringify(n));return(0,$_e.generateHash)(e.join(";"))}Object.defineProperty(Tg,"__esModule",{value:!0}),Tg.SQLSource=void 0;const M_e=rv,j_e=ks,iv=Ur;class U_e extends j_e.Source{constructor(e,n){super({connectionName:e,select:n}),this.connectionName=e,this.select=n,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSentence(){return this.requestBlock||(this.requestBlock=(0,M_e.makeSQLSentence)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var n;if(!this.validateConnectionName())return;const r=super.needs(e);if(r)return r;const i=this.sqlSentence(),s=(n=this.translator())===null||n===void 0?void 0:n.root.sqlQueryZone;if(!s){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}s.reference(i.name,this.location);const o=s.getEntry(i.name);if(o.status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0};o.status==="present"&&e.checkExperimentalDialect(this,o.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return iv.ErrorFactory.structDef;const n=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!n)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),iv.ErrorFactory.structDef;const r=this.sqlSentence();n.reference(r.name,this.location);const i=n.getEntry(r.name);if(i.status==="error"){const s=i.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+s.join(`
1258
1258
  `)),iv.ErrorFactory.structDef}else if(i.status==="present"){const s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},u=this.document(),a=u==null?void 0:u.currentModelAnnotation();return a&&(o.modelAnnotation=a),o}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),iv.ErrorFactory.structDef}}Tg.SQLSource=U_e,Object.defineProperty(nv,"__esModule",{value:!0}),nv.SQSource=void 0;const q_e=So,H_e=bg,z_e=Tg;class Q_e extends q_e.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 z_e.SQLSource){const e=new H_e.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}nv.SQSource=Q_e;var sv={};Object.defineProperty(sv,"__esModule",{value:!0}),sv.SQExtend=void 0;const G_e=xg,W_e=So;class V_e extends W_e.SourceQueryElement{constructor(e,n,r){super({sqSrc:e,extend:n}),this.sqSrc=e,this.extend=n,this.includeList=r,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new G_e.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}sv.SQExtend=V_e;var ov={},uv={};Object.defineProperty(uv,"__esModule",{value:!0}),uv.CompositeSource=void 0;const Y_e=Ke,K_e=ks;class X_e extends K_e.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,n){const r=this.sources.map(l=>l.withParameters(e,n)),i=r[0].connection,s=r[0].dialect,o="composite_source",u=[],a=new Map;return this.sources.forEach((l,c)=>{var f;const x=r[c];x.connection!==i&&l.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${x.connection}\` differs from previous connection \`${i}\``);for(const h of x.fields){if(!(0,Y_e.isAtomic)(h)){l.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${h.name}\` is not atomic and will be ignored`);continue}if(h.accessModifier==="private")continue;const p=(f=h.as)!==null&&f!==void 0?f:h.name,m=a.get(p);if(m===void 0){const g={...h,name:p,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[p],joinedUsage:{}},code:this.code,location:this.codeLocation};a.set(p,g),u.push(g)}else h.accessModifier==="internal"&&(m.accessModifier="internal")}}),{type:"composite",sources:r,connection:i,fields:u,dialect:s,name:o,parameters:r[0].parameters}}}uv.CompositeSource=X_e,Object.defineProperty(ov,"__esModule",{value:!0}),ov.SQCompose=void 0;const J_e=uv,Z_e=So;class eve extends Z_e.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(n=>n.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(tve(e))return this.asSource=new J_e.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}ov.SQCompose=eve;function tve(t){return t.every(e=>e!==void 0)}var av={},qa={},Rg={},nve=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),rve=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ive=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&nve(e,t,n);return rve(e,t),e};Object.defineProperty(Rg,"__esModule",{value:!0}),Rg.BinaryBoolean=void 0;const sve=fs,ove=ive(Wt),uve=Co,ave=jt,lve=ct;class cve extends lve.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="abstract boolean binary",this.legalChildTypes=[ove.boolT]}getExpression(e){const n=this.left.getExpression(e),r=this.right.getExpression(e);return this.typeCheck(this.left,n)&&this.typeCheck(this.right,r)?(0,ave.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,uve.getExprNode)(this.op),kids:{left:n.value,right:r.value}},from:[n,r]}):(0,sve.errorFor)("logical-op expected boolean")}}Rg.BinaryBoolean=cve;var fve=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),xve=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dve=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&fve(e,t,n);return xve(e,t),e};Object.defineProperty(qa,"__esModule",{value:!0}),qa.ExprLegacyIn=qa.ExprEquality=qa.ExprCompare=void 0;const tn=dve(Wt),hve=jt,pve=ct,gve=Rg,mve={"~":[tn.stringT],"!~":[tn.stringT],"<":[tn.numberT,tn.stringT,tn.dateT,tn.timestampT],"<=":[tn.numberT,tn.stringT,tn.dateT,tn.timestampT],"=":[tn.numberT,tn.stringT,tn.dateT,tn.timestampT],"!=":[tn.numberT,tn.stringT,tn.dateT,tn.timestampT],">=":[tn.numberT,tn.stringT,tn.dateT,tn.timestampT],">":[tn.numberT,tn.stringT,tn.dateT,tn.timestampT]};class wz extends gve.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="a<=>b",this.legalChildTypes=mve[n]}getExpression(e){return this.right.apply(e,this.op,this.left)}}qa.ExprCompare=wz;class yve extends wz{constructor(e,n,r){super(e,n,r),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,n,r){return super.apply(e,n,r,!0)}}qa.ExprEquality=yve;class Eve extends pve.ExpressionDef{constructor(e,n,r){super(),this.expr=e,this.notIn=n,this.choices=r,this.elementType="in",this.has({expr:e,choices:r})}getExpression(e){const n=this.expr.getExpression(e),r=this.choices.map(i=>i.getExpression(e));return(0,hve.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:n.value,oneOf:r.map(i=>i.value)}},from:[n,...r]})}}qa.ExprLegacyIn=Eve;var Og={},uh={};Object.defineProperty(uh,"__esModule",{value:!0}),uh.ExprTime=void 0;const Ave=Ke,_ve=jt,vve=ct;class P7 extends vve.ExpressionDef{constructor(e,n,r){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,_ve.computedExprValue)({dataType:{type:e},value:n,from:r??[]})}getExpression(e){return this.translationValue}static fromValue(e,n){let r=n.value;if(e!==n.type){const i={node:"cast",safe:!1,dstType:{type:e},e:n.value};(0,Ave.isTemporalType)(n.type)&&(i.srcType={type:n.type}),r=i}return new P7(e,r,[n])}}uh.ExprTime=P7;var g0={};Object.defineProperty(g0,"__esModule",{value:!0}),g0.Range=void 0;const Sve=fs,Cve=jt,bve=ct;class Tve extends bve.ExpressionDef{constructor(e,n){super({first:e,last:n}),this.first=e,this.last=n,this.elementType="range"}apply(e,n,r){switch(n){case"=":case"!=":{const i=n==="="?">=":"<",s=n==="="?"and":"or",o=n==="="?"<":">=",u=this.first.apply(e,i,r),a=this.last.apply(e,o,r);return(0,Cve.computedExprValue)({dataType:{type:"boolean"},value:{node:s,kids:{left:u.value,right:a.value}},from:[u,a]})}case">":return this.last.apply(e,">=",r);case">=":return this.first.apply(e,">=",r);case"<":return this.first.apply(e,"<",r);case"<=":return this.last.apply(e,"<",r)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Sve.errorFor)("a range is not a value")}}g0.Range=Tve;var Rve=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Ove=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dve=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Rve(e,t,n);return Ove(e,t),e};Object.defineProperty(Og,"__esModule",{value:!0}),Og.ExprGranularTime=void 0;const M7=Ke,wve=fs,Fz=Dve(Wt),Nz=Ni,Fve=ct,lv=uh,Lz=g0;class Nve extends Fve.ExpressionDef{constructor(e,n,r){super({expr:e}),this.expr=e,this.units=n,this.truncate=r,this.elementType="granularTime",this.legalChildTypes=[Fz.timestampT,Fz.dateT]}granular(){return!0}getExpression(e){const n=this.units,r=this.expr.getExpression(e);if(M7.TD.isTemporal(r)){const s={...r,timeframe:n};return this.truncate&&(s.value={node:"trunc",e:(0,M7.mkTemporal)(r.value,r.type),units:n}),s}r.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${r.type}'`);const i={...r};return r.type==="error"&&(i.type=(0,M7.isDateUnit)(n)?"date":"timestamp"),{...i,value:(0,wve.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const n=this.getExpression(e),r={node:"numberLiteral",literal:"1"};if(n.type==="timestamp"){const u=lv.ExprTime.fromValue("timestamp",n),a=new lv.ExprTime("timestamp",(0,Nz.timeOffset)("timestamp",n.value,"+",r,this.units),[n]);return new Lz.Range(u,a)}const i=new lv.ExprTime("date",n.value,[n]),s=(0,Nz.timeOffset)("date",n.value,"+",r,this.units),o=new lv.ExprTime("date",s,[n]);return new Lz.Range(i,o)}}Og.ExprGranularTime=Nve,Object.defineProperty(av,"__esModule",{value:!0}),av.Apply=void 0;const Lve=qa,Ive=oh,Iz=Og;class Bve extends Lve.ExprCompare{constructor(e,n){super(e,"=",n),this.left=e,this.right=n,this.elementType="apply"}getExpression(e){let n=this.right;if(!this.right.granular()){const r=this.right.requestExpression(e);r&&(0,Ive.isGranularResult)(r)&&(n=new Iz.ExprGranularTime(this.right,r.timeframe,!1))}return n instanceof Iz.ExprGranularTime?n.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}av.Apply=Bve;var ah={},$ve=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),kve=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pve=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&$ve(e,t,n);return kve(e,t),e};Object.defineProperty(ah,"__esModule",{value:!0}),ah.BinaryNumeric=void 0;const Mve=Pve(Wt),jve=ct;class Uve extends jve.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="numeric binary abstract",this.legalChildTypes=[Mve.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}ah.BinaryNumeric=Uve;var cv={},qve=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Hve=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zve=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&qve(e,t,n);return Hve(e,t),e};Object.defineProperty(cv,"__esModule",{value:!0}),cv.Boolean=void 0;const Qve=ct,Gve=zve(Wt);let Wve=class extends Qve.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Gve.boolT,value:{node:this.value}}}};cv.Boolean=Wve;var m0={};Object.defineProperty(m0,"__esModule",{value:!0}),m0.FunctionOrdering=m0.FunctionOrderBy=void 0;const j7=Ke,Bz=Ye,Vve=_f;class Yve extends Bz.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const n=this.field.getExpression(e);return(0,j7.expressionIsAggregate)(n.expressionType)||((0,j7.expressionIsScalar)(n.expressionType)?(!(this.field instanceof Vve.ExprIdReference)||n.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:n.value,dir:this.dir}}getAggregateOrderBy(e,n){if(this.field){const r=this.field.getExpression(e);return(0,j7.expressionIsScalar)(r.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),n||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:r.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}m0.FunctionOrderBy=Yve;class Kve extends Bz.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(n=>n.getAnalyticOrderBy(e))}getAggregateOrderBy(e,n){return this.list.map(r=>r.getAggregateOrderBy(e,n))}}m0.FunctionOrdering=Kve;var fv={};Object.defineProperty(fv,"__esModule",{value:!0}),fv.ExprAddSub=void 0;const Xve=ah;class Jve extends Xve.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}fv.ExprAddSub=Jve;var Ha={},Zve=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),e5e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),t5e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Zve(e,t,n);return e5e(e,t),e};Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.ExprAggregateFunction=void 0;const Dg=Ke,n5e=Nt,r5e=fs,$z=br,kz=t5e(Wt),i5e=ht,s5e=ct,o5e=Cr,u5e=_f;class a5e extends s5e.ExpressionDef{constructor(e,n,r){super(),this.func=e,this.legalChildTypes=[kz.numberT],this.elementType=e,this.explicitSource=r,n&&(this.expr=n,this.has({expr:n}))}getExpression(e){var n,r,i;const s=e.isQueryFieldSpace()?e.inputSpace():e;let o=this.expr,u=(n=this.expr)===null||n===void 0?void 0:n.getExpression(s),a=(r=this.source)===null||r===void 0?void 0:r.path,l=[];if(this.source){const f=this.source.getField(s);if(f.found){l=f.joinPath;const x=f.found,h=x.typeDesc();if(!(x instanceof $z.StructSpaceField))if((0,Dg.isAtomicFieldType)(h.type)){o=this.source,u={...kz.atomicDef(h),expressionType:h.expressionType,value:h.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:h.evalSpace,compositeFieldUsage:h.compositeFieldUsage},a=this.source.path.slice(0,-1);const p=this.getJoinUsage(s);(p.length===1||p.length>1&&p.slice(1).every(g=>l5e(g,p[0])))&&(a=p[0].map(g=>g.name),l=p[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${h.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(u===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,Dg.expressionIsAggregate)(u.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(u.type==="error")){const f=this.getJoinUsage(s),x=this.source!==void 0||this.explicitSource;if(o&&!(!this.source&&f.every(p=>p.length===0))&&!this.isSymmetricFunction()){const p=q7(l,f),m=H7(this.elementType,p),g=x?m==null?void 0:m.message:"Join path is required for this calculation";if(g){const y=c5e(g,f,o,this.elementType),E=(i=m==null?void 0:m.code)!==null&&i!==void 0?i:"bad-join-usage";m?this.logError(E,y):this.logWarning(E,y)}}}if(this.typeCheck(this.expr||this,{...u,expressionType:"scalar"})){const f={node:"aggregate",function:this.func,e:u.value};return a&&a.length>0&&(f.structPath=a),{...this.returns(u),expressionType:"aggregate",value:f,evalSpace:"output"}}return(0,r5e.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const n=[];if(this.source&&this.source.getField(e).found){const i={node:"field",path:this.source.path};n.push(...U7(e,i))}if(this.expr){const r=this.expr.getExpression(e).value;n.push(...U7(e,r))}return n}}Ha.ExprAggregateFunction=a5e;function l5e(t,e){let n=t.length;if(n!==e.length)return!1;for(;n>0;)if(n-=1,t[n].name!==e[n].name)return!1;return!0}function U7(t,e){const n=[],r=(i,s)=>{const o=s[0],u=s.slice(1),a=i.entry(o);if(a===void 0)throw new Error(`Invalid field lookup ${o}`);if(a instanceof $z.StructSpaceField&&u.length>0){const l=r(a.fieldSpace,u);return{...l,joinPath:[{...a.joinPathElement,name:o},...l.joinPath]}}else if(a instanceof o5e.SpaceField){if(u.length!==0)throw new Error(`${o} cannot contain a ${u.join(".")}`);const l=a.fieldDef();if(l)return{fs:i,def:l,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const i of(0,n5e.exprWalk)(e))if(i.node==="field"){const s=r(t,i.path),o=s.def;if((0,Dg.isAtomic)(o)&&!(0,Dg.isJoined)(o))if((0,Dg.hasExpression)(o)){const u=U7(s.fs,o.e);n.push(...u.map(a=>[...s.joinPath,...a]))}else n.push(s.joinPath)}else if(i.node==="source-reference")if(i.path){const s=r(t,i.path);n.push(s.joinPath)}else n.push([]);return n}function q7(t,e){const n=[];for(const r of e){let i=0;for(let a=0;a<t.length&&a<r.length&&t[a].name===r[a].name;a++)i=a+1;const s=t.slice(i),o=r.slice(i),u=[...s.map(a=>({...a,reverse:!0})),...o.map(a=>({...a,reverse:!1}))];n.push(u)}return n}function H7(t,e){for(const n of e)for(const r of n){if(r.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${r.name}\``};if(r.joinElementType==="array"&&!r.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${r.name}\``};if(r.joinType==="many"&&!r.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${r.name}\``}}}function c5e(t,e,n,r){if(e.length===0)return t;let i=e[0];for(const p of e.slice(1))for(let m=0;m<i.length;m++){const g=i[m],y=p[m];if(g.name!==y.name){i=i.slice(0,m);break}}const s=q7(i,e),o=H7(r,s),u=i.slice().reverse().findIndex(p=>p.joinType==="many"||p.joinType==="cross"),a=u===-1?0:i.length-u,l=i.slice(0,a),c=q7(l,e),f=H7(r,c),x=i.length>0?i.map(p=>p.name).join("."):"source",h=l.length>0?l.map(p=>p.name).join("."):"source";if(o)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const p=n instanceof i5e.FieldReference?`${n.refString}.${r}()`:n instanceof u5e.ExprIdReference?`${n.fieldReference.refString}.${r}()`:`${x}.${r}(${n.code})`,m=`${h}.${r}(${n.code})`;let g=`${t}; use \`${p}\``;return f===void 0&&h!==x&&(g+=` or \`${m}\` to get a result weighted with respect to \`${h}\``),g}}var xv={};Object.defineProperty(xv,"__esModule",{value:!0}),xv.ExprAlternationTree=void 0;const Pz=jt,lh=ct,f5e=Co;function z7(t){const e=t.atExpr();switch(e.atNodeType()){case lh.ATNodeType.And:case lh.ATNodeType.Partial:return;case lh.ATNodeType.Or:{if(e instanceof Mz){const n=z7(e.left);if(n){const r=z7(e.right);if(r)return[...n,...r]}}return}default:return e.granular()?void 0:[e]}}class Mz extends lh.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="alternation",this.elementType=`${n}alternation${n}`}equalityList(){return this.inList===void 0&&(this.inList=z7(this)||[]),this.inList}apply(e,n,r,i){if((0,f5e.isEquality)(n)){const u=this.equalityList();if(u.length>0&&(n==="="||n==="!=")){const a=r.getExpression(e),l=u.map(c=>c.getExpression(e));return(0,Pz.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:n==="!=",kids:{e:a.value,oneOf:l.map(c=>c.value)}},from:[a,...l]})}u.length===0&&i&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${n} operator`)}const s=this.left.apply(e,n,r),o=this.right.apply(e,n,r);return(0,Pz.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:s.value,right:o.value}},from:[s,o]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?lh.ATNodeType.Or:lh.ATNodeType.And}}xv.ExprAlternationTree=Mz;var ch={};Object.defineProperty(ch,"__esModule",{value:!0}),ch.ExprAsymmetric=void 0;const x5e=Ha;class d5e extends x5e.ExprAggregateFunction{constructor(e,n,r,i){super(e,n,i),this.func=e,this.expr=n,this.source=r,this.has({source:r})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}ch.ExprAsymmetric=d5e;var dv={};Object.defineProperty(dv,"__esModule",{value:!0}),dv.ExprAvg=void 0;const h5e=ch;class p5e extends h5e.ExprAsymmetric{constructor(e,n,r){super("avg",e,n,r),this.has({source:n})}}dv.ExprAvg=p5e;var hv={};Object.defineProperty(hv,"__esModule",{value:!0}),hv.ExprCast=void 0;const g5e=Ni,m5e=jt,y5e=ct;class E5e extends y5e.ExpressionDef{constructor(e,n,r=!1){super({expr:e}),this.expr=e,this.castType=n,this.safe=r,this.elementType="cast"}getExpression(e){const n=this.expr.getExpression(e);let r={type:"error"};if(typeof this.castType=="string")r={type:this.castType};else{const i=e.dialectObj();i&&(i.validateTypeName(this.castType.raw)?r=i.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${i.name} dialect`),this.safe&&!i.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,m5e.computedExprValue)({dataType:r,value:(0,g5e.castTo)(this.castType,n.value,n.type,this.safe),from:[n]})}}hv.ExprCast=E5e;var pv={},A5e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),_5e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),v5e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&A5e(e,t,n);return _5e(e,t),e};Object.defineProperty(pv,"__esModule",{value:!0}),pv.ExprCoalesce=void 0;const jz=ts,Uz=v5e(Wt),S5e=ct;class C5e extends S5e.ExpressionDef{constructor(e,n){super({expr:e,altExpr:n}),this.expr=e,this.altExpr=n,this.elementType="coalesce expression",this.legalChildTypes=Uz.anyAtomicT}getExpression(e){const n=this.expr.getExpression(e),r=this.altExpr.getExpression(e);return n.type==="null"?r:(Uz.typeEq(n,r)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${n.type}, ${r.type})`),{...n.type==="error"?r:n,expressionType:(0,jz.maxExpressionType)(n.expressionType,r.expressionType),value:{node:"coalesce",kids:{left:n.value,right:r.value}},evalSpace:(0,jz.mergeEvalSpaces)(n.evalSpace,r.evalSpace)})}}pv.ExprCoalesce=C5e;var gv={};Object.defineProperty(gv,"__esModule",{value:!0}),gv.ExprCount=void 0;const b5e=ut,T5e=Ha;class R5e extends T5e.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const n={node:"aggregate",function:"count",e:{node:""}};return this.source&&(n.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:n,evalSpace:"output",compositeFieldUsage:(0,b5e.emptyCompositeFieldUsage)()}}}gv.ExprCount=R5e;var mv={},O5e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),D5e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),w5e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&O5e(e,t,n);return D5e(e,t),e};Object.defineProperty(mv,"__esModule",{value:!0}),mv.ExprCountDistinct=void 0;const yv=w5e(Wt),F5e=Ha;class N5e extends F5e.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[yv.numberT,yv.stringT,yv.dateT,yv.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}mv.ExprCountDistinct=N5e;var Ev={},y0={};Object.defineProperty(y0,"__esModule",{value:!0}),y0.Limit=void 0;const L5e=Ye,I5e=Dn;class B5e extends L5e.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=I5e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}y0.Limit=B5e;var fh={};Object.defineProperty(fh,"__esModule",{value:!0}),fh.PartitionBy=void 0;const $5e=Ye;class k5e extends $5e.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}fh.PartitionBy=k5e;var wg={},E0={};Object.defineProperty(E0,"__esModule",{value:!0}),E0.FieldName=void 0;const P5e=Ye;class M5e extends P5e.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])}}E0.FieldName=M5e;var j5e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),U5e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),q5e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&j5e(e,t,n);return U5e(e,t),e};Object.defineProperty(wg,"__esModule",{value:!0}),wg.ExprFunc=void 0;const nr=Ke,H5e=fs,z5e=Ef,Q5e=jt,G5e=ct,W5e=E0,qz=Nt,Hz=q5e(Wt),V5e=ut;class Y5e extends G5e.ExpressionDef{constructor(e,n,r,i,s){super({args:n}),this.name=e,this.args=n,this.isRaw=r,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var n,r,i;const s=this.name.toLowerCase(),o=e?(r=(n=this.getDialectNamespace(e))===null||n===void 0?void 0:n.getEntry(s))===null||r===void 0?void 0:r.entry:void 0,u=o??((i=this.modelEntry(s))===null||i===void 0?void 0:i.entry);return u===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):u.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${u.type}) is not a function`),{found:void 0,error:"called non function"}):(u.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${u.name}' instead`),{found:u,error:void 0})}getPropsExpression(e,n){var r,i,s,o;const u=this.args.map(L=>L.getExpression(e));if(this.isRaw){const L=[`${this.name}(`];u.forEach((q,Y)=>{Y!==0&&L.push(","),L.push(q.value)}),L.push(")");const I=(r=u[0])!==null&&r!==void 0?r:{type:"number"},M=this.rawType?{type:this.rawType}:I;return(0,Q5e.computedExprValue)({dataType:M,value:(0,qz.composeSQLExpr)(L),from:u})}const a=(i=e.dialectObj())===null||i===void 0?void 0:i.name,{found:l,error:c}=this.findFunctionDef(a);if(l===void 0)return(0,H5e.errorFor)(c);let f,x=(s=this.source)===null||s===void 0?void 0:s.path;if(this.source){const I=this.source.getField(e).found;if(I){const M=I.typeDesc();if((0,nr.isAtomicFieldType)(M.type))f={...Hz.atomicDef(M),expressionType:M.expressionType,value:{node:"field",path:this.source.path},evalSpace:M.evalSpace,compositeFieldUsage:M.compositeFieldUsage},x=this.source.path.slice(0,-1);else if(!(I instanceof z5e.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${M.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const h=[...f?[f]:[],...u],p=K5e(l,h);if(p===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${h.map(L=>L.type).join(", ")})`);const{overload:m,expressionTypeErrors:g,evalSpaceErrors:y,nullabilityErrors:E,returnType:A}=p;for(const L of g){const I=L.argIndex-(f?1:0),M=(0,nr.expressionIsScalar)(L.maxExpressionType)?"scalar":"scalar or aggregate";this.args[I].logError("invalid-function-argument-expression-type",`Parameter ${L.argIndex+1} ('${L.param.name}') of ${this.name} must be ${M}, but received ${L.actualExpressionType}`)}for(const L of y){const I=L.argIndex-(f?1:0),M=L.maxEvalSpace==="literal"?"literal":L.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[I].logError("invalid-function-argument-evaluation-space",`Parameter ${L.argIndex+1} ('${L.param.name}') of ${this.name} must be ${M}, but received ${L.actualEvalSpace}`)}for(const L of E){const I=L.argIndex-(f?1:0);this.args[I].logError("literal-null-function-argument",`Parameter ${L.argIndex+1} ('${L.param.name}') of ${this.name} must not be a literal null`)}p.returnTypeError&&this.logError(p.returnTypeError.code,p.returnTypeError.parameters);const _=m.returnType,v=(0,nr.maxOfExpressionTypes)([(o=_.expressionType)!==null&&o!==void 0?o:"scalar",...h.map(L=>L.expressionType)]);if(!(0,nr.expressionIsAggregate)(m.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${h.map(L=>L.type).join(", ")}) with source`);const S={node:"function_call",overload:m,name:this.name,kids:{args:h.map(L=>L.value)},expressionType:v,structPath:x};let C=S;if(n!=null&&n.orderBys&&n.orderBys.length>0){const L=(0,nr.expressionIsAnalytic)(m.returnType.expressionType);if(L||this.inExperiment("aggregate_order_by",!0)||n.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),m.supportsOrderBy||L){const I=m.supportsOrderBy!=="only_default",M=n.orderBys.flatMap(q=>L?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,I));S.kids.orderBy=M}else n.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((n==null?void 0:n.limit)!==void 0&&(m.supportsLimit?S.limit=n.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),n!=null&&n.partitionBys&&n.partitionBys.length>0){const L=[];for(const I of n.partitionBys)for(const M of I.partitionFields){const q=M.getField(e);q.found===void 0?M.logError("partition-by-not-found",`${M.refString} is not defined`):(0,nr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,nr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?M.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):L.push(M.nameString)}S.partitionBy=L}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);const L=h[0].value;if(L.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${l.name}\``);else{const I=L.literal,M=X5e(I),q=M.filter(W=>W.type==="interpolation"&&W.name.includes(".")).map(W=>W.type==="interpolation"?`\${${W.name}}`:`\${${W.value}}`);if(q.length>0){const W=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${q.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",W)}const Y=[];for(const W of M)if(W.type==="string")Y.push(W.value);else if(W.name==="TABLE")Y.push({node:"source-reference"});else{const ae=new W5e.FieldName(W.name);this.has({name:ae});const pe=e.lookup([ae]);if(pe.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${pe.error.message}`);pe.found.refType==="parameter"?Y.push({node:"parameter",path:[W.name]}):Y.push({node:"field",path:[W.name]})}C=(0,qz.composeSQLExpr)(Y)}}const b=(0,nr.mergeEvalSpaces)(...h.map(L=>L.evalSpace)),F=b==="constant"?"constant":(0,nr.expressionIsScalar)(v)?b:"output";return{...(0,nr.isAtomic)(A)?Hz.atomicDef(A):A,expressionType:v,value:C,evalSpace:F,compositeFieldUsage:(0,V5e.mergeCompositeFieldUsage)(...h.map(L=>L.compositeFieldUsage))}}}wg.ExprFunc=Y5e;function K5e(t,e){var n;for(const r of t.overloads){const i=new Map;let s=0,o=!0,u=!1;const a=[],l=[],c=[];for(let h=0;h<e.length;h++){const p=e[h],m=r.params[s];if(m===void 0){o=!1;break}if(!m.allowedTypes.some(y=>{var E;const{dataTypeMatch:A,genericsSet:_}=xh(i,(E=r.genericTypes)!==null&&E!==void 0?E:[],p,y);for(const v of _)i.set(v.name,v.type);return y.expressionType&&((0,nr.isExpressionTypeLEQ)(p.expressionType,y.expressionType)||a.push({argIndex:h,maxExpressionType:y.expressionType,actualExpressionType:p.expressionType,param:m})),(y.evalSpace==="literal"&&p.evalSpace!=="literal"||y.evalSpace==="constant"&&(p.evalSpace==="input"||p.evalSpace==="output")||(0,nr.expressionIsAnalytic)(r.returnType.expressionType)&&p.evalSpace==="input")&&l.push({argIndex:h,param:m,maxEvalSpace:y.evalSpace,actualEvalSpace:p.evalSpace}),y.evalSpace==="literal"&&p.type==="null"&&c.push({argIndex:h,param:m}),A})){o=!1;break}m.isVariadic?h===e.length-1&&(u=!0):s++}if(!u&&(s!==e.length||s!==r.params.length))continue;const f=Av(r.returnType,i),x=(n=f.returnType)!==null&&n!==void 0?n:{type:"number"};if(o)return{overload:r,expressionTypeErrors:a,evalSpaceErrors:l,nullabilityErrors:c,returnTypeError:f.error,returnType:x}}}function X5e(t){const e=[];let n=t;for(;n.length;){const r=n.indexOf("${");if(r===-1){e.push({type:"string",value:n});break}else{const i=n.slice(r).indexOf("}");if(i===-1){e.push({type:"string",value:n});break}r>0&&e.push({type:"string",value:n.slice(0,r)}),e.push({type:"interpolation",name:n.slice(r+2,i+r)}),n=n.slice(i+r+1)}}return e}function xh(t,e,n,r){var i,s,o,u;if(nr.TD.eq(r,n)||r.type==="any"||r.type!=="generic"&&(n.type==="null"||n.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(r.type==="array"&&n.type==="array"){if((0,nr.isScalarArray)(n))return(0,nr.isRepeatedRecordFunctionParam)(r)?{dataTypeMatch:!1,genericsSet:[]}:xh(t,e,n.elementTypeDef,r.elementTypeDef);if((0,nr.isRepeatedRecordFunctionParam)(r)){const a={type:"record",fields:r.fields},l={type:"record",fields:n.fields};return xh(t,e,l,a)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(r.type==="record"&&n.type==="record"){const a=[],l=new Map;for(const c of r.fields)l.set((i=c.as)!==null&&i!==void 0?i:c.name,c);for(const c of n.fields){const f=l.get((s=c.as)!==null&&s!==void 0?s:c.name);if(f===void 0)return{dataTypeMatch:!1,genericsSet:[]};const x=xh(new Map([...t.entries(),...a.map(h=>[h.name,h.type])]),e,c,f);a.push(...x.genericsSet)}return{dataTypeMatch:!0,genericsSet:a}}else if(r.type==="generic"){const a=t.get(r.generic);if(a!==void 0&&a.type!=="null"&&a.type!=="error")return xh(t,e,n,a);const l=(u=(o=e.find(c=>c.name===r.generic))===null||o===void 0?void 0:o.acceptibleTypes)!==null&&u!==void 0?u:[];for(const c of l){const f=xh(t,e,n,c);if(f.dataTypeMatch){if(!(0,nr.isAtomic)(n)&&n.type!=="null")continue;const x={name:r.generic,type:n};return{dataTypeMatch:!0,genericsSet:[...f.genericsSet,x]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function Av(t,e){switch(t.type){case"array":{if("fields"in t){const i=t.fields.map(s=>{const o=Av(s,e);return{...s,...o}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:i}}}const n=Av(t.elementTypeDef,e);if(n.error)return n;const r=n.returnType;return r.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:r.fields}}:(0,nr.isAtomic)(r)?{error:void 0,returnType:{type:"array",elementTypeDef:r}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(r=>{const i=Av(r,e);return{...r,...i}})}};case"generic":{const n=e.get(t.generic);return n===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:n}}default:return{error:void 0,returnType:t}}}var J5e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Z5e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),eSe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&J5e(e,t,n);return Z5e(e,t),e};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.ExprProps=void 0;const tSe=Ke,nSe=fs,rSe=eSe(Wt),iSe=m0,sSe=y0,oSe=fh,uSe=ct,aSe=wg;class lSe extends uSe.ExpressionDef{constructor(e,n){super({expr:e,statements:n}),this.expr=e,this.statements=n,this.elementType="expression with props",this.legalChildTypes=rSe.anyAtomicT}getFilteredExpression(e,n,r){if(r.length>0){if(!this.expr.supportsWhere(n))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),n;const i=[];for(const s of r){const o=s.getFilterList(e);if(o.find(u=>(0,tSe.expressionIsCalculation)(u.expressionType)))return s.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),n;i.push(...o)}return this.typeCheck(this.expr,{...n,expressionType:"scalar"})?{...n,value:{node:"filteredExpr",kids:{e:n.value,filterList:i}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${n.expressionType}' data`),(0,nSe.errorFor)("cannot filter type"))}return n}getExpression(e){const n=[];let r;const i=[],s=[];for(const u of this.statements)u instanceof oSe.PartitionBy?this.expr.canSupportPartitionBy()?n.push(u):u.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):u instanceof sSe.Limit?r?u.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?r=u:u.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):u instanceof iSe.FunctionOrdering?this.expr.canSupportOrderBy()?i.push(u):u.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):s.push(u);const o=this.expr instanceof aSe.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:n,limit:r,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}}Ev.ExprProps=lSe;var _v={},cSe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),fSe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xSe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&cSe(e,t,n);return fSe(e,t),e};Object.defineProperty(_v,"__esModule",{value:!0}),_v.ExprLogicalOp=void 0;const dSe=Rg,zz=xSe(Wt);class hSe extends dSe.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[zz.boolT,zz.aggregateBoolT]}}_v.ExprLogicalOp=hSe;var vv={},pSe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),gSe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),mSe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&pSe(e,t,n);return gSe(e,t),e};Object.defineProperty(vv,"__esModule",{value:!0}),vv.ExprMax=void 0;const Sv=mSe(Wt),ySe=Ha;class ESe extends ySe.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[Sv.numberT,Sv.stringT,Sv.dateT,Sv.timestampT]}returns(e){return e}}vv.ExprMax=ESe;var Cv={},ASe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),_Se=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vSe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&ASe(e,t,n);return _Se(e,t),e};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.ExprMin=void 0;const bv=vSe(Wt),SSe=Ha;class CSe extends SSe.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[bv.numberT,bv.stringT,bv.dateT,bv.timestampT]}returns(e){return e}}Cv.ExprMin=CSe;var Tv={},bSe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),TSe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),RSe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&bSe(e,t,n);return TSe(e,t),e};Object.defineProperty(Tv,"__esModule",{value:!0}),Tv.ExprMinus=void 0;const OSe=fs,Qz=RSe(Wt),DSe=ct;class wSe extends DSe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Qz.numberT]}getExpression(e){const n=this.expr.getExpression(e);return Qz.typeIn(n,this.legalChildTypes)?{...n,type:"number",value:{node:"unary-",e:n.value}}:(0,OSe.errorFor)("negate requires number")}}Tv.ExprMinus=wSe;var Rv={};Object.defineProperty(Rv,"__esModule",{value:!0}),Rv.ExprMulDiv=void 0;const FSe=ah;class NSe extends FSe.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}Rv.ExprMulDiv=NSe;var Ov={},Fg={};Object.defineProperty(Fg,"__esModule",{value:!0}),Fg.Unary=void 0;const LSe=ct;class ISe extends LSe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Fg.Unary=ISe;var BSe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),$Se=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kSe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&BSe(e,t,n);return $Se(e,t),e};Object.defineProperty(Ov,"__esModule",{value:!0}),Ov.ExprNot=void 0;const Gz=kSe(Wt),PSe=Fg;class MSe extends PSe.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[Gz.boolT,Gz.nullT]}getExpression(e){const n=this.expr.getExpression(e),r=this.typeCheck(this.expr,n);return{...n,type:"boolean",value:{node:"not",e:r?n.value:{node:"false"}}}}}Ov.ExprNot=MSe;var Dv={};Object.defineProperty(Dv,"__esModule",{value:!0}),Dv.ExprNow=void 0;const jSe=ct,USe=ut;class qSe extends jSe.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now"},compositeFieldUsage:(0,USe.emptyCompositeFieldUsage)()}}}Dv.ExprNow=qSe;var wv={};Object.defineProperty(wv,"__esModule",{value:!0}),wv.ExprNULL=void 0;const HSe=jt,zSe=ct;class QSe extends zSe.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,HSe.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}}wv.ExprNULL=QSe;var Fv={};Object.defineProperty(Fv,"__esModule",{value:!0}),Fv.ExprNumber=void 0;const GSe=jt,WSe=ct;class VSe extends WSe.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),n=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,GSe.literalExprValue)({dataType:n,value:{node:"numberLiteral",literal:this.n}})}}Fv.ExprNumber=VSe;var Nv={};Object.defineProperty(Nv,"__esModule",{value:!0}),Nv.ExprParens=void 0;const Q7=ct;class YSe extends Q7.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const n=this.expr.getExpression(e);return{...n,value:{node:"()",e:n.value}}}apply(e,n,r,i){return this.expr.atNodeType()===Q7.ATNodeType.Or?this.expr.apply(e,n,r,i):(0,Q7.applyBinary)(e,r,n,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Nv.ExprParens=YSe;var Lv={};Object.defineProperty(Lv,"__esModule",{value:!0}),Lv.ExprRegEx=void 0;const KSe=jt,XSe=ct;class JSe extends XSe.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,KSe.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}Lv.ExprRegEx=JSe;var Iv={};Object.defineProperty(Iv,"__esModule",{value:!0}),Iv.ExprString=void 0;const ZSe=ct,eCe=jt;class tCe extends ZSe.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,eCe.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Iv.ExprString=tCe;var Bv={};Object.defineProperty(Bv,"__esModule",{value:!0}),Bv.ExprSum=void 0;const nCe=ch;class rCe extends nCe.ExprAsymmetric{constructor(e,n,r){super("sum",e,n,r),this.has({source:n})}}Bv.ExprSum=rCe;var $v={};Object.defineProperty($v,"__esModule",{value:!0}),$v.ExprTimeExtract=void 0;const za=Ke,kv=jt,G7=ct,iCe=g0;class Ng extends G7.ExpressionDef{static extractor(e){const n=Ng.pluralMap[e];if(n)return n;if((0,za.isExtractUnit)(e))return e}constructor(e,n){super({args:n}),this.extractText=e,this.args=n,this.elementType="timeExtract"}getExpression(e){const n=Ng.extractor(this.extractText);if(n){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${n} requires one argument`);const r=this.args[0];if(r instanceof iCe.Range){let i=r.first.getExpression(e),s=r.last.getExpression(e);if(i.type==="error"||s.type==="error")return(0,kv.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[i,s]});if(!(0,za.isTemporalType)(i.type))return r.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${n} from '${i.type}'`);if(!(0,za.isTemporalType)(s.type))return r.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${n} from '${s.type}'`);let o=i.type;if(!za.TD.eq(i,s)){let u=!0;if(o="timestamp",i.type==="date"){const a=(0,G7.getMorphicValue)(i,"timestamp");a&&(i=a,u=!1)}else{const a=(0,G7.getMorphicValue)(s,"timestamp");a&&(s=a,u=!1)}if(u)return r.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${i.type} to ${s.type}`)}return["week","month","quarter","year"].includes(n)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${n}'`):(0,za.isTimestampUnit)(n)?(0,kv.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:n,kids:{left:(0,za.mkTemporal)(i.value,o),right:(0,za.mkTemporal)(s.value,o)}},from:[i,s]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${n} from a range`)}else{const i=r.getExpression(e);return(0,za.isTemporalType)(i.type)?(0,kv.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,za.mkTemporal)(i.value,i.type),units:n},from:[i]}):(i.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${i.type}'`),(0,kv.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${i.type}`,from:[i]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}$v.ExprTimeExtract=Ng,Ng.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var Pv={},bo={},Mv={};Object.defineProperty(Mv,"__esModule",{value:!0}),Mv.QueryInputSpace=void 0;const sCe=Fi,oCe=Kd;class uCe extends oCe.RefinedSpace{constructor(e,n,r){super(e),this.queryOutput=n,this._isProtectedAccessSpace=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof sCe.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}Mv.QueryInputSpace=uCe;var aCe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),lCe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),cCe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&aCe(e,t,n);return lCe(e,t),e};Object.defineProperty(bo,"__esModule",{value:!0}),bo.ReduceFieldSpace=bo.QuerySpace=bo.QueryOperationSpace=void 0;const jv=cCe(Ke),W7=c0,Wz=E0,Vz=Cr,fCe=ht,xCe=Kd,dCe=hg,hCe=br,pCe=Mv,Qa=ut,gCe=Ef;class Yz extends xCe.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,n,r,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=r,this.astEl=i,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new pCe.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),n&&this.addRefineFromFields(n)}logError(e,n,r){return this.astEl&&this.astEl.logError(e,n,r),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof hCe.StructSpaceField)r=l.fieldSpace;else{u.logError("invalid-wildcard-source",`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.logError("wildcard-source-not-defined",`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries())if(!e.except.has(u)&&a.refType!=="parameter")if(this.entry(u)){const l=(n=this.expandedWild[u])===null||n===void 0?void 0:n.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{const l=a.typeDesc();jv.TD.isAtomic(l)&&jv.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:u,entry:a}),this.expandedWild[u]={path:i.concat(u),entry:a})}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.newEntry(u.name,e,u.entry)}addValidatedCompositeFieldUserFromEntry(e,n){n instanceof Vz.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:n,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var n;const r=e.map(s=>new Wz.FieldName(s));this.astEl.has({reference:r});const i=this.exprSpace.lookup(r);if(i.found&&i.found instanceof gCe.StructSpaceFieldBase)return(n=i.found.fieldDef().onCompositeFieldUsage)!==null&&n!==void 0?n:(0,Qa.emptyCompositeFieldUsage)();throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let n=e;const r=(0,Qa.compositeFieldUsageJoinPaths)(e);for(const i of r)n=(0,Qa.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(i),n);return n}addCompositeFieldUserFromFilter(e,n){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:n})}newEntry(e,n,r){r instanceof Vz.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:n}),super.newEntry(e,n,r)}applyNextCompositeFieldUsage(e,n,r,i,s){if(i){const o=this.getCompositeFieldUsageIncludingJoinOns((0,Qa.compositeFieldUsageDifference)(i,n));if(n=(0,Qa.mergeCompositeFieldUsage)(n,o),!(0,Qa.isEmptyCompositeFieldUsage)(o)){const u=(0,Qa.narrowCompositeFieldResolution)(e,n,r);u.error?(s??this).logError("invalid-composite-field-usage",{newUsage:o,allUsage:n}):r=u.narrowedCompositeFieldResolution}}return{compositeFieldUsage:n,narrowedCompositeFieldResolution:r}}}bo.QueryOperationSpace=Yz;class Kz extends Yz{addRefineFromFields(e){var n;if(jv.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const r of e.extendSource)this.exprSpace.addFieldDef(r);for(const r of e.queryFields)if(r.type==="fieldref"){const i=this.exprSpace.lookup(r.path.map(s=>new Wz.FieldName(s)));if(i.found){const s=r.path[r.path.length-1];this.setEntry(s,i.found),this.addValidatedCompositeFieldUserFromEntry(s,i.found)}}else if(r.type!=="turtle"){const i=new dCe.ColumnSpaceField(r),s=(n=r.as)!==null&&n!==void 0?n:r.name;this.setEntry(s,i),this.addValidatedCompositeFieldUserFromEntry(s,i)}}}pushFields(...e){for(const n of e)n instanceof fCe.WildcardFieldReference?this.addWild(n):super.pushFields(n)}canContain(e){return!0}queryFieldDefs(){const e=[];let n=(0,Qa.emptyCompositeFieldUsage)(),r=(0,Qa.emptyNarrowedCompositeFieldResolution)();const i=this.inputSpace().structDef();for(const s of this.compositeFieldUsers){let o;if(s.type==="filter")s.filter.compositeFieldUsage&&(o=s.filter.compositeFieldUsage);else{const{name:a,field:l}=s,c=this.expandedWild[a];if(c)e.push({type:"fieldref",path:c.path}),o=c.entry.typeDesc().compositeFieldUsage;else{const f=l.getQueryFieldDef(this.exprSpace);if(f){const x=l.typeDesc();o=x.compositeFieldUsage,x&&x.type!=="error"&&this.canContain(x)&&!yCe(f)&&e.push(f)}}}const u=this.applyNextCompositeFieldUsage(i,n,r,o,s.logTo);n=u.compositeFieldUsage,r=u.narrowedCompositeFieldResolution}return this._compositeFieldUsage=n,e}getQuerySegment(e){const n=this.getPipeSegment(e);if(jv.isQuerySegment(n))return n;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const n={type:this.segmentType,queryFields:this.queryFieldDefs()};if(n.queryFields=(0,W7.mergeFields)(e==null?void 0:e.queryFields,n.queryFields),e!=null&&e.extendSource&&(n.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const r=[],i=this.exprSpace.structDef();for(const s of this.exprSpace.extendList){const o=i.fields.find(u=>(0,W7.nameFromDef)(u)===s);o&&r.push(o)}n.extendSource=(0,W7.mergeFields)(n.extendSource,r)}return this.newTimezone&&(n.queryTimezone=this.newTimezone),n}lookup(e){const n=super.lookup(e);return n.found?{...n,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}bo.QuerySpace=Kz;class mCe extends Kz{constructor(){super(...arguments),this.segmentType="reduce"}}bo.ReduceFieldSpace=mCe;function yCe(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var ECe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),ACe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_Ce=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&ECe(e,t,n);return ACe(e,t),e};Object.defineProperty(Pv,"__esModule",{value:!0}),Pv.ExprUngroup=void 0;const Xz=Ke,vCe=bo,Jz=_Ce(Wt),SCe=ct;class CCe extends SCe.ExpressionDef{constructor(e,n,r){super({expr:n,fields:r}),this.control=e,this.expr=n,this.fields=r,this.legalChildTypes=Jz.anyAtomicT,this.elementType="ungroup"}getExpression(e){const n=this.expr.getExpression(e);if(!(0,Xz.expressionIsAggregate)(n.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Xz.expressionIsUngroupedAggregate)(n.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const r={node:this.control,e:n.value};if(this.typeCheck(this.expr,{...n,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const i=[],s=this.control==="exclude";for(const o of this.fields){let u=e.outputSpace(),a=!0;for(;u;){const l=u.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),a=!1;else if(u instanceof vCe.QuerySpace){u=u.nestParent;continue}break}if(a){const l=s?"exclude()":"all()";o.logError("ungroup-field-not-in-output",`${l} '${o.refString}' is missing from query output`)}}r.fields=i}return{...Jz.atomicDef(n),expressionType:"ungrouped_aggregate",value:r,evalSpace:"output",compositeFieldUsage:n.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}Pv.ExprUngroup=CCe;var Uv={},bCe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),TCe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),RCe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&bCe(e,t,n);return TCe(e,t),e};Object.defineProperty(Uv,"__esModule",{value:!0}),Uv.ForRange=void 0;const OCe=fs,Zz=RCe(Wt),qv=Ni,DCe=jt,wCe=ct,Hv=uh,eQ=g0;class FCe extends wCe.ExpressionDef{constructor(e,n,r){super({from:e,duration:n,timeframe:r}),this.from=e,this.duration=n,this.timeframe=r,this.elementType="forRange",this.legalChildTypes=[Zz.timestampT,Zz.dateT]}apply(e,n,r){const i=this.from.getExpression(e),s=r.getExpression(e);if(!this.typeCheck(r,s))return(0,OCe.errorFor)("no time for range");const o=this.duration.getExpression(e);if(o.type!=="number")return o.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${o.type}'`),(0,DCe.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[i,s]});const u=this.timeframe.text;let a=(0,qv.resolution)(u);if(i.type==="timestamp"&&(a="timestamp"),s.type==="date"&&a==="date"){const p=this.from,m=(0,qv.timeOffset)("date",i.value,"+",o.value,u),g=new Hv.ExprTime("date",m);return new eQ.Range(p,g).apply(e,n,r)}const l=Hv.ExprTime.fromValue("timestamp",s);let c=this.from,f=i.value;if(i.type==="date"){const p=i.morphic&&i.morphic.timestamp;p?f=p:f=(0,qv.castTo)("timestamp",f,"date"),c=new Hv.ExprTime("timestamp",f,[i])}const x=(0,qv.timeOffset)("timestamp",f,"+",o.value,u),h=new Hv.ExprTime("timestamp",x,[i,o]);return new eQ.Range(c,h).apply(e,n,l)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Uv.ForRange=FCe;var rr={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});class Sf extends Error{}class NCe extends Sf{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class LCe extends Sf{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class ICe extends Sf{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Lg extends Sf{}class tQ extends Sf{constructor(e){super(`Invalid unit ${e}`)}}class Ps extends Sf{}class A0 extends Sf{constructor(){super("Zone is an abstract class")}}const je="numeric",To="short",hs="long",V7={year:je,month:je,day:je},nQ={year:je,month:To,day:je},BCe={year:je,month:To,day:je,weekday:To},rQ={year:je,month:hs,day:je},iQ={year:je,month:hs,day:je,weekday:hs},sQ={hour:je,minute:je},oQ={hour:je,minute:je,second:je},uQ={hour:je,minute:je,second:je,timeZoneName:To},aQ={hour:je,minute:je,second:je,timeZoneName:hs},lQ={hour:je,minute:je,hourCycle:"h23"},cQ={hour:je,minute:je,second:je,hourCycle:"h23"},fQ={hour:je,minute:je,second:je,hourCycle:"h23",timeZoneName:To},xQ={hour:je,minute:je,second:je,hourCycle:"h23",timeZoneName:hs},dQ={year:je,month:je,day:je,hour:je,minute:je},hQ={year:je,month:je,day:je,hour:je,minute:je,second:je},pQ={year:je,month:To,day:je,hour:je,minute:je},gQ={year:je,month:To,day:je,hour:je,minute:je,second:je},$Ce={year:je,month:To,day:je,weekday:To,hour:je,minute:je},mQ={year:je,month:hs,day:je,hour:je,minute:je,timeZoneName:To},yQ={year:je,month:hs,day:je,hour:je,minute:je,second:je,timeZoneName:To},EQ={year:je,month:hs,day:je,weekday:hs,hour:je,minute:je,timeZoneName:hs},AQ={year:je,month:hs,day:je,weekday:hs,hour:je,minute:je,second:je,timeZoneName:hs};function Tt(t){return typeof t>"u"}function Cf(t){return typeof t=="number"}function zv(t){return typeof t=="number"&&t%1===0}function kCe(t){return typeof t=="string"}function PCe(t){return Object.prototype.toString.call(t)==="[object Date]"}function _Q(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function MCe(t){return Array.isArray(t)?t:[t]}function vQ(t,e,n){if(t.length!==0)return t.reduce((r,i)=>{const s=[e(i),i];return r&&n(r[0],s[0])===r[0]?r:s},null)[1]}function jCe(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function dh(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ga(t,e,n){return zv(t)&&t>=e&&t<=n}function UCe(t,e){return t-e*Math.floor(t/e)}function Bn(t,e=2){const n=t<0;let r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function _0(t){if(!(Tt(t)||t===null||t===""))return parseInt(t,10)}function bf(t){if(!(Tt(t)||t===null||t===""))return parseFloat(t)}function Y7(t){if(!(Tt(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function K7(t,e,n=!1){const r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function Ig(t){return t%4===0&&(t%100!==0||t%400===0)}function Bg(t){return Ig(t)?366:365}function Qv(t,e){const n=UCe(e-1,12)+1,r=t+(e-n)/12;return n===2?Ig(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function X7(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 Gv(t){const e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,n=t-1,r=(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400))%7;return e===4||r===3?53:52}function J7(t){return t>99?t:t>60?1900+t:2e3+t}function SQ(t,e,n,r=null){const i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(s.timeZone=r);const o={timeZoneName:e,...s},u=new Intl.DateTimeFormat(n,o).formatToParts(i).find(a=>a.type.toLowerCase()==="timezonename");return u?u.value:null}function Wv(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const r=parseInt(e,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function CQ(t){const e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new Ps(`Invalid unit value ${t}`);return e}function Vv(t,e){const n={};for(const r in t)if(dh(t,r)){const i=t[r];if(i==null)continue;n[e(r)]=CQ(i)}return n}function $g(t,e){const n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Bn(n,2)}:${Bn(r,2)}`;case"narrow":return`${i}${n}${r>0?`:${r}`:""}`;case"techie":return`${i}${Bn(n,2)}${Bn(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Yv(t){return jCe(t,["hour","minute","second","millisecond"])}const bQ=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,qCe=["January","February","March","April","May","June","July","August","September","October","November","December"],TQ=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],HCe=["J","F","M","A","M","J","J","A","S","O","N","D"];function RQ(t){switch(t){case"narrow":return[...HCe];case"short":return[...TQ];case"long":return[...qCe];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const OQ=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],DQ=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],zCe=["M","T","W","T","F","S","S"];function wQ(t){switch(t){case"narrow":return[...zCe];case"short":return[...DQ];case"long":return[...OQ];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const FQ=["AM","PM"],QCe=["Before Christ","Anno Domini"],GCe=["BC","AD"],WCe=["B","A"];function NQ(t){switch(t){case"narrow":return[...WCe];case"short":return[...GCe];case"long":return[...QCe];default:return null}}function VCe(t){return FQ[t.hour<12?0:1]}function YCe(t,e){return wQ(e)[t.weekday-1]}function KCe(t,e){return RQ(e)[t.month-1]}function XCe(t,e){return NQ(e)[t.year<0?0:1]}function JCe(t,e,n="always",r=!1){const i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},s=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&s){const f=t==="days";switch(e){case 1:return f?"tomorrow":`next ${i[t][0]}`;case-1:return f?"yesterday":`last ${i[t][0]}`;case 0:return f?"today":`this ${i[t][0]}`}}const o=Object.is(e,-0)||e<0,u=Math.abs(e),a=u===1,l=i[t],c=r?a?l[1]:l[2]||l[1]:a?i[t][0]:t;return o?`${u} ${c} ago`:`in ${u} ${c}`}function LQ(t,e){let n="";for(const r of t)r.literal?n+=r.val:n+=e(r.val);return n}const ZCe={D:V7,DD:nQ,DDD:rQ,DDDD:iQ,t:sQ,tt:oQ,ttt:uQ,tttt:aQ,T:lQ,TT:cQ,TTT:fQ,TTTT:xQ,f:dQ,ff:pQ,fff:mQ,ffff:EQ,F:hQ,FF:gQ,FFF:yQ,FFFF:AQ};class Ii{static create(e,n={}){return new Ii(e,n)}static parseFormat(e){let n=null,r="",i=!1;const s=[];for(let o=0;o<e.length;o++){const u=e.charAt(o);u==="'"?(r.length>0&&s.push({literal:i,val:r}),n=null,r="",i=!i):i||u===n?r+=u:(r.length>0&&s.push({literal:!1,val:r}),r=u,n=u)}return r.length>0&&s.push({literal:i,val:r}),s}static macroTokenToFormatOpts(e){return ZCe[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTime(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTimeParts(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).formatToParts()}resolvedOptions(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Bn(e,n);const r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const r=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(h,p)=>this.loc.extract(e,h,p),o=h=>e.isOffsetFixed&&e.offset===0&&h.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,h.format):"",u=()=>r?VCe(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),a=(h,p)=>r?KCe(e,h):s(p?{month:h}:{month:h,day:"numeric"},"month"),l=(h,p)=>r?YCe(e,h):s(p?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),c=h=>{const p=Ii.macroTokenToFormatOpts(h);return p?this.formatWithSystemDefault(e,p):h},f=h=>r?XCe(e,h):s({era:h},"era"),x=h=>{switch(h){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return u();case"d":return i?s({day:"numeric"},"day"):this.num(e.day);case"dd":return i?s({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?s({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?s({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return a("short",!0);case"LLLL":return a("long",!0);case"LLLLL":return a("narrow",!0);case"M":return i?s({month:"numeric"},"month"):this.num(e.month);case"MM":return i?s({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return a("short",!1);case"MMMM":return a("long",!1);case"MMMMM":return a("narrow",!1);case"y":return i?s({year:"numeric"},"year"):this.num(e.year);case"yy":return i?s({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?s({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?s({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(h)}};return LQ(Ii.parseFormat(n),x)}formatDurationFromString(e,n){const r=a=>{switch(a[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=a=>l=>{const c=r(l);return c?this.num(a.get(c),l.length):l},s=Ii.parseFormat(n),o=s.reduce((a,{literal:l,val:c})=>l?a:a.concat(c),[]),u=e.shiftTo(...o.map(r).filter(a=>a));return LQ(s,i(u))}}class Ro{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}let hh=class{get type(){throw new A0}get name(){throw new A0}get ianaName(){return this.name}get isUniversal(){throw new A0}offsetName(e,n){throw new A0}formatOffset(e,n){throw new A0}offset(e){throw new A0}equals(e){throw new A0}get isValid(){throw new A0}},Z7=null;class Kv extends hh{static get instance(){return Z7===null&&(Z7=new Kv),Z7}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return SQ(e,n,r)}formatOffset(e,n){return $g(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}let Xv={};function e4e(t){return Xv[t]||(Xv[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"})),Xv[t]}const t4e={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function n4e(t,e){const n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,i,s,o,u,a,l,c]=r;return[o,i,s,u,a,l,c]}function r4e(t,e){const n=t.formatToParts(e),r=[];for(let i=0;i<n.length;i++){const{type:s,value:o}=n[i],u=t4e[s];s==="era"?r[u]=o:Tt(u)||(r[u]=parseInt(o,10))}return r}let Jv={};class Fu extends hh{static create(e){return Jv[e]||(Jv[e]=new Fu(e)),Jv[e]}static resetCache(){Jv={},Xv={}}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=Fu.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return SQ(e,n,r,this.name)}formatOffset(e,n){return $g(this.offset(e),n)}offset(e){const n=new Date(e);if(isNaN(n))return NaN;const r=e4e(this.name);let[i,s,o,u,a,l,c]=r.formatToParts?r4e(r,n):n4e(r,n);u==="BC"&&(i=-Math.abs(i)+1);const x=X7({year:i,month:s,day:o,hour:a===24?0:a,minute:l,second:c,millisecond:0});let h=+n;const p=h%1e3;return h-=p>=0?p:1e3+p,(x-h)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let eD=null;class qr extends hh{static get utcInstance(){return eD===null&&(eD=new qr(0)),eD}static instance(e){return e===0?qr.utcInstance:new qr(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new qr(Wv(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${$g(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${$g(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return $g(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class IQ extends hh{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 v0(t,e){if(Tt(t)||t===null)return e;if(t instanceof hh)return t;if(kCe(t)){const n=t.toLowerCase();return n==="local"||n==="system"?e:n==="utc"||n==="gmt"?qr.utcInstance:qr.parseSpecifier(n)||Fu.create(t)}else return Cf(t)?qr.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new IQ(t)}let BQ=()=>Date.now(),$Q="system",kQ=null,PQ=null,MQ=null,jQ;class $n{static get now(){return BQ}static set now(e){BQ=e}static set defaultZone(e){$Q=e}static get defaultZone(){return v0($Q,Kv.instance)}static get defaultLocale(){return kQ}static set defaultLocale(e){kQ=e}static get defaultNumberingSystem(){return PQ}static set defaultNumberingSystem(e){PQ=e}static get defaultOutputCalendar(){return MQ}static set defaultOutputCalendar(e){MQ=e}static get throwOnInvalid(){return jQ}static set throwOnInvalid(e){jQ=e}static resetCaches(){gn.resetCache(),Fu.resetCache()}}let UQ={};function i4e(t,e={}){const n=JSON.stringify([t,e]);let r=UQ[n];return r||(r=new Intl.ListFormat(t,e),UQ[n]=r),r}let tD={};function nD(t,e={}){const n=JSON.stringify([t,e]);let r=tD[n];return r||(r=new Intl.DateTimeFormat(t,e),tD[n]=r),r}let rD={};function s4e(t,e={}){const n=JSON.stringify([t,e]);let r=rD[n];return r||(r=new Intl.NumberFormat(t,e),rD[n]=r),r}let iD={};function o4e(t,e={}){const{base:n,...r}=e,i=JSON.stringify([t,r]);let s=iD[i];return s||(s=new Intl.RelativeTimeFormat(t,e),iD[i]=s),s}let kg=null;function u4e(){return kg||(kg=new Intl.DateTimeFormat().resolvedOptions().locale,kg)}function a4e(t){const e=t.indexOf("-u-");if(e===-1)return[t];{let n;const r=t.substring(0,e);try{n=nD(t).resolvedOptions()}catch{n=nD(r).resolvedOptions()}const{numberingSystem:i,calendar:s}=n;return[r,i,s]}}function l4e(t,e,n){return(n||e)&&(t+="-u",n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function c4e(t){const e=[];for(let n=1;n<=12;n++){const r=ft.utc(2016,n,1);e.push(t(r))}return e}function f4e(t){const e=[];for(let n=1;n<=7;n++){const r=ft.utc(2016,11,13+n);e.push(t(r))}return e}function Zv(t,e,n,r,i){const s=t.listingMode(n);return s==="error"?null:s==="en"?r(e):i(e)}function x4e(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}class d4e{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;const{padTo:i,floor:s,...o}=r;if(!n||Object.keys(o).length>0){const u={useGrouping:!1,...r};r.padTo>0&&(u.minimumIntegerDigits=r.padTo),this.inf=s4e(e,u)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):K7(e,3);return Bn(n,this.padTo)}}}class h4e{constructor(e,n,r){this.opts=r;let i;if(e.zone.isUniversal){const o=-1*(e.offset/60),u=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&Fu.create(u).valid?(i=u,this.dt=e):(i="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:ft.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);const s={...this.opts};i&&(s.timeZone=i),this.dtf=nD(n,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}}class p4e{constructor(e,n,r){this.opts={style:"long",...r},!n&&_Q()&&(this.rtf=o4e(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):JCe(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}class gn{static fromOpts(e){return gn.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,n,r,i=!1){const s=e||$n.defaultLocale,o=s||(i?"en-US":u4e()),u=n||$n.defaultNumberingSystem,a=r||$n.defaultOutputCalendar;return new gn(o,u,a,s)}static resetCache(){kg=null,tD={},rD={},iD={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r}={}){return gn.create(e,n,r)}constructor(e,n,r,i){const[s,o,u]=a4e(e);this.locale=s,this.numberingSystem=n||o||null,this.outputCalendar=r||u||null,this.intl=l4e(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=x4e(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:gn.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1,r=!0){return Zv(this,e,r,RQ,()=>{const i=n?{month:e,day:"numeric"}:{month:e},s=n?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=c4e(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,n=!1,r=!0){return Zv(this,e,r,wQ,()=>{const i=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=n?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=f4e(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return Zv(this,void 0,e,()=>FQ,()=>{if(!this.meridiemCache){const n={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ft.utc(2016,11,13,9),ft.utc(2016,11,13,19)].map(r=>this.extract(r,n,"dayperiod"))}return this.meridiemCache})}eras(e,n=!0){return Zv(this,e,n,NQ,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[ft.utc(-40,1,1),ft.utc(2017,1,1)].map(i=>this.extract(i,r,"era"))),this.eraCache[e]})}extract(e,n,r){const i=this.dtFormatter(e,n),s=i.formatToParts(),o=s.find(u=>u.type.toLowerCase()===r);return o?o.value:null}numberFormatter(e={}){return new d4e(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new h4e(e,this.intl,n)}relFormatter(e={}){return new p4e(this.intl,this.isEnglish(),e)}listFormatter(e={}){return i4e(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 ph(...t){const e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function gh(...t){return e=>t.reduce(([n,r,i],s)=>{const[o,u,a]=s(e,i);return[{...n,...o},u||r,a]},[{},null,1]).slice(0,2)}function mh(t,...e){if(t==null)return[null,null];for(const[n,r]of e){const i=n.exec(t);if(i)return r(i)}return[null,null]}function qQ(...t){return(e,n)=>{const r={};let i;for(i=0;i<t.length;i++)r[t[i]]=_0(e[n+i]);return[r,null,n+i]}}const HQ=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,g4e=`(?:${HQ.source}?(?:\\[(${bQ.source})\\])?)?`,sD=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,zQ=RegExp(`${sD.source}${g4e}`),oD=RegExp(`(?:T${zQ.source})?`),m4e=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,y4e=/(\d{4})-?W(\d\d)(?:-?(\d))?/,E4e=/(\d{4})-?(\d{3})/,A4e=qQ("weekYear","weekNumber","weekDay"),_4e=qQ("year","ordinal"),v4e=/(\d{4})-(\d\d)-(\d\d)/,QQ=RegExp(`${sD.source} ?(?:${HQ.source}|(${bQ.source}))?`),S4e=RegExp(`(?: ${QQ.source})?`);function yh(t,e,n){const r=t[e];return Tt(r)?n:_0(r)}function C4e(t,e){return[{year:yh(t,e),month:yh(t,e+1,1),day:yh(t,e+2,1)},null,e+3]}function Eh(t,e){return[{hours:yh(t,e,0),minutes:yh(t,e+1,0),seconds:yh(t,e+2,0),milliseconds:Y7(t[e+3])},null,e+4]}function Pg(t,e){const n=!t[e]&&!t[e+1],r=Wv(t[e+1],t[e+2]),i=n?null:qr.instance(r);return[{},i,e+3]}function Mg(t,e){const n=t[e]?Fu.create(t[e]):null;return[{},n,e+1]}const b4e=RegExp(`^T?${sD.source}$`),T4e=/^-?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 R4e(t){const[e,n,r,i,s,o,u,a,l]=t,c=e[0]==="-",f=a&&a[0]==="-",x=(h,p=!1)=>h!==void 0&&(p||h&&c)?-h:h;return[{years:x(bf(n)),months:x(bf(r)),weeks:x(bf(i)),days:x(bf(s)),hours:x(bf(o)),minutes:x(bf(u)),seconds:x(bf(a),a==="-0"),milliseconds:x(Y7(l),f)}]}const O4e={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 uD(t,e,n,r,i,s,o){const u={year:e.length===2?J7(_0(e)):_0(e),month:TQ.indexOf(n)+1,day:_0(r),hour:_0(i),minute:_0(s)};return o&&(u.second=_0(o)),t&&(u.weekday=t.length>3?OQ.indexOf(t)+1:DQ.indexOf(t)+1),u}const D4e=/^(?:(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 w4e(t){const[,e,n,r,i,s,o,u,a,l,c,f]=t,x=uD(e,i,r,n,s,o,u);let h;return a?h=O4e[a]:l?h=0:h=Wv(c,f),[x,new qr(h)]}function F4e(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const N4e=/^(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$/,L4e=/^(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$/,I4e=/^(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 GQ(t){const[,e,n,r,i,s,o,u]=t;return[uD(e,i,r,n,s,o,u),qr.utcInstance]}function B4e(t){const[,e,n,r,i,s,o,u]=t;return[uD(e,u,n,r,i,s,o),qr.utcInstance]}const $4e=ph(m4e,oD),k4e=ph(y4e,oD),P4e=ph(E4e,oD),M4e=ph(zQ),WQ=gh(C4e,Eh,Pg,Mg),j4e=gh(A4e,Eh,Pg,Mg),U4e=gh(_4e,Eh,Pg,Mg),q4e=gh(Eh,Pg,Mg);function H4e(t){return mh(t,[$4e,WQ],[k4e,j4e],[P4e,U4e],[M4e,q4e])}function z4e(t){return mh(F4e(t),[D4e,w4e])}function Q4e(t){return mh(t,[N4e,GQ],[L4e,GQ],[I4e,B4e])}function G4e(t){return mh(t,[T4e,R4e])}const W4e=gh(Eh);function V4e(t){return mh(t,[b4e,W4e])}const Y4e=ph(v4e,S4e),K4e=ph(QQ),X4e=gh(Eh,Pg,Mg);function J4e(t){return mh(t,[Y4e,WQ],[K4e,X4e])}const Z4e="Invalid Duration",VQ={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}},ebe={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},...VQ},Ms=146097/400,Ah=146097/4800,tbe={years:{quarters:4,months:12,weeks:Ms/7,days:Ms,hours:Ms*24,minutes:Ms*24*60,seconds:Ms*24*60*60,milliseconds:Ms*24*60*60*1e3},quarters:{months:3,weeks:Ms/28,days:Ms/4,hours:Ms*24/4,minutes:Ms*24*60/4,seconds:Ms*24*60*60/4,milliseconds:Ms*24*60*60*1e3/4},months:{weeks:Ah/7,days:Ah,hours:Ah*24,minutes:Ah*24*60,seconds:Ah*24*60*60,milliseconds:Ah*24*60*60*1e3},...VQ},Tf=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],nbe=Tf.slice(0).reverse();function Rf(t,e,n=!1){const r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new Rt(r)}function rbe(t){return t<0?Math.floor(t):Math.ceil(t)}function YQ(t,e,n,r,i){const s=t[i][n],o=e[n]/s,u=Math.sign(o)===Math.sign(r[i]),a=!u&&r[i]!==0&&Math.abs(o)<=1?rbe(o):Math.trunc(o);r[i]+=a,e[n]-=a*s}function ibe(t,e){nbe.reduce((n,r)=>Tt(e[r])?n:(n&&YQ(t,e,n,e,r),r),null)}class Rt{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||gn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n?tbe:ebe,this.isLuxonDuration=!0}static fromMillis(e,n){return Rt.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new Ps(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new Rt({values:Vv(e,Rt.normalizeUnit),loc:gn.fromObject(n),conversionAccuracy:n.conversionAccuracy})}static fromDurationLike(e){if(Cf(e))return Rt.fromMillis(e);if(Rt.isDuration(e))return e;if(typeof e=="object")return Rt.fromObject(e);throw new Ps(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[r]=G4e(e);return r?Rt.fromObject(r,n):Rt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[r]=V4e(e);return r?Rt.fromObject(r,n):Rt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new Ps("need to specify a reason the Duration is invalid");const r=e instanceof Ro?e:new Ro(e,n);if($n.throwOnInvalid)throw new ICe(r);return new Rt({invalid:r})}static normalizeUnit(e){const n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new tQ(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){const r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?Ii.create(this.loc,r).formatDurationFromString(this,e):Z4e}toHuman(e={}){const n=Tf.map(r=>{const i=this.values[r];return Tt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=K7(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();if(n<0||n>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};const r=this.shiftTo("hours","minutes","seconds","milliseconds");let i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||r.seconds!==0||r.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||r.milliseconds!==0)&&(i+=".SSS"));let s=r.toFormat(i);return e.includePrefix&&(s="T"+s),s}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=Rt.fromDurationLike(e),r={};for(const i of Tf)(dh(n.values,i)||dh(this.values,i))&&(r[i]=n.get(i)+this.get(i));return Rf(this,{values:r},!0)}minus(e){if(!this.isValid)return this;const n=Rt.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const r of Object.keys(this.values))n[r]=CQ(e(this.values[r],r));return Rf(this,{values:n},!0)}get(e){return this[Rt.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...Vv(e,Rt.normalizeUnit)};return Rf(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n}),s={loc:i};return r&&(s.conversionAccuracy=r),Rf(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return ibe(this.matrix,e),Rf(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>Rt.normalizeUnit(o));const n={},r={},i=this.toObject();let s;for(const o of Tf)if(e.indexOf(o)>=0){s=o;let u=0;for(const l in r)u+=this.matrix[l][o]*r[l],r[l]=0;Cf(i[o])&&(u+=i[o]);const a=Math.trunc(u);n[o]=a,r[o]=(u*1e3-a*1e3)/1e3;for(const l in i)Tf.indexOf(l)>Tf.indexOf(o)&&YQ(this.matrix,i,l,n,o)}else Cf(i[o])&&(r[o]=i[o]);for(const o in r)r[o]!==0&&(n[s]+=o===s?r[o]:r[o]/this.matrix[s][o]);return Rf(this,{values:n},!0).normalize()}negate(){if(!this.isValid)return this;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Rf(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(r,i){return r===void 0||r===0?i===void 0||i===0:r===i}for(const r of Tf)if(!n(this.values[r],e.values[r]))return!1;return!0}}const jg="Invalid Interval";function sbe(t,e){return!t||!t.isValid?mn.invalid("missing or invalid start"):!e||!e.isValid?mn.invalid("missing or invalid end"):e<t?mn.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class mn{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new Ps("need to specify a reason the Interval is invalid");const r=e instanceof Ro?e:new Ro(e,n);if($n.throwOnInvalid)throw new LCe(r);return new mn({invalid:r})}static fromDateTimes(e,n){const r=zg(e),i=zg(n),s=sbe(r,i);return s??new mn({start:r,end:i})}static after(e,n){const r=Rt.fromDurationLike(n),i=zg(e);return mn.fromDateTimes(i,i.plus(r))}static before(e,n){const r=Rt.fromDurationLike(n),i=zg(e);return mn.fromDateTimes(i.minus(r),i)}static fromISO(e,n){const[r,i]=(e||"").split("/",2);if(r&&i){let s,o;try{s=ft.fromISO(r,n),o=s.isValid}catch{o=!1}let u,a;try{u=ft.fromISO(i,n),a=u.isValid}catch{a=!1}if(o&&a)return mn.fromDateTimes(s,u);if(o){const l=Rt.fromISO(i,n);if(l.isValid)return mn.after(s,l)}else if(a){const l=Rt.fromISO(r,n);if(l.isValid)return mn.before(u,l)}}return mn.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;const n=this.start.startOf(e),r=this.end.startOf(e);return Math.floor(r.diff(n,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?mn.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(zg).filter(o=>this.contains(o)).sort(),r=[];let{s:i}=this,s=0;for(;i<this.e;){const o=n[s]||this.e,u=+o>+this.e?this.e:o;r.push(mn.fromDateTimes(i,u)),i=u,s+=1}return r}splitBy(e){const n=Rt.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,i=1,s;const o=[];for(;r<this.e;){const u=this.start.plus(n.mapUnits(a=>a*i));s=+u>+this.e?this.e:u,o.push(mn.fromDateTimes(r,s)),r=s,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:mn.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return mn.fromDateTimes(n,r)}static merge(e){const[n,r]=e.sort((i,s)=>i.s-s.s).reduce(([i,s],o)=>s?s.overlaps(o)||s.abutsStart(o)?[i,s.union(o)]:[i.concat([s]),o]:[i,o],[[],null]);return r&&n.push(r),n}static xor(e){let n=null,r=0;const i=[],s=e.map(a=>[{time:a.s,type:"s"},{time:a.e,type:"e"}]),o=Array.prototype.concat(...s),u=o.sort((a,l)=>a.time-l.time);for(const a of u)r+=a.type==="s"?1:-1,r===1?n=a.time:(n&&+n!=+a.time&&i.push(mn.fromDateTimes(n,a.time)),n=null);return mn.merge(i)}difference(...e){return mn.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:jg}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:jg}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:jg}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:jg}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:jg}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):Rt.invalid(this.invalidReason)}mapEndpoints(e){return mn.fromDateTimes(e(this.s),e(this.e))}}let Ug=class{static hasDST(e=$n.defaultZone){const n=ft.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Fu.isValidZone(e)}static normalizeZone(e){return v0(e,$n.defaultZone)}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||gn.create(n,r,s)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||gn.create(n,r,s)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||gn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||gn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return gn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return gn.create(n,null,"gregory").eras(e)}static features(){return{relative:_Q()}}};function KQ(t,e){const n=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(Rt.fromMillis(r).as("days"))}function obe(t,e,n){const r=[["years",(u,a)=>a.year-u.year],["quarters",(u,a)=>a.quarter-u.quarter],["months",(u,a)=>a.month-u.month+(a.year-u.year)*12],["weeks",(u,a)=>{const l=KQ(u,a);return(l-l%7)/7}],["days",KQ]],i={};let s,o;for(const[u,a]of r)if(n.indexOf(u)>=0){s=u;let l=a(t,e);o=t.plus({[u]:l}),o>e?(t=t.plus({[u]:l-1}),l-=1):t=o,i[u]=l}return[t,i,o,s]}function ube(t,e,n,r){let[i,s,o,u]=obe(t,e,n);const a=e-i,l=n.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[u]:1})),o!==i&&(s[u]=(s[u]||0)+a/(o-i)));const c=Rt.fromObject(s,r);return l.length>0?Rt.fromMillis(a,r).shiftTo(...l).plus(c):c}const aD={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},XQ={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]},abe=aD.hanidec.replace(/[\[|\]]/g,"").split("");function lbe(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);if(t[n].search(aD.hanidec)!==-1)e+=abe.indexOf(t[n]);else for(const i in XQ){const[s,o]=XQ[i];r>=s&&r<=o&&(e+=r-s)}}return parseInt(e,10)}else return e}function Oo({numberingSystem:t},e=""){return new RegExp(`${aD[t||"latn"]}${e}`)}const cbe="missing Intl.DateTimeFormat.formatToParts support";function Pt(t,e=n=>n){return{regex:t,deser:([n])=>e(lbe(n))}}const JQ="[  ]",ZQ=new RegExp(JQ,"g");function fbe(t){return t.replace(/\./g,"\\.?").replace(ZQ,JQ)}function eG(t){return t.replace(/\./g,"").replace(ZQ," ").toLowerCase()}function Do(t,e){return t===null?null:{regex:RegExp(t.map(fbe).join("|")),deser:([n])=>t.findIndex(r=>eG(n)===eG(r))+e}}function tG(t,e){return{regex:t,deser:([,n,r])=>Wv(n,r),groups:e}}function lD(t){return{regex:t,deser:([e])=>e}}function xbe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function dbe(t,e){const n=Oo(e),r=Oo(e,"{2}"),i=Oo(e,"{3}"),s=Oo(e,"{4}"),o=Oo(e,"{6}"),u=Oo(e,"{1,2}"),a=Oo(e,"{1,3}"),l=Oo(e,"{1,6}"),c=Oo(e,"{1,9}"),f=Oo(e,"{2,4}"),x=Oo(e,"{4,6}"),h=g=>({regex:RegExp(xbe(g.val)),deser:([y])=>y,literal:!0}),m=(g=>{if(t.literal)return h(g);switch(g.val){case"G":return Do(e.eras("short",!1),0);case"GG":return Do(e.eras("long",!1),0);case"y":return Pt(l);case"yy":return Pt(f,J7);case"yyyy":return Pt(s);case"yyyyy":return Pt(x);case"yyyyyy":return Pt(o);case"M":return Pt(u);case"MM":return Pt(r);case"MMM":return Do(e.months("short",!0,!1),1);case"MMMM":return Do(e.months("long",!0,!1),1);case"L":return Pt(u);case"LL":return Pt(r);case"LLL":return Do(e.months("short",!1,!1),1);case"LLLL":return Do(e.months("long",!1,!1),1);case"d":return Pt(u);case"dd":return Pt(r);case"o":return Pt(a);case"ooo":return Pt(i);case"HH":return Pt(r);case"H":return Pt(u);case"hh":return Pt(r);case"h":return Pt(u);case"mm":return Pt(r);case"m":return Pt(u);case"q":return Pt(u);case"qq":return Pt(r);case"s":return Pt(u);case"ss":return Pt(r);case"S":return Pt(a);case"SSS":return Pt(i);case"u":return lD(c);case"uu":return lD(u);case"uuu":return Pt(n);case"a":return Do(e.meridiems(),0);case"kkkk":return Pt(s);case"kk":return Pt(f,J7);case"W":return Pt(u);case"WW":return Pt(r);case"E":case"c":return Pt(n);case"EEE":return Do(e.weekdays("short",!1,!1),1);case"EEEE":return Do(e.weekdays("long",!1,!1),1);case"ccc":return Do(e.weekdays("short",!0,!1),1);case"cccc":return Do(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return tG(new RegExp(`([+-]${u.source})(?::(${r.source}))?`),2);case"ZZZ":return tG(new RegExp(`([+-]${u.source})(${r.source})?`),2);case"z":return lD(/[a-z_+-/]{1,256}?/i);default:return h(g)}})(t)||{invalidReason:cbe};return m.token=t,m}const hbe={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 pbe(t,e,n){const{type:r,value:i}=t;if(r==="literal")return{literal:!0,val:i};const s=n[r];let o=hbe[r];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function gbe(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function mbe(t,e,n){const r=t.match(e);if(r){const i={};let s=1;for(const o in n)if(dh(n,o)){const u=n[o],a=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(r.slice(s,s+a))),s+=a}return[r,i]}else return[r,{}]}function ybe(t){const e=s=>{switch(s){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let n=null,r;return Tt(t.z)||(n=Fu.create(t.z)),Tt(t.Z)||(n||(n=new qr(t.Z)),r=t.Z),Tt(t.q)||(t.M=(t.q-1)*3+1),Tt(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),Tt(t.u)||(t.S=Y7(t.u)),[Object.keys(t).reduce((s,o)=>{const u=e(o);return u&&(s[u]=t[o]),s},{}),n,r]}let cD=null;function Ebe(){return cD||(cD=ft.fromMillis(1555555555555)),cD}function Abe(t,e){if(t.literal)return t;const n=Ii.macroTokenToFormatOpts(t.val);if(!n)return t;const s=Ii.create(e,n).formatDateTimeParts(Ebe()).map(o=>pbe(o,e,n));return s.includes(void 0)?t:s}function _be(t,e){return Array.prototype.concat(...t.map(n=>Abe(n,e)))}function nG(t,e,n){const r=_be(Ii.parseFormat(n),t),i=r.map(o=>dbe(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:r,invalidReason:s.invalidReason};{const[o,u]=gbe(i),a=RegExp(o,"i"),[l,c]=mbe(e,a,u),[f,x,h]=c?ybe(c):[null,null,void 0];if(dh(c,"a")&&dh(c,"H"))throw new Lg("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:r,regex:a,rawMatches:l,matches:c,result:f,zone:x,specificOffset:h}}}function vbe(t,e,n){const{result:r,zone:i,specificOffset:s,invalidReason:o}=nG(t,e,n);return[r,i,s,o]}const rG=[0,31,59,90,120,151,181,212,243,273,304,334],iG=[0,31,60,91,121,152,182,213,244,274,305,335];function js(t,e){return new Ro("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function sG(t,e,n){const r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);const i=r.getUTCDay();return i===0?7:i}function oG(t,e,n){return n+(Ig(t)?iG:rG)[e-1]}function uG(t,e){const n=Ig(t)?iG:rG,r=n.findIndex(s=>s<e),i=e-n[r];return{month:r+1,day:i}}function fD(t){const{year:e,month:n,day:r}=t,i=oG(e,n,r),s=sG(e,n,r);let o=Math.floor((i-s+10)/7),u;return o<1?(u=e-1,o=Gv(u)):o>Gv(e)?(u=e+1,o=1):u=e,{weekYear:u,weekNumber:o,weekday:s,...Yv(t)}}function aG(t){const{weekYear:e,weekNumber:n,weekday:r}=t,i=sG(e,1,4),s=Bg(e);let o=n*7+r-i-3,u;o<1?(u=e-1,o+=Bg(u)):o>s?(u=e+1,o-=Bg(e)):u=e;const{month:a,day:l}=uG(u,o);return{year:u,month:a,day:l,...Yv(t)}}function xD(t){const{year:e,month:n,day:r}=t,i=oG(e,n,r);return{year:e,ordinal:i,...Yv(t)}}function lG(t){const{year:e,ordinal:n}=t,{month:r,day:i}=uG(e,n);return{year:e,month:r,day:i,...Yv(t)}}function Sbe(t){const e=zv(t.weekYear),n=Ga(t.weekNumber,1,Gv(t.weekYear)),r=Ga(t.weekday,1,7);return e?n?r?!1:js("weekday",t.weekday):js("week",t.week):js("weekYear",t.weekYear)}function Cbe(t){const e=zv(t.year),n=Ga(t.ordinal,1,Bg(t.year));return e?n?!1:js("ordinal",t.ordinal):js("year",t.year)}function cG(t){const e=zv(t.year),n=Ga(t.month,1,12),r=Ga(t.day,1,Qv(t.year,t.month));return e?n?r?!1:js("day",t.day):js("month",t.month):js("year",t.year)}function fG(t){const{hour:e,minute:n,second:r,millisecond:i}=t,s=Ga(e,0,23)||e===24&&n===0&&r===0&&i===0,o=Ga(n,0,59),u=Ga(r,0,59),a=Ga(i,0,999);return s?o?u?a?!1:js("millisecond",i):js("second",r):js("minute",n):js("hour",e)}const dD="Invalid DateTime",xG=864e13;function e5(t){return new Ro("unsupported zone",`the zone "${t.name}" is not supported`)}function hD(t){return t.weekData===null&&(t.weekData=fD(t.c)),t.weekData}function qg(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new ft({...n,...e,old:n})}function dG(t,e,n){let r=t-e*60*1e3;const i=n.offset(r);if(e===i)return[r,e];r-=(i-e)*60*1e3;const s=n.offset(r);return i===s?[r,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function hG(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function t5(t,e,n){return dG(X7(t),e,n)}function pG(t,e){const n=t.o,r=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:r,month:i,day:Math.min(t.c.day,Qv(r,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=Rt.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),u=X7(s);let[a,l]=dG(u,n,t.zone);return o!==0&&(a+=o,l=t.zone.offset(a)),{ts:a,o:l}}function Hg(t,e,n,r,i,s){const{setZone:o,zone:u}=n;if(t&&Object.keys(t).length!==0){const a=e||u,l=ft.fromObject(t,{...n,zone:a,specificOffset:s});return o?l:l.setZone(u)}else return ft.invalid(new Ro("unparsable",`the input "${i}" can't be parsed as ${r}`))}function n5(t,e,n=!0){return t.isValid?Ii.create(gn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function pD(t,e){const n=t.c.year>9999||t.c.year<0;let r="";return n&&t.c.year>=0&&(r+="+"),r+=Bn(t.c.year,n?6:4),e?(r+="-",r+=Bn(t.c.month),r+="-",r+=Bn(t.c.day)):(r+=Bn(t.c.month),r+=Bn(t.c.day)),r}function gG(t,e,n,r,i,s){let o=Bn(t.c.hour);return e?(o+=":",o+=Bn(t.c.minute),(t.c.second!==0||!n)&&(o+=":")):o+=Bn(t.c.minute),(t.c.second!==0||!n)&&(o+=Bn(t.c.second),(t.c.millisecond!==0||!r)&&(o+=".",o+=Bn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=Bn(Math.trunc(-t.o/60)),o+=":",o+=Bn(Math.trunc(-t.o%60))):(o+="+",o+=Bn(Math.trunc(t.o/60)),o+=":",o+=Bn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}const mG={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},bbe={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Tbe={ordinal:1,hour:0,minute:0,second:0,millisecond:0},yG=["year","month","day","hour","minute","second","millisecond"],Rbe=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Obe=["year","ordinal","hour","minute","second","millisecond"];function EG(t){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new tQ(t);return e}function AG(t,e){const n=v0(e.zone,$n.defaultZone),r=gn.fromObject(e),i=$n.now();let s,o;if(Tt(t.year))s=i;else{for(const l of yG)Tt(t[l])&&(t[l]=mG[l]);const u=cG(t)||fG(t);if(u)return ft.invalid(u);const a=n.offset(i);[s,o]=t5(t,a,n)}return new ft({ts:s,zone:n,loc:r,o})}function _G(t,e,n){const r=Tt(n.round)?!0:n.round,i=(o,u)=>(o=K7(o,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(o,u)),s=o=>n.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(n.unit)return i(s(n.unit),n.unit);for(const o of n.units){const u=s(o);if(Math.abs(u)>=1)return i(u,o)}return i(t>e?-0:0,n.units[n.units.length-1])}function vG(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}class ft{constructor(e){const n=e.zone||$n.defaultZone;let r=e.invalid||(Number.isNaN(e.ts)?new Ro("invalid input"):null)||(n.isValid?null:e5(n));this.ts=Tt(e.ts)?$n.now():e.ts;let i=null,s=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[i,s]=[e.old.c,e.old.o];else{const u=n.offset(this.ts);i=hG(this.ts,u),r=Number.isNaN(i.year)?new Ro("invalid input"):null,i=r?null:i,s=r?null:u}this._zone=n,this.loc=e.loc||gn.create(),this.invalid=r,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new ft({})}static local(){const[e,n]=vG(arguments),[r,i,s,o,u,a,l]=n;return AG({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static utc(){const[e,n]=vG(arguments),[r,i,s,o,u,a,l]=n;return e.zone=qr.utcInstance,AG({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static fromJSDate(e,n={}){const r=PCe(e)?e.valueOf():NaN;if(Number.isNaN(r))return ft.invalid("invalid input");const i=v0(n.zone,$n.defaultZone);return i.isValid?new ft({ts:r,zone:i,loc:gn.fromObject(n)}):ft.invalid(e5(i))}static fromMillis(e,n={}){if(Cf(e))return e<-xG||e>xG?ft.invalid("Timestamp out of range"):new ft({ts:e,zone:v0(n.zone,$n.defaultZone),loc:gn.fromObject(n)});throw new Ps(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(Cf(e))return new ft({ts:e*1e3,zone:v0(n.zone,$n.defaultZone),loc:gn.fromObject(n)});throw new Ps("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const r=v0(n.zone,$n.defaultZone);if(!r.isValid)return ft.invalid(e5(r));const i=$n.now(),s=Tt(n.specificOffset)?r.offset(i):n.specificOffset,o=Vv(e,EG),u=!Tt(o.ordinal),a=!Tt(o.year),l=!Tt(o.month)||!Tt(o.day),c=a||l,f=o.weekYear||o.weekNumber,x=gn.fromObject(n);if((c||u)&&f)throw new Lg("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&u)throw new Lg("Can't mix ordinal dates with month/day");const h=f||o.weekday&&!c;let p,m,g=hG(i,s);h?(p=Rbe,m=bbe,g=fD(g)):u?(p=Obe,m=Tbe,g=xD(g)):(p=yG,m=mG);let y=!1;for(const b of p){const F=o[b];Tt(F)?y?o[b]=m[b]:o[b]=g[b]:y=!0}const E=h?Sbe(o):u?Cbe(o):cG(o),A=E||fG(o);if(A)return ft.invalid(A);const _=h?aG(o):u?lG(o):o,[v,S]=t5(_,s,r),C=new ft({ts:v,zone:r,o:S,loc:x});return o.weekday&&c&&e.weekday!==C.weekday?ft.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${C.toISO()}`):C}static fromISO(e,n={}){const[r,i]=H4e(e);return Hg(r,i,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[r,i]=z4e(e);return Hg(r,i,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[r,i]=Q4e(e);return Hg(r,i,n,"HTTP",n)}static fromFormat(e,n,r={}){if(Tt(e)||Tt(n))throw new Ps("fromFormat requires an input string and a format");const{locale:i=null,numberingSystem:s=null}=r,o=gn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[u,a,l,c]=vbe(o,e,n);return c?ft.invalid(c):Hg(u,a,r,`format ${n}`,e,l)}static fromString(e,n,r={}){return ft.fromFormat(e,n,r)}static fromSQL(e,n={}){const[r,i]=J4e(e);return Hg(r,i,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new Ps("need to specify a reason the DateTime is invalid");const r=e instanceof Ro?e:new Ro(e,n);if($n.throwOnInvalid)throw new NCe(r);return new ft({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?hD(this).weekYear:NaN}get weekNumber(){return this.isValid?hD(this).weekNumber:NaN}get weekday(){return this.isValid?hD(this).weekday:NaN}get ordinal(){return this.isValid?xD(this.c).ordinal:NaN}get monthShort(){return this.isValid?Ug.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Ug.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Ug.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Ug.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 Ig(this.year)}get daysInMonth(){return Qv(this.year,this.month)}get daysInYear(){return this.isValid?Bg(this.year):NaN}get weeksInWeekYear(){return this.isValid?Gv(this.weekYear):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:r,calendar:i}=Ii.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:i}}toUTC(e=0,n={}){return this.setZone(qr.instance(e),n)}toLocal(){return this.setZone($n.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=v0(e,$n.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(n||r){const s=e.offset(this.ts),o=this.toObject();[i]=t5(o,s,e)}return qg(this,{ts:i,zone:e})}else return ft.invalid(e5(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return qg(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=Vv(e,EG),r=!Tt(n.weekYear)||!Tt(n.weekNumber)||!Tt(n.weekday),i=!Tt(n.ordinal),s=!Tt(n.year),o=!Tt(n.month)||!Tt(n.day),u=s||o,a=n.weekYear||n.weekNumber;if((u||i)&&a)throw new Lg("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new Lg("Can't mix ordinal dates with month/day");let l;r?l=aG({...fD(this.c),...n}):Tt(n.ordinal)?(l={...this.toObject(),...n},Tt(n.day)&&(l.day=Math.min(Qv(l.year,l.month),l.day))):l=lG({...xD(this.c),...n});const[c,f]=t5(l,this.o,this.zone);return qg(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;const n=Rt.fromDurationLike(e);return qg(this,pG(this,n))}minus(e){if(!this.isValid)return this;const n=Rt.fromDurationLike(e).negate();return qg(this,pG(this,n))}startOf(e){if(!this.isValid)return this;const n={},r=Rt.normalizeUnit(e);switch(r){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break}if(r==="weeks"&&(n.weekday=1),r==="quarters"){const i=Math.ceil(this.month/3);n.month=(i-1)*3+1}return this.set(n)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,n={}){return this.isValid?Ii.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):dD}toLocaleString(e=V7,n={}){return this.isValid?Ii.create(this.loc.clone(n),e).formatDateTime(this):dD}toLocaleParts(e={}){return this.isValid?Ii.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;const o=e==="extended";let u=pD(this,o);return u+="T",u+=gG(this,o,n,r,i,s),u}toISODate({format:e="extended"}={}){return this.isValid?pD(this,e==="extended"):null}toISOWeekDate(){return n5(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+gG(this,o==="extended",n,e,r,s):null}toRFC2822(){return n5(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return n5(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?pD(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let i="HH:mm:ss.SSS";return(n||e)&&(r&&(i+=" "),n?i+="z":e&&(i+="ZZ")),n5(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():dD}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return Rt.invalid("created by diffing an invalid DateTime");const i={locale:this.locale,numberingSystem:this.numberingSystem,...r},s=MCe(n).map(Rt.normalizeUnit),o=e.valueOf()>this.valueOf(),u=o?this:e,a=o?e:this,l=ube(u,a,s,i);return o?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(ft.now(),e,n)}until(e){return this.isValid?mn.fromDateTimes(this,e):this}hasSame(e,n){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n)<=r&&r<=i.endOf(n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const n=e.base||ft.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0;let i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),_G(n,this.plus(r),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?_G(e.base||ft.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(ft.isDateTime))throw new Ps("min requires all arguments be DateTimes");return vQ(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(ft.isDateTime))throw new Ps("max requires all arguments be DateTimes");return vQ(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){const{locale:i=null,numberingSystem:s=null}=r,o=gn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return nG(o,e,n)}static fromStringExplain(e,n,r={}){return ft.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return V7}static get DATE_MED(){return nQ}static get DATE_MED_WITH_WEEKDAY(){return BCe}static get DATE_FULL(){return rQ}static get DATE_HUGE(){return iQ}static get TIME_SIMPLE(){return sQ}static get TIME_WITH_SECONDS(){return oQ}static get TIME_WITH_SHORT_OFFSET(){return uQ}static get TIME_WITH_LONG_OFFSET(){return aQ}static get TIME_24_SIMPLE(){return lQ}static get TIME_24_WITH_SECONDS(){return cQ}static get TIME_24_WITH_SHORT_OFFSET(){return fQ}static get TIME_24_WITH_LONG_OFFSET(){return xQ}static get DATETIME_SHORT(){return dQ}static get DATETIME_SHORT_WITH_SECONDS(){return hQ}static get DATETIME_MED(){return pQ}static get DATETIME_MED_WITH_SECONDS(){return gQ}static get DATETIME_MED_WITH_WEEKDAY(){return $Ce}static get DATETIME_FULL(){return mQ}static get DATETIME_FULL_WITH_SECONDS(){return yQ}static get DATETIME_HUGE(){return EQ}static get DATETIME_HUGE_WITH_SECONDS(){return AQ}}function zg(t){if(ft.isDateTime(t))return t;if(t&&t.valueOf&&Cf(t.valueOf()))return ft.fromJSDate(t);if(t&&typeof t=="object")return ft.fromObject(t);throw new Ps(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const Dbe="2.5.2";var wbe=Li.DateTime=ft;Li.Duration=Rt,Li.FixedOffsetZone=qr,Li.IANAZone=Fu,Li.Info=Ug,Li.Interval=mn,Li.InvalidZone=IQ,Li.Settings=$n,Li.SystemZone=Kv,Li.VERSION=Dbe,Li.Zone=hh,Object.defineProperty(rr,"__esModule",{value:!0}),rr.LiteralYear=rr.LiteralQuarter=rr.LiteralMonth=rr.LiteralWeek=rr.LiteralDay=rr.LiteralHour=rr.LiteralTimestamp=rr.TimeFormatError=void 0;const S0=Li,Fbe=Ke,Nbe=jt,Lbe=g0,SG=uh,gD=ct;class Ibe extends Error{}rr.TimeFormatError=Ibe;function Of(t,e){const n=t.slice(1);if(e){const r=n.match(/\[[^\]]+]$/);if(r)return{tzSpec:r[0].slice(1,-1),text:n.slice(0,-r[0].length)}}return{text:n}}const CG="yyyy",bG=`${CG}-LL`,Us=`${bG}-dd`,TG=`${Us} HH`,RG=`${TG}:mm`,mD=`${RG}:ss`;class OG extends gD.ExpressionDef{constructor(e,n,r){super(),this.units=n,this.timeType=r,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,n){const r={node:"timeLiteral",literal:e,typeDef:{type:n}};return this.timeZone&&(r.timezone=this.timeZone),r}makeValue(e,n){const r=this.makeLiteral(e,n);return(0,Nbe.literalTimeResult)({value:r,dataType:{type:n},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class yD extends OG{constructor(e,n){super(e,n,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let n;const r=Of(e,!0);e=r.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),r.text=e);const i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=S0.DateTime.fromFormat(e,mD);if(s.isValid)return new yD(r,n);if(s=S0.DateTime.fromFormat(e,RG),s.isValid){r.text=r.text+":00",n="minute";const o=s.plus({minute:1}).toFormat(mD);return new ED(r,n,"timestamp",o)}}}rr.LiteralTimestamp=yD;class ED extends OG{constructor(e,n,r,i){super(e,n,r),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,n,r){let i=this.getExpression(e),s=this.getNext();if(s){const o=r.getExpression(e);if(o.type==="timestamp"){const u=(0,gD.getMorphicValue)(i,"timestamp"),a=(0,gD.getMorphicValue)(s,"timestamp");if(u&&a)i=u,s=a;else return super.apply(e,n,r)}if(s&&(0,Fbe.isTemporalType)(o.type)){const u=o.type;return new Lbe.Range(new SG.ExprTime(u,i.value),new SG.ExprTime(u,s.value)).apply(e,n,r)}}return super.apply(e,n,r)}}class AD extends ED{constructor(e,n){super(e,"hour","timestamp",n),this.elementType="literal:hour"}static parse(e){const n=Of(e,!1);let r=n.text;const i=S0.DateTime.fromFormat(n.text,TG);if(i.isValid)return n.text=n.text+":00:00",r=i.plus({hour:1}).toFormat(mD),new AD(n,r)}}rr.LiteralHour=AD;class Qg extends ED{constructor(e,n,r){super(e,n,"date",r)}getExpression(e){const n=this.makeValue(this.literalPart,"date"),r=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...n,morphic:{timestamp:r},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),n=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:n}}}}class _D extends Qg{constructor(e,n){super(e,"day",n),this.elementType="literal:day"}static parse(e){const n=Of(e,!1);let r=n.text;const i=S0.DateTime.fromFormat(n.text,Us);if(i.isValid)return r=i.plus({day:1}).toFormat(Us),new _D(n,r)}}rr.LiteralDay=_D;class vD extends Qg{constructor(e,n){super(e,"week",n),this.elementType="literal:week"}static parse(e){const n=Of(e,!1);let r=n.text;const i=n.text.slice(0,10),s=S0.DateTime.fromFormat(i,Us);if(s.isValid&&s.weekday===7){const u=s.plus({days:7});return n.text=s.toFormat(Us),r=u.toFormat(Us),new vD(n,r)}}}rr.LiteralWeek=vD;class SD extends Qg{constructor(e,n){super(e,"month",n),this.elementType="literal:month"}static parse(e){const n=Of(e,!1);let r=n.text;const i=S0.DateTime.fromFormat(n.text,bG);if(i.isValid){const s=i.plus({months:1});return n.text=i.toFormat(Us),r=s.toFormat(Us),new SD(n,r)}}}rr.LiteralMonth=SD;class CD extends Qg{constructor(e,n){super(e,"quarter",n),this.elementType="literal:quarter"}static parse(e){const n=Of(e,!1);let r=n.text;const i=n.text.match(/(^\d{4})-[qQ](\d)$/);if(i){const s=Number.parseInt(i[2])-1;let o=S0.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));const u=o.plus({quarter:1});return n.text=o.toFormat(Us),r=u.toFormat(Us),new CD(n,r)}}}rr.LiteralQuarter=CD;class bD extends Qg{constructor(e,n){super(e,"year",n),this.elementType="literal:year"}static parse(e){const n=Of(e,!1);let r=n.text;const i=S0.DateTime.fromFormat(n.text,CG);if(i.isValid){const s=i.plus({year:1});return n.text=i.toFormat(Us),r=s.toFormat(Us),new bD(n,r)}}}rr.LiteralYear=bD;var r5={};Object.defineProperty(r5,"__esModule",{value:!0}),r5.PartialCompare=void 0;const DG=ct;class Bbe extends DG.ExpressionDef{constructor(e,n){super({right:n}),this.op=e,this.right=n,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,n,r){return this.right.apply(e,this.op,r)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return DG.ATNodeType.Partial}}r5.PartialCompare=Bbe;var _h={},$be=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),kbe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pbe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&$be(e,t,n);return kbe(e,t),e};Object.defineProperty(_h,"__esModule",{value:!0}),_h.PickWhen=_h.Pick=void 0;const vh=Pbe(Wt),wG=jt,Mbe=ct,jbe=Ye;function i5(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Ube extends Mbe.ExpressionDef{constructor(e,n){super({choices:e}),this.choices=e,this.elsePick=n,this.elementType="pick",this.has({elsePick:n})}requestExpression(e){if(this.elsePick!==void 0){for(const n of this.choices){if(n.pick===void 0)return;const r=n.when.requestExpression(e);if(r===void 0||r.type!=="boolean")return}return this.getExpression(e)}}apply(e,n,r){var i;const s={node:"case",kids:{caseWhen:[],caseThen:[]}};let o;const u=[];for(const x of this.choices){const h=x.when.apply(e,"=",r),p=x.pick?x.pick.getExpression(e):r.getExpression(e);if(u.push(h,p),o&&!vh.typeEq(o,p,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:p.type,returnType:o.type});o=i5(o,p),s.kids.caseWhen.push(h.value),s.kids.caseThen.push(p.value)}const a=(i=this.elsePick)===null||i===void 0?void 0:i.getExpression(e),l=r.getExpression(e);u.push(l),a&&u.push(a);const c=a??l,f=i5(o,c);return vh.typeEq(f,c,!0)?(s.kids.caseElse=c.value,(0,wG.computedExprValue)({dataType:f,value:s,from:u})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:c.type,returnType:f.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:c.type,returnType:f.type})}getExpression(e){const n={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const r=[],i=[];for(const a of this.choices){if(a.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");a.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const c=a.pick.getExpression(e),f=a.when.getExpression(e);r.push({pick:c,when:f}),i.push(c,f)}let s;for(const a of r){if(!vh.typeEq(a.when,vh.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:a.when.type});if(s&&!vh.typeEq(s,a.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:a.pick.type,returnType:s.type});s=i5(s,a.pick),n.kids.caseWhen.push(a.when.value),n.kids.caseThen.push(a.pick.value)}const o=this.elsePick.getExpression(e);i.push(o);const u=i5(s,o);return vh.typeEq(u,o,!0)?(n.kids.caseElse=o.value,(0,wG.computedExprValue)({dataType:u,value:n,from:i})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:o.type,returnType:u.type})}}_h.Pick=Ube;class qbe extends jbe.MalloyElement{constructor(e,n){super({when:n}),this.pick=e,this.when=n,this.elementType="caseWhen",this.has({pick:e})}}_h.PickWhen=qbe;var Sh={},Hbe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),zbe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qbe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Hbe(e,t,n);return zbe(e,t),e};Object.defineProperty(Sh,"__esModule",{value:!0}),Sh.CaseWhen=Sh.Case=void 0;const Gbe=jt,Wbe=ct,Vbe=Ye,Ch=Qbe(Wt);function FG(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Ybe extends Wbe.ExpressionDef{constructor(e,n,r){super({choices:n}),this.value=e,this.choices=n,this.elseValue=r,this.elementType="case",this.has({elseValue:r,value:e})}getExpression(e){const n={node:"case",kids:{caseWhen:[],caseThen:[]}},r=[];let i;if(this.value){const u=this.value.getExpression(e);r.push(u),n.kids.caseValue=u.value,i=u}const s=[];for(const u of this.choices){const a=u.when.getExpression(e),l=u.then.getExpression(e);s.push({when:a,then:l}),r.push(a,l)}let o;for(const u of s){if(i!==void 0){if(!Ch.typeEq(u.when,i))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:u.when.type,valueType:i.type})}else if(!Ch.typeEq(u.when,Ch.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:u.when.type});if(o&&!Ch.typeEq(o,u.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:u.then.type,returnType:o.type});o=FG(o,u.then),n.kids.caseWhen.push(u.when.value),n.kids.caseThen.push(u.then.value)}if(this.elseValue){const u=this.elseValue.getExpression(e);if(o&&!Ch.typeEq(o,u,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:u.type,returnType:o.type});o=FG(o,u),r.push(u),n.kids.caseElse=u.value}return(0,Gbe.computedExprValue)({value:n,dataType:o?Ch.atomicDef(o):{type:"null"},from:r})}}Sh.Case=Ybe;class Kbe extends Vbe.MalloyElement{constructor(e,n){super({when:e,then:n}),this.when=e,this.then=n,this.elementType="caseWhen"}}Sh.CaseWhen=Kbe;var s5={},Df={},Xbe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Jbe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zbe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Xbe(e,t,n);return Jbe(e,t),e};Object.defineProperty(Df,"__esModule",{value:!0}),Df.RecordLiteral=Df.RecordElement=void 0;const NG=ts,eTe=jt,tTe=ct,nTe=Ye,rTe=Zbe(Wt);class iTe extends nTe.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const n=e.path.fieldReference.path;this.key=n[n.length-1]}}}Df.RecordElement=iTe;class sTe extends tTe.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,n){var r;const i={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},s=[];let o=0;for(const u of this.pairs){const a=(r=u.key)!==null&&r!==void 0?r:n[o];if(o+=1,a===void 0){u.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const l=u.value.getExpression(e);NG.TD.isAtomic(l)?(s.push(l),i.kids[a]=l.value,i.typeDef.fields.push((0,NG.mkFieldDef)(rTe.atomicDef(l),a))):u.value.logError("illegal-record-property-type",`Record property '${u.key} is type '${l.type}', which is not a legal property value type`)}return(0,eTe.computedExprValue)({value:i,dataType:i.typeDef,from:s})}getNextElement(e,n){const r=n.value;return r.node==="recordLiteral"?this.getRecord(e,Object.keys(r.kids)):this.getRecord(e,[])}}Df.RecordLiteral=sTe;var oTe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),uTe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),aTe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&oTe(e,t,n);return uTe(e,t),e};Object.defineProperty(s5,"__esModule",{value:!0}),s5.ArrayLiteral=void 0;const lTe=jt,cTe=ct,LG=aTe(Wt),fTe=Df;class xTe extends cTe.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const n=[],r=[];let i;if(this.elements.length>0)for(const a of this.elements){const l=i&&a instanceof fTe.RecordLiteral?a.getNextElement(e,i):a.getExpression(e);if(r.push(l),l.type!=="error"){if(i){if(!LG.typeEq(i,l)){a.logError("array-values-incompatible","All array elements must be same type");continue}}else i=l;n.push(l.value)}}const s=LG.atomicDef(i||{type:"number"}),o=s.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:s.fields}:{type:"array",elementTypeDef:s},u={node:"arrayLiteral",kids:{values:n},typeDef:o};return(0,lTe.computedExprValue)({dataType:o,value:u,from:r})}}s5.ArrayLiteral=xTe;var o5={};Object.defineProperty(o5,"__esModule",{value:!0}),o5.Timeframe=void 0;const dTe=Ke,hTe=Ye;class pTe extends hTe.MalloyElement{constructor(e){super(),this.elementType="timeframe";let n=e.toLowerCase();n.endsWith("s")&&(n=n.slice(0,-1)),this.text=(0,dTe.isTimestampUnit)(n)?n:"second"}}o5.Timeframe=pTe;var C0={};Object.defineProperty(C0,"__esModule",{value:!0}),C0.ImportStatement=C0.ImportSelect=C0.ImportSourceName=void 0;const TD=Ye;class gTe extends TD.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}C0.ImportSourceName=gTe;class mTe extends TD.MalloyElement{constructor(e,n){super(),this.text=e,this.from=n,this.elementType="importName",n&&this.has({from:n})}}C0.ImportSelect=mTe;class yTe extends TD.ListOf{constructor(e,n){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,n).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const r=e.childRequest(this.fullURL);if(r)return r}}execute(e){const n=this.translator();if(!n)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const r=n.root.importZone.getEntry(this.fullURL);if(r.status==="present"){const i=n.getChildExports(this.fullURL);if(this.notEmpty())for(const s of this.list){const o=s.from||s;if(e.getEntry(s.text))s.logError("name-conflict-on-selective-import",`Cannot redefine '${s.text}'`);else if(i[o.text]){const u={...i[o.text]};s.from&&(u.as=s.text),e.setEntry(s.text,{entry:u,exported:!1})}else o.logError("selective-import-not-found",`Cannot find '${o.text}', not imported`)}else for(const[s,o]of Object.entries(n.getChildExports(this.fullURL)))e.getEntry(s)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else r.status==="error"?this.logError("failed-import",`import failed: '${r.message}'`):this.logError("failed-import",`import failed with status: '${r.status}'`)}}}C0.ImportStatement=yTe;var Gg={};Object.defineProperty(Gg,"__esModule",{value:!0}),Gg.ExtendBlock=void 0;const ETe=Ye,ATe=Dn;class _Te extends ETe.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=ATe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)for(const r of n.list)e.inputFS.extendSource(r)}}Gg.ExtendBlock=_Te;var u5={};Object.defineProperty(u5,"__esModule",{value:!0}),u5.Argument=void 0;const vTe=Ye;class STe extends vTe.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}u5.Argument=STe;var a5={};Object.defineProperty(a5,"__esModule",{value:!0}),a5.HasParameter=void 0;const IG=Ke,CTe=Ye;class bTe extends CTe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,IG.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const n=this.default.constantValue();return this.type&&this.type!==n.type&&n.type!=="null"&&n.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),n.type==="null"?this.type?{type:this.type,value:n.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:n.value,name:this.name,type:"error"}):!(0,IG.isCastType)(n.type)&&n.type!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${n.type}\``),{value:n.value,name:this.name,type:"error"}):{value:n.value,name:this.name,type:n.type}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}a5.HasParameter=bTe;var l5={};Object.defineProperty(l5,"__esModule",{value:!0}),l5.AnonymousQuery=void 0;const TTe=Ye,RTe=Sr;class OTe extends TTe.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=RTe.extendNoteMethod,this.has({queryExpr:e})}execute(e){const n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const r={...n.query()},i=this.note||{};r.annotation&&(i.inherits=r.annotation),(i.notes||i.blockNotes||i.inherits)&&(r.annotation=i),e.queryList.push(r)}}l5.AnonymousQuery=OTe;var b0={};Object.defineProperty(b0,"__esModule",{value:!0}),b0.View=void 0;const DTe=Ye;let wTe=class extends DTe.MalloyElement{pipeline(e,n){return this.pipelineComp(e,n).pipeline}};b0.View=wTe;var c5={};Object.defineProperty(c5,"__esModule",{value:!0}),c5.ViewArrow=void 0;const FTe=br,NTe=b0;class LTe extends NTe.View{constructor(e,n){super({base:e,operation:n}),this.base=e,this.operation=n,this.elementType="viewArrow"}pipelineComp(e){const n=this.base.pipelineComp(e),r=new FTe.StaticSourceSpace(n.outputStruct),i=this.operation.pipelineComp(r);return{pipeline:[...n.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,n,r){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}c5.ViewArrow=LTe;var f5={},Wg={};Object.defineProperty(Wg,"__esModule",{value:!0}),Wg.refine=void 0;const RD=ts,ITe=ut,OD=c0;function BTe(t,e,n){var r,i;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const s={...e[0]},o=n;if((0,RD.isRawSegment)(s))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&(o.orderBy!==void 0&&!o.defaultOrderBy&&(s.orderBy===void 0||s.defaultOrderBy?s.orderBy=o.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(r=s.filterList)!==null&&r!==void 0?r:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,RD.isQuerySegment)(o)&&(0,RD.isQuerySegment)(s)){const u=[],a=[],l=new Map(s.queryFields.map(c=>[(0,OD.nameFromDef)(c),c]));for(const c of o.queryFields)l.has((0,OD.nameFromDef)(c))?u.push(c):a.push(c);s.queryFields=[...s.queryFields,...a],u.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${u.map(OD.nameFromDef)}`),s.compositeFieldUsage=(0,ITe.mergeCompositeFieldUsage)(s.compositeFieldUsage,o.compositeFieldUsage)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}Wg.refine=BTe,Object.defineProperty(f5,"__esModule",{value:!0}),f5.ViewRefine=void 0;const $Te=Ur,kTe=ds,PTe=Wg,MTe=b0;class jTe extends MTe.View{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="refine"}pipelineComp(e,n){const r=this.base.pipelineComp(e),i=this.refinement.refine(e,r.pipeline,n);return{pipeline:i,annotation:r.annotation,outputStruct:i.length>0?(0,kTe.getFinalStruct)(this.refinement,e.structDef(),i):$Te.ErrorFactory.structDef}}refine(e,n,r){const i=this.pipeline(e,r);return i.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),n):(0,PTe.refine)(this,n,i[0])}getImplicitName(){return this.base.getImplicitName()}}f5.ViewRefine=jTe;var x5={};Object.defineProperty(x5,"__esModule",{value:!0}),x5.ReferenceView=void 0;const DD=Ke,BG=Ur,UTe=ds,qTe=Cr,HTe=Wg,zTe=b0;class QTe extends zTe.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,n){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:n}={forRefinement:!1}){const r=this.reference.getField(e),i=function(){return{inputStruct:BG.ErrorFactory.structDef,outputStruct:BG.ErrorFactory.structDef,pipeline:[],error:!0}};if(!r.found)return this.reference.logError(r.error.code,r.error.message),i();if(!(r.found instanceof qTe.SpaceField))throw new Error("Expected space field");const s=r.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,DD.isAtomic)(s)){const o={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:s.compositeFieldUsage},u=this.reference.nameString,a={...(0,DD.sourceBase)(e.structDef()),type:"query_result",name:u,fields:[s]};return{pipeline:[o],name:u,outputStruct:a}}else return(0,DD.isTurtle)(s)?this.reference.list.length>1?(n?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,UTe.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(n?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.logError("nest-of-source","This operation is not supported"),i())}getRefinementSegment(e){const{pipeline:n,error:r}=this._pipelineComp(e,{forRefinement:!0});if(!r){if(n.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return n[0]}}refine(e,n,r){const i=this.getRefinementSegment(e);return i?(0,HTe.refine)(this,n,i):n}getImplicitName(){return this.reference.nameString}}x5.ReferenceView=QTe;var d5={},Vg={},h5={},Yg={};Object.defineProperty(Yg,"__esModule",{value:!0}),Yg.Index=void 0;const GTe=Ye,WTe=Dn;let VTe=class extends GTe.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=WTe.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};Yg.Index=VTe;var Kg={};Object.defineProperty(Kg,"__esModule",{value:!0}),Kg.SampleProperty=void 0;const YTe=Ye,$G=Dn;class KTe extends YTe.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=$G.LegalRefinementStage.Tail,this.forceQueryClass=$G.QueryClass.Index}sampling(){return this.sample}}Kg.SampleProperty=KTe;var p5={};Object.defineProperty(p5,"__esModule",{value:!0}),p5.IndexFieldSpace=void 0;const kG=ut,PG=Ke,wD=ht,XTe=Cr,JTe=bo,ZTe=mg,e6e=br;class t6e extends JTe.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const n of e)n instanceof wD.FieldReference?super.pushFields(n):n instanceof wD.WildcardFieldReference?this.addWild(n):n.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let n=(0,kG.emptyCompositeFieldUsage)(),r=(0,kG.emptyNarrowedCompositeFieldResolution)();const i=[],s=this.inputSpace().structDef();for(const[o,u]of this.entries())if(u instanceof XTe.SpaceField){let a,l;const c=this.expandedWild[o];if(c)i.push({type:"fieldref",path:c.path}),a=c.entry.typeDesc().compositeFieldUsage;else if(u instanceof ZTe.ReferenceField){const x=u.fieldRef,h=x.getField(this.exprSpace);h.error?x.logError(h.error.code,h.error.message):(i.push(x.refToField),a=h.found.typeDesc().compositeFieldUsage,l=x)}const f=this.applyNextCompositeFieldUsage(s,n,r,a,l);n=f.compositeFieldUsage,r=f.narrowedCompositeFieldResolution}return this._compositeFieldUsage=n,{type:"index",indexFields:i}}addRefineFromFields(e){}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof e6e.StructSpaceField)r=l.fieldSpace;else{u.logError("invalid-wildcard-source",`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.logError("wildcard-source-not-found",`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries()){if(e.except.has(u)||a.refType==="parameter")continue;const l=wD.IndexFieldReference.indexOutputName([...i,u]);if(this.entry(l)){const c=(n=this.expandedWild[l].path)===null||n===void 0?void 0:n.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=a.typeDesc();PG.TD.isLeafAtomic(c)&&(0,PG.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:l,entry:a}),this.expandedWild[l]={path:i.concat(u),entry:a})}}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}p5.IndexFieldSpace=t6e,Object.defineProperty(h5,"__esModule",{value:!0}),h5.IndexBuilder=void 0;const FD=Ke,n6e=Ur,r6e=wu,i6e=Yg,s6e=y0,o6e=Kg,u6e=p5,ND=ut;class a6e{constructor(e,n,r,i){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new u6e.IndexFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof r6e.Filter?e.queryExecute(this):e instanceof s6e.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof i6e.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof o6e.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var n;if(e&&!(0,FD.isIndexSegment)(e)&&!(0,FD.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),n6e.ErrorFactory.indexSegment;const r=this.resultFS.getPipeSegment(e),i=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!i?r.filterList=this.filters:i&&(r.filterList=[...i,...this.filters]),e!=null&&e.limit&&(r.limit=e.limit),this.limit&&(r.limit=this.limit.limit),this.indexOn&&(r.weightMeasure=this.indexOn.refString),e&&(0,FD.isIndexSegment)(e)&&(e!=null&&e.sample)&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const s=e&&e.type==="index"&&(n=e.compositeFieldUsage)!==null&&n!==void 0?n:(0,ND.emptyCompositeFieldUsage)();return r.compositeFieldUsage=(0,ND.mergeCompositeFieldUsage)(s,this.compositeFieldUsage),r}}h5.IndexBuilder=a6e;var g5={},Xg={};Object.defineProperty(Xg,"__esModule",{value:!0}),Xg.GroupBy=void 0;const l6e=xs,MG=Dn;class c6e extends l6e.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=MG.LegalRefinementStage.Single,this.forceQueryClass=MG.QueryClass.Grouping}}Xg.GroupBy=c6e;var m5={};Object.defineProperty(m5,"__esModule",{value:!0}),m5.ProjectFieldSpace=void 0;const y5=Ke,f6e=bo;class x6e extends f6e.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!y5.TD.isAtomic(e)||(0,y5.expressionIsAggregate)(e.expressionType)?!1:(0,y5.expressionInvolvesAggregate)(e.expressionType)&&(0,y5.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}m5.ProjectFieldSpace=x6e;var T0={},wf={};Object.defineProperty(wf,"__esModule",{value:!0}),wf.Ordering=wf.OrderBy=void 0;const d6e=Ke,jG=E0,UG=Ye,h6e=Dn;class p6e extends UG.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e instanceof jG.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var n;if(this.field instanceof jG.FieldName&&e.isQueryFieldSpace()){const i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.logError(s.error.code,s.error.message),(!s.found||!s.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,d6e.expressionIsAnalytic)((n=s.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const r={field:this.modelField};return this.dir&&(r.dir=this.dir),r}}wf.OrderBy=p6e;class g6e extends UG.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=h6e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(n=>n.getOrderBy(e))}}wf.Ordering=g6e,Object.defineProperty(T0,"__esModule",{value:!0}),T0.ReduceBuilder=T0.QuerySegmentBuilder=void 0;const wo=Ke,m6e=Ur,y6e=E0,E6e=y0,A6e=wf,_6e=bo,v6e=xs,LD=ut;function qG(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class HG{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof v6e.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof E6e.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof A6e.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,n){var r;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(n.orderBy=e.orderBy),!this.limit&&e.limit&&(n.limit=e.limit)),this.order&&(n.orderBy=this.order.getOrderBy(this.inputFS),delete n.defaultOrderBy),this.limit&&(n.limit=this.limit);const i=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!i?n.filterList=this.filters:i&&(n.filterList=[...i,...this.filters]),this.alwaysJoins.length>0&&(n.alwaysJoins=[...this.alwaysJoins]);const s=e&&(0,wo.isQuerySegment)(e)&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,LD.emptyCompositeFieldUsage)();n.compositeFieldUsage=(0,LD.mergeCompositeFieldUsage)(s,this.compositeFieldUsage)}}T0.QuerySegmentBuilder=HG;class S6e extends HG{constructor(e,n,r,i){super(),this.type="grouping",this.resultFS=new _6e.ReduceFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let n;if(e)if((0,wo.isReduceSegment)(e)||(0,wo.isPartialSegment)(e))n=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),m6e.ErrorFactory.reduceSegment;const r=this.resultFS.getQuerySegment(n);if(this.refineFrom(n,r),r.orderBy){for(const i of r.orderBy)if(typeof i.field=="number"){const s=r.queryFields[i.field-1];i.field=qG(s)}}if(r.orderBy===void 0||r.defaultOrderBy){let i;for(const s of r.queryFields){let o=!1,u=!1,a;const l=qG(s);if(s.type==="fieldref"){const c=s.path.map(x=>new y6e.FieldName(x)),f=this.inputFS.lookup(c).found;if(f){const x=f.typeDesc();a=x.type,o=(0,wo.expressionIsAggregate)(x.expressionType),u=(0,wo.expressionIsAnalytic)(x.expressionType)}else continue}else a=s.type,o=(0,wo.hasExpression)(s)&&(0,wo.expressionIsAggregate)(s.expressionType),u=(0,wo.hasExpression)(s)&&(0,wo.expressionIsAnalytic)(s.expressionType);if((0,wo.isTemporalType)(a)||o){r.defaultOrderBy=!0,r.orderBy=[{field:l,dir:"desc"}],i=void 0;break}(0,wo.canOrderBy)(a)&&!u&&!i&&(i=l)}i&&(r.defaultOrderBy=!0,r.orderBy=[{field:i,dir:"asc"}])}return r}}T0.ReduceBuilder=S6e,Object.defineProperty(g5,"__esModule",{value:!0}),g5.ProjectBuilder=void 0;const zG=Ke,C6e=Ur,b6e=Xg,T6e=m5,R6e=T0;class O6e extends R6e.QuerySegmentBuilder{constructor(e,n,r,i){super(),this.type="project",this.resultFS=new T6e.ProjectFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof b6e.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let n;if(e)if((0,zG.isProjectSegment)(e)||(0,zG.isPartialSegment)(e))n=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),C6e.ErrorFactory.projectSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}g5.ProjectBuilder=O6e;var E5={};Object.defineProperty(E5,"__esModule",{value:!0}),E5.PartialBuilder=void 0;const D6e=ts,w6e=T0;class F6e extends w6e.ReduceBuilder{finalize(e){const n=super.finalize(e);if((0,D6e.isQuerySegment)(n))return{...n,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${n.type}`)}}E5.PartialBuilder=F6e,Object.defineProperty(Vg,"__esModule",{value:!0}),Vg.QOpDesc=void 0;const N6e=h5,L6e=g5,I6e=T0,B6e=Ye,$6e=ds,k6e=br,Ff=Dn,P6e=E5;class M6e extends B6e.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let n,r=!1;this.refineThis&&(this.refineThis.type==="reduce"?n=Ff.QueryClass.Grouping:this.refineThis.type==="project"?n=Ff.QueryClass.Project:this.refineThis.type==="index"&&(n=Ff.QueryClass.Index));for(const i of this.list)i.forceQueryClass&&(n?n!==i.forceQueryClass&&i.logError(`illegal-${n}-operation`,`Not legal in ${n} query`):n=i.forceQueryClass),r||(r=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return n===void 0&&r&&(this.logError("ambiguous-view-type",{}),n=Ff.QueryClass.Project),this.opClass=n,n}refineFrom(e){this.refineThis=e}getBuilder(e,n,r){switch(this.computeType()){case Ff.QueryClass.Grouping:return new I6e.ReduceBuilder(e,this.refineThis,n,r);case Ff.QueryClass.Project:return new L6e.ProjectBuilder(e,this.refineThis,n,r);case Ff.QueryClass.Index:return new N6e.IndexBuilder(e,this.refineThis,n,r);case void 0:return new P6e.PartialBuilder(e,this.refineThis,n,r)}}getOp(e,n){const r=this.getBuilder(e,n,this);for(const s of this.list)r.execute(s);const i=r.finalize(this.refineThis);return{segment:i,outputSpace:()=>new k6e.StaticSourceSpace((0,$6e.opOutputStruct)(this,e.structDef(),i))}}}Vg.QOpDesc=M6e,Object.defineProperty(d5,"__esModule",{value:!0}),d5.QOpDescView=void 0;const j6e=Ke,U6e=br,QG=Vg,q6e=ds,ID=Dn,H6e=b0;class z6e extends H6e.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,n){const r=this.operation.getOp(e,n);return{pipeline:[r.segment],outputStruct:r.outputSpace().structDef()}}getOp(e,n,r,i){return(0,j6e.isRawSegment)(i)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),i):(r.refineFrom(i),r.getOp(e,n).segment)}refine(e,n,r){const i=[...n];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,r,this.operation,i[0])];const s=new QG.QOpDesc([]),o=new QG.QOpDesc([]);for(const u of this.operation.list)switch(u.queryRefinementStage){case ID.LegalRefinementStage.Head:s.push(u);break;case ID.LegalRefinementStage.Single:u.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case ID.LegalRefinementStage.Tail:o.push(u);break;default:u.logError("illegal-refinement-operation","Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){const u=i.length-1;this.has({tailRefinements:o});const a=(0,q6e.getFinalStruct)(this,e.structDef(),i.slice(-1));i[u]=this.getOp(new U6e.StaticSourceSpace(a),void 0,o,i[u])}return i}getImplicitName(){}}d5.QOpDescView=z6e;var yn={},Q6e=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),G6e=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),W6e=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Q6e(e,t,n);return G6e(e,t),e};Object.defineProperty(yn,"__esModule",{value:!0}),yn.FieldDefinitionValue=yn.DefSpace=yn.DimensionFieldDeclaration=yn.MeasureFieldDeclaration=yn.DeclareFieldDeclaration=yn.ProjectFieldDeclaration=yn.GroupByFieldDeclaration=yn.AggregateFieldDeclaration=yn.CalculateFieldDeclaration=yn.AtomicFieldDeclaration=void 0;const BD=Ke,GG=W6e(Wt),V6e=oh,Y6e=Ye,Nf=qn,K6e=Sr,X6e=Cr;class R0 extends Y6e.MalloyElement{constructor(e,n,r){super({expr:e}),this.expr=e,this.defineName=n,this.exprSrc=r,this.isNoteableObj=!0,this.extendNote=K6e.extendNoteMethod}getName(){return this.defineName}fieldDef(e,n){return this.queryFieldDef(new $D(e,this),n)}executesInOutputSpace(){return!1}queryFieldDef(e,n){let r;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const o=this.executesInOutputSpace()?i():e;r=this.expr.getExpression(o)}catch(o){return this.logError("failed-field-definition",`Cannot define '${n}', ${o.message}`),{name:n,type:"error"}}if(r.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),r={type:"number",value:r.value,expressionType:r.expressionType,evalSpace:r.evalSpace,compositeFieldUsage:r.compositeFieldUsage}),(0,BD.isAtomicFieldType)(r.type)&&r.type!=="error"){this.typecheckExprValue(r);const o=(0,BD.mkFieldDef)(GG.atomicDef(r),n);return(o.type==="date"||o.type==="timestamp")&&(0,V6e.isGranularResult)(r)&&(o.timeframe=r.timeframe),o.location=this.location,o.e=r.value,o.compositeFieldUsage=r.compositeFieldUsage,r.expressionType&&(o.expressionType=r.expressionType),this.exprSrc&&(o.code=this.exprSrc),this.note&&(o.annotation=this.note),o}if(!(e instanceof $D&&e.foundCircle)&&r.type!=="error"){const o=GG.inspect(r);this.logError("invalid-type-for-field-definition",`Cannot define '${n}', unexpected type: ${o}`)}return{name:n,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new WG(e,this))}}yn.AtomicFieldDeclaration=R0;class J6e extends R0{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}yn.CalculateFieldDeclaration=J6e;class Z6e extends R0{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckAggregate)(e,this)}}yn.AggregateFieldDeclaration=Z6e;class eRe extends R0{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckGroupBy)(e,this)}}yn.GroupByFieldDeclaration=eRe;class tRe extends R0{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckProject)(e,this)}}yn.ProjectFieldDeclaration=tRe;class nRe extends R0{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckDeclare)(e,this)}}yn.DeclareFieldDeclaration=nRe;class rRe extends R0{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckMeasure)(e,this)}}yn.MeasureFieldDeclaration=rRe;class iRe extends R0{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Nf.typecheckDimension)(e,this)}}yn.DimensionFieldDeclaration=iRe;class $D{constructor(e,n){this.realFS=e,this.circular=n,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}yn.DefSpace=$D;class WG extends X6e.SpaceField{constructor(e,n){super(),this.space=e,this.exprDef=n,this.fieldName=n.defineName}get name(){return this.fieldName}fieldDef(){var e;const n=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=n,n}getQueryFieldDef(e){if(!this.defInQuery){const n=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=n}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,BD.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}entryType(){return(this.defInQuery||this.fieldDef()).type}}yn.FieldDefinitionValue=WG;var A5={};Object.defineProperty(A5,"__esModule",{value:!0}),A5.Aggregate=void 0;const sRe=xs,VG=Dn;let oRe=class extends sRe.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=VG.LegalRefinementStage.Single,this.forceQueryClass=VG.QueryClass.Grouping}};A5.Aggregate=oRe;var _5={};Object.defineProperty(_5,"__esModule",{value:!0}),_5.Calculate=void 0;const uRe=xs,aRe=Dn;class lRe extends uRe.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=aRe.LegalRefinementStage.Single}}_5.Calculate=lRe;var Jg={};Object.defineProperty(Jg,"__esModule",{value:!0}),Jg.Dimensions=void 0;const cRe=f0;class fRe extends cRe.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}Jg.Dimensions=fRe;var Zg={};Object.defineProperty(Zg,"__esModule",{value:!0}),Zg.Measures=void 0;const xRe=f0;class dRe extends xRe.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}Zg.Measures=dRe;var v5={};Object.defineProperty(v5,"__esModule",{value:!0}),v5.Nests=void 0;const hRe=xs,YG=Dn;class pRe extends hRe.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=YG.LegalRefinementStage.Single,this.forceQueryClass=YG.QueryClass.Grouping}}v5.Nests=pRe;var S5={};Object.defineProperty(S5,"__esModule",{value:!0}),S5.ProjectStatement=void 0;const gRe=xs,KG=Dn;class mRe extends gRe.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=KG.QueryClass.Project,this.queryRefinementStage=KG.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}S5.ProjectStatement=mRe;var O0={},Wa={};Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.findReferences=Wa.deprecatedParseTableURI=Wa.constructTableKey=void 0;const yRe=Wl,kD=fn;function PD(t){const e=(0,kD.getStringIfShort)(t);if(e)return e;const n=[],r=t.string().sqlString();if(r){for(const i of(0,kD.getStringParts)(r))typeof i=="string"&&n.push(i);return n.join("")}return""}class ERe{constructor(e,n){this.trans=e,this.tokens=n,this.needTables={},this.needImports={}}registerTableReference(e,n,r){const i=XG(e,n);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:n,firstReference:r})}enterTableMethod(e){const n=(0,kD.getId)(e.connectionId()),r=PD(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(n,r,i)}enterTableFunction(e){const n=PD(e.tableURI()),{connectionName:r,tablePath:i}=JG(n),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const n=PD(e);this.needImports[n]||(this.needImports[n]=this.trans.rangeFromContext(e))}}function XG(t,e){return t===void 0?e:`${t}:${e}`}Wa.constructTableKey=XG;function JG(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,n,r]=e;return{connectionName:n,tablePath:r}}else return{tablePath:t}}Wa.deprecatedParseTableURI=JG;function ARe(t,e,n){const r=new ERe(t,e),i=r;return yRe.ParseTreeWalker.DEFAULT.walk(i,n),{tables:r.needTables,urls:r.needImports}}Wa.findReferences=ARe,Object.defineProperty(O0,"__esModule",{value:!0}),O0.TableFunctionSource=O0.TableMethodSource=O0.TableSource=void 0;const ZG=Wa,_Re=ks,eW=Ur;class MD extends _Re.Source{getSourceDef(){var e,n,r;const i=this.getTableInfo();if(i===void 0)return eW.ErrorFactory.structDef;const{tablePath:s,connectionName:o}=i,u=(0,ZG.constructTableKey)(o,s),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(u);let l=`Schema read failure for table '${s}' for connection '${o}'`;if(a){if(a.status==="present"){(n=this.document())===null||n===void 0||n.checkExperimentalDialect(this,a.value.dialect),a.value.location=this.location,a.value.fields.forEach(f=>{f.location=this.location});const c={...a.value,fields:a.value.fields.map(f=>({...f,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(c),c}a.status==="error"&&(l=a.message)}return this.logError("failed-to-fetch-table-schema",l),eW.ErrorFactory.structDef}}O0.TableSource=MD;class vRe extends MD{constructor(e,n){super(),this.connectionName=e,this.tablePath=n,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}O0.TableMethodSource=vRe;class SRe extends MD{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,ZG.deprecatedParseTableURI)(this.tableURI)}}O0.TableFunctionSource=SRe;var C5={};Object.defineProperty(C5,"__esModule",{value:!0}),C5.SQLString=void 0;const CRe=Ye,tW=So;class bRe extends CRe.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(TRe)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof tW.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const n of this.elements)if(typeof n=="string")e.push({sql:n});else{const r=n.getQuery();r?e.push(r.query()):n.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}C5.SQLString=bRe;function TRe(t){return t instanceof tW.SourceQueryElement}var b5={};Object.defineProperty(b5,"__esModule",{value:!0}),b5.SourceDesc=void 0;const RRe=Ye;class ORe extends RRe.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}b5.SourceDesc=ORe;var T5={};Object.defineProperty(T5,"__esModule",{value:!0}),T5.isSourceProperty=void 0;const DRe=wu,wRe=f0,FRe=Zd,NRe=d0,LRe=eh,IRe=th,BRe=nh,$Re=x0,kRe=Fi;function PRe(t){return t instanceof DRe.Filter||t instanceof kRe.JoinStatement||t instanceof wRe.DeclareFields||t instanceof FRe.FieldListEdit||t instanceof NRe.Renames||t instanceof LRe.PrimaryKey||t instanceof $Re.ObjectAnnotation||t instanceof IRe.Views||t instanceof BRe.TimezoneStatement}T5.isSourceProperty=PRe;var R5={};Object.defineProperty(R5,"__esModule",{value:!0}),R5.isFieldCollectionMember=void 0;const MRe=yn,nW=ht;function jRe(t){return t instanceof nW.FieldReference||t instanceof nW.WildcardFieldReference||t instanceof MRe.AtomicFieldDeclaration}R5.isFieldCollectionMember=jRe;var O5={};Object.defineProperty(O5,"__esModule",{value:!0}),O5.isQueryElement=void 0;const URe=rh,qRe=ih,HRe=Cg,zRe=bg;function QRe(t){return t instanceof URe.QueryArrow||t instanceof qRe.QueryRefine||t instanceof HRe.QueryReference||t instanceof zRe.QueryRaw}O5.isQueryElement=QRe;var rW={};Object.defineProperty(rW,"__esModule",{value:!0});var D5={};Object.defineProperty(D5,"__esModule",{value:!0}),D5.isQueryProperty=void 0;function GRe(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}D5.isQueryProperty=GRe;var w5={};Object.defineProperty(w5,"__esModule",{value:!0}),w5.isQueryExtendProperty=void 0;const WRe=Jg,VRe=Fi,YRe=Zg;function KRe(t){return t instanceof WRe.Dimensions||t instanceof YRe.Measures||t instanceof VRe.JoinStatement}w5.isQueryExtendProperty=KRe;var F5={};Object.defineProperty(F5,"__esModule",{value:!0}),F5.isFieldPropStatement=void 0;const XRe=m0,JRe=wu,ZRe=y0,eOe=fh;function tOe(t){return t instanceof JRe.Filter||t instanceof ZRe.Limit||t instanceof eOe.PartitionBy||t instanceof XRe.FunctionOrdering}F5.isFieldPropStatement=tOe,function(t){var e=T&&T.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=T&&T.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(lg,t),n(Vd,t),n(Yd,t),n(ks,t),n(xg,t),n(So,t),n(J_,t),n(Z_,t),n(nv,t),n(Eg,t),n(sv,t),n(ov,t),n(vo,t),n(Zd,t),n(eh,t),n(d0,t),n(th,t),n(nh,t),n(av,t),n(ah,t),n(cv,t),n(m0,t),n(fv,t),n(Ha,t),n(xv,t),n(ch,t),n(dv,t),n(hv,t),n(pv,t),n(qa,t),n(gv,t),n(mv,t),n(Ev,t),n(wg,t),n(Og,t),n(_f,t),n(_v,t),n(vv,t),n(Cv,t),n(Tv,t),n(Rv,t),n(Ov,t),n(Dv,t),n(wv,t),n(Fv,t),n(Nv,t),n(Lv,t),n(Iv,t),n(Bv,t),n($v,t),n(Pv,t),n(Uv,t),n(rr,t),n(r5,t),n(fh,t),n(_h,t),n(Sh,t),n(s5,t),n(Df,t),n(g0,t),n(o5,t),n(Fg,t),n(C0,t),n(Gg,t),n(u5,t),n(a5,t),n(l5,t),n(ih,t),n(rh,t),n(b0,t),n(c5,t),n(f5,t),n(x5,t),n(d5,t),n(yn,t),n(ht,t),n(A5,t),n(_5,t),n(f0,t),n(Jg,t),n(Gg,t),n(wu,t),n(Xg,t),n(Yg,t),n(Fi,t),n(cg,t),n(y0,t),n(Zg,t),n(lg,t),n(v5,t),n(wf,t),n(S5,t),n(Vg,t),n(Kg,t),n(sh,t),n(Af,t),n(Tg,t),n(O0,t),n(C5,t),n(x0,t),n(Co,t),n(b5,t),n(T5,t),n(ct,t),n(R5,t),n(E0,t),n(Ye,t),n(O5,t),n(rW,t),n(D5,t),n(w5,t),n(F5,t)}(z_);var N5={},bh={};Object.defineProperty(bh,"__esModule",{value:!0}),bh.ConstantExpression=bh.ConstantFieldSpace=void 0;const nOe=ct;class iW{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}bh.ConstantFieldSpace=iW;class rOe extends nOe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new iW),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,n,r){return this.expr.apply(e,n,r)}requestExpression(e){return this.expr.requestExpression(e)}}bh.ConstantExpression=rOe;var iOe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),sOe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oOe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&iOe(e,t,n);return sOe(e,t),e};Object.defineProperty(N5,"__esModule",{value:!0}),N5.MalloyToAST=void 0;const sW=PA,uOe=xp,te=oOe(z_),jD=Q_,oW=Jn,aOe=z_,kn=fn,UD=Ke,lOe=ou,cOe=bh,fOe=Ru;class uW extends te.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class qD extends te.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const xOe=["##! m4warnings=error"];class dOe extends uOe.AbstractParseTreeVisitor{constructor(e,n,r){super(),this.parseInfo=e,this.msgLog=n,this.compilerFlags=r;for(const i of xOe){const s=lOe.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,n){return this.contextError(e,"internal-translator-error",{message:n}),new Error(`Internal Translator Error: ${n}`)}astError(e,n,r,i){this.msgLog.log((0,jD.makeLogMessage)(n,r,{at:e.location,...i}))}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new oW.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,n,r,i){this.msgLog.log((0,jD.makeLogMessage)(n,r,{at:this.getLocation(e),...i}))}warnWithReplacement(e,n,r,i){this.msgLog.log((0,jD.makeLogMessage)(e,n,{at:{url:this.parseInfo.sourceURL,range:r},severity:"warn",replacement:i}))}inExperiment(e,n){const r=this.compilerFlags.tag("experimental");return r&&(r.bare()||r.has(e))?!0:(this.contextError(n,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,n,r){const i=this.m4Severity();i&&this.contextError(e,n,r,{severity:i})}only(e,n,r){const i=[];for(const s of e){const o=n(s);o?i.push(o):s instanceof qD||this.astError(s,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${s.elementType}' when it needed '${r}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new te.FieldName((0,kn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new te.ModelEntryReference((0,kn.getId)(e)),e.id())}defaultResult(){return new te.Unimplemented}astAt(e,n){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(n)},e}getSourceCode(e){const n=e.start.startIndex,r=e.stop||e.start,i=new oW.Interval(n,r.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){const n=this.getFieldExpr(e),r=new te.FilterElement(n,this.getSourceCode(e));return this.astAt(r,e)}getFieldDefs(e,n){return e.map(r=>this.getFieldDef(r,n))}getFieldExpr(e){const n=this.visit(e);if(n instanceof te.ExpressionDef)return this.astAt(n,e);throw this.internalError(e,`expression node unknown type '${n.elementType}'`)}getFilterShortcut(e){const n=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"filter-shortcut","Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new te.Filter([n])}getPlainStringFrom(e){const[n,r]=(0,kn.getPlainString)(e);for(const i of r)i instanceof sW.ParserRuleContext&&this.contextError(i,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return n||""}makeSqlString(e,n){for(const r of e.sqlInterpolation())r.CLOSE_CODE()&&this.m4advisory(r,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const r of(0,kn.getStringParts)(e))r instanceof sW.ParserRuleContext?n.push(this.visit(r)):n.push(r);n.complete(),this.astAt(n,e)}parseTime(e,n){let r=n(e.text);return r||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),r=new te.LiteralTimestamp({text:e.text})),this.astAt(r,e)}getNotes(e){return e.ANNOTATION().map(n=>({text:n.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const n=this.only(e.malloyStatement().map(r=>this.visit(r)),r=>te.isDocStatementOrDocStatementList(r)&&r,"statement");return new te.Document(n)}visitDefineSourceStatement(e){const r=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new te.DefineSourceList(r);return s.extendNote({blockNotes:i}),s}getSourceParameter(e){const n=e.fieldExpr(),r=n?this.astAt(new cOe.ConstantExpression(this.getFieldExpr(n)),n):void 0,i=e.malloyType(),s=i?this.getMalloyType(i):void 0;return this.astAt(new te.HasParameter({name:(0,kn.getId)(e.parameterNameDef()),type:s,default:r}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(n=>this.getSourceParameter(n)))}visitSourceDefinition(e){const n=this.visit(e.sqExplore()),r=this.getSourceParameters(e.sourceParameters()),i=new te.DefineSource((0,kn.getId)(e.sourceNameDef()),n instanceof te.SourceQueryElement?n:void 0,!0,r),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const n=e.filterShortcut(),r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>te.isSourceProperty(s)&&s,"source property"),i=new te.SourceDesc(r);return n&&i.push(this.getFilterShortcut(n)),i}visitTableFunction(e){const n=this.getPlainStringFrom(e.tableURI()),r=this.astAt(new te.TableFunctionSource(n),e);return this.m4advisory(e,"table-function","`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),r}visitTableMethod(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=this.getPlainStringFrom(e.tablePath());return this.astAt(new te.TableMethodSource(r,i),e)}visitSqlSource(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=new te.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);const o=e.shortString();o&&i.push((0,kn.getShortString)(o));const u=new te.SQLSource(r,i);return this.astAt(u,e)}visitDefJoinMany(e){const n=this.getAccessLabel(e.accessLabel()),r=[];for(const s of e.joinList().joinDef()){const o=this.visit(s);o instanceof te.Join&&(r.push(o),o instanceof te.ExpressionJoin?(o.joinType="many",o.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):o instanceof te.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const i=new te.JoinStatement(r,n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinOne(e){const n=this.getAccessLabel(e.accessLabel()),r=this.getJoinList(e.joinList()),i=[];for(const o of r)o instanceof te.Join&&(i.push(o),o instanceof te.ExpressionJoin&&(o.joinType="one"));const s=new te.JoinStatement(i,n);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinCross(e){const n=this.getAccessLabel(e.accessLabel()),r=this.getJoinList(e.joinList()),i=[];for(const o of r)o instanceof te.Join&&(i.push(o),o instanceof te.ExpressionJoin?o.joinType="cross":o.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const s=new te.JoinStatement(i,n);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}getJoinList(e){return this.only(e.joinDef().map(n=>this.visit(n)),n=>n instanceof te.Join&&n,"join")}getJoinFrom(e){const n=e.isExplore(),r=this.getModelEntryName(e.joinNameDef());if(n){const s=this.getSqExpr(n.sqExpr()),o=this.getNotes(n._before_is).concat(this.getNotes(n._after_is));return{joinFrom:s,notes:o,joinAs:r}}const i=e.sourceArguments();return i?{joinFrom:this.astAt(new te.SQReference(r,this.getSQArguments(i)),e),notes:[],joinAs:r}:{joinAs:r,joinFrom:new te.SQReference(r),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var n;const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=new te.ExpressionJoin(r,i),u=e.joinExpression(),a=((n=e.matrixOperation())===null||n===void 0?void 0:n.text.toLocaleLowerCase())||"left";return(0,UD.isMatrixOperation)(a)?o.matrixOperation=a:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),u&&(o.joinOn=this.getFieldExpr(u)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){const{joinAs:n,joinFrom:r,notes:i}=this.getJoinFrom(e.joinFrom()),s=this.getFieldExpr(e.fieldExpr()),o=new te.KeyJoin(n,r,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,n){const r=e.fieldExpr(),i=(0,kn.getId)(e.fieldNameDef()),s=this.getFieldExpr(r),o=new n(s,i,this.getSourceCode(r)),u=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:u}),this.astAt(o,e)}visitDefDimensions(e){const n=this.getAccessLabel(e.accessLabel()),r=this.getFieldDefs(e.defList().fieldDef(),te.DimensionFieldDeclaration),i=new te.Dimensions(r,n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(i,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const n=this.getAccessLabel(e.accessLabel()),r=this.getFieldDefs(e.defList().fieldDef(),te.MeasureFieldDeclaration),i=new te.Measures(r,n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(i,e)}visitQueryExtend(e){const n=[],r=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(const s of r)if(te.isQueryExtendProperty(s))n.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);const i=new te.ExtendBlock(n);return this.astAt(i,e)}visitDeclareStatement(e){const n=this.getAccessLabel(e.accessLabel()),r=this.getFieldDefs(e.defList().fieldDef(),te.DeclareFieldDeclaration),i=new te.DeclareFields(r,n),s=this.astAt(i,e);return this.m4advisory(e,"declare","`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),s}visitExploreRenameDef(e){const n=e.fieldName(0),r=e.fieldName(1),i=new te.RenameField((0,kn.getId)(n),this.getFieldName(r));return this.astAt(i,e)}visitDefExploreRename(e){const n=this.getAccessLabel(e.accessLabel()),i=e.renameList().exploreRenameDef().map(o=>this.visitExploreRenameDef(o)),s=new te.Renames(i,n);return this.astAt(s,e)}visitFilterClauseList(e){return new te.Filter(e.fieldExpr().map(n=>this.getFilterElement(n)))}visitWhereStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!1,this.astAt(n,e)}visitHavingStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!0,this.astAt(n,e)}visitDefExploreQuery(e){const n=this.getAccessLabel(e.accessLabel()),r=e.subQueryDefList().exploreQueryDef().map(o=>this.visitExploreQueryDef(o)),i=new te.Views(r,n),s=this.getNotes(e.tags());return i.extendNote({blockNotes:s}),e.QUERY()&&this.m4advisory(e,"query-in-source","Use view: inside of a source instead of query:"),i}visitDefExplorePrimaryKey(e){const n=new te.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(n,e)}getFieldNameList(e,n){const r=e.fieldName().map(i=>this.astAt(new n([this.getFieldName(i)]),i));return new te.FieldReferences(r)}visitDefExploreEditField(e){const n=e.ACCEPT()?"accept":"except";return new te.FieldListEdit(n,this.getFieldNameList(e.fieldNameList(),te.AcceptExceptFieldReference))}visitSQInclude(e){const n=this.getSqExpr(e.sqExpr()),r=e.includeBlock(),i=r?this.getIncludeItems(r):void 0,s=new te.SQExtend(n,new te.SourceDesc([]),i);return this.astAt(s,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const n=this.getPlainStringFrom(e),r=this.astAt(new te.TimezoneStatement(n),e.string());return r.isValid||this.astError(r,"invalid-timezone",{timezone:r.tz}),this.astAt(r,e)}visitQueryProperties(e){const n=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>te.isQueryProperty(i)&&i,"query statement"),r=e.filterShortcut();return r&&n.push(this.getFilterShortcut(r)),new te.QOpDesc(n)}getFieldPath(e,n){const r=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new n(r),e)}getQueryFieldDef(e,n){const r=this.getFieldDef(e,n);return this.astAt(r,e)}getQueryFieldEntry(e,n,r){const i=e.taggedRef();if(i)return this.getTaggedRef(i,n,r);const s=e.fieldDef();if(s)return this.getQueryFieldDef(s,n);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,n,r){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,n,r)),i=>i instanceof te.FieldReference||i instanceof te.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){const n=new te.Aggregate(this.getQueryItems(e.queryFieldList(),te.AggregateFieldDeclaration,te.AggregateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitGroupByStatement(e){const n=new te.GroupBy(this.getQueryItems(e.queryFieldList(),te.GroupByFieldDeclaration,te.GroupByFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCalculateStatement(e){const n=new te.Calculate(this.getQueryItems(e.queryFieldList(),te.CalculateFieldDeclaration,te.CalculateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}getTaggedRef(e,n,r){const i=e.refExpr();if(i){const o=this.getFieldPath(e.fieldPath(),te.ExpressionFieldReference);let u;const a=i.timeframe();a&&(u=new te.ExprGranularTime(new te.ExprIdReference(o),this.visitTimeframe(a).text,!0));const l=i.aggregate();if(l){const f=l.text.toLowerCase();if(f==="sum")u=new te.ExprSum(void 0,o);else return this.contextError(l,"invalid-reference-only-aggregation",`\`${f}\` is not legal in a reference-only aggregation`),o}const c=new n(u,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}const s=this.getFieldPath(e.fieldPath(),r);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,n,r){const i=e.fieldDef();if(i)return this.getFieldDef(i,n);const s=e.taggedRef();if(s)return this.getTaggedRef(s,n,r);const o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const n=e.collectionMember().map(r=>this.getFieldCollectionMember(r,te.ProjectFieldDeclaration,te.ProjectFieldReference));return this.astAt(new te.ProjectStatement(n),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","project: keyword is deprecated, use select:");const n=this.visitFieldCollection(e.fieldCollection());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCollectionWildCard(e){var n;const r=e.fieldPath(),i=r?this.getFieldPath(r,te.ProjectFieldReference):void 0,s=this.astAt(new te.WildcardFieldReference(i),e),o=((n=e.starQualified())===null||n===void 0?void 0:n.fieldNameList())||[];for(const u of o)for(const a of u.fieldName())s.except.add((0,kn.getId)(a));return s}visitIndexFields(e){const n=e.indexElement().map(r=>{const i=r.fieldPath();if(!i)return this.astAt(new te.WildcardFieldReference(void 0),e);const s=this.getFieldPath(i,te.IndexFieldReference);return r.STAR()?this.astAt(new te.WildcardFieldReference(s),e):this.astAt(s,e)});return new te.FieldReferences(n)}visitIndexStatement(e){const n=this.visitIndexFields(e.indexFields()),r=new te.Index(n),i=e.fieldName();return i&&r.useWeight(this.getFieldName(i)),this.astAt(r,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new te.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0;return this.astAt(new te.FunctionOrderBy(i,n),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const n=e.aggregateOrderBySpec().map(r=>this.visitAggregateOrderBySpec(r));return this.astAt(new te.FunctionOrdering(n),e)}visitOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.INTEGER_LITERAL();if(r)return new te.OrderBy(this.getNumber(r),n);const i=e.fieldName();if(i)return new te.OrderBy(this.getFieldName(i),n);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const n=e.orderBySpec().map(r=>this.visitOrderBySpec(r));return this.astAt(new te.Ordering(n),e)}visitTopStatement(e){const n=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new te.Limit(n),e)}visitTopLevelQueryDefs(e){const n=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),r=this.getNotes(e.tags()),i=new te.DefineQueryList(n);return i.extendNote({blockNotes:r}),i}visitTopLevelQueryDef(e){const n=(0,kn.getId)(e.queryName()),r=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(r instanceof te.SourceQueryElement){const s=new te.DefineQuery(n,r);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${r.elementType}'`)}visitAnonymousQuery(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new te.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(n,"anonymous-query","Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new te.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){const n=this.visitNestedQueryList(e.nestedQueryList());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitNestedQueryList(e){return new te.Nests(this.only(e.nestEntry().map(n=>this.visit(n)),n=>n instanceof te.NestFieldDeclaration&&n,"query"))}visitNestDef(e){const n=e.queryName();let r;const i=this.getVExpr(e.vExpr());if(n)r=(0,kn.getId)(n);else{const u=i.getImplicitName();u===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),r=u??"__unnamed__"}const s=new te.NestFieldDeclaration(r,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){const n=(0,kn.getId)(e.exploreQueryNameDef()),r=new te.ViewFieldDeclaration(n,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return r.extendNote({notes:i}),this.astAt(r,e)}visitExprNot(e){return new te.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new te.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(n=>this.getFieldExpr(n))}visitExprLogicalOr(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new te.ExprLogicalOp(n,"or",r)}visitExprLogicalAnd(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new te.ExprLogicalOp(n,"and",r)}visitExprOrTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new te.ExprAlternationTree(n,"|",r),e)}visitExprAndTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new te.ExprAlternationTree(n,"&",r),e)}visitExprCoalesce(e){const n=this.getFieldExpr(e.fieldExpr()[0]),r=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new te.ExprCoalesce(n,r),e)}visitPartialAllowedFieldExpr(e){var n;const r=this.getFieldExpr(e.fieldExpr()),i=(n=e.compareOp())===null||n===void 0?void 0:n.text;if(i){if(te.isComparison(i))return this.astAt(new te.PartialCompare(i,r),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return r}visitExprString(e){const n=this.getPlainStringFrom(e);return new te.ExprString(n)}visitExprRegex(e){const n=e.HACKY_REGEX().text;return new te.ExprRegEx(n.slice(2,-1))}visitExprNow(e){return new te.ExprNow}visitExprNumber(e){return new te.ExprNumber(e.text)}visitExprFieldPath(e){const n=new te.ExprIdReference(this.getFieldPath(e.fieldPath(),te.ExpressionFieldReference));return this.astAt(n,e)}visitExprNULL(e){return new te.ExprNULL}visitExprExpr(e){return new te.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new te.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new te.ExprAddSub(n,i,r)}visitExprMulDiv(e){const n=e.STAR()?"*":e.SLASH()?"/":"%";return new te.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const n=e.compareOp().text,r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));if(te.isEquality(n))return this.astAt(new te.ExprEquality(r,n,i),e);if(te.isComparison(n))return this.astAt(new te.ExprCompare(r,n,i),e);throw this.internalError(e,`untranslatable comparison operator '${n}'`)}visitExprUngroup(e){const n=e.fieldName().map(i=>this.getFieldName(i)),r=e.ungroup().text.toLowerCase();return this.astAt(new te.ExprUngroup(r==="all"?r:"exclude",this.getFieldExpr(e.fieldExpr()),n),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const n=e.fieldPath(),r=this.getFieldPath(n,te.ExpressionFieldReference),i=n&&r?this.astAt(r,n):void 0,s=e.aggregate().text.toLowerCase(),o=e.fieldExpr();if(e.aggregate().COUNT())return o&&this.contextError(o,"count-expression-with-locality","Expression illegal inside path.count()"),new te.ExprCount(i);const u=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(u)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s));else{const a=this.astAt(new te.ExprIdReference(r),n);return s==="min"?new te.ExprMin(a):new te.ExprMax(a)}else{if(s==="avg")return new te.ExprAvg(u,i);if(s==="sum")return new te.ExprSum(u,i);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${s}`)}return new te.ExprNULL}visitExprPathlessAggregate(e){const n=e.fieldExpr(),r=n?this.getFieldExpr(n):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,"wildcard-in-aggregate",`* illegal inside ${s}()`),s==="count")return this.astAt(r?new te.ExprCountDistinct(r):new te.ExprCount,e);if(s==="min"){if(r)return new te.ExprMin(r);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s))}else if(s==="max"){if(r)return new te.ExprMax(r);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(s))}else{if(r===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(s)),new te.ExprNULL;const o=e.SOURCE_KW()!==void 0;if(s==="avg")return new te.ExprAvg(r,i,o);if(s==="sum")return new te.ExprSum(r,i,o)}return new te.ExprNULL}visitExprApply(e){return new te.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new te.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new te.ExprCast(this.getFieldExpr(e.fieldExpr()),n)}getMalloyType(e){const n=e.text;if((0,UD.isCastType)(n))return n;throw this.internalError(e,`unknown type '${n}'`)}getMalloyOrSQLType(e){const n=e.malloyType();if(n)return this.getMalloyType(n);const r=e.string();if(r)return{raw:this.getPlainStringFrom({string:()=>r})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new te.ExprCast(this.getFieldExpr(e.fieldExpr()),n,!0)}visitExprTimeTrunc(e){return new te.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new te.Timeframe(e.text)}visitExprForRange(e){const n=this.getFieldExpr(e._startAt),r=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new te.ForRange(n,r,i)}visitExprAggFunc(e){const n=e.argumentList(),r=n?this.allFieldExpressions(n.fieldExpr()):[],i=(0,kn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,te.ExpressionFieldReference):void 0,u=s&&o?this.astAt(o,s):void 0;return te.ExprTimeExtract.extractor(i)?this.astAt(new te.ExprTimeExtract(i,r),e):this.astAt(new te.ExprFunc(i,r,!1,void 0,u),e)}visitExprFunc(e){var n,r;const i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,u=(n=e.malloyType())===null||n===void 0?void 0:n.text;let a;u&&((0,UD.isCastType)(u)?a=u:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${u}'`),a=void 0));let l=(0,kn.getOptionalId)(e)||((r=e.timeframe())===null||r===void 0?void 0:r.text);return l===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),l="FUNCTION_NAME_ERROR"),te.ExprTimeExtract.extractor(l)?this.astAt(new te.ExprTimeExtract(l,s),e):this.astAt(new te.ExprFunc(l,s,o,a),e)}visitExprDuration(e){return new te.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const n=e._valueExpr,r=n?this.getFieldExpr(n):void 0,i=e.caseWhen(),s=i.map(a=>new te.CaseWhen(this.getFieldExpr(a._condition),this.getFieldExpr(a._result))),o=e._caseElse,u=o?this.getFieldExpr(o):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.parseInfo.rangeFromContext(e),`${[...n?[`${this.getSourceCode(n)} ?`]:[],...i.map(a=>`pick ${this.getSourceCode(a._result)} when ${this.getSourceCode(a._condition)}`),o?`else ${o.text}`:"else null"].join(" ")}`),new te.Case(r,s,u)}visitPickStatement(e){const n=e.pick().map(r=>{let i;return r._pickValue&&(i=this.getFieldExpr(r._pickValue)),new te.PickWhen(i,this.getFieldExpr(r._pickWhen))});return e.ELSE()?new te.Pick(n,this.getFieldExpr(e._pickElse)):new te.Pick(n)}visitExprFieldProps(e){const n=this.only(e.fieldProperties().fieldPropertyStatement().map(r=>this.visit(r)),r=>te.isFieldPropStatement(r)&&r,"field property statement");return new te.ExprProps(this.getFieldExpr(e.fieldExpr()),n)}visitPartitionByStatement(e){return this.astAt(new te.PartitionBy(e.id().map(n=>this.astAt(new te.PartitionByFieldReference([this.astAt(new te.FieldName((0,kn.idToStr)(n)),n)]),n))),e)}visitLiteralTimestamp(e){return this.parseTime(e,te.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,te.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,te.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,te.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,te.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,te.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,te.LiteralYear.parse)}visitImportStatement(e){const n=this.getPlainStringFrom(e.importURL()),r=this.astAt(new te.ImportStatement(n,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(const s of i.importItem()){const o=s.id(),u=o[1]?this.astAt(new te.ImportSourceName((0,kn.idToStr)(o[1])),o[1]):void 0;r.push(this.astAt(new te.ImportSelect((0,kn.idToStr)(o[0]),u),o[0]))}return r}visitDebugExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const n=e.sampleSpec().INTEGER_LITERAL();if(n)return new te.SampleProperty({rows:this.getNumber(n)});const r=e.sampleSpec().PERCENT_LITERAL();if(r)return new te.SampleProperty({percent:this.getNumber(r)});const i=e.sampleSpec().TRUE()!==void 0;return new te.SampleProperty({enable:i})}visitDocAnnotations(e){const n=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),r=new te.ModelAnnotation(n);return this.compilerFlags=r.getCompilerFlags(this.compilerFlags,this.msgLog),r}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new qD(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new qD(e.text)}visitDefExploreAnnotation(e){const n=this.getNotes(e);return new te.ObjectAnnotation(n)}getSQArgument(e){const n=e.argumentId(),r=n?this.astAt(new te.PartitionByFieldReference([this.astAt(new te.FieldName((0,kn.idToStr)(n.id())),n)]),n):void 0;return this.astAt(new te.Argument({id:r,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(n=>this.getSQArgument(n))}visitSQID(e){const n=this.getModelEntryName(e),r=this.getSQArguments(e.sourceArguments());return this.astAt(new te.SQReference(n,r),e.id())}getSqExpr(e){const n=this.visit(e);return n instanceof te.SourceQueryElement?n:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${n.elementType}'`),new uW)}visitSQExtendedSource(e){const n=this.getSqExpr(e.sqExpr()),r=e.includeBlock(),i=r?this.getIncludeItems(r):void 0,s=new te.SQExtend(n,this.getSourceExtensions(e.exploreProperties()),i);return this.astAt(s,e)}getIncludeItems(e){return this.inExperiment("access_modifiers",e),e.includeItem().map(n=>this.getIncludeItem(n)).filter(fOe.isNotUndefined)}getIncludeItem(e){var n;const r=e.tags(),i=r?this.getNotes(r):[],s=e.includeExceptList();if(s){r&&i.length>0&&this.contextError(r,"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const o=this.getExcludeList(s);return this.astAt(new te.IncludeExceptItem(o),e)}else{const o=e.includeList();if(o===void 0){this.contextError((n=e.orphanedAnnotation())!==null&&n!==void 0?n:e,"orphaned-object-annotation","This tag is not attached to anything",{severity:"warn"});return}const u=this.getAccessLabelProp(e.accessLabelProp()),a=this.getIncludeList(o),l=this.astAt(new te.IncludeAccessItem(u,a),e);return l.extendNote({blockNotes:i}),l}}getIncludeList(e){const n=e.includeField();if(n===void 0)throw this.internalError(e,"Expected a field name list");return n.map(r=>this.getIncludeListItem(r))}getExcludeList(e){return e.includeExceptListItem().map(n=>{n.tags().ANNOTATION().length>0&&this.contextError(n.tags(),"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const r=n.fieldName();if(r)return this.astAt(new te.AccessModifierFieldReference([this.astAt(new te.FieldName(n.text),n)]),r);const i=n.collectionWildCard();if(i)return this.astAt(this.visitCollectionWildCard(i),i);throw this.internalError(n,"Expected a field name or wildcard")})}getIncludeListItem(e){const n=e.collectionWildCard(),r=n?this.visitCollectionWildCard(n):void 0,i=e._as?e._as.text:void 0,s=e.tags(),o=s?this.getNotes(s):[],u=e.isDefine(),a=u?this.getIsNotes(u):[],l=[...o,...a],c=e._name?this.astAt(new te.AccessModifierFieldReference([this.astAt(this.getFieldName(e._name),e._name)]),e._name):void 0,f=c??r;if(f===void 0)throw this.internalError(e,"Expected a field name or wildcard");const x=this.astAt(new te.IncludeListItem(f,i),e);return x.extendNote({notes:l}),x}visitSQParens(e){const n=this.getSqExpr(e.sqExpr());return this.astAt(n,e)}visitSQCompose(e){const n=e.sqExpr().map(r=>this.getSqExpr(r));return this.inExperiment("composite_sources",e),this.astAt(new te.SQCompose(n),e)}visitSQArrow(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new te.SQArrow(n,this.getVExpr(r));return this.astAt(i,e)}getVExpr(e){const n=this.visit(e);if(n instanceof te.View)return n;throw this.internalError(e,`Expected view, got a '${n.elementType}'`)}visitSegField(e){return new te.ReferenceView(this.getFieldPath(e.fieldPath(),te.ViewOrScalarFieldReference))}visitSegOps(e){return new te.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new te.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new te.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new te.SQRefine(n,this.getVExpr(r));return this.astAt(i,e)}visitSQTable(e){const n=this.visit(e.exploreTable());if(n instanceof aOe.TableSource){const r=new te.SQSource(n);return this.astAt(r,e)}return new uW}visitSQSQL(e){const n=new te.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(n,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new te.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const n=new te.ExprIdReference(this.getFieldPath(e.fieldPath(),te.ExpressionFieldReference));return this.astAt(new te.RecordElement({path:n}),e)}visitRecordExpr(e){const n=this.getFieldExpr(e.fieldExpr()),r=e.recordKey(),i=r?{key:(0,kn.getId)(r),value:n}:{value:n};return this.astAt(new te.RecordElement(i),e)}visitExprLiteralRecord(e){const n=this.only(e.recordElement().map(r=>this.astAt(this.visit(r),r)),r=>r instanceof te.RecordElement&&r,"a legal record property description");return new te.RecordLiteral(n)}visitExprArrayLiteral(e){const n=e.fieldExpr().map(i=>this.getFieldExpr(i)),r=new te.ArrayLiteral(n);return this.astAt(r,e)}visitExprWarnLike(e){let n="~";const r=e.fieldExpr(0),i=e.fieldExpr(1),s=this.parseInfo.rangeFromContext(e);return e.NOT()?(n="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",s,`${this.getSourceCode(r)} !~ ${this.getSourceCode(i)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",s,`${this.getSourceCode(r)} ~ ${this.getSourceCode(i)}`),this.astAt(new te.ExprCompare(this.getFieldExpr(r),n,this.getFieldExpr(i)),e)}visitExprWarnNullCmp(e){let n="=";const r=e.fieldExpr(),i=this.parseInfo.rangeFromContext(e);e.NOT()?(n="!=",this.warnWithReplacement("sql-is-not-null","Use '!= NULL' to check for NULL instead of 'IS NOT NULL'",i,`${this.getSourceCode(r)} != null`)):this.warnWithReplacement("sql-is-null","Use '= NULL' to check for NULL instead of 'IS NULL'",i,`${this.getSourceCode(r)} = null`);const s=new te.ExprNULL;return this.astAt(new te.ExprCompare(this.getFieldExpr(r),n,s),e)}visitExprWarnIn(e){const n=this.getFieldExpr(e.fieldExpr()),r=!!e.NOT(),i=e.fieldExprList().fieldExpr(),s=this.astAt(new te.ExprLegacyIn(n,r,i.map(o=>this.getFieldExpr(o))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${r?" NOT":""} IN (a,b,c)`,this.parseInfo.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${r?"!=":"="} (${i.map(o=>this.getSourceCode(o)).join(" | ")})`),s}}N5.MalloyToAST=dOe;var L5={};Object.defineProperty(L5,"__esModule",{value:!0}),L5.Zone=void 0;class hOe{constructor(){this.location={},this.zone=new Map}get(e){const n=this.zone.get(e);if((n==null?void 0:n.status)==="present")return n.value}getEntry(e){const n=this.zone.get(e);return n?n.firstReference||!this.location[e]?n:{...n,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,n){this.zone.set(e,{status:"present",value:n})}reference(e,n){const r=this.zone.get(e);(r==null?void 0:r.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:n}),this.location[e]=n)}getUndefined(){const e=[];for(const[n,r]of this.zone)r.status==="reference"&&e.push(n);return e.length>0?e:void 0}updateFrom(e,n){if(e)for(const[r,i]of Object.entries(e))i!==void 0&&this.define(r,i);if(n)for(const[r,i]of Object.entries(n))this.zone.set(r,{status:"error",message:i})}}L5.Zone=hOe;var I5={};Object.defineProperty(I5,"__esModule",{value:!0}),I5.walkForDocumentSymbols=void 0;const pOe=Wl,gOe=fn;class mOe{constructor(e,n,r,i){this.translator=e,this.tokens=n,this.scopes=r,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const n=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=n)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const n=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=n)}enterSourceDefinition(e){const n=this.translator.rangeFromContext(e);this.scopes.push({range:n,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const n=this.popScope();n&&this.symbols.push(n)}enterDefExploreQuery(e){const n=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=n)}enterExploreQueryDef(e){const n={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},r=this.peekScope();r&&r.children.push(n),this.scopes.push(n),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const n=e.queryName();if(n)return n.id().text;let r,i=!1;const s={enterVArrow(u){u.vExpr().enterRule(s)},enterVSeg(u){u.segExpr().enterRule(o)}},o={enterSegField(u){const a=u.fieldPath().fieldName();i||(r??(r=a[a.length-1].id().text))},enterSegParen(u){u.vExpr().enterRule(s)},enterSegRefine(u){u._lhs.enterRule(o)},enterSegOps(){r=void 0,i=!0}};return e.vExpr().enterRule(s),r}handleNestEntry(e){const n=this.getNestDefName(e);if(n===void 0)return;const r={range:this.translator.rangeFromContext(e),name:n,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(r),r}enterNestDef(e){const n=this.handleNestEntry(e);n&&this.scopes.push(n)}exitNestDef(e){this.popScope()}enterFieldDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterQueryFieldEntry(e){var n;const r=(n=e.taggedRef())===null||n===void 0?void 0:n.fieldPath();if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const n={range:this.translator.rangeFromContext(e),name:e.joinFrom().joinNameDef().id().text,type:"join",children:[]},r=this.peekScope();r&&r.children.push(n)}enterImportStatement(e){const n=(0,gOe.getStringIfShort)(e.importURL());n&&this.scopes.push({range:this.translator.rangeFromContext(e),name:n,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const n=this.peekScope();if(n)for(const r of e.importItem()){const i={range:this.translator.rangeFromContext(e),name:r.text,type:"import_item",children:[]};n.children.push(i)}}}function yOe(t,e,n){const r=new mOe(t,e,[],[]),i=r;return pOe.ParseTreeWalker.DEFAULT.walk(i,n),r.symbols}I5.walkForDocumentSymbols=yOe;var B5={};Object.defineProperty(B5,"__esModule",{value:!0}),B5.walkForDocumentCompletions=void 0;const EOe=Wl,AOe=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],_Oe=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],vOe=["source","explore","query","sql"];class SOe{constructor(e,n,r){this.tokens=e,this.completions=n,this.position=r}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){const{start:n,end:r}=e,i=this.position.line>n.line||this.position.line===n.line&&this.position.character>=n.character,s=this.position.line<r.line||this.position.line===r.line&&this.position.character<=r.character;return i&&s}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.exploreStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of AOe)this.completions.push({type:"explore_property",text:`${r}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.queryStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of _Oe)this.completions.push({type:"query_property",text:`${r}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.malloyStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of vOe)this.completions.push({type:"model_property",text:`${r}: `})}}}function COe(t,e,n){const r=new SOe(t,[],n),i=r;return EOe.ParseTreeWalker.DEFAULT.walk(i,e),r.completions}B5.walkForDocumentCompletions=COe;var $5={};Object.defineProperty($5,"__esModule",{value:!0}),$5.walkForDocumentHelpContext=void 0;const bOe=D6;class TOe extends bOe.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let n=this.defaultResult();if(this.inRange(this.rangeOf(e))){n={type:this.type,token:e.start.text};const r=e.childCount;for(let i=0;i<r;i++){const o=e.getChild(i).accept(this);o&&(n=this.aggregateResult(n,o))}}return n}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,n){return n}}function ROe(t,e){return new TOe(e).visit(t)}$5.walkForDocumentHelpContext=ROe;var k5={};Object.defineProperty(k5,"__esModule",{value:!0}),k5.ReferenceList=void 0;const OOe=Ru;class DOe{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let n=0,r=this.references.length;for(;n<r;){const i=Math.floor((n+r)/2),s=this.references[i].location.range.end;s.line<e.line||s.line===e.line&&s.character<e.character?n=i+1:r=i}return n}add(e){if(e.location.url!==this.sourceURL)return;const n=this.findIndexBefore(e.location.range.end);n<this.references.length&&this.isPositionEqual(e,this.references[n])||this.references.splice(n,0,e)}isPositionEqual(e,n){const r=e.location.range,i=n.location.range;return r.start.line===i.start.line&&r.start.character===i.start.character&&r.end.line===i.end.line&&r.end.character===i.end.character}find(e){const n=this.findIndexBefore(e);if(n===this.references.length)return;const r=this.references[n];if((0,OOe.locationContainsPosition)(r.location,e))return r}}k5.ReferenceList=DOe;var P5={};Object.defineProperty(P5,"__esModule",{value:!0}),P5.isNeedResponse=void 0;function wOe(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}P5.isNeedResponse=wOe;var M5={};Object.defineProperty(M5,"__esModule",{value:!0}),M5.walkForModelAnnotation=void 0;const FOe=Wl;class NOe{constructor(e,n,r){this.translator=e,this.tokens=n,this.parseInfo=r,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}enterDocAnnotations(e){const n=e.DOC_ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}));this.notes.push(...n)}get annotation(){return{notes:this.notes}}}function LOe(t,e,n){const r=new NOe(t,e,n),i=r;return FOe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.annotation}M5.walkForModelAnnotation=LOe;var j5={};Object.defineProperty(j5,"__esModule",{value:!0}),j5.walkForTablePath=void 0;const aW=fn,IOe=Wl;class BOe{constructor(e,n){this.translator=e,this.tokens=n,this.pathInfos=[]}enterTableMethod(e){const n=(0,aW.getId)(e.connectionId()),[r,i]=(0,aW.getPlainString)(e.tablePath(),!0);r!==void 0&&this.pathInfos.push({connectionId:n,tablePath:r,range:this.translator.rangeFromContext(e)})}}function $Oe(t,e,n){const r=new BOe(t,e),i=r;return IOe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.pathInfos}j5.walkForTablePath=$Oe;var kOe=T&&T.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),POe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),MOe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&kOe(e,t,n);return POe(e,t),e};Object.defineProperty(_u,"__esModule",{value:!0}),_u.MalloyParserErrorHandler=_u.MalloyTranslator=_u.MalloyChildTranslator=_u.MalloyTranslation=void 0;const lW=PA,jOe=Ke,UOe=ZA,qOe=N,cW=MOe(z_),HOe=N5,HD=Q_,zOe=Wa,zD=L5,QOe=I5,GOe=B5,WOe=$5,VOe=k5,U5=P5,YOe=Ru,fW=ou,KOe=M5,XOe=j5;class JOe extends UOe.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}class ZOe{step(e){if(this.response)return this.response;if(e.urlIsFullPath===void 0)try{const s=new URL(e.sourceURL);e.urlIsFullPath=!0}catch(s){const o=s instanceof Error?s.message:"";e.urlIsFullPath=!1,e.root.logError("failed-to-compute-absolute-import-url",`Could not compute full path URL: ${o}`)}if(!e.urlIsFullPath)return e.fatalResponse();const n=e.root.importZone.getEntry(e.sourceURL);if(n.status!=="present"){if(n.status==="error"){const s=n.firstReference||e.defaultLocation();return e.root.logError("import-error",{message:n.message,url:e.sourceURL},{at:s}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const r=n.value===""?`
1259
1259
  `:n.value;this.sourceInfo=this.getSourceInfo(r);let i;try{i=this.runParser(r,e)}catch(s){e.root.logError("parse-exception",{message:s.message}),i=void 0}return e.root.logger.hasErrors()?this.response={parse:i,...e.fatalResponse()}:this.response={parse:i},this.response}getSourceInfo(e){const n=/\r?\n/,r={at:[],lines:[],length:e.length};let i=e,s=0;for(;i!=="";){const o=i.match(n);if(o&&o.index!==void 0){r.lines.push(i.slice(0,o.index));const u=o.index+o[0].length;r.at.push({begin:s,end:s+u}),s+=u,i=i.slice(u)}else{r.lines.push(i),r.at.push({begin:s,end:s+i.length});break}}return r}runParser(e,n){const r=lW.CharStreams.fromString(e),i=new JOe(r),s=new lW.CommonTokenStream(i),o=new qOe.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new dW(n,n.root.logger));const u=o[n.grammarRule];if(!u)throw new Error(`No such parse rule as ${n.grammarRule}`);return{root:u.call(o),tokenStream:s,sourceStream:r,sourceURL:n.sourceURL,importBaseURL:n.importBaseURL||n.sourceURL,rangeFromContext:a=>n.rangeFromContext(a),malloyVersion:"4.0.0"}}}class e7e{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){const n=this.parseStep.step(e);if(n.parse===void 0)return n;if(!this.parseReferences){this.parseReferences=(0,zOe.findReferences)(e,n.parse.tokenStream,n.parse.root);for(const o in this.parseReferences.tables)e.root.schemaZone.reference(o,{url:e.sourceURL,range:this.parseReferences.tables[o].firstReference});for(const o in this.parseReferences.urls){const u=this.parseReferences.urls[o];try{const a=decodeURI(new URL(o,e.importBaseURL||e.sourceURL).toString());e.addChild(a),e.imports.push({importURL:a,location:{url:e.sourceURL,range:u}}),e.root.importZone.reference(a,{url:e.sourceURL,range:u})}catch{e.root.logError("invalid-import-url",`Malformed URL '${o}'"`,{at:{url:e.sourceURL,range:u}})}}}if(e.root.logger.hasErrors())return null;let r={};const i=e.root.schemaZone.getUndefined();if(i){const o={};for(const u of i){const a=this.parseReferences.tables[u];o[u]={connectionName:a.connectionName,tablePath:a.tablePath}}r={tables:o}}const s=e.root.importZone.getUndefined();if(s&&(r={...r,urls:s}),(0,U5.isNeedResponse)(r))return r;for(const o of e.childTranslators.values()){const u=o.importsAndTablesStep.step(o);if((0,U5.isNeedResponse)(u))return u}return null}}class t7e{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;const n=this.importStep.step(e);if(n)return n;const r=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;const i=r==null?void 0:r.parse;if(!i)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");const s=new HOe.MalloyToAST(i,e.root.logger,e.compilerFlags),o=s.visit(i.root);if(e.compilerFlags=s.compilerFlags,o.elementType==="unimplemented"&&o.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node"),!this.walked){for(const u of o.walk())u instanceof cW.Unimplemented&&u.logError("untranslated-parse-node","INTERNAL COMPILER ERROR: Untranslated parse node");this.walked=!0}if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;for(const u of e.childTranslators.values()){const a=u.astStep.step(u);if((0,U5.isNeedResponse)(a))return a}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}}class n7e{constructor(e){this.parseStep=e}step(e){if(!this.response){const n=this.parseStep.step(e);if(n.parse){let r;try{r=(0,QOe.walkForDocumentSymbols)(e,n.parse.tokenStream,n.parse.root)}catch{}this.response={symbols:r,final:!0}}else return n}return this.response}}class r7e{constructor(e){this.parseStep=e}step(e,n){const r=this.parseStep.step(e);if(r.parse){let i=[];if(n!==void 0)try{i=(0,GOe.walkForDocumentCompletions)(r.parse.tokenStream,r.parse.root,n)}catch{}return{...r,completions:i}}else return r}}class i7e{constructor(e){this.parseStep=e}step(e,n){const r=this.parseStep.step(e);if(r.parse){let i;if(n!==void 0)try{i=(0,WOe.walkForDocumentHelpContext)(r.parse.root,n)}catch{}return{...r,helpContext:i}}else return r}}class s7e{constructor(e){this.parseStep=e}step(e,n){if(!this.response){const r=this.parseStep.step(e);if(!r.parse||r.final)return r;{const i=(0,KOe.walkForModelAnnotation)(e,r.parse.tokenStream,r.parse);this.response={modelAnnotation:{...i,inherits:n==null?void 0:n.annotation}}}}return this.response}}class o7e{constructor(e){this.parseStep=e}step(e){if(!this.response){const n=this.parseStep.step(e);if(n.parse){const r=(0,XOe.walkForTablePath)(e,n.parse.tokenStream,n.parse);this.response={pathInfo:r}}else return n}return this.response}}class u7e{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,n){if(this.response)return this.response;if(n&&!this.importedAnnotations){const i=fW.Tag.annotationToTag(n.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}const r=this.astStep.step(e);if((0,U5.isNeedResponse)(r))return r;if(!r.ast)return this.response=r,this.response;if(e.grammarRule==="malloyDocument")if(r.ast instanceof cW.Document){const i=r.ast;for(i.initModelDef(n);;){const s=i.compile();if(s.needs)return s.needs;e.modelDef=s.modelDef,e.queryList=s.queryList,e.sqlBlocks=s.sqlBlocks;break}}else e.root.logError("parsed-non-malloy-document",{url:e.sourceURL},{at:e.defaultLocation()});return e.root.logger.hasErrors()?this.response={fromSources:e.getDependencies(),...e.fatalResponse()}:this.response={translated:{modelDef:e.modelDef,queryList:e.queryList,sqlBlocks:e.sqlBlocks},fromSources:e.getDependencies(),...e.problemResponse(),final:!0},this.response}}class QD{constructor(e,n=null,r="malloyDocument"){this.sourceURL=e,this.importBaseURL=n,this.grammarRule=r,this.queryList=[],this.sqlBlocks=[],this.imports=[],this.compilerFlags=new fW.Tag,this.dialectAlreadyChecked={},this.allDialectsEnabled=!1,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new ZOe,this.modelAnnotationStep=new s7e(this.parseStep),this.metadataStep=new n7e(this.parseStep),this.completionsStep=new r7e(this.parseStep),this.helpContextStep=new i7e(this.parseStep),this.importsAndTablesStep=new e7e(this.parseStep),this.astStep=new t7e(this.importsAndTablesStep),this.tablePathInfoStep=new o7e(this.parseStep),this.translateStep=new u7e(this.astStep),this.references=new VOe.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new xW(e,this.root))}getDependencies(){const e=[this.sourceURL];for(const[n,r]of this.childTranslators)e.push(...r.getDependencies());return e}addReference(e){this.references.add(e)}referenceAt(e){return this.references.find(e)}fatalResponse(){return{final:!0,...this.problemResponse()}}problemResponse(){return{problems:this.problems()}}problems(){return[...this.root.logger.getLog()]}getLineMap(e){var n,r;if(e===this.sourceURL)return(n=this.parseStep.sourceInfo)===null||n===void 0?void 0:n.lines;const i=this.childTranslators.get(e);if(i)return(r=i.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines}codeAtLocation(e){const n=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return n[e.range.start.line].slice(e.range.start.character,e.range.end.character);let r="";r+=n[e.range.start.line].slice(e.range.start.character);for(let i=e.range.start.line+1;i<e.range.end.line;i++)r+=n[i];return r+=n[e.range.end.line].slice(0,e.range.end.character),r}prettyErrors(){let e="",n="";for(const r of this.root.logger.getLog()){let i=r.message,s=this.sourceURL;if(r.at){s=r.at.url;const o=r.at.range.start.line,u=r.at.range.start.character,a=this.getLineMap(r.at.url);if(a){const l=a[o];i=`line ${o+1}: ${r.message}
1260
1260
  | ${l}`,u>0&&(i=i+`