@malloydata/render 0.0.223 → 0.0.224-dev241217171758

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.
@@ -3440,7 +3440,7 @@ const xce = {
3440
3440
  T: ["string", "number", "date", "timestamp", "boolean", "json"]
3441
3441
  },
3442
3442
  takes: { value: { dimension: { generic: "T" } } },
3443
- returns: { measure: "string" },
3443
+ returns: { measure: { sql_native: "hyperloglog" } },
3444
3444
  isSymmetric: !0,
3445
3445
  impl: {
3446
3446
  function: "APPROX_SET"
@@ -3451,7 +3451,7 @@ const xce = {
3451
3451
  T: ["string", "number", "date", "timestamp", "boolean", "json"]
3452
3452
  },
3453
3453
  takes: { value: { dimension: { generic: "T" } }, accuracy: "number" },
3454
- returns: { measure: "string" },
3454
+ returns: { measure: { sql_native: "hyperloglog" } },
3455
3455
  isSymmetric: !0,
3456
3456
  impl: {
3457
3457
  function: "APPROX_SET"
@@ -3459,30 +3459,30 @@ const xce = {
3459
3459
  }
3460
3460
  }, vce = {
3461
3461
  takes: {
3462
- value: "string"
3462
+ value: { sql_native: "hyperloglog" }
3463
3463
  },
3464
- returns: { measure: "string" },
3464
+ returns: { measure: { sql_native: "hyperloglog" } },
3465
3465
  impl: { function: "MERGE" },
3466
3466
  isSymmetric: !0
3467
3467
  }, Cce = {
3468
3468
  takes: {
3469
- value: "string"
3469
+ value: { sql_native: "hyperloglog" }
3470
3470
  },
3471
3471
  returns: { dimension: "number" },
3472
3472
  impl: { function: "CARDINALITY" }
3473
3473
  }, Sce = {
3474
3474
  takes: {
3475
- value: "string"
3475
+ value: { sql_native: "hyperloglog" }
3476
3476
  },
3477
- returns: { dimension: "string" },
3477
+ returns: { dimension: { sql_native: "varbinary" } },
3478
3478
  impl: {
3479
3479
  sql: "CAST(${value} AS VARBINARY)"
3480
3480
  }
3481
3481
  }, bce = {
3482
3482
  takes: {
3483
- value: "string"
3483
+ value: { sql_native: "varbinary" }
3484
3484
  },
3485
- returns: { dimension: "string" },
3485
+ returns: { dimension: { sql_native: "hyperloglog" } },
3486
3486
  impl: {
3487
3487
  sql: "CAST(${value} AS HyperLogLog)"
3488
3488
  }
@@ -54094,7 +54094,7 @@ Pd.exploreQueryWalkerBuilder = gRe;
54094
54094
  var Oe = {}, fS = {};
54095
54095
  Object.defineProperty(fS, "__esModule", { value: !0 });
54096
54096
  fS.MALLOY_VERSION = void 0;
54097
- fS.MALLOY_VERSION = "0.0.223";
54097
+ fS.MALLOY_VERSION = "0.0.224";
54098
54098
  Object.defineProperty(Oe, "__esModule", { value: !0 });
54099
54099
  Oe.CSVWriter = Oe.JSONWriter = Oe.DataWriter = Oe.DataRecord = Oe.DataArray = Oe.Result = Oe.ExploreMaterializer = Oe.PreparedResultMaterializer = Oe.QueryMaterializer = Oe.ModelMaterializer = Oe.SingleConnectionRuntime = Oe.ConnectionRuntime = Oe.Runtime = Oe.ExploreField = Oe.JoinRelationship = Oe.QueryField = Oe.Query = Oe.StringField = Oe.UnsupportedField = Oe.JSONField = Oe.BooleanField = Oe.NumberField = Oe.TimestampField = Oe.DateField = Oe.TimestampTimeframe = Oe.DateTimeframe = Oe.AtomicField = Oe.AtomicFieldType = Oe.Explore = Oe.SourceRelationship = Oe.FixedConnectionMap = Oe.InMemoryURLReader = Oe.EmptyURLReader = Oe.PreparedResult = Oe.DocumentCompletion = Oe.DocumentSymbol = Oe.DocumentPosition = Oe.DocumentRange = Oe.DocumentTablePath = Oe.Parse = Oe.PreparedQuery = Oe.Model = Oe.MalloyError = Oe.Malloy = void 0;
54100
54100
  const mRe = CN, Jn = hs, hj = AJ, An = Du, B6 = mh, yRe = fS;
@@ -75,7 +75,7 @@ ${(0,ace.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,zi.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,zi.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,zi.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,U$.expandOverrideMap)(cce.SNOWFLAKE_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,U$.expandBlueprintMap)(lce.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,zi.isRepeatedRecord)(e)){const r=`OBJECT(${e.fields.reduce((i,s)=>{var o;if((0,zi.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,zi.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 xce[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(",")}]`}}Cy.SnowflakeDialect=dce,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(Cy,t)}(RT);var DT={},Tx={},Ry={};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.TRINO_DIALECT_FUNCTIONS=void 0;const hce={takes:{value:"number",percentage:"number"},returns:{measure:"number"},impl:{function:"APPROX_PERCENTILE"}},pce={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}}},returns:{measure:{generic:"T"}},impl:{function:"ARBITRARY"}},gce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_OR_AGG"}},mce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_AND_AGG"}},yce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_XOR_AGG"}},Ece={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_AND"}},Ace={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_OR"}},_ce={takes:{y:{dimension:"number"},x:{dimension:"number"}},returns:{measure:"number"},impl:{sql:"CORR(${y}, ${x})"}},vce={takes:{value:{dimension:"any"}},returns:{measure:"number"},impl:{function:"APPROX_DISTINCT"},isSymmetric:!0},Cce={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"}}},Sce={takes:{value:"string"},returns:{measure:"string"},impl:{function:"MERGE"},isSymmetric:!0},bce={takes:{value:"string"},returns:{dimension:"number"},impl:{function:"CARDINALITY"}},Tce={takes:{value:"string"},returns:{dimension:"string"},impl:{sql:"CAST(${value} AS VARBINARY)"}},Rce={takes:{value:"string"},returns:{dimension:"string"},impl:{sql:"CAST(${value} AS HyperLogLog)"}},Oce={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},Dce={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},NT={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})"}}},Nce={default_separator:{...NT.default_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ',')"}},with_separator:{...NT.with_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ${separator})"}}},Fce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"VARIANCE"}},wce={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_AND"}},Lce={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_OR"}},Ice={takes:{ts_val:"timestamp",format:"string"},returns:"string",impl:{function:"DATE_FORMAT"}},Bce={takes:{ts_string:"string",format:"string"},returns:"timestamp",impl:{sql:"DATE_PARSE(${ts_string}, ${format})"}},$ce={takes:{unixtime:"number"},returns:"timestamp",impl:{function:"FROM_UNIXTIME"}},kce={takes:{json_val:"string",json_path:"string"},returns:"string",impl:{function:"JSON_EXTRACT_SCALAR"}},Pce={takes:{str:"string",pattern:["string","regular expression"]},returns:"boolean",impl:{function:"REGEXP_LIKE"}},Mce={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"}}},jce={takes:{ts_val:"timestamp"},returns:"number",impl:{function:"TO_UNIXTIME"}},Uce={takes:{},returns:{calculation:"number"},impl:{function:"PERCENT_RANK",needsWindowOrderBy:!0}},qce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_FRAGMENT"}},Hce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_HOST"}},zce={takes:{url:"string",parameter:"string"},returns:"string",impl:{function:"URL_EXTRACT_PARAMETER"}},Qce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PATH"}},Gce={takes:{url:"string"},returns:"number",impl:{function:"URL_EXTRACT_PORT"}},Wce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PROTOCOL"}},Vce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_QUERY"}},Yce={takes:{src:"string",splitChar:"string"},returns:{array:"string"},impl:{function:"SPLIT"}};Ry.TRINO_DIALECT_FUNCTIONS={approx_percentile:hce,arbitrary:pce,bitwise_and_agg:gce,bitwise_or_agg:mce,bitwise_xor_agg:yce,bool_and:Ece,bool_or:Ace,corr:_ce,count_approx:vce,hll_accumulate:Cce,hll_combine:Sce,max_by:Oce,min_by:Dce,string_agg:NT,string_agg_distinct:Nce,variance:Fce,bitwise_and:wce,bitwise_or:Lce,date_format:Ice,date_parse:Bce,from_unixtime:$ce,hll_estimate:bce,hll_export:Tce,hll_import:Rce,json_extract_scalar:kce,regexp_like:Pce,regexp_replace:Mce,to_unixtime:jce,url_extract_fragment:qce,url_extract_host:Hce,url_extract_parameter:zce,url_extract_path:Qce,url_extract_port:Gce,url_extract_protocol:Wce,url_extract_query:Vce,percent_rank:Uce,split:Yce};var Oy={};Object.defineProperty(Oy,"__esModule",{value:!0}),Oy.TRINO_MALLOY_STANDARD_OVERLOADS=void 0;const FT=it;Oy.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,FT.sql)`CONCAT(${(0,FT.spread)((0,FT.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(Tx,"__esModule",{value:!0}),Tx.PrestoDialect=Tx.TrinoDialect=void 0;const q$=Dt,qo=We,H$=Al,Kce=yl,z$=my,Jce=Ry,Xce=Oy;function Zce(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function wT(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const efe={string:"VARCHAR",number:"DOUBLE"},tfe={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 _l extends z$.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,zi.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,zi.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,zi.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,U$.expandOverrideMap)(cce.SNOWFLAKE_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,U$.expandBlueprintMap)(lce.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,zi.isRepeatedRecord)(e)){const r=`OBJECT(${e.fields.reduce((i,s)=>{var o;if((0,zi.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,zi.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 xce[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(",")}]`}}Cy.SnowflakeDialect=dce,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(Cy,t)}(RT);var DT={},Tx={},Ry={};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.TRINO_DIALECT_FUNCTIONS=void 0;const hce={takes:{value:"number",percentage:"number"},returns:{measure:"number"},impl:{function:"APPROX_PERCENTILE"}},pce={generic:{T:["string","number","date","timestamp","boolean","json"]},takes:{value:{dimension:{generic:"T"}}},returns:{measure:{generic:"T"}},impl:{function:"ARBITRARY"}},gce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_OR_AGG"}},mce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_AND_AGG"}},yce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"BITWISE_XOR_AGG"}},Ece={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_AND"}},Ace={takes:{value:{dimension:"boolean"}},returns:{measure:"boolean"},impl:{function:"BOOL_OR"}},_ce={takes:{y:{dimension:"number"},x:{dimension:"number"}},returns:{measure:"number"},impl:{sql:"CORR(${y}, ${x})"}},vce={takes:{value:{dimension:"any"}},returns:{measure:"number"},impl:{function:"APPROX_DISTINCT"},isSymmetric:!0},Cce={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"}}},Sce={takes:{value:{sql_native:"hyperloglog"}},returns:{measure:{sql_native:"hyperloglog"}},impl:{function:"MERGE"},isSymmetric:!0},bce={takes:{value:{sql_native:"hyperloglog"}},returns:{dimension:"number"},impl:{function:"CARDINALITY"}},Tce={takes:{value:{sql_native:"hyperloglog"}},returns:{dimension:{sql_native:"varbinary"}},impl:{sql:"CAST(${value} AS VARBINARY)"}},Rce={takes:{value:{sql_native:"varbinary"}},returns:{dimension:{sql_native:"hyperloglog"}},impl:{sql:"CAST(${value} AS HyperLogLog)"}},Oce={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},Dce={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},NT={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})"}}},Nce={default_separator:{...NT.default_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ',')"}},with_separator:{...NT.with_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ${separator})"}}},Fce={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"VARIANCE"}},wce={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_AND"}},Lce={takes:{val1:"number",val2:"number"},returns:"number",impl:{function:"BITWISE_OR"}},Ice={takes:{ts_val:"timestamp",format:"string"},returns:"string",impl:{function:"DATE_FORMAT"}},Bce={takes:{ts_string:"string",format:"string"},returns:"timestamp",impl:{sql:"DATE_PARSE(${ts_string}, ${format})"}},$ce={takes:{unixtime:"number"},returns:"timestamp",impl:{function:"FROM_UNIXTIME"}},kce={takes:{json_val:"string",json_path:"string"},returns:"string",impl:{function:"JSON_EXTRACT_SCALAR"}},Pce={takes:{str:"string",pattern:["string","regular expression"]},returns:"boolean",impl:{function:"REGEXP_LIKE"}},Mce={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"}}},jce={takes:{ts_val:"timestamp"},returns:"number",impl:{function:"TO_UNIXTIME"}},Uce={takes:{},returns:{calculation:"number"},impl:{function:"PERCENT_RANK",needsWindowOrderBy:!0}},qce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_FRAGMENT"}},Hce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_HOST"}},zce={takes:{url:"string",parameter:"string"},returns:"string",impl:{function:"URL_EXTRACT_PARAMETER"}},Qce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PATH"}},Gce={takes:{url:"string"},returns:"number",impl:{function:"URL_EXTRACT_PORT"}},Wce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_PROTOCOL"}},Vce={takes:{url:"string"},returns:"string",impl:{function:"URL_EXTRACT_QUERY"}},Yce={takes:{src:"string",splitChar:"string"},returns:{array:"string"},impl:{function:"SPLIT"}};Ry.TRINO_DIALECT_FUNCTIONS={approx_percentile:hce,arbitrary:pce,bitwise_and_agg:gce,bitwise_or_agg:mce,bitwise_xor_agg:yce,bool_and:Ece,bool_or:Ace,corr:_ce,count_approx:vce,hll_accumulate:Cce,hll_combine:Sce,max_by:Oce,min_by:Dce,string_agg:NT,string_agg_distinct:Nce,variance:Fce,bitwise_and:wce,bitwise_or:Lce,date_format:Ice,date_parse:Bce,from_unixtime:$ce,hll_estimate:bce,hll_export:Tce,hll_import:Rce,json_extract_scalar:kce,regexp_like:Pce,regexp_replace:Mce,to_unixtime:jce,url_extract_fragment:qce,url_extract_host:Hce,url_extract_parameter:zce,url_extract_path:Qce,url_extract_port:Gce,url_extract_protocol:Wce,url_extract_query:Vce,percent_rank:Uce,split:Yce};var Oy={};Object.defineProperty(Oy,"__esModule",{value:!0}),Oy.TRINO_MALLOY_STANDARD_OVERLOADS=void 0;const FT=it;Oy.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,FT.sql)`CONCAT(${(0,FT.spread)((0,FT.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(Tx,"__esModule",{value:!0}),Tx.PrestoDialect=Tx.TrinoDialect=void 0;const q$=Dt,qo=We,H$=Al,Kce=yl,z$=my,Jce=Ry,Xce=Oy;function Zce(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function wT(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const efe={string:"VARCHAR",number:"DOUBLE"},tfe={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 _l extends z$.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
@@ -1260,7 +1260,7 @@ QUERY: ${(0,_H.inspect)(n,{breakLength:72,depth:1/0})}`)}return vH.ErrorFactory.
1260
1260
  | ${l}`,u>0&&(i=i+`
1261
1261
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1262
1262
  `+i,n=s),e!==""?e=`${e}
1263
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,Q6e.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,eRe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}su.MalloyTranslation=XO;class yG extends XO{constructor(e,n){super(e),this.root=n}}su.MalloyChildTranslator=yG;class dRe extends XO{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new JO.Zone,this.importZone=new JO.Zone,this.sqlQueryZone=new JO.Zone,this.root=this,this.logger=new KO.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,KO.makeLogMessage)(e,n,{severity:"error",...r})),e}}su.MalloyTranslator=dRe;class EG{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,KO.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}su.MalloyParserErrorHandler=EG;var Kd={};Object.defineProperty(Kd,"__esModule",{value:!0}),Kd.exploreQueryWalkerBuilder=Kd.ExploreQueryWalker=void 0;const hRe=bl;class AG{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Kd.ExploreQueryWalker=AG;function pRe(t,e){const n=new AG(t),r=n;return hRe.ParseTreeWalker.DEFAULT.walk(r,e),n}Kd.exploreQueryWalkerBuilder=pRe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=su;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Kd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(cR);var Oe={},Gv={};Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.MALLOY_VERSION=void 0,Gv.MALLOY_VERSION="0.0.223",Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.PreparedResultMaterializer=Oe.QueryMaterializer=Oe.ModelMaterializer=Oe.SingleConnectionRuntime=Oe.ConnectionRuntime=Oe.Runtime=Oe.ExploreField=Oe.JoinRelationship=Oe.QueryField=Oe.Query=Oe.StringField=Oe.UnsupportedField=Oe.JSONField=Oe.BooleanField=Oe.NumberField=Oe.TimestampField=Oe.DateField=Oe.TimestampTimeframe=Oe.DateTimeframe=Oe.AtomicField=Oe.AtomicFieldType=Oe.Explore=Oe.SourceRelationship=Oe.FixedConnectionMap=Oe.InMemoryURLReader=Oe.EmptyURLReader=Oe.PreparedResult=Oe.DocumentCompletion=Oe.DocumentSymbol=Oe.DocumentPosition=Oe.DocumentRange=Oe.DocumentTablePath=Oe.Parse=Oe.PreparedQuery=Oe.Model=Oe.MalloyError=Oe.Malloy=void 0;const gRe=cR,Zn=Qi,_G=OQ,_n=zo,ZO=Cx,mRe=Gv;class In{static get version(){return mRe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new gRe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new CG(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return In._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>In._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new mg(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new mg(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new vG(`Error(s) compiling model:
1263
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,Q6e.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,eRe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}su.MalloyTranslation=XO;class yG extends XO{constructor(e,n){super(e),this.root=n}}su.MalloyChildTranslator=yG;class dRe extends XO{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new JO.Zone,this.importZone=new JO.Zone,this.sqlQueryZone=new JO.Zone,this.root=this,this.logger=new KO.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,KO.makeLogMessage)(e,n,{severity:"error",...r})),e}}su.MalloyTranslator=dRe;class EG{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,KO.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}su.MalloyParserErrorHandler=EG;var Kd={};Object.defineProperty(Kd,"__esModule",{value:!0}),Kd.exploreQueryWalkerBuilder=Kd.ExploreQueryWalker=void 0;const hRe=bl;class AG{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Kd.ExploreQueryWalker=AG;function pRe(t,e){const n=new AG(t),r=n;return hRe.ParseTreeWalker.DEFAULT.walk(r,e),n}Kd.exploreQueryWalkerBuilder=pRe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=su;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Kd;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(cR);var Oe={},Gv={};Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.MALLOY_VERSION=void 0,Gv.MALLOY_VERSION="0.0.224",Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.CSVWriter=Oe.JSONWriter=Oe.DataWriter=Oe.DataRecord=Oe.DataArray=Oe.Result=Oe.ExploreMaterializer=Oe.PreparedResultMaterializer=Oe.QueryMaterializer=Oe.ModelMaterializer=Oe.SingleConnectionRuntime=Oe.ConnectionRuntime=Oe.Runtime=Oe.ExploreField=Oe.JoinRelationship=Oe.QueryField=Oe.Query=Oe.StringField=Oe.UnsupportedField=Oe.JSONField=Oe.BooleanField=Oe.NumberField=Oe.TimestampField=Oe.DateField=Oe.TimestampTimeframe=Oe.DateTimeframe=Oe.AtomicField=Oe.AtomicFieldType=Oe.Explore=Oe.SourceRelationship=Oe.FixedConnectionMap=Oe.InMemoryURLReader=Oe.EmptyURLReader=Oe.PreparedResult=Oe.DocumentCompletion=Oe.DocumentSymbol=Oe.DocumentPosition=Oe.DocumentRange=Oe.DocumentTablePath=Oe.Parse=Oe.PreparedQuery=Oe.Model=Oe.MalloyError=Oe.Malloy=void 0;const gRe=cR,Zn=Qi,_G=OQ,_n=zo,ZO=Cx,mRe=Gv;class In{static get version(){return mRe.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new gRe.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new CG(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return In._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>In._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new mg(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new mg(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new vG(`Error(s) compiling model:
1264
1264
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const A=await e.readURL(new URL(E)),_={[E]:A};m.update({urls:_})}catch(A){m.update({errors:{urls:{[E]:A.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const A in g.tables){const{connectionName:_,tablePath:v}=g.tables[A],C=E.get(_);C===void 0?E.set(_,{[A]:v}):C[A]=v}for(const[A,_]of E)try{const v=await n.lookupConnection(A),{schemas:C,errors:S}=await In.safelyFetchTableSchema(v,_,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:C,errors:{tables:S}})}catch(v){const C={},S={};for(const b in _)S[b]=v.toString();m.update({tables:C,errors:{tables:S}})}}if(g.compileSQL){const E=g.compileSQL,A=E.connection;try{const _=await n.lookupConnection(A),v=In.compileSQLBlock(_.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),C=await _.fetchSchemaForSQLStruct(v,{refreshTimestamp:p,modelAnnotation:y});C.error&&m.update({errors:{compileSQL:{[v.name]:C.error}}}),C.structDef&&m.update({compileSQL:{[v.name]:C.structDef}})}catch(_){const v={};v[E.name]=_.toString(),m.update({errors:{compileSQL:v}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,Zn.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new Zn.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new _g({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new _g({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new ss(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new cf(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Oe.Malloy=In;class vG extends Error{constructor(e,n=[]){super(e),this.problems=n}}Oe.MalloyError=vG;let mg=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return _n.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new Jd(n,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new Jd(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Jd(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,Zn.isSourceDef)(n))return new ss(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(Zn.isSourceDef).map(e=>new ss(e))}get namedQueries(){const e=n=>n.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}};Oe.Model=mg;class Jd{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=_n.Tag.annotationToTag(this._modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new Zn.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new yg({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,Zn.isSourceDef)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Oe.PreparedQuery=Jd;class CG{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new Wv(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new SG(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new bG(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Oe.Parse=CG;class SG{constructor(e){this._range=Xd.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}Oe.DocumentTablePath=SG;class Xd{constructor(e,n){this._start=e,this._end=n}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new Xd(new eD(e.start.line,e.start.character),new eD(e.end.line,e.end.character))}}Oe.DocumentRange=Xd;class eD{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Oe.DocumentPosition=eD;class Wv{constructor(e){this._range=Xd.fromJSON(e.range),this._lensRange=e.lensRange?Xd.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new Wv(n))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}Oe.DocumentSymbol=Wv;class bG{constructor(e){this.type=e.type,this.text=e.text}}Oe.DocumentCompletion=bG;class yg{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new yg(e,n)}tagParse(e){const n=_n.Tag.annotationToTag(this.modelDef.annotation).tag;return e=_n.Tag.addModelScope(e,n),_n.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return _n.Tag.annotationToTag(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new ss(n,this.sourceExplore)}catch{return new ss(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,Zn.isSourceDef)(n))return new ss(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Oe.PreparedResult=yg;class TG{async readURL(e){throw new Error("No files.")}}Oe.EmptyURLReader=TG;class yRe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Oe.InMemoryURLReader=yRe;class Eg{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new Eg(new Map(e.map(n=>[n.name,n])))}}Oe.FixedConnectionMap=Eg;var RG;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(RG||(Oe.SourceRelationship=RG={}));class tD{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ss}isQuery(){return this instanceof aD}}class ss extends tD{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,Zn.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return _n.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=_n.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Jd(r,this.modelDef,[],e)}get modelDef(){if(!(0,Zn.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new mg(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,Zn.isJoined)(r))return[i,new lD(r,this,s)];if(r.type==="turtle")return[i,new aD(r,this,s)];if(r.type==="string")return[i,new uD(r,this,s)];if(r.type==="number")return[i,new Vv(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new Vv({...r,type:"number"},this,s)]:[i,new nD(r,this,s)];if(r.type==="timestamp")return[i,new rD(r,this,s)];if(r.type==="boolean")return[i,new iD(r,this,s)];if(r.type==="json")return[i,new sD(r,this,s)];if(r.type==="sql native")return[i,new oD(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof lD}get filters(){var e;return(0,Zn.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,Zn.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ss.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ss.fromJSON(e.sourceExplore):void 0;return new ss(e._structDef,n,r)}get location(){return this.structDef.location}}Oe.Explore=ss;var gu;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(gu||(Oe.AtomicFieldType=gu={}));class u0 extends tD{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return gu.String;case"boolean":return gu.Boolean;case"date":return gu.Date;case"timestamp":return gu.Timestamp;case"number":return gu.Number;case"json":return gu.Json;case"sql native":return gu.NativeUnsupported;case"error":return gu.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,Zn.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,Zn.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof uD}isNumber(){return this instanceof Vv}isDate(){return this instanceof nD}isBoolean(){return this instanceof iD}isJSON(){return this instanceof sD}isTimestamp(){return this instanceof rD}isUnsupported(){return this instanceof oD}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Oe.AtomicField=u0;var lf;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(lf||(Oe.DateTimeframe=lf={}));var mu;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(mu||(Oe.TimestampTimeframe=mu={}));class nD extends u0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return lf.Day;case"week":return lf.Week;case"month":return lf.Month;case"quarter":return lf.Quarter;case"year":return lf.Year}}}Oe.DateField=nD;class rD extends u0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return mu.Day;case"week":return mu.Week;case"month":return mu.Month;case"quarter":return mu.Quarter;case"year":return mu.Year;case"second":return mu.Second;case"hour":return mu.Hour;case"minute":return mu.Minute}}}Oe.TimestampField=rD;class Vv extends u0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Oe.NumberField=Vv;class iD extends u0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Oe.BooleanField=iD;class sD extends u0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Oe.JSONField=sD;class oD extends u0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Oe.UnsupportedField=oD;class uD extends u0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Oe.StringField=uD;class OG extends tD{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Oe.Query=OG;class aD extends OG{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=_n.Tag.addModelScope(e,this.parent.modelTag),_n.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return _n.Tag.annotationToTaglines(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}Oe.QueryField=aD;var Zd;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Zd||(Oe.JoinRelationship=Zd={}));class lD extends ss{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,Zn.isJoined)(this.structDef))switch(this.structDef.join){case"one":return Zd.OneToOne;case"many":case"cross":return Zd.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===Zd.OneToOne}get isArray(){return this.joinRelationship!==Zd.OneToOne}tagParse(e){return e=_n.Tag.addModelScope(e,this._parentExplore.modelTag),_n.Tag.annotationToTag(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}Oe.ExploreField=lD;class cD{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&(UG(s)?n=s:CRe(s)?r=s:qG(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new TG),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Ag(this,async()=>{const s=e instanceof URL?await In.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):In.parse({source:e,eventStream:this.eventStream,options:n});return In.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new Ag(this,async()=>new mg(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}Oe.Runtime=cD;class ERe extends cD{constructor(e,n){if(n===void 0){const r=e;super(Eg.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,Eg.fromArray(r)),this.rawConnections=r}}}Oe.ConnectionRuntime=ERe;class ARe extends cD{constructor(...e){let n,r,i;for(const s of e)UG(s)&&(n=s),SRe(s)&&(r=s),qG(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,ZO.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,ZO.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,ZO.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Oe.SingleConnectionRuntime=ARe;class Yv{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new DG(this.runtime,e,n)}makeExploreMaterializer(e,n){return new FG(this.runtime,e,n)}makePreparedResultMaterializer(e){return new NG(this.runtime,e)}}class Ag extends Yv{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await In.parse({url:e,urlReader:s,options:n}):In.parse({source:e,options:n}),a=await this.getModel();return(await In.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new Ag(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await In.parse({url:e,urlReader:r,options:n}):In.parse({source:e,options:n}),o=await this.getModel();return await In.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new Zn.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,Zn.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,Zn.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1265
1265
  run: ${e}
1266
1266
  -> ${o}
@@ -4357,7 +4357,7 @@ const axe = {
4357
4357
  T: ["string", "number", "date", "timestamp", "boolean", "json"]
4358
4358
  },
4359
4359
  takes: { value: { dimension: { generic: "T" } } },
4360
- returns: { measure: "string" },
4360
+ returns: { measure: { sql_native: "hyperloglog" } },
4361
4361
  isSymmetric: !0,
4362
4362
  impl: {
4363
4363
  function: "APPROX_SET"
@@ -4368,7 +4368,7 @@ const axe = {
4368
4368
  T: ["string", "number", "date", "timestamp", "boolean", "json"]
4369
4369
  },
4370
4370
  takes: { value: { dimension: { generic: "T" } }, accuracy: "number" },
4371
- returns: { measure: "string" },
4371
+ returns: { measure: { sql_native: "hyperloglog" } },
4372
4372
  isSymmetric: !0,
4373
4373
  impl: {
4374
4374
  function: "APPROX_SET"
@@ -4376,30 +4376,30 @@ const axe = {
4376
4376
  }
4377
4377
  }, yxe = {
4378
4378
  takes: {
4379
- value: "string"
4379
+ value: { sql_native: "hyperloglog" }
4380
4380
  },
4381
- returns: { measure: "string" },
4381
+ returns: { measure: { sql_native: "hyperloglog" } },
4382
4382
  impl: { function: "MERGE" },
4383
4383
  isSymmetric: !0
4384
4384
  }, Exe = {
4385
4385
  takes: {
4386
- value: "string"
4386
+ value: { sql_native: "hyperloglog" }
4387
4387
  },
4388
4388
  returns: { dimension: "number" },
4389
4389
  impl: { function: "CARDINALITY" }
4390
4390
  }, Axe = {
4391
4391
  takes: {
4392
- value: "string"
4392
+ value: { sql_native: "hyperloglog" }
4393
4393
  },
4394
- returns: { dimension: "string" },
4394
+ returns: { dimension: { sql_native: "varbinary" } },
4395
4395
  impl: {
4396
4396
  sql: "CAST(${value} AS VARBINARY)"
4397
4397
  }
4398
4398
  }, vxe = {
4399
4399
  takes: {
4400
- value: "string"
4400
+ value: { sql_native: "varbinary" }
4401
4401
  },
4402
- returns: { dimension: "string" },
4402
+ returns: { dimension: { sql_native: "hyperloglog" } },
4403
4403
  impl: {
4404
4404
  sql: "CAST(${value} AS HyperLogLog)"
4405
4405
  }
@@ -55253,7 +55253,7 @@ yh.exploreQueryWalkerBuilder = x7e;
55253
55253
  var we = {}, G4 = {};
55254
55254
  Object.defineProperty(G4, "__esModule", { value: !0 });
55255
55255
  G4.MALLOY_VERSION = void 0;
55256
- G4.MALLOY_VERSION = "0.0.223";
55256
+ G4.MALLOY_VERSION = "0.0.224";
55257
55257
  Object.defineProperty(we, "__esModule", { value: !0 });
55258
55258
  we.CSVWriter = we.JSONWriter = we.DataWriter = we.DataRecord = we.DataArray = we.Result = we.ExploreMaterializer = we.PreparedResultMaterializer = we.QueryMaterializer = we.ModelMaterializer = we.SingleConnectionRuntime = we.ConnectionRuntime = we.Runtime = we.ExploreField = we.JoinRelationship = we.QueryField = we.Query = we.StringField = we.UnsupportedField = we.JSONField = we.BooleanField = we.NumberField = we.TimestampField = we.DateField = we.TimestampTimeframe = we.DateTimeframe = we.AtomicField = we.AtomicFieldType = we.Explore = we.SourceRelationship = we.FixedConnectionMap = we.InMemoryURLReader = we.EmptyURLReader = we.PreparedResult = we.DocumentCompletion = we.DocumentSymbol = we.DocumentPosition = we.DocumentRange = we.DocumentTablePath = we.Parse = we.PreparedQuery = we.Model = we.MalloyError = we.Malloy = void 0;
55259
55259
  const d7e = JF, nr = Cs, Xj = Ki, Sn = Wu, AR = Zh, h7e = G4;
@@ -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,kk.expandOverrideMap)(rxe.SNOWFLAKE_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,kk.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(",")}]`}}AE.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(AE,t)}(_6);var S6={},nd={},CE={};Object.defineProperty(CE,"__esModule",{value:!0}),CE.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},C6={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:{...C6.default_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ',')"}},with_separator:{...C6.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"}};CE.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:C6,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 bE={};Object.defineProperty(bE,"__esModule",{value:!0}),bE.TRINO_MALLOY_STANDARD_OVERLOADS=void 0;const b6=at;bE.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,b6.sql)`CONCAT(${(0,b6.spread)((0,b6.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 Pk=Nt,iu=Ke,Mk=ql,Hxe=jl,jk=hE,zxe=CE,Qxe=bE;function Gxe(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function T6(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 jk.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,kk.expandOverrideMap)(rxe.SNOWFLAKE_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,kk.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(",")}]`}}AE.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(AE,t)}(_6);var S6={},nd={},CE={};Object.defineProperty(CE,"__esModule",{value:!0}),CE.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},C6={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:{...C6.default_separator,isSymmetric:!0,impl:{sql:"ARRAY_JOIN(ARRAY_AGG(DISTINCT ${value} ${order_by:}), ',')"}},with_separator:{...C6.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"}};CE.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:C6,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 bE={};Object.defineProperty(bE,"__esModule",{value:!0}),bE.TRINO_MALLOY_STANDARD_OVERLOADS=void 0;const b6=at;bE.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,b6.sql)`CONCAT(${(0,b6.spread)((0,b6.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 Pk=Nt,iu=Ke,Mk=ql,Hxe=jl,jk=hE,zxe=CE,Qxe=bE;function Gxe(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function T6(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 jk.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
@@ -1260,7 +1260,7 @@ QUERY: ${(0,mz.inspect)(n,{breakLength:72,depth:1/0})}`)}return yz.ErrorFactory.
1260
1260
  | ${l}`,u>0&&(i=i+`
1261
1261
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1262
1262
  `+i,n=s),e!==""?e=`${e}
1263
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,jOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,YOe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}_u.MalloyTranslation=GD;class dW extends GD{constructor(e,n){super(e),this.root=n}}_u.MalloyChildTranslator=dW;class a7e extends GD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new QD.Zone,this.importZone=new QD.Zone,this.sqlQueryZone=new QD.Zone,this.root=this,this.logger=new zD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,zD.makeLogMessage)(e,n,{severity:"error",...r})),e}}_u.MalloyTranslator=a7e;class hW{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,zD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}_u.MalloyParserErrorHandler=hW;var Th={};Object.defineProperty(Th,"__esModule",{value:!0}),Th.exploreQueryWalkerBuilder=Th.ExploreQueryWalker=void 0;const l7e=Wl;class pW{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Th.ExploreQueryWalker=pW;function c7e(t,e){const n=new pW(t),r=n;return l7e.ParseTreeWalker.DEFAULT.walk(r,e),n}Th.exploreQueryWalkerBuilder=c7e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=_u;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Th;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(iO);var we={},H5={};Object.defineProperty(H5,"__esModule",{value:!0}),H5.MALLOY_VERSION=void 0,H5.MALLOY_VERSION="0.0.223",Object.defineProperty(we,"__esModule",{value:!0}),we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const f7e=iO,ir=ts,gW=Li,Cn=ou,WD=Zx,x7e=H5;class Pn{static get version(){return x7e.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new f7e.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new yW(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Pn._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>Pn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new nm(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new nm(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new mW(`Error(s) compiling model:
1263
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,jOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,YOe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}_u.MalloyTranslation=GD;class dW extends GD{constructor(e,n){super(e),this.root=n}}_u.MalloyChildTranslator=dW;class a7e extends GD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new QD.Zone,this.importZone=new QD.Zone,this.sqlQueryZone=new QD.Zone,this.root=this,this.logger=new zD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,zD.makeLogMessage)(e,n,{severity:"error",...r})),e}}_u.MalloyTranslator=a7e;class hW{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,zD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}_u.MalloyParserErrorHandler=hW;var Th={};Object.defineProperty(Th,"__esModule",{value:!0}),Th.exploreQueryWalkerBuilder=Th.ExploreQueryWalker=void 0;const l7e=Wl;class pW{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Th.ExploreQueryWalker=pW;function c7e(t,e){const n=new pW(t),r=n;return l7e.ParseTreeWalker.DEFAULT.walk(r,e),n}Th.exploreQueryWalkerBuilder=c7e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=_u;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Th;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(iO);var we={},H5={};Object.defineProperty(H5,"__esModule",{value:!0}),H5.MALLOY_VERSION=void 0,H5.MALLOY_VERSION="0.0.224",Object.defineProperty(we,"__esModule",{value:!0}),we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const f7e=iO,ir=ts,gW=Li,Cn=ou,WD=Zx,x7e=H5;class Pn{static get version(){return x7e.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new f7e.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new yW(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Pn._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>Pn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new nm(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new nm(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new mW(`Error(s) compiling model:
1264
1264
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const A=await e.readURL(new URL(E)),_={[E]:A};m.update({urls:_})}catch(A){m.update({errors:{urls:{[E]:A.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const A in g.tables){const{connectionName:_,tablePath:v}=g.tables[A],S=E.get(_);S===void 0?E.set(_,{[A]:v}):S[A]=v}for(const[A,_]of E)try{const v=await n.lookupConnection(A),{schemas:S,errors:C}=await Pn.safelyFetchTableSchema(v,_,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:S,errors:{tables:C}})}catch(v){const S={},C={};for(const b in _)C[b]=v.toString();m.update({tables:S,errors:{tables:C}})}}if(g.compileSQL){const E=g.compileSQL,A=E.connection;try{const _=await n.lookupConnection(A),v=Pn.compileSQLBlock(_.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),S=await _.fetchSchemaForSQLStruct(v,{refreshTimestamp:p,modelAnnotation:y});S.error&&m.update({errors:{compileSQL:{[v.name]:S.error}}}),S.structDef&&m.update({compileSQL:{[v.name]:S.structDef}})}catch(_){const v={};v[E.name]=_.toString(),m.update({errors:{compileSQL:v}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,ir.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new ir.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new om({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new om({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new ps(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new If(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}we.Malloy=Pn;class mW extends Error{constructor(e,n=[]){super(e),this.problems=n}}we.MalloyError=mW;let nm=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return Cn.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new Rh(n,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new Rh(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Rh(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,ir.isSourceDef)(n))return new ps(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(ir.isSourceDef).map(e=>new ps(e))}get namedQueries(){const e=n=>n.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}};we.Model=nm;class Rh{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Cn.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new ir.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new rm({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,ir.isSourceDef)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=Rh;class yW{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new z5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new EW(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new AW(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=yW;class EW{constructor(e){this._range=Oh.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}we.DocumentTablePath=EW;class Oh{constructor(e,n){this._start=e,this._end=n}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new Oh(new VD(e.start.line,e.start.character),new VD(e.end.line,e.end.character))}}we.DocumentRange=Oh;class VD{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=VD;class z5{constructor(e){this._range=Oh.fromJSON(e.range),this._lensRange=e.lensRange?Oh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new z5(n))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}we.DocumentSymbol=z5;class AW{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=AW;class rm{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new rm(e,n)}tagParse(e){const n=Cn.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Cn.Tag.annotationToTag(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new ps(n,this.sourceExplore)}catch{return new ps(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,ir.isSourceDef)(n))return new ps(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=rm;class _W{async readURL(e){throw new Error("No files.")}}we.EmptyURLReader=_W;class d7e{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}we.InMemoryURLReader=d7e;class im{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new im(new Map(e.map(n=>[n.name,n])))}}we.FixedConnectionMap=im;var vW;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(vW||(we.SourceRelationship=vW={}));class YD{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ps}isQuery(){return this instanceof nw}}class ps extends YD{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,ir.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return Cn.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Cn.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Rh(r,this.modelDef,[],e)}get modelDef(){if(!(0,ir.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new nm(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,ir.isJoined)(r))return[i,new rw(r,this,s)];if(r.type==="turtle")return[i,new nw(r,this,s)];if(r.type==="string")return[i,new tw(r,this,s)];if(r.type==="number")return[i,new Q5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new Q5({...r,type:"number"},this,s)]:[i,new KD(r,this,s)];if(r.type==="timestamp")return[i,new XD(r,this,s)];if(r.type==="boolean")return[i,new JD(r,this,s)];if(r.type==="json")return[i,new ZD(r,this,s)];if(r.type==="sql native")return[i,new ew(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof rw}get filters(){var e;return(0,ir.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,ir.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ps.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ps.fromJSON(e.sourceExplore):void 0;return new ps(e._structDef,n,r)}get location(){return this.structDef.location}}we.Explore=ps;var Nu;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Nu||(we.AtomicFieldType=Nu={}));class D0 extends YD{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return Nu.String;case"boolean":return Nu.Boolean;case"date":return Nu.Date;case"timestamp":return Nu.Timestamp;case"number":return Nu.Number;case"json":return Nu.Json;case"sql native":return Nu.NativeUnsupported;case"error":return Nu.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,ir.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,ir.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof tw}isNumber(){return this instanceof Q5}isDate(){return this instanceof KD}isBoolean(){return this instanceof JD}isJSON(){return this instanceof ZD}isTimestamp(){return this instanceof XD}isUnsupported(){return this instanceof ew}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=D0;var Lf;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Lf||(we.DateTimeframe=Lf={}));var Lu;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Lu||(we.TimestampTimeframe=Lu={}));class KD extends D0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Lf.Day;case"week":return Lf.Week;case"month":return Lf.Month;case"quarter":return Lf.Quarter;case"year":return Lf.Year}}}we.DateField=KD;class XD extends D0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Lu.Day;case"week":return Lu.Week;case"month":return Lu.Month;case"quarter":return Lu.Quarter;case"year":return Lu.Year;case"second":return Lu.Second;case"hour":return Lu.Hour;case"minute":return Lu.Minute}}}we.TimestampField=XD;class Q5 extends D0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}we.NumberField=Q5;class JD extends D0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}we.BooleanField=JD;class ZD extends D0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}we.JSONField=ZD;class ew extends D0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=ew;class tw extends D0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}we.StringField=tw;class SW extends YD{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=SW;class nw extends SW{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}we.QueryField=nw;var Dh;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Dh||(we.JoinRelationship=Dh={}));class rw extends ps{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,ir.isJoined)(this.structDef))switch(this.structDef.join){case"one":return Dh.OneToOne;case"many":case"cross":return Dh.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===Dh.OneToOne}get isArray(){return this.joinRelationship!==Dh.OneToOne}tagParse(e){return e=Cn.Tag.addModelScope(e,this._parentExplore.modelTag),Cn.Tag.annotationToTag(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}we.ExploreField=rw;class iw{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&($W(s)?n=s:y7e(s)?r=s:kW(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new _W),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new sm(this,async()=>{const s=e instanceof URL?await Pn.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):Pn.parse({source:e,eventStream:this.eventStream,options:n});return Pn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new sm(this,async()=>new nm(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}we.Runtime=iw;class h7e extends iw{constructor(e,n){if(n===void 0){const r=e;super(im.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,im.fromArray(r)),this.rawConnections=r}}}we.ConnectionRuntime=h7e;class p7e extends iw{constructor(...e){let n,r,i;for(const s of e)$W(s)&&(n=s),E7e(s)&&(r=s),kW(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,WD.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,WD.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,WD.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=p7e;class G5{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new CW(this.runtime,e,n)}makeExploreMaterializer(e,n){return new TW(this.runtime,e,n)}makePreparedResultMaterializer(e){return new bW(this.runtime,e)}}class sm extends G5{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await Pn.parse({url:e,urlReader:s,options:n}):Pn.parse({source:e,options:n}),a=await this.getModel();return(await Pn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new sm(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await Pn.parse({url:e,urlReader:r,options:n}):Pn.parse({source:e,options:n}),o=await this.getModel();return await Pn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new ir.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,ir.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,ir.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1265
1265
  run: ${e}
1266
1266
  -> ${o}
@@ -4357,7 +4357,7 @@ const axe = {
4357
4357
  T: ["string", "number", "date", "timestamp", "boolean", "json"]
4358
4358
  },
4359
4359
  takes: { value: { dimension: { generic: "T" } } },
4360
- returns: { measure: "string" },
4360
+ returns: { measure: { sql_native: "hyperloglog" } },
4361
4361
  isSymmetric: !0,
4362
4362
  impl: {
4363
4363
  function: "APPROX_SET"
@@ -4368,7 +4368,7 @@ const axe = {
4368
4368
  T: ["string", "number", "date", "timestamp", "boolean", "json"]
4369
4369
  },
4370
4370
  takes: { value: { dimension: { generic: "T" } }, accuracy: "number" },
4371
- returns: { measure: "string" },
4371
+ returns: { measure: { sql_native: "hyperloglog" } },
4372
4372
  isSymmetric: !0,
4373
4373
  impl: {
4374
4374
  function: "APPROX_SET"
@@ -4376,30 +4376,30 @@ const axe = {
4376
4376
  }
4377
4377
  }, yxe = {
4378
4378
  takes: {
4379
- value: "string"
4379
+ value: { sql_native: "hyperloglog" }
4380
4380
  },
4381
- returns: { measure: "string" },
4381
+ returns: { measure: { sql_native: "hyperloglog" } },
4382
4382
  impl: { function: "MERGE" },
4383
4383
  isSymmetric: !0
4384
4384
  }, Exe = {
4385
4385
  takes: {
4386
- value: "string"
4386
+ value: { sql_native: "hyperloglog" }
4387
4387
  },
4388
4388
  returns: { dimension: "number" },
4389
4389
  impl: { function: "CARDINALITY" }
4390
4390
  }, Axe = {
4391
4391
  takes: {
4392
- value: "string"
4392
+ value: { sql_native: "hyperloglog" }
4393
4393
  },
4394
- returns: { dimension: "string" },
4394
+ returns: { dimension: { sql_native: "varbinary" } },
4395
4395
  impl: {
4396
4396
  sql: "CAST(${value} AS VARBINARY)"
4397
4397
  }
4398
4398
  }, vxe = {
4399
4399
  takes: {
4400
- value: "string"
4400
+ value: { sql_native: "varbinary" }
4401
4401
  },
4402
- returns: { dimension: "string" },
4402
+ returns: { dimension: { sql_native: "hyperloglog" } },
4403
4403
  impl: {
4404
4404
  sql: "CAST(${value} AS HyperLogLog)"
4405
4405
  }
@@ -55253,7 +55253,7 @@ yh.exploreQueryWalkerBuilder = x7e;
55253
55253
  var we = {}, G4 = {};
55254
55254
  Object.defineProperty(G4, "__esModule", { value: !0 });
55255
55255
  G4.MALLOY_VERSION = void 0;
55256
- G4.MALLOY_VERSION = "0.0.223";
55256
+ G4.MALLOY_VERSION = "0.0.224";
55257
55257
  Object.defineProperty(we, "__esModule", { value: !0 });
55258
55258
  we.CSVWriter = we.JSONWriter = we.DataWriter = we.DataRecord = we.DataArray = we.Result = we.ExploreMaterializer = we.PreparedResultMaterializer = we.QueryMaterializer = we.ModelMaterializer = we.SingleConnectionRuntime = we.ConnectionRuntime = we.Runtime = we.ExploreField = we.JoinRelationship = we.QueryField = we.Query = we.StringField = we.UnsupportedField = we.JSONField = we.BooleanField = we.NumberField = we.TimestampField = we.DateField = we.TimestampTimeframe = we.DateTimeframe = we.AtomicField = we.AtomicFieldType = we.Explore = we.SourceRelationship = we.FixedConnectionMap = we.InMemoryURLReader = we.EmptyURLReader = we.PreparedResult = we.DocumentCompletion = we.DocumentSymbol = we.DocumentPosition = we.DocumentRange = we.DocumentTablePath = we.Parse = we.PreparedQuery = we.Model = we.MalloyError = we.Malloy = void 0;
55259
55259
  const d7e = JF, nr = Cs, Xj = Ki, Sn = Wu, AR = Zh, h7e = G4;
@@ -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
@@ -1260,7 +1260,7 @@ QUERY: ${(0,gz.inspect)(n,{breakLength:72,depth:1/0})}`)}return mz.ErrorFactory.
1260
1260
  | ${l}`,u>0&&(i=i+`
1261
1261
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1262
1262
  `+i,n=s),e!==""?e=`${e}
1263
- ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,jOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,YOe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}_u.MalloyTranslation=QD;class xW extends QD{constructor(e,n){super(e),this.root=n}}_u.MalloyChildTranslator=xW;class a7e extends QD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new zD.Zone,this.importZone=new zD.Zone,this.sqlQueryZone=new zD.Zone,this.root=this,this.logger=new HD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,HD.makeLogMessage)(e,n,{severity:"error",...r})),e}}_u.MalloyTranslator=a7e;class dW{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,HD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}_u.MalloyParserErrorHandler=dW;var Th={};Object.defineProperty(Th,"__esModule",{value:!0}),Th.exploreQueryWalkerBuilder=Th.ExploreQueryWalker=void 0;const l7e=Wl;class hW{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Th.ExploreQueryWalker=hW;function c7e(t,e){const n=new hW(t),r=n;return l7e.ParseTreeWalker.DEFAULT.walk(r,e),n}Th.exploreQueryWalkerBuilder=c7e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=_u;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Th;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(rO);var we={},q5={};Object.defineProperty(q5,"__esModule",{value:!0}),q5.MALLOY_VERSION=void 0,q5.MALLOY_VERSION="0.0.223",Object.defineProperty(we,"__esModule",{value:!0}),we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const f7e=rO,ir=ts,pW=Li,Cn=ou,GD=Zx,x7e=q5;class Pn{static get version(){return x7e.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new f7e.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new mW(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Pn._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>Pn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new em(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new em(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new gW(`Error(s) compiling model:
1263
+ ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];((0,jOe.isSourceDef)(u)||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,YOe.locationContainsPosition)(r.location,e))return r}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}_u.MalloyTranslation=QD;class xW extends QD{constructor(e,n){super(e),this.root=n}}_u.MalloyChildTranslator=xW;class a7e extends QD{constructor(e,n=null,r=null,i=null){super(e,n),this.eventStream=i,this.schemaZone=new zD.Zone,this.importZone=new zD.Zone,this.sqlQueryZone=new zD.Zone,this.root=this,this.logger=new HD.BaseMessageLogger(i),r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}logError(e,n,r){return this.logger.log((0,HD.makeLogMessage)(e,n,{severity:"error",...r})),e}}_u.MalloyTranslator=a7e;class dW{constructor(e,n){this.translator=e,this.messages=n}logError(e,n,r){return this.messages.log((0,HD.makeLogMessage)(e,n,{severity:"error",...r})),e}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u};this.logError("syntax-error",{message:s},{at:{url:this.translator.sourceURL,range:a}})}}_u.MalloyParserErrorHandler=dW;var Th={};Object.defineProperty(Th,"__esModule",{value:!0}),Th.exploreQueryWalkerBuilder=Th.ExploreQueryWalker=void 0;const l7e=Wl;class hW{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}Th.ExploreQueryWalker=hW;function c7e(t,e){const n=new hW(t),r=n;return l7e.ParseTreeWalker.DEFAULT.walk(r,e),n}Th.exploreQueryWalkerBuilder=c7e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=_u;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=Th;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(rO);var we={},q5={};Object.defineProperty(q5,"__esModule",{value:!0}),q5.MALLOY_VERSION=void 0,q5.MALLOY_VERSION="0.0.224",Object.defineProperty(we,"__esModule",{value:!0}),we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const f7e=rO,ir=ts,pW=Li,Cn=ou,GD=Zx,x7e=q5;class Pn{static get version(){return x7e.MALLOY_VERSION}static _parse(e,n,r,i){n===void 0&&(n=new URL("internal://internal.malloy"));let s=n;i!=null&&i.importBaseURL&&(s=i==null?void 0:i.importBaseURL);const o=new f7e.MalloyTranslator(n.toString(),s.toString(),{urls:{[n.toString()]:e}},r);return i!=null&&i.testEnvironment&&(o.allDialectsEnabled=!0),new mW(o)}static parse({url:e,urlReader:n,source:r,eventStream:i,options:s}){if(r!==void 0)return Pn._parse(r,e,i,s);if(n===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return n.readURL(e).then(o=>Pn._parse(o,e,i,s))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o,eventStream:u,replaceMaterializedReferences:a,materializedTablePrefix:l}){var c,f,x,h;let p;s&&(p=typeof s=="number"?s:Date.now());const m=r._translator;for(;;){const g=m.translate(i==null?void 0:i._modelDef);if(g.final){if(g.translated)return new em(g.translated.modelDef,g.translated.queryList,g.problems||[],[...(c=i==null?void 0:i.fromSources)!==null&&c!==void 0?c:[],...(f=g.fromSources)!==null&&f!==void 0?f:[]],y=>m.referenceAt(y),y=>m.importAt(y));if(o){const y={name:"modelDidNotCompile",exports:[],contents:{}},E=(i==null?void 0:i._modelDef)||y;return new em(E,[],g.problems||[],[...(x=i==null?void 0:i.fromSources)!==null&&x!==void 0?x:[],...(h=g.fromSources)!==null&&h!==void 0?h:[]],A=>m.referenceAt(A),A=>m.importAt(A))}else{const y=g.problems||[],E=m.prettyErrors();throw new gW(`Error(s) compiling model:
1264
1264
  ${E}`,y)}}else{if(g.urls)for(const E of g.urls)try{if(E.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const A=await e.readURL(new URL(E)),_={[E]:A};m.update({urls:_})}catch(A){m.update({errors:{urls:{[E]:A.message}}})}const{modelAnnotation:y}=m.modelAnnotation(i==null?void 0:i._modelDef);if(g.tables){const E=new Map;for(const A in g.tables){const{connectionName:_,tablePath:v}=g.tables[A],S=E.get(_);S===void 0?E.set(_,{[A]:v}):S[A]=v}for(const[A,_]of E)try{const v=await n.lookupConnection(A),{schemas:S,errors:C}=await Pn.safelyFetchTableSchema(v,_,{refreshTimestamp:p,modelAnnotation:y});m.update({tables:S,errors:{tables:C}})}catch(v){const S={},C={};for(const b in _)C[b]=v.toString();m.update({tables:S,errors:{tables:C}})}}if(g.compileSQL){const E=g.compileSQL,A=E.connection;try{const _=await n.lookupConnection(A),v=Pn.compileSQLBlock(_.dialectName,g.partialModel,E,{replaceMaterializedReferences:a,materializedTablePrefix:l,eventStream:u}),S=await _.fetchSchemaForSQLStruct(v,{refreshTimestamp:p,modelAnnotation:y});S.error&&m.update({errors:{compileSQL:{[v.name]:S.error}}}),S.structDef&&m.update({compileSQL:{[v.name]:S.structDef}})}catch(_){const v={};v[E.name]=_.toString(),m.update({errors:{compileSQL:v}})}}}}}static async safelyFetchTableSchema(e,n,r){const i=await e.fetchSchemaForTables(n,r);for(const s of Object.keys(n))if(i.schemas[s]===void 0&&i.errors[s]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${s} from ${e.dialectName}`);return i}static compileSQLBlock(e,n,r,i){let s,o="",u=!1;for(const c of r.select)if((0,ir.isSegmentSQL)(c))o+=c.sql,u=c.sql.match(/\(\s*$/)!==null;else{if(!s){if(!n)throw new Error("Internal error: Partial model missing when compiling SQL block");s=new ir.QueryModel(n,i==null?void 0:i.eventStream)}const f=s.compileQuery(c,i,!1).sql;o+=u?f:`(${f})`,u=!1}const{name:a,connection:l}=r;return{type:"sql_select",name:a,connection:l,dialect:e,selectStr:o,fields:[]}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(o)}if(r){const o=await i.runSQL(r.selectStr);return new im({structs:[r],sql:r.selectStr,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,lastStageName:r.name,malloy:"",connectionName:r.connection,sourceExplore:"",sourceFilters:[],profilingUrl:o.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const o=await i.runSQL(n.sql,s);return new im({...n._rawQuery,result:o.rows,totalRows:o.totalRows,runStats:o.runStats,profilingUrl:o.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){if(r===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const o=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(o)}if(!i.canStream())throw new Error(`Connection '${o}' cannot stream results.`);let u,a;if(r)a=new ps(r),u=r.selectStr;else if(n!==void 0)a=n.resultExplore,u=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let l=0;for await(const c of i.runSQLStream(u,s))yield new If(c,l,a,void 0,void 0),l+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const i=(r==null?void 0:r.connection)||(n==null?void 0:n.connectionName),s=await e.lookupConnection(i);if(r)return await s.estimateQueryCost(r.selectStr);if(n)return await s.estimateQueryCost(n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}we.Malloy=Pn;class gW extends Error{constructor(e,n=[]){super(e),this.problems=n}}we.MalloyError=gW;let em=class{constructor(e,n,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.queryList=n,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return Cn.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new Rh(n,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new Rh(this.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new Rh(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if((0,ir.isSourceDef)(n))return new ps(n);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(ir.isSourceDef).map(e=>new ps(e))}get namedQueries(){const e=n=>n.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}};we.Model=em;class Rh{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Cn.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const r=new ir.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new tm({...r,queryName:this.name||r.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,ir.isSourceDef)(n))throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=Rh;class mW{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new H5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new yW(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new EW(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=mW;class yW{constructor(e){this._range=Oh.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}we.DocumentTablePath=yW;class Oh{constructor(e,n){this._start=e,this._end=n}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new Oh(new WD(e.start.line,e.start.character),new WD(e.end.line,e.end.character))}}we.DocumentRange=Oh;class WD{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=WD;class H5{constructor(e){this._range=Oh.fromJSON(e.range),this._lensRange=e.lensRange?Oh.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new H5(n))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}we.DocumentSymbol=H5;class EW{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=EW;class tm{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new tm(e,n)}tagParse(e){const n=Cn.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Cn.Tag.addModelScope(e,n),Cn.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Cn.Tag.annotationToTag(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new ps(n,this.sourceExplore)}catch{return new ps(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if((0,ir.isSourceDef)(n))return new ps(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=tm;class AW{async readURL(e){throw new Error("No files.")}}we.EmptyURLReader=AW;class d7e{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}we.InMemoryURLReader=d7e;class nm{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new nm(new Map(e.map(n=>[n.name,n])))}}we.FixedConnectionMap=nm;var _W;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(_W||(we.SourceRelationship=_W={}));class VD{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ps}isQuery(){return this instanceof tw}}class ps extends VD{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,ir.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return Cn.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Cn.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n=this.sourceStructDef;if(!n)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const r={type:"query",structRef:n,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new Rh(r,this.modelDef,[],e)}get modelDef(){if(!(0,ir.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new em(this.modelDef,[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if((0,ir.isJoined)(r))return[i,new nw(r,this,s)];if(r.type==="turtle")return[i,new tw(r,this,s)];if(r.type==="string")return[i,new ew(r,this,s)];if(r.type==="number")return[i,new z5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new z5({...r,type:"number"},this,s)]:[i,new YD(r,this,s)];if(r.type==="timestamp")return[i,new KD(r,this,s)];if(r.type==="boolean")return[i,new XD(r,this,s)];if(r.type==="json")return[i,new JD(r,this,s)];if(r.type==="sql native")return[i,new ZD(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n,r;if(!this._allFieldsWithOrder){const i=[...((r=(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.orderBy)===null||r===void 0?void 0:r.map(o=>{if(typeof o.field=="string")return{field:this.fieldMap.get(o.field),dir:o.dir};throw new Error("Does not support mapping order by from number.")}))||[]],s=new Set(i.map(o=>o.field.name));this._allFieldsWithOrder=[...i,...this.allFields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof nw}get filters(){var e;return(0,ir.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,n;return(n=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||n===void 0?void 0:n.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,ir.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ps.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ps.fromJSON(e.sourceExplore):void 0;return new ps(e._structDef,n,r)}get location(){return this.structDef.location}}we.Explore=ps;var Nu;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Nu||(we.AtomicFieldType=Nu={}));class D0 extends VD{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return Nu.String;case"boolean":return Nu.Boolean;case"date":return Nu.Date;case"timestamp":return Nu.Timestamp;case"number":return Nu.Number;case"json":return Nu.Json;case"sql native":return Nu.NativeUnsupported;case"error":return Nu.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,ir.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,ir.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof ew}isNumber(){return this instanceof z5}isDate(){return this instanceof YD}isBoolean(){return this instanceof XD}isJSON(){return this instanceof JD}isTimestamp(){return this instanceof KD}isUnsupported(){return this instanceof ZD}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=D0;var Lf;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Lf||(we.DateTimeframe=Lf={}));var Lu;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Lu||(we.TimestampTimeframe=Lu={}));class YD extends D0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Lf.Day;case"week":return Lf.Week;case"month":return Lf.Month;case"quarter":return Lf.Quarter;case"year":return Lf.Year}}}we.DateField=YD;class KD extends D0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Lu.Day;case"week":return Lu.Week;case"month":return Lu.Month;case"quarter":return Lu.Quarter;case"year":return Lu.Year;case"second":return Lu.Second;case"hour":return Lu.Hour;case"minute":return Lu.Minute}}}we.TimestampField=KD;class z5 extends D0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}we.NumberField=z5;class XD extends D0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}we.BooleanField=XD;class JD extends D0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}we.JSONField=JD;class ZD extends D0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=ZD;class ew extends D0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}we.StringField=ew;class vW extends VD{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=vW;class tw extends vW{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Cn.Tag.addModelScope(e,this.parent.modelTag),Cn.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Cn.Tag.annotationToTaglines(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}we.QueryField=tw;var Dh;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(Dh||(we.JoinRelationship=Dh={}));class nw extends ps{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){if((0,ir.isJoined)(this.structDef))switch(this.structDef.join){case"one":return Dh.OneToOne;case"many":case"cross":return Dh.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===Dh.OneToOne}get isArray(){return this.joinRelationship!==Dh.OneToOne}tagParse(e){return e=Cn.Tag.addModelScope(e,this._parentExplore.modelTag),Cn.Tag.annotationToTag(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}we.ExploreField=nw;class rw{constructor(...e){this.isTestRuntime=!1;let n,r,i;for(const s of e)s!==void 0&&(BW(s)?n=s:y7e(s)?r=s:$W(s)?i=s:r={lookupConnection:()=>Promise.resolve(s)});if(n===void 0&&(n=new AW),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r,this._eventStream=i}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new rm(this,async()=>{const s=e instanceof URL?await Pn.parse({url:e,urlReader:this.urlReader,eventStream:this.eventStream,options:n}):Pn.parse({source:e,eventStream:this.eventStream,options:n});return Pn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i,eventStream:this.eventStream,replaceMaterializedReferences:n==null?void 0:n.replaceMaterializedReferences,materializedTablePrefix:n==null?void 0:n.materializedTablePrefix})},n)}_loadModelFromModelDef(e,n){return new rm(this,async()=>new em(e,[],[],[]),n)}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n,r)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n,r)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}}we.Runtime=rw;class h7e extends rw{constructor(e,n){if(n===void 0){const r=e;super(nm.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,nm.fromArray(r)),this.rawConnections=r}}}we.ConnectionRuntime=h7e;class p7e extends rw{constructor(...e){let n,r,i;for(const s of e)BW(s)&&(n=s),E7e(s)&&(r=s),$W(s)&&(i=s);if(r===void 0)throw new Error("Expected connection to be passed into SingleConnectionRuntime");super(n,r,i),this.connection=r}get supportsNesting(){return(0,GD.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,GD.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,GD.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=p7e;class Q5{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,n){return new SW(this.runtime,e,n)}makeExploreMaterializer(e,n){return new bW(this.runtime,e,n)}makePreparedResultMaterializer(e){return new CW(this.runtime,e)}}class rm extends Q5{constructor(e,n,r){super(e,n),this.runtime=e,this.compileQueryOptions=r}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...n})}loadQueryByName(e,n){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...n})}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await Pn.parse({url:e,urlReader:s,options:n}):Pn.parse({source:e,options:n}),a=await this.getModel();return(await Pn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i,...this.compileQueryOptions})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new rm(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await Pn.parse({url:e,urlReader:r,options:n}):Pn.parse({source:e,options:n}),o=await this.getModel();return await Pn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError,...this.compileQueryOptions})},n)}async search(e,n,r=1e3,i=void 0,s){const o=await this.materialize(),u=new ir.QueryModel(o._modelDef,s),a=o.getExploreByName(e).structDef;if(!(0,ir.isSourceDef)(a))throw new Error("Source to be searched was unexpectedly, not a source");const l=a.connection,c=await this.runtime.connections.lookupConnection(l);return await u.searchIndex(c,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(!(0,ir.isSourceDef)(s.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1265
1265
  run: ${e}
1266
1266
  -> ${o}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.223",
3
+ "version": "0.0.224-dev241217171758",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "build-types": "tsc --build --declaration --emitDeclarationOnly"
31
31
  },
32
32
  "dependencies": {
33
- "@malloydata/malloy": "^0.0.223",
33
+ "@malloydata/malloy": "^0.0.224-dev241217171758",
34
34
  "@tanstack/solid-virtual": "^3.10.4",
35
35
  "component-register": "^0.8.6",
36
36
  "lodash": "^4.17.20",